Integrated the version info of IoTivity
[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_COMM_ERROR;
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_NOT_ACCEPTABLE:
865             ret = CA_NOT_ACCEPTABLE;
866             break;
867         case OC_STACK_UNAUTHORIZED_REQ:
868             ret = CA_UNAUTHORIZED_REQ;
869             break;
870         case OC_STACK_FORBIDDEN_REQ:
871             ret = CA_FORBIDDEN_REQ;
872             break;
873         case OC_STACK_INTERNAL_SERVER_ERROR:
874             ret = CA_INTERNAL_SERVER_ERROR;
875             break;
876         case OC_STACK_BAD_ENDPOINT:
877             ret = CA_BAD_REQ;
878         default:
879             break;
880     }
881     return ret;
882 }
883
884 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
885 {
886     CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
887
888     // supply default behavior.
889     if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
890     {
891         caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
892     }
893     if ((caFlags & OC_MASK_SCOPE) == 0)
894     {
895         caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
896     }
897     return caFlags;
898 }
899
900 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
901 {
902     return (OCTransportFlags)caFlags;
903 }
904
905 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
906 {
907     uint32_t lowerBound  = 0;
908     uint32_t higherBound = 0;
909
910     if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
911     {
912         return OC_STACK_INVALID_PARAM;
913     }
914
915     OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
916
917     cbNode->presence->TTL = maxAgeSeconds;
918
919     for (int index = 0; index < PresenceTimeOutSize; index++)
920     {
921         // Guard against overflow
922         if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
923                                      * 100)
924         {
925             lowerBound = GetTicks((PresenceTimeOut[index] *
926                                   cbNode->presence->TTL *
927                                   MILLISECONDS_PER_SECOND)/100);
928         }
929         else
930         {
931             lowerBound = GetTicks(UINT32_MAX);
932         }
933
934         if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
935                                      * 100)
936         {
937             higherBound = GetTicks((PresenceTimeOut[index + 1] *
938                                    cbNode->presence->TTL *
939                                    MILLISECONDS_PER_SECOND)/100);
940         }
941         else
942         {
943             higherBound = GetTicks(UINT32_MAX);
944         }
945
946         cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
947
948         OIC_LOG_V(DEBUG, TAG, "lowerBound timeout  %d", lowerBound);
949         OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
950         OIC_LOG_V(DEBUG, TAG, "timeOut entry  %d", cbNode->presence->timeOut[index]);
951     }
952
953     cbNode->presence->TTLlevel = 0;
954
955     OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
956     return OC_STACK_OK;
957 }
958
959 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
960 {
961     if (trigger == OC_PRESENCE_TRIGGER_CREATE)
962     {
963         return OC_RSRVD_TRIGGER_CREATE;
964     }
965     else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
966     {
967         return OC_RSRVD_TRIGGER_CHANGE;
968     }
969     else
970     {
971         return OC_RSRVD_TRIGGER_DELETE;
972     }
973 }
974
975 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
976 {
977     if(!triggerStr)
978     {
979         return OC_PRESENCE_TRIGGER_CREATE;
980     }
981     else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
982     {
983         return OC_PRESENCE_TRIGGER_CREATE;
984     }
985     else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
986     {
987         return OC_PRESENCE_TRIGGER_CHANGE;
988     }
989     else
990     {
991         return OC_PRESENCE_TRIGGER_DELETE;
992     }
993 }
994
995 OCStackResult OCEncodeAddressForRFC6874(char *outputAddress,
996                                         size_t outputSize,
997                                         const char *inputAddress)
998 {
999     VERIFY_NON_NULL(inputAddress,  FATAL, OC_STACK_INVALID_PARAM);
1000     VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
1001
1002     size_t inputLength = strnlen(inputAddress, outputSize);
1003
1004     // inputSize includes the null terminator
1005     size_t inputSize = inputLength + 1;
1006
1007     if (inputSize > outputSize)
1008     {
1009         OIC_LOG_V(ERROR, TAG,
1010                   "OCEncodeAddressForRFC6874 failed: "
1011                   "outputSize (%zu) < inputSize (%zu)",
1012                   outputSize, inputSize);
1013
1014         return OC_STACK_ERROR;
1015     }
1016
1017     char* percentChar = strchr(inputAddress, '%');
1018
1019     // If there is no '%' character, then no change is required to the string.
1020     if (NULL == percentChar)
1021     {
1022         OICStrcpy(outputAddress, outputSize, inputAddress);
1023         return OC_STACK_OK;
1024     }
1025
1026     const char* addressPart = &inputAddress[0];
1027     const char* scopeIdPart = percentChar + 1;
1028
1029     // Sanity check to make sure this string doesn't have more '%' characters
1030     if (NULL != strchr(scopeIdPart, '%'))
1031     {
1032         return OC_STACK_ERROR;
1033     }
1034
1035     // If no string follows the first '%', then the input was invalid.
1036     if (scopeIdPart[0] == '\0')
1037     {
1038         OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
1039         return OC_STACK_ERROR;
1040     }
1041
1042     // Check to see if the string is already encoded
1043     if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
1044     {
1045         OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: Input string is already encoded");
1046         return OC_STACK_ERROR;
1047     }
1048
1049     // Fail if we don't have room for encoded string's two additional chars
1050     if (outputSize < (inputSize + 2))
1051     {
1052         OIC_LOG(ERROR, TAG, "OCEncodeAddressForRFC6874 failed: encoded output will not fit!");
1053         return OC_STACK_ERROR;
1054     }
1055
1056     // Restore the null terminator with an escaped '%' character, per RFC 6874
1057     OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
1058     strcat(outputAddress, "%25");
1059     strcat(outputAddress, scopeIdPart);
1060
1061     return OC_STACK_OK;
1062 }
1063
1064 OCStackResult OCDecodeAddressForRFC6874(char *outputAddress,
1065                                         size_t outputSize,
1066                                         const char *inputAddress,
1067                                         const char *end)
1068 {
1069     VERIFY_NON_NULL(inputAddress,  FATAL, OC_STACK_INVALID_PARAM);
1070     VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
1071
1072     if (NULL == end)
1073     {
1074         end = inputAddress + strlen(inputAddress);
1075     }
1076     size_t inputLength = end - inputAddress;
1077
1078     const char *percent = strchr(inputAddress, '%');
1079     if (!percent || (percent > end))
1080     {
1081         OICStrcpyPartial(outputAddress, outputSize, inputAddress, inputLength);
1082     }
1083     else
1084     {
1085         if (percent[1] != '2' || percent[2] != '5')
1086         {
1087             return OC_STACK_INVALID_URI;
1088         }
1089
1090         size_t addrlen = percent - inputAddress + 1;
1091         OICStrcpyPartial(outputAddress, outputSize, inputAddress, addrlen);
1092         OICStrcpyPartial(outputAddress + addrlen, outputSize - addrlen,
1093                          percent + 3, end - percent - 3);
1094     }
1095
1096     return OC_STACK_OK;
1097 }
1098
1099 /**
1100  * The cononical presence allows constructed URIs to be string compared.
1101  *
1102  * requestUri must be a char array of size CA_MAX_URI_LENGTH
1103  */
1104 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint,
1105                                     char *presenceUri, bool isMulticast)
1106 {
1107     VERIFY_NON_NULL(endpoint   , FATAL, OC_STACK_INVALID_PARAM);
1108     VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
1109
1110     if (isMulticast)
1111     {
1112         OIC_LOG(DEBUG, TAG, "Make Multicast Presence URI");
1113         return snprintf(presenceUri, CA_MAX_URI_LENGTH, "%s", OC_RSRVD_PRESENCE_URI);
1114     }
1115
1116     CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
1117     if (ep->adapter == CA_ADAPTER_IP)
1118     {
1119         if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
1120         {
1121             if ('\0' == ep->addr[0])  // multicast
1122             {
1123                 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
1124             }
1125             else
1126             {
1127                 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
1128
1129                 OCStackResult result = OCEncodeAddressForRFC6874(addressEncoded,
1130                                                                  sizeof(addressEncoded),
1131                                                                  ep->addr);
1132
1133                 if (OC_STACK_OK != result)
1134                 {
1135                     return -1;
1136                 }
1137
1138                 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
1139                         addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
1140             }
1141         }
1142         else
1143         {
1144             if ('\0' == ep->addr[0])  // multicast
1145             {
1146                 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
1147                 ep->port = OC_MULTICAST_PORT;
1148             }
1149             return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
1150                     ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
1151         }
1152     }
1153
1154     // might work for other adapters (untested, but better than nothing)
1155     return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
1156                     OC_RSRVD_PRESENCE_URI);
1157 }
1158
1159
1160 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
1161                             const CAResponseInfo_t *responseInfo)
1162 {
1163     VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
1164     VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
1165
1166     OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1167     ClientCB * cbNode = NULL;
1168     char *resourceTypeName = NULL;
1169     OCClientResponse *response = NULL;
1170     OCStackResult result = OC_STACK_ERROR;
1171     uint32_t maxAge = 0;
1172     int uriLen;
1173     char presenceUri[CA_MAX_URI_LENGTH];
1174
1175     int presenceSubscribe = 0;
1176     int multicastPresenceSubscribe = 0;
1177
1178     if (responseInfo->result != CA_CONTENT)
1179     {
1180         OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1181         return OC_STACK_ERROR;
1182     }
1183
1184     response = (OCClientResponse *)OICCalloc(1, sizeof(*response));
1185     if (!response)
1186     {
1187             OIC_LOG(ERROR, TAG, "Allocating memory for response failed");
1188             return OC_STACK_ERROR;
1189     }
1190     response->devAddr.adapter = OC_DEFAULT_ADAPTER;
1191
1192     response->payload = NULL;
1193     response->result = OC_STACK_OK;
1194
1195     CopyEndpointToDevAddr(endpoint, &response->devAddr);
1196     FixUpClientResponse(response);
1197
1198     if (responseInfo->info.payload)
1199     {
1200         result = OCParsePayload(&response->payload,
1201                 PAYLOAD_TYPE_PRESENCE,
1202                 responseInfo->info.payload,
1203                 responseInfo->info.payloadSize);
1204
1205         if(result != OC_STACK_OK)
1206         {
1207             OIC_LOG(ERROR, TAG, "Presence parse failed");
1208             goto exit;
1209         }
1210         if(!response->payload || response->payload->type != PAYLOAD_TYPE_PRESENCE)
1211         {
1212             OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1213             result = OC_STACK_ERROR;
1214             goto exit;
1215         }
1216         response->sequenceNumber = ((OCPresencePayload*)response->payload)->sequenceNumber;
1217         resourceTypeName = ((OCPresencePayload*)response->payload)->resourceType;
1218         maxAge = ((OCPresencePayload*)response->payload)->maxAge;
1219     }
1220
1221     // check for unicast presence
1222     uriLen = FormCanonicalPresenceUri(endpoint, presenceUri,
1223                                       responseInfo->isMulticast);
1224     if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1225     {
1226         result = OC_STACK_INVALID_URI;
1227         goto exit;
1228     }
1229     OIC_LOG(INFO, TAG, "check for unicast presence");
1230     cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1231     if (cbNode)
1232     {
1233         presenceSubscribe = 1;
1234     }
1235     else
1236     {
1237         // check for multicast presence
1238         OIC_LOG(INFO, TAG, "check for multicast presence");
1239         cbNode = GetClientCB(NULL, 0, NULL, OC_RSRVD_PRESENCE_URI);
1240         if (cbNode)
1241         {
1242             multicastPresenceSubscribe = 1;
1243         }
1244     }
1245
1246     if (!presenceSubscribe && !multicastPresenceSubscribe)
1247     {
1248         OIC_LOG(INFO, TAG, "Received a presence notification, "
1249                 "but need to register presence callback, ignoring");
1250         goto exit;
1251     }
1252
1253     if (presenceSubscribe)
1254     {
1255         if(cbNode->sequenceNumber == response->sequenceNumber)
1256         {
1257             OIC_LOG(INFO, TAG, "No presence change");
1258             ResetPresenceTTL(cbNode, maxAge);
1259             OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1260             goto exit;
1261         }
1262
1263         if(maxAge == 0)
1264         {
1265             OIC_LOG(INFO, TAG, "Stopping presence");
1266             response->result = OC_STACK_PRESENCE_STOPPED;
1267             if(cbNode->presence)
1268             {
1269                 OICFree(cbNode->presence->timeOut);
1270                 OICFree(cbNode->presence);
1271                 cbNode->presence = NULL;
1272             }
1273         }
1274         else
1275         {
1276             if(!cbNode->presence)
1277             {
1278                 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1279
1280                 if(!(cbNode->presence))
1281                 {
1282                     OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1283                     result = OC_STACK_NO_MEMORY;
1284                     goto exit;
1285                 }
1286
1287                 VERIFY_NON_NULL_V(cbNode->presence);
1288                 cbNode->presence->timeOut = NULL;
1289                 cbNode->presence->timeOut = (uint32_t *)
1290                         OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1291                 if(!(cbNode->presence->timeOut)){
1292                     OIC_LOG(ERROR, TAG,
1293                                   "Could not allocate memory for cbNode->presence->timeOut");
1294                     OICFree(cbNode->presence);
1295                     result = OC_STACK_NO_MEMORY;
1296                     goto exit;
1297                 }
1298             }
1299
1300             ResetPresenceTTL(cbNode, maxAge);
1301
1302             cbNode->sequenceNumber = response->sequenceNumber;
1303         }
1304     }
1305     else
1306     {
1307         // This is the multicast case
1308         OIC_LOG(INFO, TAG, "this is the multicast presence");
1309         if (0 == maxAge)
1310         {
1311             OIC_LOG(INFO, TAG, "Stopping presence");
1312             response->result = OC_STACK_PRESENCE_STOPPED;
1313         }
1314     }
1315
1316     // Ensure that a filter is actually applied.
1317     if (resourceTypeName && cbNode->filterResourceType)
1318     {
1319         OIC_LOG_V(INFO, TAG, "find resource type : %s", resourceTypeName);
1320         if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1321         {
1322             goto exit;
1323         }
1324     }
1325
1326     OIC_LOG(INFO, TAG, "Callback for presence");
1327
1328     cbResult = cbNode->callBack(cbNode->context, cbNode->handle, response);
1329
1330     if (cbResult == OC_STACK_DELETE_TRANSACTION)
1331     {
1332         FindAndDeleteClientCB(cbNode);
1333     }
1334
1335 exit:
1336     OCPayloadDestroy(response->payload);
1337     OICFree(response);
1338     return result;
1339 }
1340
1341 OCStackResult HandleBatchResponse(char *requestUri, OCRepPayload **payload)
1342 {
1343     if (requestUri && *payload)
1344     {
1345         char *interfaceName = NULL;
1346         char *rtTypeName = NULL;
1347         char *uriQuery = NULL;
1348         char *uriWithoutQuery = NULL;
1349         if (OC_STACK_OK == getQueryFromUri(requestUri, &uriQuery, &uriWithoutQuery))
1350         {
1351             if (OC_STACK_OK == ExtractFiltersFromQuery(uriQuery, &interfaceName, &rtTypeName))
1352             {
1353                 if (0 == strcmp(OC_RSRVD_INTERFACE_BATCH, interfaceName))
1354                 {
1355                     char *uri = (*payload)->uri;
1356                     if (uri && 0 != strcmp(uriWithoutQuery, uri))
1357                     {
1358                         OCRepPayload *newPayload = OCRepPayloadCreate();
1359                         if (newPayload)
1360                         {
1361                             OCRepPayloadSetUri(newPayload, uri);
1362                             newPayload->next = *payload;
1363                             *payload = newPayload;
1364                         }
1365                     }
1366                 }
1367             }
1368         }
1369         OICFree(interfaceName);
1370         OICFree(rtTypeName);
1371         OICFree(uriQuery);
1372         OICFree(uriWithoutQuery);
1373         return OC_STACK_OK;
1374     }
1375     return OC_STACK_INVALID_PARAM;
1376 }
1377
1378 #ifndef WITH_ARDUINO
1379 OCStackResult OCMapZoneIdToLinkLocalEndpoint(OCDiscoveryPayload *payload, uint32_t ifindex)
1380 {
1381     if (!payload)
1382     {
1383         OIC_LOG(ERROR, TAG, "Given argument payload is NULL!!");
1384         return OC_STACK_INVALID_PARAM;
1385     }
1386
1387     OCResourcePayload *curRes = payload->resources;
1388
1389     while (curRes != NULL)
1390     {
1391         OCEndpointPayload* eps = curRes->eps;
1392
1393         while (eps != NULL)
1394         {
1395             if (eps->family & OC_IP_USE_V6)
1396             {
1397                 CATransportFlags_t scopeLevel;
1398                 if (CA_STATUS_OK == CAGetIpv6AddrScope(eps->addr, &scopeLevel))
1399                 {
1400                     if (CA_SCOPE_LINK == scopeLevel)
1401                     {
1402                         char *zoneId = NULL;
1403                         if (OC_STACK_OK == OCGetLinkLocalZoneId(ifindex, &zoneId))
1404                         {
1405                             assert(zoneId != NULL);
1406                             // put zoneId to end of addr
1407                             OICStrcat(eps->addr, OC_MAX_ADDR_STR_SIZE, "%");
1408                             OICStrcat(eps->addr, OC_MAX_ADDR_STR_SIZE, zoneId);
1409                             OICFree(zoneId);
1410                         }
1411                         else
1412                         {
1413                             OIC_LOG(ERROR, TAG, "failed at parse zone-id for link-local address");
1414                             return OC_STACK_ERROR;
1415                         }
1416                     }
1417                 }
1418                 else
1419                 {
1420                     OIC_LOG(ERROR, TAG, "failed at parse ipv6 scope level");
1421                     return OC_STACK_ERROR;
1422                 }
1423             }
1424             eps = eps->next;
1425         }
1426         curRes = curRes->next;
1427     }
1428
1429     return OC_STACK_OK;
1430 }
1431 #endif
1432
1433 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1434 {
1435     OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1436
1437     if(responseInfo->info.resourceUri &&
1438         strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1439     {
1440         HandlePresenceResponse(endPoint, responseInfo);
1441         return;
1442     }
1443
1444     ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1445             responseInfo->info.tokenLength, NULL, NULL);
1446
1447     ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1448             responseInfo->info.tokenLength);
1449
1450     if(cbNode)
1451     {
1452         OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1453
1454         // check obs header option
1455         bool obsHeaderOpt = false;
1456         CAHeaderOption_t *options = responseInfo->info.options;
1457         for (uint8_t i = 0; i< responseInfo->info.numOptions; i++)
1458         {
1459             if (options && (options[i].optionID == COAP_OPTION_OBSERVE))
1460             {
1461                 obsHeaderOpt = true;
1462                 break;
1463             }
1464         }
1465
1466         if(responseInfo->result == CA_EMPTY)
1467         {
1468             OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1469             // We do not have a case for the client to receive a RESET
1470             if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1471             {
1472                 //This is the case of receiving an ACK on a request to a slow resource!
1473                 OIC_LOG(INFO, TAG, "This is a pure ACK");
1474                 //TODO: should we inform the client
1475                 //      app that at least the request was received at the server?
1476             }
1477         }
1478         else if (CA_RETRANSMIT_TIMEOUT == responseInfo->result
1479                 || CA_NOT_ACCEPTABLE == responseInfo->result)
1480         {
1481             if (CA_RETRANSMIT_TIMEOUT == responseInfo->result)
1482             {
1483                 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1484                 OIC_LOG(INFO, TAG, "Calling into application address space");
1485             }
1486             else
1487             {
1488                 OIC_LOG(INFO, TAG, "Server doesn't support the requested payload format");
1489                 OIC_LOG(INFO, TAG, "Calling into application address space");
1490             }
1491
1492             OCClientResponse *response = NULL;
1493
1494             response = (OCClientResponse *)OICCalloc(1, sizeof(*response));
1495             if (!response)
1496             {
1497                 OIC_LOG(ERROR, TAG, "Allocating memory for response failed");
1498                 return;
1499             }
1500
1501             response->devAddr.adapter = OC_DEFAULT_ADAPTER;
1502             CopyEndpointToDevAddr(endPoint, &response->devAddr);
1503             FixUpClientResponse(response);
1504             response->resourceUri = responseInfo->info.resourceUri;
1505             memcpy(response->identity.id, responseInfo->info.identity.id,
1506                                                 sizeof (response->identity.id));
1507             response->identity.id_length = responseInfo->info.identity.id_length;
1508
1509             response->result = CAResponseToOCStackResult(responseInfo->result);
1510             cbNode->callBack(cbNode->context,
1511                     cbNode->handle, response);
1512             FindAndDeleteClientCB(cbNode);
1513             OICFree(response);
1514         }
1515         else if ((cbNode->method == OC_REST_OBSERVE || cbNode->method == OC_REST_OBSERVE_ALL)
1516                 && (responseInfo->result == CA_CONTENT) && !obsHeaderOpt)
1517         {
1518             OCClientResponse *response = NULL;
1519
1520             response = (OCClientResponse *)OICCalloc(1, sizeof(*response));
1521             if (!response)
1522             {
1523                 OIC_LOG(ERROR, TAG, "Allocating memory for response failed");
1524                 return;
1525             }
1526
1527             response->devAddr.adapter = OC_DEFAULT_ADAPTER;
1528             CopyEndpointToDevAddr(endPoint, &response->devAddr);
1529             FixUpClientResponse(response);
1530             response->resourceUri = responseInfo->info.resourceUri;
1531             memcpy(response->identity.id, responseInfo->info.identity.id,
1532                                     sizeof (response->identity.id));
1533             response->identity.id_length = responseInfo->info.identity.id_length;
1534             response->result = OC_STACK_OK;
1535
1536             OIC_LOG(DEBUG, TAG, "This is response of observer cancel or observer request fail");
1537
1538             cbNode->callBack(cbNode->context,
1539                              cbNode->handle,
1540                              response);
1541             FindAndDeleteClientCB(cbNode);
1542             OICFree(response);
1543         }
1544         else
1545         {
1546             OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1547             OIC_LOG(INFO, TAG, "Calling into application address space");
1548
1549             OCClientResponse *response = NULL;
1550             OCPayloadType type = PAYLOAD_TYPE_INVALID;
1551
1552             response = (OCClientResponse *)OICCalloc(1, sizeof(*response));
1553             if (!response)
1554             {
1555                 OIC_LOG(ERROR, TAG, "Allocating memory for response failed");
1556                 return;
1557             }
1558
1559             response->devAddr.adapter = OC_DEFAULT_ADAPTER;
1560             response->sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1561             CopyEndpointToDevAddr(endPoint, &response->devAddr);
1562             FixUpClientResponse(response);
1563             response->resourceUri = responseInfo->info.resourceUri;
1564             memcpy(response->identity.id, responseInfo->info.identity.id,
1565                                                 sizeof (response->identity.id));
1566             response->identity.id_length = responseInfo->info.identity.id_length;
1567
1568             response->result = CAResponseToOCStackResult(responseInfo->result);
1569
1570             if(responseInfo->info.payload &&
1571                responseInfo->info.payloadSize)
1572             {
1573                 // check the security resource
1574                 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1575                 {
1576                     type = PAYLOAD_TYPE_SECURITY;
1577                 }
1578                 else if (cbNode->method == OC_REST_DISCOVER)
1579                 {
1580                     if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1581                                 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1582                     {
1583                         type = PAYLOAD_TYPE_DISCOVERY;
1584                     }
1585 #ifdef WITH_MQ
1586                     else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1587                     {
1588                         type = PAYLOAD_TYPE_DISCOVERY;
1589                     }
1590 #endif
1591                     else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1592                     {
1593                         type = PAYLOAD_TYPE_REPRESENTATION;
1594                     }
1595                     else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1596                     {
1597                         type = PAYLOAD_TYPE_REPRESENTATION;
1598                     }
1599                     else if (strcmp(cbNode->requestUri, OC_RSRVD_INTROSPECTION_URI) == 0)
1600                     {
1601                         type = PAYLOAD_TYPE_REPRESENTATION;
1602                     }
1603                     else if (strcmp(cbNode->requestUri, OC_RSRVD_INTROSPECTION_PAYLOAD_URI) == 0)
1604                     {
1605                         type = PAYLOAD_TYPE_REPRESENTATION;
1606                     }
1607 #ifdef ROUTING_GATEWAY
1608                     else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1609                     {
1610                         type = PAYLOAD_TYPE_REPRESENTATION;
1611                     }
1612 #endif
1613                     else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1614                     {
1615                         type = PAYLOAD_TYPE_REPRESENTATION;
1616                     }
1617 #ifdef TCP_ADAPTER
1618                     else if (strcmp(cbNode->requestUri, OC_RSRVD_KEEPALIVE_URI) == 0)
1619                     {
1620                         type = PAYLOAD_TYPE_REPRESENTATION;
1621                     }
1622 #endif
1623                     else
1624                     {
1625                         OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1626                                 cbNode->method, cbNode->requestUri);
1627                         return;
1628                     }
1629                 }
1630                 else if (cbNode->method == OC_REST_GET ||
1631                          cbNode->method == OC_REST_PUT ||
1632                          cbNode->method == OC_REST_POST ||
1633                          cbNode->method == OC_REST_OBSERVE ||
1634                          cbNode->method == OC_REST_OBSERVE_ALL ||
1635                          cbNode->method == OC_REST_DELETE)
1636                 {
1637                     if (cbNode->requestUri)
1638                     {
1639                         if (0 == strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri))
1640                         {
1641                             type = PAYLOAD_TYPE_REPRESENTATION;
1642                         }
1643                         else if (0 == strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri))
1644                         {
1645                             type = PAYLOAD_TYPE_REPRESENTATION;
1646                         }
1647                         if (type == PAYLOAD_TYPE_INVALID)
1648                         {
1649                             OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1650                                     cbNode->method, cbNode->requestUri);
1651                             type = PAYLOAD_TYPE_REPRESENTATION;
1652                         }
1653                     }
1654                     else
1655                     {
1656                         OIC_LOG(INFO, TAG, "No Request URI, PROXY URI");
1657                         type = PAYLOAD_TYPE_REPRESENTATION;
1658                     }
1659                 }
1660                 else
1661                 {
1662                     OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1663                             cbNode->method, cbNode->requestUri);
1664                     OICFree(response);
1665                     return;
1666                 }
1667
1668                 // In case of error, still want application to receive the error message.
1669                 if (OCResultToSuccess(response->result) || PAYLOAD_TYPE_REPRESENTATION == type)
1670                 {
1671                     if (OC_STACK_OK != OCParsePayload(&response->payload,
1672                             type,
1673                             responseInfo->info.payload,
1674                             responseInfo->info.payloadSize))
1675                     {
1676                         OIC_LOG(ERROR, TAG, "Error converting payload");
1677                         OCPayloadDestroy(response->payload);
1678                         return;
1679                     }
1680
1681                     // Check endpoints has link-local ipv6 address.
1682                     // if there is, map zone-id which parsed from ifindex
1683 #ifndef WITH_ARDUINO
1684                     if (PAYLOAD_TYPE_DISCOVERY == response->payload->type)
1685                     {
1686                         OCDiscoveryPayload *disPayload = (OCDiscoveryPayload*)(response->payload);
1687                         if (OC_STACK_OK !=
1688                             OCMapZoneIdToLinkLocalEndpoint(disPayload, response->devAddr.ifindex))
1689                         {
1690                             OIC_LOG(ERROR, TAG, "failed at map zone-id for link-local address");
1691                             OCPayloadDestroy(response->payload);
1692                             return;
1693                         }
1694                     }
1695 #endif
1696                 }
1697                 else
1698                 {
1699                     response->resourceUri = OICStrdup(cbNode->requestUri);
1700                 }
1701             }
1702
1703             response->numRcvdVendorSpecificHeaderOptions = 0;
1704             if((responseInfo->info.numOptions > 0) && (responseInfo->info.options != NULL))
1705             {
1706                 int start = 0;
1707                 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1708                 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1709                 {
1710                     size_t i;
1711                     uint32_t observationOption;
1712                     uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1713                     for (observationOption=0, i=0;
1714                             i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1715                             i++)
1716                     {
1717                         observationOption =
1718                             (observationOption << 8) | optionData[i];
1719                     }
1720                     response->sequenceNumber = observationOption;
1721                     response->numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1722                     start = 1;
1723                 }
1724                 else
1725                 {
1726                     response->numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1727                 }
1728
1729                 if(response->numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1730                 {
1731                     OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1732                     OCPayloadDestroy(response->payload);
1733                     OICFree(response);
1734                     return;
1735                 }
1736
1737                 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1738                 {
1739                     memcpy (&(response->rcvdVendorSpecificHeaderOptions[i-start]),
1740                             &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1741                 }
1742             }
1743
1744             if (cbNode->method == OC_REST_OBSERVE &&
1745                 response->sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1746                 cbNode->sequenceNumber <=  MAX_SEQUENCE_NUMBER &&
1747                 response->sequenceNumber <= cbNode->sequenceNumber)
1748             {
1749                 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1750                                                  response->sequenceNumber);
1751             }
1752             else
1753             {
1754 #ifdef RD_CLIENT
1755                 if (cbNode->requestUri)
1756                 {
1757                     // if request uri is '/oic/rd', update ins value of resource.
1758                     char *targetUri = strstr(cbNode->requestUri, OC_RSRVD_RD_URI);
1759                     if (targetUri)
1760                     {
1761                         OCUpdateResourceInsWithResponse(cbNode->requestUri, response);
1762                     }
1763                 }
1764 #endif
1765                 // set remoteID(device ID) into OCClientResponse callback parameter
1766                 if (OC_REST_DISCOVER == cbNode->method && PAYLOAD_TYPE_DISCOVERY == type)
1767                 {
1768                     OCDiscoveryPayload *payload = (OCDiscoveryPayload*) response->payload;
1769                     // Payload can be empty in case of error message.
1770                     if (payload && payload->sid)
1771                     {
1772                         OICStrcpy(response->devAddr.remoteId, sizeof(response->devAddr.remoteId),
1773                                   payload->sid);
1774                         OIC_LOG_V(INFO, TAG, "Device ID of response : %s",
1775                                   response->devAddr.remoteId);
1776
1777 #if defined(TCP_ADAPTER) && defined(WITH_CLOUD)
1778                         CAConnectUserPref_t connPrefer = CA_USER_PREF_CLOUD;
1779                         CAResult_t ret = CAUtilCMGetConnectionUserConfig(&connPrefer);
1780                         if (ret == CA_STATUS_OK && connPrefer != CA_USER_PREF_CLOUD)
1781                         {
1782                             OCCMDiscoveryResource(response);
1783                         }
1784 #endif
1785                     }
1786                 }
1787                 if (response->payload && response->payload->type == PAYLOAD_TYPE_REPRESENTATION)
1788                 {
1789                     HandleBatchResponse(cbNode->requestUri, (OCRepPayload **)&response->payload);
1790                 }
1791
1792                 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1793                                                                         cbNode->handle,
1794                                                                         response);
1795                 cbNode->sequenceNumber = response->sequenceNumber;
1796
1797                 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1798                 {
1799                     FindAndDeleteClientCB(cbNode);
1800                 }
1801                 else
1802                 {
1803                     // To keep discovery callbacks active.
1804                     cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1805                                             MILLISECONDS_PER_SECOND);
1806                 }
1807             }
1808
1809             //Need to send ACK when the response is CON
1810             if(responseInfo->info.type == CA_MSG_CONFIRM)
1811             {
1812                 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1813                         CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1814             }
1815
1816             OCPayloadDestroy(response->payload);
1817             OICFree(response);
1818         }
1819         return;
1820     }
1821
1822     if(observer)
1823     {
1824         OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1825         if(responseInfo->result == CA_EMPTY)
1826         {
1827             OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1828             if(responseInfo->info.type == CA_MSG_RESET)
1829             {
1830                 OIC_LOG(INFO, TAG, "This is a RESET");
1831                 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1832                         OC_OBSERVER_NOT_INTERESTED);
1833             }
1834             else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1835             {
1836                 OIC_LOG(INFO, TAG, "This is a pure ACK");
1837                 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1838                         OC_OBSERVER_STILL_INTERESTED);
1839             }
1840         }
1841         else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1842         {
1843             OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1844             OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1845                     OC_OBSERVER_FAILED_COMM);
1846         }
1847         return;
1848     }
1849
1850     if(!cbNode && !observer)
1851     {
1852         if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1853            || myStackMode == OC_GATEWAY)
1854         {
1855             OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1856             if(responseInfo->result == CA_EMPTY)
1857             {
1858                 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1859             }
1860             else
1861             {
1862                 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1863                 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1864                                         CA_MSG_RESET, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1865             }
1866         }
1867
1868         if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1869            || myStackMode == OC_GATEWAY)
1870         {
1871             OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1872             if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1873             {
1874                 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1875                                             responseInfo->info.messageId);
1876             }
1877             if (responseInfo->info.type == CA_MSG_RESET)
1878             {
1879                 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1880                                             responseInfo->info.messageId);
1881             }
1882         }
1883
1884         return;
1885     }
1886 }
1887
1888 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1889 {
1890     VERIFY_NON_NULL_NR(endPoint, FATAL);
1891     VERIFY_NON_NULL_NR(responseInfo, FATAL);
1892
1893     OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1894     OIC_TRACE_BEGIN(%s:HandleCAResponses, TAG);
1895 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1896 #ifdef ROUTING_GATEWAY
1897     bool needRIHandling = false;
1898     /*
1899      * Routing manager is going to update either of endpoint or response or both.
1900      * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1901      * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1902      * destination.
1903      */
1904     OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1905                                          &needRIHandling);
1906     if(ret != OC_STACK_OK || !needRIHandling)
1907     {
1908         OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1909         OIC_TRACE_END();
1910         return;
1911     }
1912 #endif
1913
1914     /*
1915      * Put source in sender endpoint so that the next packet from application can be routed to
1916      * proper destination and remove "RM" coap header option before passing request / response to
1917      * RI as this option will make no sense to either RI or application.
1918      */
1919     RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1920                  (uint8_t *) &(responseInfo->info.numOptions),
1921                  (CAEndpoint_t *) endPoint);
1922 #endif
1923
1924     OCHandleResponse(endPoint, responseInfo);
1925
1926     OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1927     OIC_TRACE_END();
1928 }
1929
1930 /*
1931  * This function handles error response from CA
1932  * code shall be added to handle the errors
1933  */
1934 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1935 {
1936     VERIFY_NON_NULL_NR(endPoint, FATAL);
1937     VERIFY_NON_NULL_NR(errorInfo, FATAL);
1938
1939     OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1940     OIC_TRACE_BEGIN(%s:HandleCAErrorResponse, TAG);
1941
1942     ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1943                                    errorInfo->info.tokenLength, NULL, NULL);
1944     if (cbNode)
1945     {
1946         OCClientResponse *response = NULL;
1947
1948         response = (OCClientResponse *)OICCalloc(1, sizeof(*response));
1949         if (!response)
1950         {
1951             OIC_LOG(ERROR, TAG, "Allocating memory for response failed");
1952             return;
1953         }
1954
1955         response->devAddr.adapter = OC_DEFAULT_ADAPTER;
1956         CopyEndpointToDevAddr(endPoint, &response->devAddr);
1957         FixUpClientResponse(response);
1958         response->resourceUri = errorInfo->info.resourceUri;
1959         memcpy(response->identity.id, errorInfo->info.identity.id,
1960                sizeof (response->identity.id));
1961         response->identity.id_length = errorInfo->info.identity.id_length;
1962         response->result = CAResultToOCResult(errorInfo->result);
1963
1964         cbNode->callBack(cbNode->context, cbNode->handle, response);
1965         OICFree(response);
1966     }
1967
1968     ResourceObserver *observer = GetObserverUsingToken(errorInfo->info.token,
1969                                                        errorInfo->info.tokenLength);
1970     if (observer)
1971     {
1972         OIC_LOG(INFO, TAG, "Receiving communication error for an observer");
1973         OCStackResult result = CAResultToOCResult(errorInfo->result);
1974         if (OC_STACK_COMM_ERROR == result)
1975         {
1976             OCStackFeedBack(errorInfo->info.token, errorInfo->info.tokenLength,
1977                             OC_OBSERVER_FAILED_COMM);
1978         }
1979     }
1980
1981     OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1982     OIC_TRACE_END();
1983 }
1984
1985 /*
1986  * This function sends out Direct Stack Responses. These are responses that are not coming
1987  * from the application entity handler. These responses have no payload and are usually ACKs,
1988  * RESETs or some error conditions that were caught by the stack.
1989  */
1990 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1991         const CAResponseResult_t responseResult, const CAMessageType_t type,
1992         const uint8_t numOptions, const CAHeaderOption_t *options,
1993         CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1994         CADataType_t dataType)
1995 {
1996     OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1997     CAResponseInfo_t respInfo = {
1998         .result = responseResult
1999     };
2000     respInfo.info.messageId = coapID;
2001     respInfo.info.numOptions = numOptions;
2002
2003     if (respInfo.info.numOptions)
2004     {
2005         respInfo.info.options =
2006             (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
2007         memcpy (respInfo.info.options, options,
2008                 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
2009
2010     }
2011
2012     respInfo.info.payload = NULL;
2013     respInfo.info.token = token;
2014     respInfo.info.tokenLength = tokenLength;
2015     respInfo.info.type = type;
2016     respInfo.info.resourceUri = OICStrdup (resourceUri);
2017     respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
2018     respInfo.info.dataType = dataType;
2019
2020 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2021     // Add the destination to route option from the endpoint->routeData.
2022     bool doPost = false;
2023     OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
2024     if(OC_STACK_OK != result)
2025     {
2026         OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
2027         OICFree (respInfo.info.resourceUri);
2028         OICFree (respInfo.info.options);
2029         return result;
2030     }
2031     if (doPost)
2032     {
2033         OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
2034         CARequestInfo_t reqInfo = {.method = CA_POST };
2035         /* The following initialization is not done in a single initializer block as in
2036          * arduino, .c file is compiled as .cpp and moves it from C99 to C++11.  The latter
2037          * does not have designated initalizers. This is a work-around for now.
2038          */
2039         reqInfo.info.type = CA_MSG_NONCONFIRM;
2040         reqInfo.info.messageId = coapID;
2041         reqInfo.info.tokenLength = tokenLength;
2042         reqInfo.info.token = token;
2043         reqInfo.info.numOptions = respInfo.info.numOptions;
2044         reqInfo.info.payload = NULL;
2045         reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
2046         if (reqInfo.info.numOptions)
2047         {
2048             reqInfo.info.options =
2049                 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
2050             if (NULL == reqInfo.info.options)
2051             {
2052                 OIC_LOG(ERROR, TAG, "Calloc failed");
2053                 OICFree (reqInfo.info.resourceUri);
2054                 OICFree (respInfo.info.resourceUri);
2055                 OICFree (respInfo.info.options);
2056                 return OC_STACK_NO_MEMORY;
2057             }
2058             memcpy (reqInfo.info.options, respInfo.info.options,
2059                     sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
2060
2061         }
2062         CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
2063         OICFree (reqInfo.info.resourceUri);
2064         OICFree (reqInfo.info.options);
2065         OICFree (respInfo.info.resourceUri);
2066         OICFree (respInfo.info.options);
2067         if (CA_STATUS_OK != caResult)
2068         {
2069             OIC_LOG(ERROR, TAG, "CASendRequest error");
2070             return CAResultToOCResult(caResult);
2071         }
2072     }
2073     else
2074 #endif
2075     {
2076         CAResult_t caResult = CASendResponse(endPoint, &respInfo);
2077
2078         // resourceUri in the info field is cloned in the CA layer and
2079         // thus ownership is still here.
2080         OICFree (respInfo.info.resourceUri);
2081         OICFree (respInfo.info.options);
2082         if(CA_STATUS_OK != caResult)
2083         {
2084             OIC_LOG(ERROR, TAG, "CASendResponse error");
2085             return CAResultToOCResult(caResult);
2086         }
2087     }
2088     OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
2089     return OC_STACK_OK;
2090 }
2091
2092 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
2093 {
2094     OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
2095     OCStackResult result = OC_STACK_ERROR;
2096     if (!protocolRequest)
2097     {
2098         OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
2099         return OC_STACK_INVALID_PARAM;
2100     }
2101
2102     OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
2103             protocolRequest->tokenLength);
2104     if (!request)
2105     {
2106         OIC_LOG(INFO, TAG, "This is a new Server Request");
2107         result = AddServerRequest(&request, protocolRequest->coapID,
2108                 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
2109                 protocolRequest->numRcvdVendorSpecificHeaderOptions,
2110                 protocolRequest->observationOption, protocolRequest->qos,
2111                 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
2112                 protocolRequest->payload, protocolRequest->requestToken,
2113                 protocolRequest->tokenLength, protocolRequest->resourceUrl,
2114                 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
2115                 protocolRequest->acceptVersion, &protocolRequest->devAddr);
2116         if (OC_STACK_OK != result)
2117         {
2118             OIC_LOG(ERROR, TAG, "Error adding server request");
2119             return result;
2120         }
2121
2122         if(!request)
2123         {
2124             OIC_LOG(ERROR, TAG, "Out of Memory");
2125             return OC_STACK_NO_MEMORY;
2126         }
2127
2128         if(!protocolRequest->reqMorePacket)
2129         {
2130             request->requestComplete = 1;
2131         }
2132     }
2133     else
2134     {
2135         OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
2136     }
2137
2138     if (request->requestComplete)
2139     {
2140         OIC_LOG(INFO, TAG, "This Server Request is complete");
2141         ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
2142         OCResource *resource = NULL;
2143         result = DetermineResourceHandling (request, &resHandling, &resource);
2144         if (result == OC_STACK_OK)
2145         {
2146             result = ProcessRequest(resHandling, resource, request);
2147         }
2148     }
2149     else
2150     {
2151         OIC_LOG(INFO, TAG, "This Server Request is incomplete");
2152         result = OC_STACK_CONTINUE;
2153     }
2154     return result;
2155 }
2156
2157 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2158 {
2159     OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
2160     OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
2161
2162     if (myStackMode == OC_CLIENT)
2163     {
2164         //TODO: should the client be responding to requests?
2165         return;
2166     }
2167
2168     // If the request message is Confirmable,
2169     // then the response SHOULD be returned in an Acknowledgement message.
2170     CAMessageType_t directResponseType = requestInfo->info.type;
2171     directResponseType = (directResponseType == CA_MSG_CONFIRM)
2172             ? CA_MSG_ACKNOWLEDGE : CA_MSG_NONCONFIRM;
2173
2174     char * uriWithoutQuery = NULL;
2175     char * query = NULL;
2176     OCStackResult requestResult = OC_STACK_ERROR;
2177
2178     requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
2179
2180     if (requestResult != OC_STACK_OK || !uriWithoutQuery)
2181     {
2182         OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
2183         return;
2184     }
2185     OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
2186     OIC_LOG_V(INFO, TAG, "Query : %s", query);
2187
2188     OCServerProtocolRequest serverRequest = { 0 };
2189     if (strlen(uriWithoutQuery) < MAX_URI_LENGTH)
2190     {
2191         OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
2192         OICFree(uriWithoutQuery);
2193     }
2194     else
2195     {
2196         OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
2197         OICFree(uriWithoutQuery);
2198         OICFree(query);
2199         return;
2200     }
2201
2202     if (query)
2203     {
2204         if (strlen(query) < MAX_QUERY_LENGTH)
2205         {
2206             OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
2207             OICFree(query);
2208         }
2209         else
2210         {
2211             OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
2212             OICFree(query);
2213             return;
2214         }
2215     }
2216
2217     if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
2218     {
2219         serverRequest.reqTotalSize = requestInfo->info.payloadSize;
2220         serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
2221         if (!serverRequest.payload)
2222         {
2223             OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
2224             return;
2225         }
2226         memcpy (serverRequest.payload, requestInfo->info.payload,
2227                 requestInfo->info.payloadSize);
2228     }
2229     else
2230     {
2231         serverRequest.reqTotalSize = 0;
2232     }
2233
2234     switch (requestInfo->method)
2235     {
2236         case CA_GET:
2237             serverRequest.method = OC_REST_GET;
2238             break;
2239         case CA_PUT:
2240             serverRequest.method = OC_REST_PUT;
2241             break;
2242         case CA_POST:
2243             serverRequest.method = OC_REST_POST;
2244             break;
2245         case CA_DELETE:
2246             serverRequest.method = OC_REST_DELETE;
2247             break;
2248         default:
2249             OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
2250             SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
2251                                     directResponseType, requestInfo->info.numOptions,
2252                                     requestInfo->info.options, requestInfo->info.token,
2253                                     requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2254                                     CA_RESPONSE_DATA);
2255             OICFree(serverRequest.payload);
2256             return;
2257     }
2258
2259     OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
2260                    requestInfo->info.tokenLength);
2261
2262     serverRequest.tokenLength = requestInfo->info.tokenLength;
2263     if (serverRequest.tokenLength)
2264     {
2265         // Non empty token
2266         serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
2267
2268         if (!serverRequest.requestToken)
2269         {
2270             OIC_LOG(FATAL, TAG, "Allocation for token failed.");
2271             SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
2272                                     directResponseType, requestInfo->info.numOptions,
2273                                     requestInfo->info.options, requestInfo->info.token,
2274                                     requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2275                                     CA_RESPONSE_DATA);
2276             OICFree(serverRequest.payload);
2277             return;
2278         }
2279         memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
2280     }
2281
2282     switch (requestInfo->info.acceptFormat)
2283     {
2284         case CA_FORMAT_APPLICATION_CBOR:
2285             serverRequest.acceptFormat = OC_FORMAT_CBOR;
2286             break;
2287         case CA_FORMAT_APPLICATION_VND_OCF_CBOR:
2288             serverRequest.acceptFormat = OC_FORMAT_VND_OCF_CBOR;
2289             break;
2290         case CA_FORMAT_UNDEFINED:
2291             serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
2292             break;
2293         default:
2294             serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
2295     }
2296
2297     if (requestInfo->info.type == CA_MSG_CONFIRM)
2298     {
2299         serverRequest.qos = OC_HIGH_QOS;
2300     }
2301     else
2302     {
2303         serverRequest.qos = OC_LOW_QOS;
2304     }
2305     // CA does not need the following field
2306     // Are we sure CA does not need them? how is it responding to multicast
2307     serverRequest.delayedResNeeded = 0;
2308
2309     serverRequest.coapID = requestInfo->info.messageId;
2310
2311     CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
2312
2313     // copy vendor specific header options
2314     uint8_t tempNum = (requestInfo->info.numOptions);
2315
2316     // Assume no observation requested and it is a pure GET.
2317     // If obs registration/de-registration requested it'll be fetched from the
2318     // options in GetObserveHeaderOption()
2319     serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
2320
2321     GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
2322     if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
2323     {
2324         OIC_LOG(ERROR, TAG,
2325                 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
2326         SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
2327                                 directResponseType, requestInfo->info.numOptions,
2328                                 requestInfo->info.options, requestInfo->info.token,
2329                                 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2330                                 CA_RESPONSE_DATA);
2331         OICFree(serverRequest.payload);
2332         OICFree(serverRequest.requestToken);
2333         return;
2334     }
2335     serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
2336     if (serverRequest.numRcvdVendorSpecificHeaderOptions && requestInfo->info.options)
2337     {
2338         memcpy(&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
2339                sizeof(CAHeaderOption_t) * tempNum);
2340     }
2341
2342     requestResult = HandleStackRequests (&serverRequest);
2343
2344     if (requestResult == OC_STACK_SLOW_RESOURCE)
2345     {
2346         // Send ACK to client as precursor to slow response
2347         if (requestInfo->info.type == CA_MSG_CONFIRM)
2348         {
2349             SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
2350                                     CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
2351                                     CA_RESPONSE_DATA);
2352         }
2353     }
2354     if (requestResult == OC_STACK_RESOURCE_ERROR
2355             && serverRequest.observationOption == OC_OBSERVE_REGISTER)
2356     {
2357         OIC_LOG(ERROR, TAG, "Observe Registration failed due to resource error");
2358     }
2359     else if (!OCResultToSuccess(requestResult))
2360     {
2361         OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
2362
2363         CAResponseResult_t stackResponse = OCToCAStackResult(requestResult, serverRequest.method);
2364
2365         SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
2366                                 directResponseType, requestInfo->info.numOptions,
2367                                 requestInfo->info.options, requestInfo->info.token,
2368                                 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2369                                 CA_RESPONSE_DATA);
2370     }
2371     // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
2372     // The token is copied in there, and is thus still owned by this function.
2373     OICFree(serverRequest.payload);
2374     OICFree(serverRequest.requestToken);
2375     OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
2376 }
2377
2378 //This function will be called back by CA layer when a request is received
2379 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2380 {
2381     OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2382     OIC_TRACE_BEGIN(%s:HandleCARequests, TAG);
2383     if (!endPoint)
2384     {
2385         OIC_LOG(ERROR, TAG, "endPoint is NULL");
2386         OIC_TRACE_END();
2387         return;
2388     }
2389
2390     if (!requestInfo)
2391     {
2392         OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2393         OIC_TRACE_END();
2394         return;
2395     }
2396
2397 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2398 #ifdef ROUTING_GATEWAY
2399     bool needRIHandling = false;
2400     bool isEmptyMsg = false;
2401     /*
2402      * Routing manager is going to update either of endpoint or request or both.
2403      * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2404      * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2405      * destination. It can also remove "RM" coap header option before passing request / response to
2406      * RI as this option will make no sense to either RI or application.
2407      */
2408     OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2409                                         &needRIHandling, &isEmptyMsg);
2410     if (OC_STACK_OK != ret || !needRIHandling)
2411     {
2412         OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2413         OIC_TRACE_END();
2414         return;
2415     }
2416 #endif
2417
2418     /*
2419      * Put source in sender endpoint so that the next packet from application can be routed to
2420      * proper destination and remove RM header option.
2421      */
2422     RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2423                  (uint8_t *) &(requestInfo->info.numOptions),
2424                  (CAEndpoint_t *) endPoint);
2425
2426 #ifdef ROUTING_GATEWAY
2427     if (isEmptyMsg)
2428     {
2429         /*
2430          * In Gateways, the MSGType in route option is used to check if the actual
2431          * response is EMPTY message(4 bytes CoAP Header).  In case of Client, the
2432          * EMPTY response is sent in the form of POST request which need to be changed
2433          * to a EMPTY response by RM.  This translation is done in this part of the code.
2434          */
2435         OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2436         CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2437                                      .info.messageId = requestInfo->info.messageId,
2438                                      .info.type = CA_MSG_ACKNOWLEDGE};
2439         OCHandleResponse(endPoint, &respInfo);
2440     }
2441     else
2442 #endif
2443 #endif
2444     {
2445         // Normal handling of the packet
2446         OCHandleRequests(endPoint, requestInfo);
2447     }
2448     OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2449     OIC_TRACE_END();
2450 }
2451
2452 //-----------------------------------------------------------------------------
2453 // Public APIs
2454 //-----------------------------------------------------------------------------
2455 #ifdef RA_ADAPTER
2456 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2457 {
2458     if (!raInfo           ||
2459         !raInfo->username ||
2460         !raInfo->hostname ||
2461         !raInfo->xmpp_domain)
2462     {
2463
2464         return OC_STACK_INVALID_PARAM;
2465     }
2466     OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2467     gRASetInfo = (result == OC_STACK_OK)? true : false;
2468
2469     return result;
2470 }
2471 #endif
2472
2473 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2474 {
2475     (void) ipAddr;
2476     (void) port;
2477     return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2478 }
2479
2480 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2481 {
2482     OIC_LOG(DEBUG, TAG, "call OCInit1");
2483     return OCInit2(mode, serverFlags, clientFlags, OC_DEFAULT_ADAPTER);
2484 }
2485
2486 OCStackResult OCInit2(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags,
2487                       OCTransportAdapter transportType)
2488 {
2489     OIC_LOG(INFO, TAG, "Entering OCInit2");
2490
2491     // Serialize calls to start and stop the stack.
2492     OCEnterInitializer();
2493
2494     OCStackResult result = OC_STACK_OK;
2495
2496     if (g_ocStackStartCount == 0)
2497     {
2498         // This is the first call to initialize the stack so it gets to do the real work.
2499         result = OCInitializeInternal(mode, serverFlags, clientFlags, transportType);
2500     }
2501
2502     if (result == OC_STACK_OK)
2503     {
2504         // Increment the start count since we're about to return success.
2505         assert(g_ocStackStartCount != UINT_MAX);
2506         assert(stackState == OC_STACK_INITIALIZED);
2507         g_ocStackStartCount++;
2508     }
2509
2510     OCLeaveInitializer();
2511     return result;
2512 }
2513
2514 OCStackResult OCInitializeInternal(OCMode mode, OCTransportFlags serverFlags,
2515                                    OCTransportFlags clientFlags, OCTransportAdapter transportType)
2516 {
2517     if (stackState == OC_STACK_INITIALIZED)
2518     {
2519         OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2520                 OCStop() between them are ignored.");
2521         return OC_STACK_OK;
2522     }
2523
2524 #ifndef ROUTING_GATEWAY
2525     if (OC_GATEWAY == mode)
2526     {
2527         OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2528         return OC_STACK_INVALID_PARAM;
2529     }
2530 #endif
2531
2532 #ifdef RA_ADAPTER
2533     if(!gRASetInfo)
2534     {
2535         OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2536         return OC_STACK_ERROR;
2537     }
2538 #endif
2539
2540     OIC_LOG_V(INFO, TAG, "IoTivity version is v%s", IOTIVITY_VERSION);
2541     OCStackResult result = OC_STACK_ERROR;
2542
2543     // Validate mode
2544     if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2545         || (mode == OC_GATEWAY)))
2546     {
2547         OIC_LOG(ERROR, TAG, "Invalid mode");
2548         return OC_STACK_ERROR;
2549     }
2550     myStackMode = mode;
2551
2552     if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2553     {
2554         caglobals.client = true;
2555     }
2556     if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2557     {
2558         caglobals.server = true;
2559     }
2560
2561     caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2562     if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2563     {
2564         caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2565     }
2566     caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2567     if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2568     {
2569         caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2570     }
2571
2572     defaultDeviceHandler = NULL;
2573     defaultDeviceHandlerCallbackParameter = NULL;
2574
2575     result = InitializeScheduleResourceList();
2576     VERIFY_SUCCESS(result, OC_STACK_OK);
2577
2578     result = CAResultToOCResult(CAInitialize((CATransportAdapter_t)transportType));
2579     VERIFY_SUCCESS(result, OC_STACK_OK);
2580
2581     result = CAResultToOCResult(OCSelectNetwork(transportType));
2582     VERIFY_SUCCESS(result, OC_STACK_OK);
2583
2584     result = CAResultToOCResult(CARegisterNetworkMonitorHandler(
2585       OCDefaultAdapterStateChangedHandler, OCDefaultConnectionStateChangedHandler));
2586     VERIFY_SUCCESS(result, OC_STACK_OK);
2587
2588     switch (myStackMode)
2589     {
2590         case OC_CLIENT:
2591             CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2592             result = CAResultToOCResult(CAStartDiscoveryServer());
2593             OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2594             break;
2595         case OC_SERVER:
2596             SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2597             result = CAResultToOCResult(CAStartListeningServer());
2598             OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2599             break;
2600         case OC_CLIENT_SERVER:
2601         case OC_GATEWAY:
2602             SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2603             result = CAResultToOCResult(CAStartListeningServer());
2604             if(result == OC_STACK_OK)
2605             {
2606                 result = CAResultToOCResult(CAStartDiscoveryServer());
2607             }
2608             break;
2609     }
2610     VERIFY_SUCCESS(result, OC_STACK_OK);
2611
2612 #ifdef TCP_ADAPTER
2613     CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2614 #endif
2615
2616 #ifdef WITH_PRESENCE
2617     PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2618 #endif // WITH_PRESENCE
2619
2620     //Update Stack state to initialized
2621     stackState = OC_STACK_INITIALIZED;
2622
2623     // Initialize resource
2624     if(myStackMode != OC_CLIENT)
2625     {
2626         result = initResources();
2627     }
2628
2629 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2630     RMSetStackMode(mode);
2631 #ifdef ROUTING_GATEWAY
2632     if (OC_GATEWAY == myStackMode)
2633     {
2634         result = RMInitialize();
2635     }
2636 #endif
2637 #endif
2638
2639 #ifdef TCP_ADAPTER
2640     if (result == OC_STACK_OK)
2641     {
2642         result = InitializeKeepAlive(myStackMode);
2643     }
2644 #endif
2645
2646 #if defined(TCP_ADAPTER) && defined(WITH_CLOUD)
2647     // Initialize the Connection Manager
2648     if (result == OC_STACK_OK)
2649     {
2650         result = OCCMInitialize();
2651     }
2652 #endif
2653
2654 exit:
2655     if(result != OC_STACK_OK)
2656     {
2657         OIC_LOG(ERROR, TAG, "Stack initialization error");
2658         TerminateScheduleResourceList();
2659         deleteAllResources();
2660         CATerminate();
2661         stackState = OC_STACK_UNINITIALIZED;
2662     }
2663     return result;
2664 }
2665
2666 OCStackResult OCStop()
2667 {
2668     OIC_LOG(INFO, TAG, "Entering OCStop");
2669
2670     // Serialize calls to start and stop the stack.
2671     OCEnterInitializer();
2672
2673     OCStackResult result = OC_STACK_OK;
2674
2675     if (g_ocStackStartCount == 1)
2676     {
2677         // This is the last call to stop the stack, do the real work.
2678         result = OCDeInitializeInternal();
2679     }
2680     else if (g_ocStackStartCount == 0)
2681     {
2682         OIC_LOG(ERROR, TAG, "Too many calls to OCStop");
2683         assert(!"Too many calls to OCStop");
2684         result = OC_STACK_ERROR;
2685     }
2686
2687     if (result == OC_STACK_OK)
2688     {
2689         g_ocStackStartCount--;
2690     }
2691
2692     OCLeaveInitializer();
2693     return result;
2694 }
2695
2696 OCStackResult OCDeInitializeInternal()
2697 {
2698     assert(stackState == OC_STACK_INITIALIZED);
2699
2700 #ifdef WITH_PRESENCE
2701     // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2702     // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2703     presenceResource.presenceTTL = 0;
2704 #endif // WITH_PRESENCE
2705
2706 #ifdef ROUTING_GATEWAY
2707     if (OC_GATEWAY == myStackMode)
2708     {
2709         RMTerminate();
2710     }
2711 #endif
2712
2713 #ifdef TCP_ADAPTER
2714     TerminateKeepAlive(myStackMode);
2715 #endif
2716
2717     OCStackResult result = CAResultToOCResult(
2718             CAUnregisterNetworkMonitorHandler(OCDefaultAdapterStateChangedHandler,
2719                                               OCDefaultConnectionStateChangedHandler));
2720     if (OC_STACK_OK != result)
2721     {
2722         OIC_LOG(ERROR, TAG, "CAUnregisterNetworkMonitorHandler has failed");
2723     }
2724
2725     TerminateScheduleResourceList();
2726     // Remove all observers
2727     DeleteObserverList();
2728     // Free memory dynamically allocated for resources
2729     deleteAllResources();
2730     // Remove all the client callbacks
2731     DeleteClientCBList();
2732     // Terminate connectivity-abstraction layer.
2733     CATerminate();
2734
2735 #if defined(TCP_ADAPTER) && defined(WITH_CLOUD)
2736     // Terminate the Connection Manager
2737     OCCMTerminate();
2738 #endif
2739
2740     // Unset cautil config
2741     CAUtilConfig_t configs = {(CATransportBTFlags_t)CA_DEFAULT_BT_FLAGS};
2742     CAUtilSetBTConfigure(configs);
2743
2744     stackState = OC_STACK_UNINITIALIZED;
2745     return OC_STACK_OK;
2746 }
2747
2748 OCStackResult OCStartMulticastServer()
2749 {
2750     if(stackState != OC_STACK_INITIALIZED)
2751     {
2752         OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2753         return OC_STACK_ERROR;
2754     }
2755     CAResult_t ret = CAStartListeningServer();
2756     if (CA_STATUS_OK != ret)
2757     {
2758         OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2759         return OC_STACK_ERROR;
2760     }
2761     return OC_STACK_OK;
2762 }
2763
2764 OCStackResult OCStopMulticastServer()
2765 {
2766     CAResult_t ret = CAStopListeningServer();
2767     if (CA_STATUS_OK != ret)
2768     {
2769         OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2770         return OC_STACK_ERROR;
2771     }
2772     return OC_STACK_OK;
2773 }
2774
2775 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2776 {
2777     switch (qos)
2778     {
2779         case OC_HIGH_QOS:
2780             return CA_MSG_CONFIRM;
2781         case OC_LOW_QOS:
2782         case OC_MEDIUM_QOS:
2783         case OC_NA_QOS:
2784         default:
2785             return CA_MSG_NONCONFIRM;
2786     }
2787 }
2788
2789 /**
2790  *  A request uri consists of the following components in order:
2791  *                              example
2792  *  optionally one of
2793  *      CoAP over UDP prefix    "coap://"
2794  *      CoAP over TCP prefix    "coap+tcp://"
2795  *      CoAP over DTLS prefix   "coaps://"
2796  *      CoAP over TLS prefix    "coaps+tcp://"
2797  *  optionally one of
2798  *      IPv6 address            "[1234::5678]"
2799  *      IPv4 address            "192.168.1.1"
2800  *  optional port               ":5683"
2801  *  resource uri                "/oc/core..."
2802  *
2803  *  for PRESENCE requests, extract resource type.
2804  */
2805 static OCStackResult ParseRequestUri(const char *fullUri,
2806                                         OCTransportAdapter adapter,
2807                                         OCTransportFlags flags,
2808                                         OCDevAddr **devAddr,
2809                                         char **resourceUri,
2810                                         char **resourceType)
2811 {
2812     VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2813
2814     OCStackResult result = OC_STACK_OK;
2815     OCDevAddr *da = NULL;
2816     char *colon = NULL;
2817     char *end;
2818
2819     // provide defaults for all returned values
2820     if (devAddr)
2821     {
2822         *devAddr = NULL;
2823     }
2824     if (resourceUri)
2825     {
2826         *resourceUri = NULL;
2827     }
2828     if (resourceType)
2829     {
2830         *resourceType = NULL;
2831     }
2832
2833     // delimit url prefix, if any
2834     const char *start = fullUri;
2835     char *slash2 = strstr(start, "//");
2836     if (slash2)
2837     {
2838         start = slash2 + 2;
2839     }
2840     char *slash = strchr(start, '/');
2841     if (!slash)
2842     {
2843         return OC_STACK_INVALID_URI;
2844     }
2845
2846     // process url scheme
2847     size_t prefixLen = slash2 - fullUri;
2848     bool istcp = false;
2849     if (prefixLen)
2850     {
2851         if (((prefixLen == sizeof(COAP_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAP_TCP_SCHEME, prefixLen)))
2852         || ((prefixLen == sizeof(COAPS_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAPS_TCP_SCHEME, prefixLen))))
2853         {
2854             istcp = true;
2855         }
2856     }
2857
2858     // TODO: this logic should come in with unit tests exercising the various strings
2859     // processs url prefix, if any
2860     size_t urlLen = slash - start;
2861     // port
2862     uint16_t port = 0;
2863     size_t len = 0;
2864     if (urlLen && devAddr)
2865     {   // construct OCDevAddr
2866         if (start[0] == '[')
2867         {   // ipv6 address
2868             char *close = strchr(++start, ']');
2869             if (!close || close > slash)
2870             {
2871                 return OC_STACK_INVALID_URI;
2872             }
2873             end = close;
2874             if (close[1] == ':')
2875             {
2876                 colon = close + 1;
2877             }
2878
2879             if (istcp)
2880             {
2881                 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2882             }
2883             else
2884             {
2885                 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2886             }
2887             flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2888         }
2889         else
2890         {
2891             char *dot = strchr(start, '.');
2892             if (dot && dot < slash)
2893             {   // ipv4 address
2894                 colon = strchr(start, ':');
2895                 end = (colon && colon < slash) ? colon : slash;
2896
2897                 if (istcp)
2898                 {
2899                     // coap over tcp
2900                     adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2901                 }
2902                 else
2903                 {
2904                     adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2905                 }
2906                 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2907             }
2908             else
2909             {   // MAC address
2910                 end = slash;
2911             }
2912         }
2913         len = end - start;
2914         if (len >= sizeof(da->addr))
2915         {
2916             return OC_STACK_INVALID_URI;
2917         }
2918         // collect port, if any
2919         if (colon && colon < slash)
2920         {
2921             for (colon++; colon < slash; colon++)
2922             {
2923                 char c = colon[0];
2924                 if (c < '0' || c > '9')
2925                 {
2926                     return OC_STACK_INVALID_URI;
2927                 }
2928                 port = 10 * port + c - '0';
2929             }
2930         }
2931
2932         len = end - start;
2933         if (len >= sizeof(da->addr))
2934         {
2935             return OC_STACK_INVALID_URI;
2936         }
2937
2938         da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2939         if (!da)
2940         {
2941             return OC_STACK_NO_MEMORY;
2942         }
2943
2944         // Decode address per RFC 6874.
2945         result = OCDecodeAddressForRFC6874(da->addr, sizeof(da->addr), start, end);
2946         if (result != OC_STACK_OK)
2947         {
2948              OICFree(*devAddr);
2949              return result;
2950         }
2951
2952         da->port = port;
2953         da->adapter = adapter;
2954         da->flags = flags;
2955         if (!strncmp(fullUri, "coaps", 5))
2956         {
2957             da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2958         }
2959         *devAddr = da;
2960     }
2961
2962     // process resource uri, if any
2963     if (slash)
2964     {   // request uri and query
2965         size_t ulen = strlen(slash); // resource uri length
2966         size_t tlen = 0;      // resource type length
2967         char *type = NULL;
2968
2969         static const char strPresence[] = "/oic/ad?rt=";
2970         static const size_t lenPresence = sizeof(strPresence) - 1;
2971         if (!strncmp(slash, strPresence, lenPresence))
2972         {
2973             type = slash + lenPresence;
2974             tlen = ulen - lenPresence;
2975         }
2976         // resource uri
2977         if (resourceUri)
2978         {
2979             *resourceUri = (char *)OICMalloc(ulen + 1);
2980             if (!*resourceUri)
2981             {
2982                 result = OC_STACK_NO_MEMORY;
2983                 goto error;
2984             }
2985             strcpy(*resourceUri, slash);
2986         }
2987         // resource type
2988         if (type && resourceType)
2989         {
2990             *resourceType = (char *)OICMalloc(tlen + 1);
2991             if (!*resourceType)
2992             {
2993                 result = OC_STACK_NO_MEMORY;
2994                 goto error;
2995             }
2996
2997             OICStrcpy(*resourceType, (tlen+1), type);
2998         }
2999     }
3000
3001     return OC_STACK_OK;
3002
3003 error:
3004     // free all returned values
3005     if (devAddr)
3006     {
3007         OICFree(*devAddr);
3008     }
3009     if (resourceUri)
3010     {
3011         OICFree(*resourceUri);
3012     }
3013     if (resourceType)
3014     {
3015         OICFree(*resourceType);
3016     }
3017     return result;
3018 }
3019
3020 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
3021                                        char **requestUri,
3022                                        bool isMulticast)
3023 {
3024     char uri[CA_MAX_URI_LENGTH];
3025
3026     FormCanonicalPresenceUri(endpoint, uri, isMulticast);
3027
3028     *requestUri = OICStrdup(uri);
3029     if (!*requestUri)
3030     {
3031         return OC_STACK_NO_MEMORY;
3032     }
3033
3034     return OC_STACK_OK;
3035 }
3036
3037 /**
3038  * Discover or Perform requests on a specified resource
3039  */
3040 OCStackResult OCDoResource(OCDoHandle *handle,
3041                             OCMethod method,
3042                             const char *requestUri,
3043                             const OCDevAddr *destination,
3044                             OCPayload* payload,
3045                             OCConnectivityType connectivityType,
3046                             OCQualityOfService qos,
3047                             OCCallbackData *cbData,
3048                             OCHeaderOption *options,
3049                             uint8_t numOptions)
3050 {
3051     OCStackResult ret = OCDoRequest(handle, method, requestUri,destination, payload,
3052                 connectivityType, qos, cbData, options, numOptions);
3053
3054     // This is the owner of the payload object, so we free it
3055     OCPayloadDestroy(payload);
3056     return ret;
3057 }
3058
3059 /**
3060  * Discover or Perform requests on a specified resource
3061  */
3062 OCStackResult OCDoRequest(OCDoHandle *handle,
3063                             OCMethod method,
3064                             const char *requestUri,
3065                             const OCDevAddr *destination,
3066                             OCPayload* payload,
3067                             OCConnectivityType connectivityType,
3068                             OCQualityOfService qos,
3069                             OCCallbackData *cbData,
3070                             OCHeaderOption *options,
3071                             uint8_t numOptions)
3072 {
3073     OIC_LOG(INFO, TAG, "Entering OCDoResource");
3074
3075     // Validate input parameters
3076     VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
3077     VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
3078
3079     OCStackResult result = OC_STACK_ERROR;
3080     CAResult_t caResult;
3081     CAToken_t token = NULL;
3082     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3083     ClientCB *clientCB = NULL;
3084     OCDoHandle resHandle = NULL;
3085     CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3086     OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
3087     uint32_t ttl = 0;
3088     OCTransportAdapter adapter;
3089     OCTransportFlags flags;
3090     // the request contents are put here
3091     CARequestInfo_t requestInfo = {.method = CA_GET};
3092     // requestUri  will be parsed into the following three variables
3093     OCDevAddr *devAddr = NULL;
3094     char *resourceUri = NULL;
3095     char *resourceType = NULL;
3096
3097     /*
3098      * Support original behavior with address on resourceUri argument.
3099      */
3100     adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
3101     flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
3102
3103     if (requestUri)
3104     {
3105         result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
3106         if (result != OC_STACK_OK)
3107         {
3108             OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
3109             goto exit;
3110         }
3111     }
3112     else if (!checkProxyUri(options, numOptions))
3113     {
3114         OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
3115         goto exit;
3116     }
3117
3118     switch (method)
3119     {
3120     case OC_REST_GET:
3121     case OC_REST_OBSERVE:
3122     case OC_REST_OBSERVE_ALL:
3123         requestInfo.method = CA_GET;
3124         break;
3125     case OC_REST_PUT:
3126         requestInfo.method = CA_PUT;
3127         break;
3128     case OC_REST_POST:
3129         requestInfo.method = CA_POST;
3130         break;
3131     case OC_REST_DELETE:
3132         requestInfo.method = CA_DELETE;
3133         break;
3134     case OC_REST_DISCOVER:
3135         // intentional fall through don't add break
3136 #ifdef WITH_PRESENCE
3137     case OC_REST_PRESENCE:
3138 #endif
3139         if (destination || devAddr)
3140         {
3141             requestInfo.isMulticast = false;
3142         }
3143         else
3144         {
3145             tmpDevAddr.adapter = adapter;
3146             tmpDevAddr.flags = flags;
3147             destination = &tmpDevAddr;
3148             requestInfo.isMulticast = true;
3149             qos = OC_LOW_QOS;
3150         }
3151         // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
3152         // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
3153         //                   replacing method type with GET.
3154         requestInfo.method = CA_GET;
3155         break;
3156     default:
3157         result = OC_STACK_INVALID_METHOD;
3158         goto exit;
3159     }
3160
3161     if (!devAddr && !destination)
3162     {
3163         OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
3164         result = OC_STACK_INVALID_PARAM;
3165         goto exit;
3166     }
3167
3168     /* If not original behavior, use destination argument */
3169     if (destination && !devAddr)
3170     {
3171         devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
3172         if (!devAddr)
3173         {
3174             result = OC_STACK_NO_MEMORY;
3175             goto exit;
3176         }
3177         OIC_LOG(DEBUG, TAG, "devAddr is set as destination");
3178         *devAddr = *destination;
3179     }
3180
3181     if (devAddr)
3182     {
3183         OIC_LOG_V(DEBUG, TAG, "remoteId of devAddr : %s", devAddr->remoteId);
3184     }
3185
3186     resHandle = GenerateInvocationHandle();
3187     if (!resHandle)
3188     {
3189         result = OC_STACK_NO_MEMORY;
3190         goto exit;
3191     }
3192
3193     caResult = CAGenerateToken(&token, tokenLength);
3194     if (caResult != CA_STATUS_OK)
3195     {
3196         OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3197         result= OC_STACK_ERROR;
3198         goto exit;
3199     }
3200
3201     // fill in request data
3202     requestInfo.info.type = qualityOfServiceToMessageType(qos);
3203     requestInfo.info.token = token;
3204     requestInfo.info.tokenLength = tokenLength;
3205
3206     if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
3207     {
3208         result = CreateObserveHeaderOption (&(requestInfo.info.options),
3209                                     options, numOptions, OC_OBSERVE_REGISTER);
3210         if (result != OC_STACK_OK)
3211         {
3212             goto exit;
3213         }
3214         requestInfo.info.numOptions = numOptions + 1;
3215     }
3216     else
3217     {
3218         requestInfo.info.numOptions = numOptions;
3219         requestInfo.info.options =
3220             (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
3221         memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
3222                numOptions * sizeof(CAHeaderOption_t));
3223     }
3224
3225     CopyDevAddrToEndpoint(devAddr, &endpoint);
3226
3227     if (payload)
3228     {
3229         if((result =
3230             OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
3231                 != OC_STACK_OK)
3232         {
3233             OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
3234             goto exit;
3235         }
3236
3237         uint16_t payloadVersion = OC_SPEC_VERSION_VALUE;
3238         // From OCF onwards, check version option settings
3239         if (DEFAULT_CONTENT_VERSION_VALUE <= payloadVersion)
3240         {
3241             if (numOptions > 0 && options)
3242             {
3243                 for (uint8_t i = 0; i < numOptions; i++)
3244                 {
3245                     if (COAP_OPTION_CONTENT_VERSION == options[i].optionID)
3246                     {
3247                         payloadVersion = options[i].optionData[0];
3248                         break;
3249                     }
3250                     else if (COAP_OPTION_ACCEPT_VERSION == options[i].optionID)
3251                     {
3252                         payloadVersion = options[i].optionData[0];
3253                         break;
3254                     }
3255                 }
3256             }
3257         }
3258
3259         if (DEFAULT_CONTENT_VERSION_VALUE <= payloadVersion)
3260         {
3261             requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_VND_OCF_CBOR;
3262             requestInfo.info.payloadVersion = payloadVersion;
3263         }
3264         else
3265         {
3266             requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
3267         }
3268     }
3269     else
3270     {
3271         requestInfo.info.payload = NULL;
3272         requestInfo.info.payloadSize = 0;
3273         requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
3274     }
3275
3276     // prepare for response
3277 #ifdef WITH_PRESENCE
3278     if (method == OC_REST_PRESENCE)
3279     {
3280         char *presenceUri = NULL;
3281         result = OCPreparePresence(&endpoint, &presenceUri,
3282                                    requestInfo.isMulticast);
3283         if (OC_STACK_OK != result)
3284         {
3285             goto exit;
3286         }
3287
3288         // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
3289         // Presence notification will form a canonical uri to
3290         // look for callbacks into the application.
3291         if (resourceUri)
3292         {
3293             OICFree(resourceUri);
3294         }
3295         resourceUri = presenceUri;
3296     }
3297 #endif
3298
3299     // update resourceUri onto requestInfo after check presence uri
3300     requestInfo.info.resourceUri = resourceUri;
3301
3302     ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
3303     result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
3304                             method, devAddr, resourceUri, resourceType, ttl);
3305     if (OC_STACK_OK != result)
3306     {
3307         goto exit;
3308     }
3309
3310     devAddr = NULL;       // Client CB list entry now owns it
3311     resourceUri = NULL;   // Client CB list entry now owns it
3312     resourceType = NULL;  // Client CB list entry now owns it
3313
3314 #ifdef WITH_PRESENCE
3315     if (method == OC_REST_PRESENCE)
3316     {
3317         OIC_LOG(ERROR, TAG, "AddClientCB for presence done.");
3318
3319         if (handle)
3320         {
3321             *handle = resHandle;
3322         }
3323
3324         goto exit;
3325     }
3326 #endif
3327
3328     // send request
3329     result = OCSendRequest(&endpoint, &requestInfo);
3330     if (OC_STACK_OK != result)
3331     {
3332         goto exit;
3333     }
3334
3335     if (handle)
3336     {
3337         *handle = resHandle;
3338     }
3339
3340 exit:
3341     if (result != OC_STACK_OK)
3342     {
3343         OIC_LOG(ERROR, TAG, "OCDoResource error");
3344         FindAndDeleteClientCB(clientCB);
3345         CADestroyToken(token);
3346         if (handle)
3347         {
3348             *handle = NULL;
3349         }
3350         OICFree(resHandle);
3351     }
3352
3353     OICFree(requestInfo.info.payload);
3354     OICFree(devAddr);
3355     OICFree(resourceUri);
3356     OICFree(resourceType);
3357     OICFree(requestInfo.info.options);
3358     return result;
3359 }
3360
3361 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
3362         uint8_t numOptions)
3363 {
3364     /*
3365      * This ftn is implemented one of two ways in the case of observation:
3366      *
3367      * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
3368      *      Remove the callback associated on client side.
3369      *      When the next notification comes in from server,
3370      *      reply with RESET message to server.
3371      *      Keep in mind that the server will react to RESET only
3372      *      if the last notification was sent as CON
3373      *
3374      * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
3375      *      and it is associated with an observe request
3376      *      (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
3377      *      Send CON Observe request to server with
3378      *      observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
3379      *      Remove the callback associated on client side.
3380      */
3381     OCStackResult ret = OC_STACK_OK;
3382     CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3383     CARequestInfo_t requestInfo = {.method = CA_GET};
3384
3385     if(!handle)
3386     {
3387         return OC_STACK_INVALID_PARAM;
3388     }
3389
3390     ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
3391     if (!clientCB)
3392     {
3393         OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
3394         return OC_STACK_ERROR;
3395     }
3396
3397     switch (clientCB->method)
3398     {
3399         case OC_REST_OBSERVE:
3400         case OC_REST_OBSERVE_ALL:
3401
3402             OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
3403
3404             CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
3405
3406             if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
3407             {
3408                 FindAndDeleteClientCB(clientCB);
3409                 break;
3410             }
3411
3412             OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
3413
3414             requestInfo.info.type = qualityOfServiceToMessageType(qos);
3415             requestInfo.info.token = clientCB->token;
3416             requestInfo.info.tokenLength = clientCB->tokenLength;
3417
3418             if (CreateObserveHeaderOption (&(requestInfo.info.options),
3419                     options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
3420             {
3421                 return OC_STACK_ERROR;
3422             }
3423             requestInfo.info.numOptions = numOptions + 1;
3424             requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
3425
3426
3427             ret = OCSendRequest(&endpoint, &requestInfo);
3428
3429             if (requestInfo.info.options)
3430             {
3431                 OICFree (requestInfo.info.options);
3432             }
3433             if (requestInfo.info.resourceUri)
3434             {
3435                 OICFree (requestInfo.info.resourceUri);
3436             }
3437
3438             break;
3439
3440         case OC_REST_DISCOVER:
3441             OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
3442                                            clientCB->requestUri);
3443             FindAndDeleteClientCB(clientCB);
3444             break;
3445
3446 #ifdef WITH_PRESENCE
3447         case OC_REST_PRESENCE:
3448             FindAndDeleteClientCB(clientCB);
3449             break;
3450 #endif
3451
3452         default:
3453             ret = OC_STACK_INVALID_METHOD;
3454             break;
3455     }
3456
3457     return ret;
3458 }
3459
3460 /**
3461  * @brief   Register Persistent storage callback.
3462  * @param   persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
3463  * @return
3464  *     OC_STACK_OK    - No errors; Success
3465  *     OC_STACK_INVALID_PARAM - Invalid parameter
3466  */
3467 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
3468 {
3469     OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
3470     if(!persistentStorageHandler)
3471     {
3472         OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3473         return OC_STACK_INVALID_PARAM;
3474     }
3475     else
3476     {
3477         if( !persistentStorageHandler->open ||
3478                 !persistentStorageHandler->close ||
3479                 !persistentStorageHandler->read ||
3480                 !persistentStorageHandler->unlink ||
3481                 !persistentStorageHandler->write)
3482         {
3483             OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3484             return OC_STACK_INVALID_PARAM;
3485         }
3486     }
3487     g_PersistentStorageHandler = persistentStorageHandler;
3488     return OC_STACK_OK;
3489 }
3490
3491 OCPersistentStorage *OCGetPersistentStorageHandler()
3492 {
3493     return g_PersistentStorageHandler;
3494 }
3495
3496 #ifdef WITH_PRESENCE
3497
3498 OCStackResult OCProcessPresence()
3499 {
3500     OCStackResult result = OC_STACK_OK;
3501
3502     // the following line floods the log with messages that are irrelevant
3503     // to most purposes.  Uncomment as needed.
3504     //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3505     ClientCB* cbNode = NULL;
3506     ClientCB* cbTemp = NULL;
3507     OCClientResponse clientResponse;
3508     OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3509
3510     LL_FOREACH_SAFE(cbList, cbNode, cbTemp)
3511     {
3512         if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3513         {
3514             continue;
3515         }
3516
3517         uint32_t now = GetTicks(0);
3518         OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3519                                                 cbNode->presence->TTLlevel);
3520         OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3521
3522         if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3523         {
3524             goto exit;
3525         }
3526
3527         if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3528         {
3529             OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3530                     cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3531         }
3532         if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3533         {
3534             OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3535
3536             clientResponse.sequenceNumber = 0;
3537             clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3538             clientResponse.devAddr = *cbNode->devAddr;
3539             FixUpClientResponse(&clientResponse);
3540             clientResponse.payload = NULL;
3541
3542             // Increment the TTLLevel (going to a next state), so we don't keep
3543             // sending presence notification to client.
3544             cbNode->presence->TTLlevel++;
3545             OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3546                                         cbNode->presence->TTLlevel);
3547
3548             cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3549             if (cbResult == OC_STACK_DELETE_TRANSACTION)
3550             {
3551                 FindAndDeleteClientCB(cbNode);
3552             }
3553         }
3554
3555         if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3556         {
3557             continue;
3558         }
3559
3560         CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3561         CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3562         CARequestInfo_t requestInfo = {.method = CA_GET};
3563
3564         OIC_LOG(DEBUG, TAG, "time to test server presence");
3565
3566         CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3567
3568         requestData.type = CA_MSG_NONCONFIRM;
3569         requestData.token = cbNode->token;
3570         requestData.tokenLength = cbNode->tokenLength;
3571         requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3572         requestInfo.method = CA_GET;
3573         requestInfo.info = requestData;
3574
3575         result = OCSendRequest(&endpoint, &requestInfo);
3576         if (OC_STACK_OK != result)
3577         {
3578             goto exit;
3579         }
3580
3581         cbNode->presence->TTLlevel++;
3582         OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3583     }
3584 exit:
3585     if (result != OC_STACK_OK)
3586     {
3587         OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3588     }
3589
3590     return result;
3591 }
3592 #endif // WITH_PRESENCE
3593
3594 OCStackResult OCProcess()
3595 {
3596     if (stackState == OC_STACK_UNINITIALIZED)
3597     {
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     return result;
4879 }
4880
4881 void insertResource(OCResource *resource)
4882 {
4883     if (!headResource)
4884     {
4885         headResource = resource;
4886         tailResource = resource;
4887     }
4888     else
4889     {
4890         tailResource->next = resource;
4891         tailResource = resource;
4892     }
4893     resource->next = NULL;
4894 }
4895
4896 OCResource *findResource(OCResource *resource)
4897 {
4898     OCResource *pointer = headResource;
4899
4900     while (pointer)
4901     {
4902         if (pointer == resource)
4903         {
4904             return resource;
4905         }
4906         pointer = pointer->next;
4907     }
4908     return NULL;
4909 }
4910
4911 void deleteAllResources()
4912 {
4913     OCResource *pointer = headResource;
4914     OCResource *temp = NULL;
4915
4916     while (pointer)
4917     {
4918         temp = pointer->next;
4919 #ifdef WITH_PRESENCE
4920         if (pointer != (OCResource *) presenceResource.handle)
4921         {
4922 #endif // WITH_PRESENCE
4923             deleteResource(pointer);
4924 #ifdef WITH_PRESENCE
4925         }
4926 #endif // WITH_PRESENCE
4927         pointer = temp;
4928     }
4929     memset(&platformResource, 0, sizeof(platformResource));
4930     memset(&deviceResource, 0, sizeof(deviceResource));
4931     memset(&wellKnownResource, 0, sizeof(wellKnownResource));
4932 #ifdef MQ_BROKER
4933     memset(&brokerResource, 0, sizeof(brokerResource));
4934 #endif
4935
4936     SRMDeInitSecureResources();
4937
4938 #ifdef WITH_PRESENCE
4939     // Ensure that the last resource to be deleted is the presence resource. This allows for all
4940     // presence notification attributed to their deletion to be processed.
4941     deleteResource((OCResource *) presenceResource.handle);
4942     memset(&presenceResource, 0, sizeof(presenceResource));
4943 #endif // WITH_PRESENCE
4944 }
4945
4946 OCStackResult deleteResource(OCResource *resource)
4947 {
4948     OCResource *prev = NULL;
4949     OCResource *temp = NULL;
4950     if(!resource)
4951     {
4952         OIC_LOG(DEBUG,TAG,"resource is NULL");
4953         return OC_STACK_INVALID_PARAM;
4954     }
4955
4956     OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4957
4958     temp = headResource;
4959     while (temp)
4960     {
4961         if (temp == resource)
4962         {
4963             // Invalidate all Resource Properties.
4964             resource->resourceProperties = (OCResourceProperty) 0;
4965 #ifdef WITH_PRESENCE
4966             if(resource != (OCResource *) presenceResource.handle)
4967             {
4968 #endif // WITH_PRESENCE
4969                 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4970 #ifdef WITH_PRESENCE
4971             }
4972
4973             if(presenceResource.handle)
4974             {
4975                 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4976                 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4977             }
4978 #endif
4979             // Only resource in list.
4980             if (temp == headResource && temp == tailResource)
4981             {
4982                 headResource = NULL;
4983                 tailResource = NULL;
4984             }
4985             // Deleting head.
4986             else if (temp == headResource)
4987             {
4988                 headResource = temp->next;
4989             }
4990             // Deleting tail.
4991             else if (temp == tailResource && prev)
4992             {
4993                 tailResource = prev;
4994                 tailResource->next = NULL;
4995             }
4996             else if (prev)
4997             {
4998                 prev->next = temp->next;
4999             }
5000
5001             deleteResourceElements(temp);
5002             OICFree(temp);
5003             temp = NULL;
5004             return OC_STACK_OK;
5005         }
5006         else
5007         {
5008             prev = temp;
5009             temp = temp->next;
5010         }
5011     }
5012
5013     return OC_STACK_ERROR;
5014 }
5015
5016 void deleteResourceElements(OCResource *resource)
5017 {
5018     if (!resource)
5019     {
5020         return;
5021     }
5022
5023     if (resource->uri)
5024     {
5025         OICFree(resource->uri);
5026     }
5027     if (resource->rsrcType)
5028     {
5029         deleteResourceType(resource->rsrcType);
5030     }
5031     if (resource->rsrcInterface)
5032     {
5033         deleteResourceInterface(resource->rsrcInterface);
5034     }
5035     if (resource->rsrcChildResourcesHead)
5036     {
5037         OICFree(resource->rsrcChildResourcesHead);
5038     }
5039     if (resource->rsrcAttributes)
5040     {
5041         OCDeleteResourceAttributes(resource->rsrcAttributes);
5042     }
5043 }
5044
5045 void deleteResourceType(OCResourceType *resourceType)
5046 {
5047     OCResourceType *next = NULL;
5048
5049     for (OCResourceType *pointer = resourceType; pointer; pointer = next)
5050     {
5051         next = pointer->next;
5052         if (pointer->resourcetypename)
5053         {
5054             OICFree(pointer->resourcetypename);
5055         }
5056         OICFree(pointer);
5057     }
5058 }
5059
5060 void deleteResourceInterface(OCResourceInterface *resourceInterface)
5061 {
5062     OCResourceInterface *next = NULL;
5063     for (OCResourceInterface *pointer = resourceInterface; pointer; pointer = next)
5064     {
5065         next = pointer->next;
5066         if (pointer->name)
5067         {
5068             OICFree(pointer->name);
5069         }
5070         OICFree(pointer);
5071     }
5072 }
5073
5074 void OCDeleteResourceAttributes(OCAttribute *rsrcAttributes)
5075 {
5076     OCAttribute *next = NULL;
5077     for (OCAttribute *pointer = rsrcAttributes; pointer; pointer = next)
5078     {
5079         next = pointer->next;
5080         if (pointer->attrName && 0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, pointer->attrName))
5081         {
5082             OCFreeOCStringLL((OCStringLL *)pointer->attrValue);
5083         }
5084         else if (pointer->attrValue)
5085         {
5086             OICFree(pointer->attrValue);
5087         }
5088         if (pointer->attrName)
5089         {
5090             OICFree(pointer->attrName);
5091         }
5092         OICFree(pointer);
5093     }
5094 }
5095
5096 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
5097 {
5098     OCResourceType *pointer = NULL;
5099     OCResourceType *previous = NULL;
5100     if (!resource || !resourceType)
5101     {
5102         return;
5103     }
5104     // resource type list is empty.
5105     else if (!resource->rsrcType)
5106     {
5107         resource->rsrcType = resourceType;
5108     }
5109     else
5110     {
5111         pointer = resource->rsrcType;
5112
5113         while (pointer)
5114         {
5115             if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
5116             {
5117                 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
5118                 OICFree(resourceType->resourcetypename);
5119                 OICFree(resourceType);
5120                 return;
5121             }
5122             previous = pointer;
5123             pointer = pointer->next;
5124         }
5125
5126         if (previous)
5127         {
5128             previous->next = resourceType;
5129         }
5130     }
5131     resourceType->next = NULL;
5132
5133     OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
5134 }
5135
5136 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
5137 {
5138     OCResource *resource = NULL;
5139     OCResourceType *pointer = NULL;
5140
5141     // Find the specified resource
5142     resource = findResource((OCResource *) handle);
5143     if (!resource)
5144     {
5145         return NULL;
5146     }
5147
5148     // Make sure a resource has a resourcetype
5149     if (!resource->rsrcType)
5150     {
5151         return NULL;
5152     }
5153
5154     // Iterate through the list
5155     pointer = resource->rsrcType;
5156     for(uint8_t i = 0; i< index && pointer; ++i)
5157     {
5158         pointer = pointer->next;
5159     }
5160     return pointer;
5161 }
5162
5163 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
5164 {
5165     if(resourceTypeList && resourceTypeName)
5166     {
5167         OCResourceType * rtPointer = resourceTypeList;
5168         while(resourceTypeName && rtPointer)
5169         {
5170             OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
5171             if(rtPointer->resourcetypename &&
5172                     strcmp(resourceTypeName, (const char *)
5173                     (rtPointer->resourcetypename)) == 0)
5174             {
5175                 break;
5176             }
5177             rtPointer = rtPointer->next;
5178         }
5179         return rtPointer;
5180     }
5181     return NULL;
5182 }
5183
5184 /*
5185  * Insert a new interface into interface linked list only if not already present.
5186  * If alredy present, 2nd arg is free'd.
5187  * Default interface will always be first if present.
5188  */
5189 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
5190 {
5191     OCResourceInterface *pointer = NULL;
5192     OCResourceInterface *previous = NULL;
5193
5194     newInterface->next = NULL;
5195
5196     OCResourceInterface **firstInterface = &(resource->rsrcInterface);
5197
5198     if (!*firstInterface)
5199     {
5200         // If first interface is not oic.if.baseline, by default add it as first interface type.
5201         if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
5202         {
5203             *firstInterface = newInterface;
5204         }
5205         else
5206         {
5207             OCStackResult result = BindResourceInterfaceToResource(resource,
5208                                                                     OC_RSRVD_INTERFACE_DEFAULT);
5209             if (result != OC_STACK_OK)
5210             {
5211                 OICFree(newInterface->name);
5212                 OICFree(newInterface);
5213                 return;
5214             }
5215             if (*firstInterface)
5216             {
5217                 (*firstInterface)->next = newInterface;
5218             }
5219         }
5220     }
5221     // If once add oic.if.baseline, later too below code take care of freeing memory.
5222     else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
5223     {
5224         if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
5225         {
5226             OICFree(newInterface->name);
5227             OICFree(newInterface);
5228             return;
5229         }
5230         // This code will not hit anymore, keeping
5231         else
5232         {
5233             newInterface->next = *firstInterface;
5234             *firstInterface = newInterface;
5235         }
5236     }
5237     else
5238     {
5239         pointer = *firstInterface;
5240         while (pointer)
5241         {
5242             if (strcmp(newInterface->name, pointer->name) == 0)
5243             {
5244                 OICFree(newInterface->name);
5245                 OICFree(newInterface);
5246                 return;
5247             }
5248             previous = pointer;
5249             pointer = pointer->next;
5250         }
5251
5252         if (previous)
5253         {
5254             previous->next = newInterface;
5255         }
5256     }
5257 }
5258
5259 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
5260         uint8_t index)
5261 {
5262     OCResource *resource = NULL;
5263     OCResourceInterface *pointer = NULL;
5264
5265     // Find the specified resource
5266     resource = findResource((OCResource *) handle);
5267     if (!resource)
5268     {
5269         return NULL;
5270     }
5271
5272     // Make sure a resource has a resourceinterface
5273     if (!resource->rsrcInterface)
5274     {
5275         return NULL;
5276     }
5277
5278     // Iterate through the list
5279     pointer = resource->rsrcInterface;
5280
5281     for (uint8_t i = 0; i < index && pointer; ++i)
5282     {
5283         pointer = pointer->next;
5284     }
5285     return pointer;
5286 }
5287
5288 /*
5289  * This function splits the uri using the '?' delimiter.
5290  * "uriWithoutQuery" is the block of characters between the beginning
5291  * till the delimiter or '\0' which ever comes first.
5292  * "query" is whatever is to the right of the delimiter if present.
5293  * No delimiter sets the query to NULL.
5294  * If either are present, they will be malloc'ed into the params 2, 3.
5295  * The first param, *uri is left untouched.
5296
5297  * NOTE: This function does not account for whitespace at the end of the uri NOR
5298  *       malformed uri's with '??'. Whitespace at the end will be assumed to be
5299  *       part of the query.
5300  */
5301 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
5302 {
5303     if(!uri)
5304     {
5305         return OC_STACK_INVALID_URI;
5306     }
5307     if(!query || !uriWithoutQuery)
5308     {
5309         return OC_STACK_INVALID_PARAM;
5310     }
5311
5312     *query           = NULL;
5313     *uriWithoutQuery = NULL;
5314
5315     size_t uriWithoutQueryLen = 0;
5316     size_t queryLen = 0;
5317     size_t uriLen = strlen(uri);
5318
5319     char *pointerToDelimiter = strstr(uri, "?");
5320
5321     uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
5322     queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
5323
5324     if (uriWithoutQueryLen)
5325     {
5326         *uriWithoutQuery =  (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
5327         if (!*uriWithoutQuery)
5328         {
5329             goto exit;
5330         }
5331         OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
5332     }
5333     if (queryLen)
5334     {
5335         *query = (char *) OICCalloc(queryLen + 1, 1);
5336         if (!*query)
5337         {
5338             OICFree(*uriWithoutQuery);
5339             *uriWithoutQuery = NULL;
5340             goto exit;
5341         }
5342         OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
5343     }
5344
5345     return OC_STACK_OK;
5346
5347     exit:
5348         return OC_STACK_NO_MEMORY;
5349 }
5350
5351 static const OicUuid_t* OCGetServerInstanceID(void)
5352 {
5353     static bool generated = false;
5354     static OicUuid_t sid;
5355     if (generated)
5356     {
5357         return &sid;
5358     }
5359
5360     if (OC_STACK_OK != GetDoxmDeviceID(&sid))
5361     {
5362         OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
5363         return NULL;
5364     }
5365     generated = true;
5366     return &sid;
5367 }
5368
5369 const char* OCGetServerInstanceIDString(void)
5370 {
5371     static bool generated = false;
5372     static char sidStr[UUID_STRING_SIZE];
5373
5374     if (generated)
5375     {
5376         return sidStr;
5377     }
5378
5379     const OicUuid_t *sid = OCGetServerInstanceID();
5380     if(sid && !OCConvertUuidToString(sid->id, sidStr))
5381     {
5382         OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
5383         return NULL;
5384     }
5385
5386     generated = true;
5387     return sidStr;
5388 }
5389
5390 CAResult_t OCSelectNetwork(OCTransportAdapter transportType)
5391 {
5392     OIC_LOG_V(DEBUG, TAG, "OCSelectNetwork [%d]", transportType);
5393     CAResult_t retResult = CA_STATUS_FAILED;
5394     CAResult_t caResult = CA_STATUS_OK;
5395
5396     CATransportAdapter_t connTypes[] = {
5397             CA_ADAPTER_IP,
5398             CA_ADAPTER_RFCOMM_BTEDR,
5399             CA_ADAPTER_GATT_BTLE,
5400             CA_ADAPTER_NFC
5401 #ifdef RA_ADAPTER
5402             ,CA_ADAPTER_REMOTE_ACCESS
5403 #endif
5404
5405 #ifdef TCP_ADAPTER
5406             ,CA_ADAPTER_TCP
5407 #endif
5408         };
5409     int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
5410
5411     for(int i = 0; i < numConnTypes; i++)
5412     {
5413         // If CA status is not initialized, CASelectNetwork() will not be called.
5414         if (caResult != CA_STATUS_NOT_INITIALIZED)
5415         {
5416             if ((connTypes[i] & transportType) || (OC_DEFAULT_ADAPTER == transportType))
5417             {
5418                 OIC_LOG_V(DEBUG, TAG, "call CASelectNetwork [%d]", connTypes[i]);
5419                 caResult = CASelectNetwork(connTypes[i]);
5420                 if (caResult == CA_STATUS_OK)
5421                 {
5422                     retResult = CA_STATUS_OK;
5423                 }
5424             }
5425             else
5426             {
5427                 OIC_LOG_V(DEBUG, TAG, "there is no transport type [%d]", connTypes[i]);
5428             }
5429         }
5430     }
5431
5432     if (retResult != CA_STATUS_OK)
5433     {
5434         return caResult; // Returns error of appropriate transport that failed fatally.
5435     }
5436
5437     return retResult;
5438 }
5439
5440 OCStackResult CAResultToOCResult(CAResult_t caResult)
5441 {
5442     switch (caResult)
5443     {
5444         case CA_STATUS_OK:
5445             return OC_STACK_OK;
5446         case CA_STATUS_INVALID_PARAM:
5447             return OC_STACK_INVALID_PARAM;
5448         case CA_ADAPTER_NOT_ENABLED:
5449             return OC_STACK_ADAPTER_NOT_ENABLED;
5450         case CA_SERVER_STARTED_ALREADY:
5451             return OC_STACK_OK;
5452         case CA_SERVER_NOT_STARTED:
5453             return OC_STACK_ERROR;
5454         case CA_DESTINATION_NOT_REACHABLE:
5455             return OC_STACK_COMM_ERROR;
5456         case CA_SOCKET_OPERATION_FAILED:
5457             return OC_STACK_COMM_ERROR;
5458         case CA_SEND_FAILED:
5459             return OC_STACK_COMM_ERROR;
5460         case CA_RECEIVE_FAILED:
5461             return OC_STACK_COMM_ERROR;
5462         case CA_MEMORY_ALLOC_FAILED:
5463             return OC_STACK_NO_MEMORY;
5464         case CA_REQUEST_TIMEOUT:
5465             return OC_STACK_TIMEOUT;
5466         case CA_DESTINATION_DISCONNECTED:
5467             return OC_STACK_COMM_ERROR;
5468         case CA_STATUS_FAILED:
5469             return OC_STACK_ERROR;
5470         case CA_NOT_SUPPORTED:
5471             return OC_STACK_NOTIMPL;
5472         default:
5473             return OC_STACK_ERROR;
5474     }
5475 }
5476
5477 bool OCResultToSuccess(OCStackResult ocResult)
5478 {
5479     switch (ocResult)
5480     {
5481         case OC_STACK_OK:
5482         case OC_STACK_RESOURCE_CREATED:
5483         case OC_STACK_RESOURCE_DELETED:
5484         case OC_STACK_CONTINUE:
5485         case OC_STACK_RESOURCE_CHANGED:
5486         case OC_STACK_SLOW_RESOURCE:
5487             return true;
5488         default:
5489             return false;
5490     }
5491 }
5492
5493 OCStackResult OCSetProxyURI(const char *uri)
5494 {
5495     return CAResultToOCResult(CASetProxyUri(uri));
5496 }
5497
5498 #if defined(RD_CLIENT) || defined(RD_SERVER)
5499 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, int64_t ins)
5500 {
5501     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5502
5503     OCResource *resource = NULL;
5504
5505     resource = findResource((OCResource *) handle);
5506     if (!resource)
5507     {
5508         OIC_LOG(ERROR, TAG, "Resource not found");
5509         return OC_STACK_ERROR;
5510     }
5511
5512     resource->ins = ins;
5513
5514     return OC_STACK_OK;
5515 }
5516
5517 OCStackResult OCUpdateResourceInsWithResponse(const char *requestUri,
5518                                               const OCClientResponse *response)
5519 {
5520     // Validate input parameters
5521     VERIFY_NON_NULL(requestUri, ERROR, OC_STACK_INVALID_PARAM);
5522     VERIFY_NON_NULL(response, ERROR, OC_STACK_INVALID_PARAM);
5523
5524     char *targetUri = (char *) OICMalloc(strlen(requestUri) + 1);
5525     if (!targetUri)
5526     {
5527         return OC_STACK_NO_MEMORY;
5528     }
5529     strncpy(targetUri, requestUri, strlen(requestUri) + 1);
5530
5531     if (response->result == OC_STACK_RESOURCE_CHANGED) // publish message
5532     {
5533         OIC_LOG(DEBUG, TAG, "update the ins of published resource");
5534
5535         char rdPubUri[MAX_URI_LENGTH] = { 0 };
5536         snprintf(rdPubUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
5537                  OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
5538
5539         if (strcmp(rdPubUri, targetUri) == 0)
5540         {
5541             // Update resource unique id in stack.
5542             if (response)
5543             {
5544                 if (response->payload)
5545                 {
5546                     OCRepPayload *rdPayload = (OCRepPayload *) response->payload;
5547                     OCRepPayload **links = NULL;
5548                     size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
5549                     if (OCRepPayloadGetPropObjectArray(rdPayload, OC_RSRVD_LINKS,
5550                                                        &links, dimensions))
5551                     {
5552                         size_t i = 0;
5553                         for (; i < dimensions[0]; i++)
5554                         {
5555                             char *uri = NULL;
5556                             if (OCRepPayloadGetPropString(links[i], OC_RSRVD_HREF, &uri))
5557                             {
5558                                 OCResourceHandle handle = OCGetResourceHandleAtUri(uri);
5559                                 int64_t ins = 0;
5560                                 if (OCRepPayloadGetPropInt(links[i], OC_RSRVD_INS, &ins))
5561                                 {
5562                                     OCBindResourceInsToResource(handle, ins);
5563                                 }
5564                             }
5565                         }
5566                     }
5567                 }
5568             }
5569         }
5570     }
5571     else if (response->result == OC_STACK_RESOURCE_DELETED) // delete message
5572     {
5573         OIC_LOG(DEBUG, TAG, "update the ins of deleted resource with 0");
5574
5575         uint8_t numResources = 0;
5576         OCGetNumberOfResources(&numResources);
5577
5578         char *ins = strstr(targetUri, OC_RSRVD_INS);
5579         if (!ins)
5580         {
5581             for (uint8_t i = 0; i < numResources; i++)
5582             {
5583                 OCResourceHandle resHandle = OCGetResourceHandle(i);
5584                 if (resHandle)
5585                 {
5586                     OCBindResourceInsToResource(resHandle, 0);
5587                 }
5588             }
5589         }
5590         else
5591         {
5592             const char *token = "&";
5593             char *iterTokenPtr = NULL;
5594             char *start = strtok_r(targetUri, token, &iterTokenPtr);
5595
5596              while (start != NULL)
5597              {
5598                  char *query = start;
5599                  query = strstr(query, OC_RSRVD_INS);
5600                  if (query)
5601                  {
5602                      // Arduino's AVR-GCC doesn't support strtoll().
5603                      int64_t queryIns;
5604                      int matchedItems = sscanf(query + 4, "%lld", &queryIns);
5605
5606                      if (0 == matchedItems)
5607                      {
5608                          OICFree(targetUri);
5609                          return OC_STACK_INVALID_QUERY;
5610                      }
5611
5612                      for (uint8_t i = 0; i < numResources; i++)
5613                      {
5614                          OCResourceHandle resHandle = OCGetResourceHandle(i);
5615                          if (resHandle)
5616                          {
5617                              int64_t resIns = 0;
5618                              OCGetResourceIns(resHandle, &resIns);
5619                              if (queryIns && queryIns == resIns)
5620                              {
5621                                  OCBindResourceInsToResource(resHandle, 0);
5622                                  break;
5623                              }
5624                          }
5625                      }
5626                  }
5627                  start = strtok_r(NULL, token, &iterTokenPtr);
5628              }
5629         }
5630     }
5631
5632     OICFree(targetUri);
5633     return OC_STACK_OK;
5634 }
5635
5636 OCStackResult OCGetResourceIns(OCResourceHandle handle, int64_t* ins)
5637 {
5638     OCResource *resource = NULL;
5639
5640     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5641     VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
5642
5643     resource = findResource((OCResource *) handle);
5644     if (resource)
5645     {
5646         *ins = resource->ins;
5647         return OC_STACK_OK;
5648     }
5649     return OC_STACK_ERROR;
5650 }
5651 #endif // RD_CLIENT || RD_SERVER
5652
5653 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
5654 {
5655     if (!uri)
5656     {
5657         OIC_LOG(ERROR, TAG, "Resource uri is NULL");
5658         return NULL;
5659     }
5660
5661     OCResource *pointer = headResource;
5662
5663     while (pointer)
5664     {
5665         if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
5666         {
5667             OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
5668             return pointer;
5669         }
5670         pointer = pointer->next;
5671     }
5672     return NULL;
5673 }
5674
5675 OCStackResult OCSetHeaderOption(OCHeaderOption* ocHdrOpt, size_t* numOptions, uint16_t optionID,
5676                                 void* optionData, size_t optionDataLength)
5677 {
5678     if (!ocHdrOpt)
5679     {
5680         OIC_LOG (INFO, TAG, "Header options are NULL");
5681         return OC_STACK_INVALID_PARAM;
5682     }
5683
5684     if (!optionData)
5685     {
5686         OIC_LOG (INFO, TAG, "optionData are NULL");
5687         return OC_STACK_INVALID_PARAM;
5688     }
5689
5690     if (!numOptions)
5691     {
5692         OIC_LOG (INFO, TAG, "numOptions is NULL");
5693         return OC_STACK_INVALID_PARAM;
5694     }
5695
5696     if (*numOptions >= MAX_HEADER_OPTIONS)
5697     {
5698         OIC_LOG (INFO, TAG, "Exceeding MAX_HEADER_OPTIONS");
5699         return OC_STACK_NO_MEMORY;
5700     }
5701
5702     ocHdrOpt += *numOptions;
5703     ocHdrOpt->protocolID = OC_COAP_ID;
5704     ocHdrOpt->optionID = optionID;
5705     ocHdrOpt->optionLength =
5706             (optionDataLength < MAX_HEADER_OPTION_DATA_LENGTH) ?
5707                     (uint16_t)optionDataLength : MAX_HEADER_OPTION_DATA_LENGTH;
5708     memcpy(ocHdrOpt->optionData, (const void*) optionData, ocHdrOpt->optionLength);
5709     *numOptions += 1;
5710
5711     return OC_STACK_OK;
5712 }
5713
5714 OCStackResult OCGetHeaderOption(OCHeaderOption* ocHdrOpt, size_t numOptions,
5715                                 uint16_t optionID, void* optionData, size_t optionDataLength,
5716                                 uint16_t* receivedDataLength)
5717 {
5718     if (!ocHdrOpt || !numOptions)
5719     {
5720         OIC_LOG (INFO, TAG, "No options present");
5721         return OC_STACK_OK;
5722     }
5723
5724     if (!optionData)
5725     {
5726         OIC_LOG (INFO, TAG, "optionData are NULL");
5727         return OC_STACK_INVALID_PARAM;
5728     }
5729
5730     if (!receivedDataLength)
5731     {
5732         OIC_LOG (INFO, TAG, "receivedDataLength is NULL");
5733         return OC_STACK_INVALID_PARAM;
5734     }
5735
5736     for (uint8_t i = 0; i < numOptions; i++)
5737     {
5738         if (ocHdrOpt[i].optionID == optionID)
5739         {
5740             if (optionDataLength >= ocHdrOpt->optionLength)
5741             {
5742                 memcpy(optionData, ocHdrOpt->optionData, ocHdrOpt->optionLength);
5743                 *receivedDataLength = ocHdrOpt->optionLength;
5744                 return OC_STACK_OK;
5745             }
5746             else
5747             {
5748                 OIC_LOG (ERROR, TAG, "optionDataLength is less than the length of received data");
5749                 return OC_STACK_ERROR;
5750             }
5751         }
5752     }
5753     return OC_STACK_OK;
5754 }
5755
5756 void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
5757 {
5758     OIC_LOG(DEBUG, TAG, "OCDefaultAdapterStateChangedHandler");
5759     if (g_adapterHandler)
5760     {
5761         g_adapterHandler(adapter, enabled);
5762     }
5763 }
5764
5765 void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected)
5766 {
5767     OIC_LOG(DEBUG, TAG, "OCDefaultConnectionStateChangedHandler");
5768     if (g_connectionHandler)
5769     {
5770        g_connectionHandler(info, isConnected);
5771     }
5772
5773     /*
5774      * If the client observes one or more resources over a reliable connection,
5775      * then the CoAP server (or intermediary in the role of the CoAP server)
5776      * MUST remove all entries associated with the client endpoint from the lists
5777      * of observers when the connection is either closed or times out.
5778      */
5779     if (!isConnected)
5780     {
5781         OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
5782         CopyEndpointToDevAddr(info, &devAddr);
5783
5784         // remove observer list with remote device address.
5785         DeleteObserverUsingDevAddr(&devAddr);
5786     }
5787 }
5788
5789 void OCSetNetworkMonitorHandler(CAAdapterStateChangedCB adapterHandler,
5790                                 CAConnectionStateChangedCB connectionHandler)
5791 {
5792     OIC_LOG(DEBUG, TAG, "OCSetNetworkMonitorHandler");
5793     g_adapterHandler = adapterHandler;
5794     g_connectionHandler = connectionHandler;
5795 }
5796
5797 OCStackResult OCGetDeviceId(OCUUIdentity *deviceId)
5798 {
5799     OicUuid_t oicUuid;
5800     OCStackResult ret = OC_STACK_ERROR;
5801
5802     ret = GetDoxmDeviceID(&oicUuid);
5803     if (OC_STACK_OK == ret)
5804     {
5805         memcpy(deviceId, &oicUuid, UUID_IDENTITY_SIZE);
5806     }
5807     else
5808     {
5809         OIC_LOG(ERROR, TAG, "Device ID Get error");
5810     }
5811     return ret;
5812 }
5813
5814 OCStackResult OCSetDeviceId(const OCUUIdentity *deviceId)
5815 {
5816     OicUuid_t oicUuid;
5817     OCStackResult ret = OC_STACK_ERROR;
5818
5819     memcpy(&oicUuid, deviceId, UUID_LENGTH);
5820     for (int i = 0; i < UUID_LENGTH; i++)
5821     {
5822         OIC_LOG_V(INFO, TAG, "Set Device Id %x", oicUuid.id[i]);
5823     }
5824     ret = SetDoxmDeviceID(&oicUuid);
5825     return ret;
5826 }
5827
5828 OCStackResult OCGetDeviceOwnedState(bool *isOwned)
5829 {
5830     bool isDeviceOwned = true;
5831     OCStackResult ret = OC_STACK_ERROR;
5832
5833     ret = GetDoxmIsOwned(&isDeviceOwned);
5834     if (OC_STACK_OK == ret)
5835     {
5836         *isOwned = isDeviceOwned;
5837     }
5838     else
5839     {
5840         OIC_LOG(ERROR, TAG, "Device Owned State Get error");
5841     }
5842     return ret;
5843 }
5844
5845 OCStackResult OCGetLinkLocalZoneId(uint32_t ifindex, char **zoneId)
5846 {
5847     return CAResultToOCResult(CAGetLinkLocalZoneId(ifindex, zoneId));
5848 }