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