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