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