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