Merge branch 'master' into plugin-interface
[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 ROUTING_GATEWAY
1177                     else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1178                     {
1179                         type = PAYLOAD_TYPE_REPRESENTATION;
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                     OC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1197                             cbNode->method, cbNode->requestUri);
1198                     type = PAYLOAD_TYPE_REPRESENTATION;
1199                 }
1200                 else
1201                 {
1202                     OC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1203                             cbNode->method, cbNode->requestUri);
1204                     return;
1205                 }
1206
1207                 if(OC_STACK_OK != OCParsePayload(&response.payload,
1208                             type,
1209                             responseInfo->info.payload,
1210                             responseInfo->info.payloadSize))
1211                 {
1212                     OC_LOG(ERROR, TAG, "Error converting payload");
1213                     OCPayloadDestroy(response.payload);
1214                     return;
1215                 }
1216             }
1217
1218             response.numRcvdVendorSpecificHeaderOptions = 0;
1219             if(responseInfo->info.numOptions > 0)
1220             {
1221                 int start = 0;
1222                 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1223                 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1224                 {
1225                     size_t i;
1226                     uint32_t observationOption;
1227                     uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1228                     for (observationOption=0, i=0;
1229                             i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1230                             i++)
1231                     {
1232                         observationOption =
1233                             (observationOption << 8) | optionData[i];
1234                     }
1235                     response.sequenceNumber = observationOption;
1236
1237                     response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1238                     start = 1;
1239                 }
1240                 else
1241                 {
1242                     response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1243                 }
1244
1245                 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1246                 {
1247                     OC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1248                     OCPayloadDestroy(response.payload);
1249                     return;
1250                 }
1251
1252                 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1253                 {
1254                     memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1255                             &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1256                 }
1257             }
1258
1259             if (cbNode->method == OC_REST_OBSERVE &&
1260                 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1261                 response.sequenceNumber <= cbNode->sequenceNumber)
1262             {
1263                 OC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1264                                                  response.sequenceNumber);
1265             }
1266             else
1267             {
1268                 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1269                                                                         cbNode->handle,
1270                                                                         &response);
1271                 cbNode->sequenceNumber = response.sequenceNumber;
1272
1273                 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1274                 {
1275                     FindAndDeleteClientCB(cbNode);
1276                 }
1277                 else
1278                 {
1279                     // To keep discovery callbacks active.
1280                     cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1281                                             MILLISECONDS_PER_SECOND);
1282                 }
1283             }
1284
1285             //Need to send ACK when the response is CON
1286             if(responseInfo->info.type == CA_MSG_CONFIRM)
1287             {
1288                 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1289                         CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL);
1290             }
1291
1292             OCPayloadDestroy(response.payload);
1293         }
1294         return;
1295     }
1296
1297     if(observer)
1298     {
1299         OC_LOG(INFO, TAG, "There is an observer associated with the response token");
1300         if(responseInfo->result == CA_EMPTY)
1301         {
1302             OC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1303             if(responseInfo->info.type == CA_MSG_RESET)
1304             {
1305                 OC_LOG(INFO, TAG, "This is a RESET");
1306                 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1307                         OC_OBSERVER_NOT_INTERESTED);
1308             }
1309             else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1310             {
1311                 OC_LOG(INFO, TAG, "This is a pure ACK");
1312                 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1313                         OC_OBSERVER_STILL_INTERESTED);
1314             }
1315         }
1316         else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1317         {
1318             OC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1319             OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1320                     OC_OBSERVER_FAILED_COMM);
1321         }
1322         return;
1323     }
1324
1325     if(!cbNode && !observer)
1326     {
1327         if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1328            || myStackMode == OC_GATEWAY)
1329         {
1330             OC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1331             if(responseInfo->result == CA_EMPTY)
1332             {
1333                 OC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1334             }
1335             else
1336             {
1337                 OC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1338                 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1339                         CA_MSG_RESET, 0, NULL, NULL, 0, NULL);
1340             }
1341         }
1342
1343         if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1344            || myStackMode == OC_GATEWAY)
1345         {
1346             OC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1347             if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1348             {
1349                 OC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1350                                             responseInfo->info.messageId);
1351             }
1352             if (responseInfo->info.type == CA_MSG_RESET)
1353             {
1354                 OC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1355                                             responseInfo->info.messageId);
1356             }
1357         }
1358
1359         return;
1360     }
1361
1362     OC_LOG(INFO, TAG, "Exit HandleCAResponses");
1363 }
1364
1365 /*
1366  * This function handles error response from CA
1367  * code shall be added to handle the errors
1368  */
1369 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errrorInfo)
1370 {
1371     OC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1372
1373     if(NULL == endPoint)
1374     {
1375         OC_LOG(ERROR, TAG, "endPoint is NULL");
1376         return;
1377     }
1378
1379     if(NULL == errrorInfo)
1380     {
1381         OC_LOG(ERROR, TAG, "errrorInfo is NULL");
1382         return;
1383     }
1384     OC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1385 }
1386
1387 /*
1388  * This function sends out Direct Stack Responses. These are responses that are not coming
1389  * from the application entity handler. These responses have no payload and are usually ACKs,
1390  * RESETs or some error conditions that were caught by the stack.
1391  */
1392 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1393         const CAResponseResult_t responseResult, const CAMessageType_t type,
1394         const uint8_t numOptions, const CAHeaderOption_t *options,
1395         CAToken_t token, uint8_t tokenLength, const char *resourceUri)
1396 {
1397     CAResponseInfo_t respInfo = {
1398         .result = responseResult
1399     };
1400     respInfo.info.messageId = coapID;
1401     respInfo.info.numOptions = numOptions;
1402     respInfo.info.options = (CAHeaderOption_t*)options;
1403     respInfo.info.payload = NULL;
1404     respInfo.info.token = token;
1405     respInfo.info.tokenLength = tokenLength;
1406     respInfo.info.type = type;
1407     respInfo.info.resourceUri = OICStrdup (resourceUri);
1408     respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1409
1410 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1411     // Add the destination to route option from the endpoint->routeData.
1412     OCStackResult result = RMAddInfo(endPoint->routeData,
1413                                      &(respInfo.info.options),
1414                                      &(respInfo.info.numOptions));
1415     if(OC_STACK_OK != result)
1416     {
1417         OC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1418         return result;
1419     }
1420 #endif
1421
1422     CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1423
1424     // resourceUri in the info field is cloned in the CA layer and
1425     // thus ownership is still here.
1426     OICFree (respInfo.info.resourceUri);
1427
1428     if(CA_STATUS_OK != caResult)
1429     {
1430         OC_LOG(ERROR, TAG, "CASendResponse error");
1431         return CAResultToOCResult(caResult);
1432     }
1433     return OC_STACK_OK;
1434 }
1435
1436 //This function will be called back by CA layer when a request is received
1437 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1438 {
1439     OC_LOG(INFO, TAG, "Enter HandleCARequests");
1440     if(!endPoint)
1441     {
1442         OC_LOG(ERROR, TAG, "endPoint is NULL");
1443         return;
1444     }
1445
1446     if(!requestInfo)
1447     {
1448         OC_LOG(ERROR, TAG, "requestInfo is NULL");
1449         return;
1450     }
1451
1452 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1453 #ifdef ROUTING_GATEWAY
1454     bool needRIHandling = false;
1455     /*
1456      * Routing manager is going to update either of endpoint or request or both.
1457      * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
1458      * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1459      * destination. It can also remove "RM" coap header option before passing request / response to
1460      * RI as this option will make no sense to either RI or application.
1461      */
1462     OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
1463                                      &needRIHandling);
1464     if(OC_STACK_OK != ret || !needRIHandling)
1465     {
1466         OC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1467         return;
1468     }
1469 #endif
1470
1471     /*
1472      * Put source in sender endpoint so that the next packet from application can be routed to
1473      * proper destination and remove RM header option.
1474      */
1475     RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
1476                  (uint8_t *) &(requestInfo->info.numOptions),
1477                  (CAEndpoint_t *) endPoint);
1478 #endif
1479
1480     OCStackResult requestResult = OC_STACK_ERROR;
1481
1482     if(myStackMode == OC_CLIENT)
1483     {
1484         //TODO: should the client be responding to requests?
1485         return;
1486     }
1487
1488     OCServerProtocolRequest serverRequest = {0};
1489
1490     OC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1491
1492     char * uriWithoutQuery = NULL;
1493     char * query  = NULL;
1494
1495     requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1496
1497     if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1498     {
1499         OC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1500         return;
1501     }
1502     OC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1503     OC_LOG_V(INFO, TAG, "Query : %s", query);
1504
1505     if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1506     {
1507         OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1508         OICFree(uriWithoutQuery);
1509     }
1510     else
1511     {
1512         OC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1513         OICFree(uriWithoutQuery);
1514         OICFree(query);
1515         return;
1516     }
1517
1518     if(query)
1519     {
1520         if(strlen(query) < MAX_QUERY_LENGTH)
1521         {
1522             OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1523             OICFree(query);
1524         }
1525         else
1526         {
1527             OC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1528             OICFree(query);
1529             return;
1530         }
1531     }
1532
1533     if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1534     {
1535         serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1536         serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1537         memcpy (serverRequest.payload, requestInfo->info.payload,
1538                 requestInfo->info.payloadSize);
1539     }
1540     else
1541     {
1542         serverRequest.reqTotalSize = 0;
1543     }
1544
1545     switch (requestInfo->method)
1546     {
1547         case CA_GET:
1548             serverRequest.method = OC_REST_GET;
1549             break;
1550         case CA_PUT:
1551             serverRequest.method = OC_REST_PUT;
1552             break;
1553         case CA_POST:
1554             serverRequest.method = OC_REST_POST;
1555             break;
1556         case CA_DELETE:
1557             serverRequest.method = OC_REST_DELETE;
1558             break;
1559         default:
1560             OC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1561             SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1562                         requestInfo->info.type, requestInfo->info.numOptions,
1563                         requestInfo->info.options, requestInfo->info.token,
1564                         requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1565             OICFree(serverRequest.payload);
1566             return;
1567     }
1568
1569     OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1570             requestInfo->info.tokenLength);
1571     serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1572     serverRequest.tokenLength = requestInfo->info.tokenLength;
1573
1574     if (!serverRequest.requestToken)
1575     {
1576         OC_LOG(FATAL, TAG, "Allocation for token failed.");
1577         SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1578                 requestInfo->info.type, requestInfo->info.numOptions,
1579                 requestInfo->info.options, requestInfo->info.token,
1580                 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1581         OICFree(serverRequest.payload);
1582         return;
1583     }
1584     memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1585
1586     switch (requestInfo->info.acceptFormat)
1587     {
1588         case CA_FORMAT_APPLICATION_CBOR:
1589             serverRequest.acceptFormat = OC_FORMAT_CBOR;
1590             break;
1591         case CA_FORMAT_UNDEFINED:
1592             serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1593             break;
1594         default:
1595             serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1596     }
1597
1598     if (requestInfo->info.type == CA_MSG_CONFIRM)
1599     {
1600         serverRequest.qos = OC_HIGH_QOS;
1601     }
1602     else
1603     {
1604         serverRequest.qos = OC_LOW_QOS;
1605     }
1606     // CA does not need the following field
1607     // Are we sure CA does not need them? how is it responding to multicast
1608     serverRequest.delayedResNeeded = 0;
1609
1610     serverRequest.coapID = requestInfo->info.messageId;
1611
1612     CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1613
1614     // copy vendor specific header options
1615     uint8_t tempNum = (requestInfo->info.numOptions);
1616
1617     // Assume no observation requested and it is a pure GET.
1618     // If obs registration/de-registration requested it'll be fetched from the
1619     // options in GetObserveHeaderOption()
1620     serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1621
1622     GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1623     if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1624     {
1625         OC_LOG(ERROR, TAG,
1626                 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1627         SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1628                 requestInfo->info.type, requestInfo->info.numOptions,
1629                 requestInfo->info.options, requestInfo->info.token,
1630                 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1631         OICFree(serverRequest.payload);
1632         OICFree(serverRequest.requestToken);
1633         return;
1634     }
1635     serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1636     if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1637     {
1638         memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1639             sizeof(CAHeaderOption_t)*tempNum);
1640     }
1641
1642     requestResult = HandleStackRequests (&serverRequest);
1643
1644     // Send ACK to client as precursor to slow response
1645     if(requestResult == OC_STACK_SLOW_RESOURCE)
1646     {
1647         SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1648                     CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL);
1649     }
1650     else if(requestResult != OC_STACK_OK)
1651     {
1652         OC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1653
1654         CAResponseResult_t stackResponse =
1655             OCToCAStackResult(requestResult, serverRequest.method);
1656
1657         SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1658                 requestInfo->info.type, requestInfo->info.numOptions,
1659                 requestInfo->info.options, requestInfo->info.token,
1660                 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1661     }
1662     // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1663     // The token is copied in there, and is thus still owned by this function.
1664     OICFree(serverRequest.payload);
1665     OICFree(serverRequest.requestToken);
1666     OC_LOG(INFO, TAG, "Exit HandleCARequests");
1667 }
1668
1669 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1670 {
1671     OC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1672     OCStackResult result = OC_STACK_ERROR;
1673     ResourceHandling resHandling;
1674     OCResource *resource;
1675     if(!protocolRequest)
1676     {
1677         OC_LOG(ERROR, TAG, "protocolRequest is NULL");
1678         return OC_STACK_INVALID_PARAM;
1679     }
1680
1681     OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1682             protocolRequest->tokenLength);
1683     if(!request)
1684     {
1685         OC_LOG(INFO, TAG, "This is a new Server Request");
1686         result = AddServerRequest(&request, protocolRequest->coapID,
1687                 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1688                 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1689                 protocolRequest->observationOption, protocolRequest->qos,
1690                 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1691                 protocolRequest->payload, protocolRequest->requestToken,
1692                 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1693                 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1694                 &protocolRequest->devAddr);
1695         if (OC_STACK_OK != result)
1696         {
1697             OC_LOG(ERROR, TAG, "Error adding server request");
1698             return result;
1699         }
1700
1701         if(!request)
1702         {
1703             OC_LOG(ERROR, TAG, "Out of Memory");
1704             return OC_STACK_NO_MEMORY;
1705         }
1706
1707         if(!protocolRequest->reqMorePacket)
1708         {
1709             request->requestComplete = 1;
1710         }
1711     }
1712     else
1713     {
1714         OC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1715     }
1716
1717     if(request->requestComplete)
1718     {
1719         OC_LOG(INFO, TAG, "This Server Request is complete");
1720         result = DetermineResourceHandling (request, &resHandling, &resource);
1721         if (result == OC_STACK_OK)
1722         {
1723             result = ProcessRequest(resHandling, resource, request);
1724         }
1725     }
1726     else
1727     {
1728         OC_LOG(INFO, TAG, "This Server Request is incomplete");
1729         result = OC_STACK_CONTINUE;
1730     }
1731     return result;
1732 }
1733
1734 bool validatePlatformInfo(OCPlatformInfo info)
1735 {
1736
1737     if (!info.platformID)
1738     {
1739         OC_LOG(ERROR, TAG, "No platform ID found.");
1740         return false;
1741     }
1742
1743     if (info.manufacturerName)
1744     {
1745         size_t lenManufacturerName = strlen(info.manufacturerName);
1746
1747         if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
1748         {
1749             OC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
1750             return false;
1751         }
1752     }
1753     else
1754     {
1755         OC_LOG(ERROR, TAG, "No manufacturer name present");
1756         return false;
1757     }
1758
1759     if (info.manufacturerUrl)
1760     {
1761         if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
1762         {
1763             OC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
1764             return false;
1765         }
1766     }
1767     return true;
1768 }
1769
1770 //-----------------------------------------------------------------------------
1771 // Public APIs
1772 //-----------------------------------------------------------------------------
1773 #ifdef RA_ADAPTER
1774 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
1775 {
1776     if (!raInfo           ||
1777         !raInfo->username ||
1778         !raInfo->hostname ||
1779         !raInfo->xmpp_domain)
1780     {
1781
1782         return OC_STACK_INVALID_PARAM;
1783     }
1784     OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
1785     gRASetInfo = (result == OC_STACK_OK)? true : false;
1786
1787     return result;
1788 }
1789 #endif
1790
1791 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1792 {
1793     (void) ipAddr;
1794     (void) port;
1795     return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
1796 }
1797
1798 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
1799 {
1800     if(stackState == OC_STACK_INITIALIZED)
1801     {
1802         OC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
1803                 OCStop() between them are ignored.");
1804         return OC_STACK_OK;
1805     }
1806
1807 #ifndef ROUTING_GATEWAY
1808     if (OC_GATEWAY == mode)
1809     {
1810         OC_LOG(ERROR, TAG, "Routing Manager not supported");
1811         return OC_STACK_INVALID_PARAM;
1812     }
1813 #endif
1814
1815 #ifdef RA_ADAPTER
1816     if(!gRASetInfo)
1817     {
1818         OC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
1819         return OC_STACK_ERROR;
1820     }
1821 #endif
1822
1823     OCStackResult result = OC_STACK_ERROR;
1824     OC_LOG(INFO, TAG, "Entering OCInit");
1825
1826     // Validate mode
1827     if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
1828         || (mode == OC_GATEWAY)))
1829     {
1830         OC_LOG(ERROR, TAG, "Invalid mode");
1831         return OC_STACK_ERROR;
1832     }
1833     myStackMode = mode;
1834
1835     if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
1836     {
1837         caglobals.client = true;
1838     }
1839     if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
1840     {
1841         caglobals.server = true;
1842     }
1843
1844     caglobals.serverFlags = (CATransportFlags_t)serverFlags;
1845     if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
1846     {
1847         caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
1848     }
1849     caglobals.clientFlags = (CATransportFlags_t)clientFlags;
1850     if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
1851     {
1852         caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
1853     }
1854
1855 #ifdef TCP_ADAPTER
1856     if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
1857     {
1858         caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4);
1859     }
1860     if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
1861     {
1862         caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4);
1863     }
1864 #endif
1865
1866     defaultDeviceHandler = NULL;
1867     defaultDeviceHandlerCallbackParameter = NULL;
1868     OCSeedRandom();
1869
1870     result = CAResultToOCResult(CAInitialize());
1871     VERIFY_SUCCESS(result, OC_STACK_OK);
1872
1873     result = CAResultToOCResult(OCSelectNetwork());
1874     VERIFY_SUCCESS(result, OC_STACK_OK);
1875
1876     switch (myStackMode)
1877     {
1878         case OC_CLIENT:
1879                         CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1880             result = CAResultToOCResult(CAStartDiscoveryServer());
1881             OC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
1882             break;
1883         case OC_SERVER:
1884                         SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1885             result = CAResultToOCResult(CAStartListeningServer());
1886             OC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
1887             break;
1888         case OC_CLIENT_SERVER:
1889         case OC_GATEWAY:
1890                         SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1891             result = CAResultToOCResult(CAStartListeningServer());
1892             if(result == OC_STACK_OK)
1893             {
1894                 result = CAResultToOCResult(CAStartDiscoveryServer());
1895             }
1896             break;
1897     }
1898     VERIFY_SUCCESS(result, OC_STACK_OK);
1899
1900 #ifdef WITH_PRESENCE
1901     PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
1902 #endif // WITH_PRESENCE
1903
1904     //Update Stack state to initialized
1905     stackState = OC_STACK_INITIALIZED;
1906
1907     // Initialize resource
1908     if(myStackMode != OC_CLIENT)
1909     {
1910         result = initResources();
1911     }
1912
1913     // Initialize the SRM Policy Engine
1914     if(result == OC_STACK_OK)
1915     {
1916         result = SRMInitPolicyEngine();
1917         // TODO after BeachHead delivery: consolidate into single SRMInit()
1918     }
1919
1920 #ifdef ROUTING_GATEWAY
1921     if (OC_GATEWAY == myStackMode)
1922     {
1923         result = RMInitialize();
1924     }
1925 #endif
1926
1927 exit:
1928     if(result != OC_STACK_OK)
1929     {
1930         OC_LOG(ERROR, TAG, "Stack initialization error");
1931         deleteAllResources();
1932         CATerminate();
1933         stackState = OC_STACK_UNINITIALIZED;
1934     }
1935     return result;
1936 }
1937
1938 OCStackResult OCStop()
1939 {
1940     OC_LOG(INFO, TAG, "Entering OCStop");
1941
1942     if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1943     {
1944         OC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
1945         return OC_STACK_OK;
1946     }
1947     else if (stackState != OC_STACK_INITIALIZED)
1948     {
1949         OC_LOG(ERROR, TAG, "Stack not initialized");
1950         return OC_STACK_ERROR;
1951     }
1952
1953     stackState = OC_STACK_UNINIT_IN_PROGRESS;
1954
1955 #ifdef WITH_PRESENCE
1956     // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1957     // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1958     presenceResource.presenceTTL = 0;
1959 #endif // WITH_PRESENCE
1960
1961 #ifdef ROUTING_GATEWAY
1962     if (OC_GATEWAY == myStackMode)
1963     {
1964         RMTerminate();
1965     }
1966 #endif
1967
1968     // Free memory dynamically allocated for resources
1969     deleteAllResources();
1970     DeleteDeviceInfo();
1971     DeletePlatformInfo();
1972     CATerminate();
1973     // Remove all observers
1974     DeleteObserverList();
1975     // Remove all the client callbacks
1976     DeleteClientCBList();
1977
1978         // De-init the SRM Policy Engine
1979     // TODO after BeachHead delivery: consolidate into single SRMDeInit()
1980     SRMDeInitPolicyEngine();
1981
1982
1983     stackState = OC_STACK_UNINITIALIZED;
1984     return OC_STACK_OK;
1985 }
1986
1987 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
1988 {
1989     switch (qos)
1990     {
1991         case OC_HIGH_QOS:
1992             return CA_MSG_CONFIRM;
1993         case OC_LOW_QOS:
1994         case OC_MEDIUM_QOS:
1995         case OC_NA_QOS:
1996         default:
1997             return CA_MSG_NONCONFIRM;
1998     }
1999 }
2000
2001 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
2002 {
2003     char *query;
2004
2005     query = strchr (inputUri, '?');
2006
2007     if (query != NULL)
2008     {
2009         if((query - inputUri) > MAX_URI_LENGTH)
2010         {
2011             return OC_STACK_INVALID_URI;
2012         }
2013
2014         if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
2015         {
2016             return OC_STACK_INVALID_QUERY;
2017         }
2018     }
2019     else if(uriLen > MAX_URI_LENGTH)
2020     {
2021         return OC_STACK_INVALID_URI;
2022     }
2023     return OC_STACK_OK;
2024 }
2025
2026 /**
2027  *  A request uri consists of the following components in order:
2028  *                              example
2029  *  optionally one of
2030  *      CoAP over UDP prefix    "coap://"
2031  *      CoAP over TCP prefix    "coap+tcp://"
2032  *  optionally one of
2033  *      IPv6 address            "[1234::5678]"
2034  *      IPv4 address            "192.168.1.1"
2035  *  optional port               ":5683"
2036  *  resource uri                "/oc/core..."
2037  *
2038  *  for PRESENCE requests, extract resource type.
2039  */
2040 static OCStackResult ParseRequestUri(const char *fullUri,
2041                                         OCTransportAdapter adapter,
2042                                         OCTransportFlags flags,
2043                                         OCDevAddr **devAddr,
2044                                         char **resourceUri,
2045                                         char **resourceType)
2046 {
2047     VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2048
2049     OCStackResult result = OC_STACK_OK;
2050     OCDevAddr *da = NULL;
2051     char *colon = NULL;
2052     char *end;
2053
2054     // provide defaults for all returned values
2055     if (devAddr)
2056     {
2057         *devAddr = NULL;
2058     }
2059     if (resourceUri)
2060     {
2061         *resourceUri = NULL;
2062     }
2063     if (resourceType)
2064     {
2065         *resourceType = NULL;
2066     }
2067
2068     // delimit url prefix, if any
2069     const char *start = fullUri;
2070     char *slash2 = strstr(start, "//");
2071     if (slash2)
2072     {
2073         start = slash2 + 2;
2074     }
2075     char *slash = strchr(start, '/');
2076     if (!slash)
2077     {
2078         return OC_STACK_INVALID_URI;
2079     }
2080
2081 #ifdef TCP_ADAPTER
2082     // process url scheme
2083     size_t prefixLen = slash2 - fullUri;
2084     bool istcp = false;
2085     if (prefixLen)
2086     {
2087         if ((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
2088         {
2089             istcp = true;
2090         }
2091     }
2092 #endif
2093
2094     // TODO: this logic should come in with unit tests exercising the various strings
2095     // processs url prefix, if any
2096     size_t urlLen = slash - start;
2097     // port
2098     uint16_t port = 0;
2099     size_t len = 0;
2100     if (urlLen && devAddr)
2101     {   // construct OCDevAddr
2102         if (start[0] == '[')
2103         {   // ipv6 address
2104             char *close = strchr(++start, ']');
2105             if (!close || close > slash)
2106             {
2107                 return OC_STACK_INVALID_URI;
2108             }
2109             end = close;
2110             if (close[1] == ':')
2111             {
2112                 colon = close + 1;
2113             }
2114             adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2115             flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2116         }
2117         else
2118         {
2119             char *dot = strchr(start, '.');
2120             if (dot && dot < slash)
2121             {   // ipv4 address
2122                 colon = strchr(start, ':');
2123                 end = (colon && colon < slash) ? colon : slash;
2124 #ifdef TCP_ADAPTER
2125                 if (istcp)
2126                 {   // coap over tcp
2127                     adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2128                 }
2129                 else
2130 #endif
2131                 {
2132                     adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2133                     flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2134                 }
2135             }
2136             else
2137             {   // MAC address
2138                 end = slash;
2139             }
2140         }
2141         len = end - start;
2142         if (len >= sizeof(da->addr))
2143         {
2144             return OC_STACK_INVALID_URI;
2145         }
2146         // collect port, if any
2147         if (colon && colon < slash)
2148         {
2149             for (colon++; colon < slash; colon++)
2150             {
2151                 char c = colon[0];
2152                 if (c < '0' || c > '9')
2153                 {
2154                     return OC_STACK_INVALID_URI;
2155                 }
2156                 port = 10 * port + c - '0';
2157             }
2158         }
2159
2160         len = end - start;
2161         if (len >= sizeof(da->addr))
2162         {
2163             return OC_STACK_INVALID_URI;
2164         }
2165
2166         da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2167         if (!da)
2168         {
2169             return OC_STACK_NO_MEMORY;
2170         }
2171         OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2172         da->port = port;
2173         da->adapter = adapter;
2174         da->flags = flags;
2175         if (!strncmp(fullUri, "coaps:", 6))
2176         {
2177             da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2178         }
2179         *devAddr = da;
2180     }
2181
2182     // process resource uri, if any
2183     if (slash)
2184     {   // request uri and query
2185         size_t ulen = strlen(slash); // resource uri length
2186         size_t tlen = 0;      // resource type length
2187         char *type = NULL;
2188
2189         static const char strPresence[] = "/oic/ad?rt=";
2190         static const size_t lenPresence = sizeof(strPresence) - 1;
2191         if (!strncmp(slash, strPresence, lenPresence))
2192         {
2193             type = slash + lenPresence;
2194             tlen = ulen - lenPresence;
2195         }
2196         // resource uri
2197         if (resourceUri)
2198         {
2199             *resourceUri = (char *)OICMalloc(ulen + 1);
2200             if (!*resourceUri)
2201             {
2202                 result = OC_STACK_NO_MEMORY;
2203                 goto error;
2204             }
2205             strcpy(*resourceUri, slash);
2206         }
2207         // resource type
2208         if (type && resourceType)
2209         {
2210             *resourceType = (char *)OICMalloc(tlen + 1);
2211             if (!*resourceType)
2212             {
2213                 result = OC_STACK_NO_MEMORY;
2214                 goto error;
2215             }
2216
2217             OICStrcpy(*resourceType, (tlen+1), type);
2218         }
2219     }
2220
2221     return OC_STACK_OK;
2222
2223 error:
2224     // free all returned values
2225     if (devAddr)
2226     {
2227         OICFree(*devAddr);
2228     }
2229     if (resourceUri)
2230     {
2231         OICFree(*resourceUri);
2232     }
2233     if (resourceType)
2234     {
2235         OICFree(*resourceType);
2236     }
2237     return result;
2238 }
2239
2240 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2241                                         char *resourceUri, char **requestUri)
2242 {
2243     char uri[CA_MAX_URI_LENGTH];
2244
2245     FormCanonicalPresenceUri(endpoint, resourceUri, uri);
2246
2247     *requestUri = OICStrdup(uri);
2248     if (!*requestUri)
2249     {
2250         return OC_STACK_NO_MEMORY;
2251     }
2252
2253     return OC_STACK_OK;
2254 }
2255
2256 /**
2257  * Discover or Perform requests on a specified resource
2258  */
2259 OCStackResult OCDoResource(OCDoHandle *handle,
2260                             OCMethod method,
2261                             const char *requestUri,
2262                             const OCDevAddr *destination,
2263                             OCPayload* payload,
2264                             OCConnectivityType connectivityType,
2265                             OCQualityOfService qos,
2266                             OCCallbackData *cbData,
2267                             OCHeaderOption *options,
2268                             uint8_t numOptions)
2269 {
2270     OC_LOG(INFO, TAG, "Entering OCDoResource");
2271
2272     // Validate input parameters
2273     VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2274     VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2275     VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
2276
2277     OCStackResult result = OC_STACK_ERROR;
2278     CAResult_t caResult;
2279     CAToken_t token = NULL;
2280     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2281     ClientCB *clientCB = NULL;
2282     OCDoHandle resHandle = NULL;
2283     CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2284     OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2285     uint32_t ttl = 0;
2286     OCTransportAdapter adapter;
2287     OCTransportFlags flags;
2288     // the request contents are put here
2289     CARequestInfo_t requestInfo = {.method = CA_GET};
2290     // requestUri  will be parsed into the following three variables
2291     OCDevAddr *devAddr = NULL;
2292     char *resourceUri = NULL;
2293     char *resourceType = NULL;
2294
2295     // To track if memory is allocated for additional header options
2296     uint8_t hdrOptionMemAlloc = 0;
2297
2298     // This validation is broken, but doesn't cause harm
2299     size_t uriLen = strlen(requestUri );
2300     if ((result = verifyUriQueryLength(requestUri , uriLen)) != OC_STACK_OK)
2301     {
2302         goto exit;
2303     }
2304
2305     /*
2306      * Support original behavior with address on resourceUri argument.
2307      */
2308     adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2309     flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2310
2311     result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2312
2313     if (result != OC_STACK_OK)
2314     {
2315         OC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2316         goto exit;
2317     }
2318
2319     switch (method)
2320     {
2321     case OC_REST_GET:
2322     case OC_REST_OBSERVE:
2323     case OC_REST_OBSERVE_ALL:
2324     case OC_REST_CANCEL_OBSERVE:
2325         requestInfo.method = CA_GET;
2326         break;
2327     case OC_REST_PUT:
2328         requestInfo.method = CA_PUT;
2329         break;
2330     case OC_REST_POST:
2331         requestInfo.method = CA_POST;
2332         break;
2333     case OC_REST_DELETE:
2334         requestInfo.method = CA_DELETE;
2335         break;
2336     case OC_REST_DISCOVER:
2337         qos = OC_LOW_QOS;
2338         if (destination || devAddr)
2339         {
2340             requestInfo.isMulticast = false;
2341         }
2342         else
2343         {
2344             tmpDevAddr.adapter = adapter;
2345             tmpDevAddr.flags = flags;
2346             destination = &tmpDevAddr;
2347             requestInfo.isMulticast = true;
2348         }
2349         // CA_DISCOVER will become GET and isMulticast
2350         requestInfo.method = CA_GET;
2351         break;
2352 #ifdef WITH_PRESENCE
2353     case OC_REST_PRESENCE:
2354         // Replacing method type with GET because "presence"
2355         // is a stack layer only implementation.
2356         requestInfo.method = CA_GET;
2357         break;
2358 #endif
2359     default:
2360         result = OC_STACK_INVALID_METHOD;
2361         goto exit;
2362     }
2363
2364     if (!devAddr && !destination)
2365     {
2366         OC_LOG(DEBUG, TAG, "no devAddr and no destination");
2367         result = OC_STACK_INVALID_PARAM;
2368         goto exit;
2369     }
2370
2371     /* If not original behavior, use destination argument */
2372     if (destination && !devAddr)
2373     {
2374         devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2375         if (!devAddr)
2376         {
2377             result = OC_STACK_NO_MEMORY;
2378             goto exit;
2379         }
2380         *devAddr = *destination;
2381     }
2382
2383     resHandle = GenerateInvocationHandle();
2384     if (!resHandle)
2385     {
2386         result = OC_STACK_NO_MEMORY;
2387         goto exit;
2388     }
2389
2390     caResult = CAGenerateToken(&token, tokenLength);
2391     if (caResult != CA_STATUS_OK)
2392     {
2393         OC_LOG(ERROR, TAG, "CAGenerateToken error");
2394         result= OC_STACK_ERROR;
2395         goto exit;
2396     }
2397
2398     // fill in request data
2399     requestInfo.info.type = qualityOfServiceToMessageType(qos);
2400     requestInfo.info.token = token;
2401     requestInfo.info.tokenLength = tokenLength;
2402     requestInfo.info.resourceUri = resourceUri;
2403
2404     if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2405     {
2406         result = CreateObserveHeaderOption (&(requestInfo.info.options),
2407                                     options, numOptions, OC_OBSERVE_REGISTER);
2408         if (result != OC_STACK_OK)
2409         {
2410             goto exit;
2411         }
2412         hdrOptionMemAlloc = 1;
2413         requestInfo.info.numOptions = numOptions + 1;
2414     }
2415     else
2416     {
2417         requestInfo.info.options = (CAHeaderOption_t*)options;
2418         requestInfo.info.numOptions = numOptions;
2419     }
2420
2421     CopyDevAddrToEndpoint(devAddr, &endpoint);
2422
2423     if(payload)
2424     {
2425         if((result =
2426             OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2427                 != OC_STACK_OK)
2428         {
2429             OC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2430             goto exit;
2431         }
2432         requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2433     }
2434     else
2435     {
2436         requestInfo.info.payload = NULL;
2437         requestInfo.info.payloadSize = 0;
2438         requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2439     }
2440
2441     if (result != OC_STACK_OK)
2442     {
2443         OC_LOG(ERROR, TAG, "CACreateEndpoint error");
2444         goto exit;
2445     }
2446
2447     // prepare for response
2448 #ifdef WITH_PRESENCE
2449     if (method == OC_REST_PRESENCE)
2450     {
2451         char *presenceUri = NULL;
2452         result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
2453         if (OC_STACK_OK != result)
2454         {
2455             goto exit;
2456         }
2457
2458         // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2459         // Presence notification will form a canonical uri to
2460         // look for callbacks into the application.
2461         resourceUri = presenceUri;
2462     }
2463 #endif
2464
2465     ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2466     result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2467                             method, devAddr, resourceUri, resourceType, ttl);
2468     if (OC_STACK_OK != result)
2469     {
2470         goto exit;
2471     }
2472
2473     devAddr = NULL;       // Client CB list entry now owns it
2474     resourceUri = NULL;   // Client CB list entry now owns it
2475     resourceType = NULL;  // Client CB list entry now owns it
2476
2477     // send request
2478     result = OCSendRequest(&endpoint, &requestInfo);
2479     if (OC_STACK_OK != result)
2480     {
2481         goto exit;
2482     }
2483
2484     if (handle)
2485     {
2486         *handle = resHandle;
2487     }
2488
2489 exit:
2490     if (result != OC_STACK_OK)
2491     {
2492         OC_LOG(ERROR, TAG, "OCDoResource error");
2493         FindAndDeleteClientCB(clientCB);
2494         CADestroyToken(token);
2495         if (handle)
2496         {
2497             *handle = NULL;
2498         }
2499         OICFree(resHandle);
2500     }
2501
2502     // This is the owner of the payload object, so we free it
2503     OCPayloadDestroy(payload);
2504     OICFree(requestInfo.info.payload);
2505     OICFree(devAddr);
2506     OICFree(resourceUri);
2507     OICFree(resourceType);
2508     if (hdrOptionMemAlloc)
2509     {
2510         OICFree(requestInfo.info.options);
2511     }
2512     return result;
2513 }
2514
2515 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2516         uint8_t numOptions)
2517 {
2518     /*
2519      * This ftn is implemented one of two ways in the case of observation:
2520      *
2521      * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2522      *      Remove the callback associated on client side.
2523      *      When the next notification comes in from server,
2524      *      reply with RESET message to server.
2525      *      Keep in mind that the server will react to RESET only
2526      *      if the last notification was sent as CON
2527      *
2528      * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2529      *      and it is associated with an observe request
2530      *      (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2531      *      Send CON Observe request to server with
2532      *      observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2533      *      Remove the callback associated on client side.
2534      */
2535     OCStackResult ret = OC_STACK_OK;
2536     CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2537     CARequestInfo_t requestInfo = {.method = CA_GET};
2538
2539     if(!handle)
2540     {
2541         return OC_STACK_INVALID_PARAM;
2542     }
2543
2544     ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2545     if (!clientCB)
2546     {
2547         OC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2548         return OC_STACK_ERROR;
2549     }
2550
2551     switch (clientCB->method)
2552     {
2553         case OC_REST_OBSERVE:
2554         case OC_REST_OBSERVE_ALL:
2555
2556             OC_LOG_V(INFO, TAG, "Canceling observation for resource %s",
2557                                         clientCB->requestUri);
2558             if (qos != OC_HIGH_QOS)
2559             {
2560                 FindAndDeleteClientCB(clientCB);
2561                 break;
2562             }
2563
2564             OC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2565
2566             requestInfo.info.type = qualityOfServiceToMessageType(qos);
2567             requestInfo.info.token = clientCB->token;
2568             requestInfo.info.tokenLength = clientCB->tokenLength;
2569
2570             if (CreateObserveHeaderOption (&(requestInfo.info.options),
2571                     options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2572             {
2573                 return OC_STACK_ERROR;
2574             }
2575             requestInfo.info.numOptions = numOptions + 1;
2576             requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2577
2578             CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2579
2580             ret = OCSendRequest(&endpoint, &requestInfo);
2581
2582             if (requestInfo.info.options)
2583             {
2584                 OICFree (requestInfo.info.options);
2585             }
2586             if (requestInfo.info.resourceUri)
2587             {
2588                 OICFree (requestInfo.info.resourceUri);
2589             }
2590
2591             break;
2592
2593 #ifdef WITH_PRESENCE
2594         case OC_REST_PRESENCE:
2595             FindAndDeleteClientCB(clientCB);
2596             break;
2597 #endif
2598
2599         default:
2600             ret = OC_STACK_INVALID_METHOD;
2601             break;
2602     }
2603
2604     return ret;
2605 }
2606
2607 /**
2608  * @brief   Register Persistent storage callback.
2609  * @param   persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2610  * @return
2611  *     OC_STACK_OK    - No errors; Success
2612  *     OC_STACK_INVALID_PARAM - Invalid parameter
2613  */
2614 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2615 {
2616     OC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2617     if(!persistentStorageHandler)
2618     {
2619         OC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2620         return OC_STACK_INVALID_PARAM;
2621     }
2622     else
2623     {
2624         if( !persistentStorageHandler->open ||
2625                 !persistentStorageHandler->close ||
2626                 !persistentStorageHandler->read ||
2627                 !persistentStorageHandler->unlink ||
2628                 !persistentStorageHandler->write)
2629         {
2630             OC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2631             return OC_STACK_INVALID_PARAM;
2632         }
2633     }
2634     return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2635 }
2636
2637 #ifdef WITH_PRESENCE
2638
2639 OCStackResult OCProcessPresence()
2640 {
2641     OCStackResult result = OC_STACK_OK;
2642
2643     // the following line floods the log with messages that are irrelevant
2644     // to most purposes.  Uncomment as needed.
2645     //OC_LOG(INFO, TAG, "Entering RequestPresence");
2646     ClientCB* cbNode = NULL;
2647     OCClientResponse clientResponse;
2648     OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2649
2650     LL_FOREACH(cbList, cbNode)
2651     {
2652         if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2653         {
2654             continue;
2655         }
2656
2657         uint32_t now = GetTicks(0);
2658         OC_LOG_V(DEBUG, TAG, "this TTL level %d",
2659                                                 cbNode->presence->TTLlevel);
2660         OC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2661
2662         if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
2663         {
2664             goto exit;
2665         }
2666
2667         if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2668         {
2669             OC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2670                     cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2671         }
2672         if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2673         {
2674             OC_LOG(DEBUG, TAG, "No more timeout ticks");
2675
2676             clientResponse.sequenceNumber = 0;
2677             clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2678             clientResponse.devAddr = *cbNode->devAddr;
2679             FixUpClientResponse(&clientResponse);
2680             clientResponse.payload = NULL;
2681
2682             // Increment the TTLLevel (going to a next state), so we don't keep
2683             // sending presence notification to client.
2684             cbNode->presence->TTLlevel++;
2685             OC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2686                                         cbNode->presence->TTLlevel);
2687
2688             cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2689             if (cbResult == OC_STACK_DELETE_TRANSACTION)
2690             {
2691                 FindAndDeleteClientCB(cbNode);
2692             }
2693         }
2694
2695         if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2696         {
2697             continue;
2698         }
2699
2700         CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2701         CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
2702         CARequestInfo_t requestInfo = {.method = CA_GET};
2703
2704         OC_LOG(DEBUG, TAG, "time to test server presence");
2705
2706         CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
2707
2708         requestData.type = CA_MSG_NONCONFIRM;
2709         requestData.token = cbNode->token;
2710         requestData.tokenLength = cbNode->tokenLength;
2711         requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
2712         requestInfo.method = CA_GET;
2713         requestInfo.info = requestData;
2714
2715         result = OCSendRequest(&endpoint, &requestInfo);
2716         if (OC_STACK_OK != result)
2717         {
2718             goto exit;
2719         }
2720
2721         cbNode->presence->TTLlevel++;
2722         OC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
2723     }
2724 exit:
2725     if (result != OC_STACK_OK)
2726     {
2727         OC_LOG(ERROR, TAG, "OCProcessPresence error");
2728     }
2729
2730     return result;
2731 }
2732 #endif // WITH_PRESENCE
2733
2734 OCStackResult OCProcess()
2735 {
2736 #ifdef WITH_PRESENCE
2737     OCProcessPresence();
2738 #endif
2739     CAHandleRequestResponse();
2740
2741 #ifdef ROUTING_GATEWAY
2742     RMProcess();
2743 #endif
2744     return OC_STACK_OK;
2745 }
2746
2747 #ifdef WITH_PRESENCE
2748 OCStackResult OCStartPresence(const uint32_t ttl)
2749 {
2750     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2751     OCChangeResourceProperty(
2752             &(((OCResource *)presenceResource.handle)->resourceProperties),
2753             OC_ACTIVE, 1);
2754
2755     if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
2756     {
2757         presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
2758         OC_LOG(INFO, TAG, "Setting Presence TTL to max value");
2759     }
2760     else if (0 == ttl)
2761     {
2762         presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
2763         OC_LOG(INFO, TAG, "Setting Presence TTL to default value");
2764     }
2765     else
2766     {
2767         presenceResource.presenceTTL = ttl;
2768     }
2769     OC_LOG_V(DEBUG, TAG, "Presence TTL is %lu seconds", presenceResource.presenceTTL);
2770
2771     if (OC_PRESENCE_UNINITIALIZED == presenceState)
2772     {
2773         presenceState = OC_PRESENCE_INITIALIZED;
2774
2775         OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
2776
2777         CAToken_t caToken = NULL;
2778         CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
2779         if (caResult != CA_STATUS_OK)
2780         {
2781             OC_LOG(ERROR, TAG, "CAGenerateToken error");
2782             CADestroyToken(caToken);
2783             return OC_STACK_ERROR;
2784         }
2785
2786         AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
2787                 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
2788         CADestroyToken(caToken);
2789     }
2790
2791     // Each time OCStartPresence is called
2792     // a different random 32-bit integer number is used
2793     ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2794
2795     return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
2796             OC_PRESENCE_TRIGGER_CREATE);
2797 }
2798
2799 OCStackResult OCStopPresence()
2800 {
2801     OCStackResult result = OC_STACK_ERROR;
2802
2803     if(presenceResource.handle)
2804     {
2805         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2806
2807     // make resource inactive
2808     result = OCChangeResourceProperty(
2809             &(((OCResource *) presenceResource.handle)->resourceProperties),
2810             OC_ACTIVE, 0);
2811     }
2812
2813     if(result != OC_STACK_OK)
2814     {
2815         OC_LOG(ERROR, TAG,
2816                       "Changing the presence resource properties to ACTIVE not successful");
2817         return result;
2818     }
2819
2820     return SendStopNotification();
2821 }
2822 #endif
2823
2824 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
2825                                             void* callbackParameter)
2826 {
2827     defaultDeviceHandler = entityHandler;
2828     defaultDeviceHandlerCallbackParameter = callbackParameter;
2829
2830     return OC_STACK_OK;
2831 }
2832
2833 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
2834 {
2835     OC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
2836
2837     if(myStackMode ==  OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
2838     {
2839         if (validatePlatformInfo(platformInfo))
2840         {
2841             return SavePlatformInfo(platformInfo);
2842         }
2843         else
2844         {
2845             return OC_STACK_INVALID_PARAM;
2846         }
2847     }
2848     else
2849     {
2850         return OC_STACK_ERROR;
2851     }
2852 }
2853
2854 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
2855 {
2856     OC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
2857
2858     if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
2859     {
2860         OC_LOG(ERROR, TAG, "Null or empty device name.");
2861         return OC_STACK_INVALID_PARAM;
2862     }
2863
2864     return SaveDeviceInfo(deviceInfo);
2865 }
2866
2867 OCStackResult OCCreateResource(OCResourceHandle *handle,
2868         const char *resourceTypeName,
2869         const char *resourceInterfaceName,
2870         const char *uri, OCEntityHandler entityHandler,
2871         void* callbackParam,
2872         uint8_t resourceProperties)
2873 {
2874
2875     OCResource *pointer = NULL;
2876     OCStackResult result = OC_STACK_ERROR;
2877
2878     OC_LOG(INFO, TAG, "Entering OCCreateResource");
2879
2880     if(myStackMode == OC_CLIENT)
2881     {
2882         return OC_STACK_INVALID_PARAM;
2883     }
2884     // Validate parameters
2885     if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
2886     {
2887         OC_LOG(ERROR, TAG, "URI is empty or too long");
2888         return OC_STACK_INVALID_URI;
2889     }
2890     // Is it presented during resource discovery?
2891     if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
2892     {
2893         OC_LOG(ERROR, TAG, "Input parameter is NULL");
2894         return OC_STACK_INVALID_PARAM;
2895     }
2896
2897     if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
2898     {
2899         resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
2900     }
2901
2902     // Make sure resourceProperties bitmask has allowed properties specified
2903     if (resourceProperties
2904             > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
2905                OC_EXPLICIT_DISCOVERABLE))
2906     {
2907         OC_LOG(ERROR, TAG, "Invalid property");
2908         return OC_STACK_INVALID_PARAM;
2909     }
2910
2911     // If the headResource is NULL, then no resources have been created...
2912     pointer = headResource;
2913     if (pointer)
2914     {
2915         // At least one resources is in the resource list, so we need to search for
2916         // repeated URLs, which are not allowed.  If a repeat is found, exit with an error
2917         while (pointer)
2918         {
2919             if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
2920             {
2921                 OC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
2922                 return OC_STACK_INVALID_PARAM;
2923             }
2924             pointer = pointer->next;
2925         }
2926     }
2927     // Create the pointer and insert it into the resource list
2928     pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
2929     if (!pointer)
2930     {
2931         result = OC_STACK_NO_MEMORY;
2932         goto exit;
2933     }
2934     pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
2935
2936     insertResource(pointer);
2937
2938     // Set the uri
2939     pointer->uri = OICStrdup(uri);
2940     if (!pointer->uri)
2941     {
2942         result = OC_STACK_NO_MEMORY;
2943         goto exit;
2944     }
2945
2946     // Set properties.  Set OC_ACTIVE
2947     pointer->resourceProperties = (OCResourceProperty) (resourceProperties
2948             | OC_ACTIVE);
2949
2950     // Add the resourcetype to the resource
2951     result = BindResourceTypeToResource(pointer, resourceTypeName);
2952     if (result != OC_STACK_OK)
2953     {
2954         OC_LOG(ERROR, TAG, "Error adding resourcetype");
2955         goto exit;
2956     }
2957
2958     // Add the resourceinterface to the resource
2959     result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
2960     if (result != OC_STACK_OK)
2961     {
2962         OC_LOG(ERROR, TAG, "Error adding resourceinterface");
2963         goto exit;
2964     }
2965
2966     // If an entity handler has been passed, attach it to the newly created
2967     // resource.  Otherwise, set the default entity handler.
2968     if (entityHandler)
2969     {
2970         pointer->entityHandler = entityHandler;
2971         pointer->entityHandlerCallbackParam = callbackParam;
2972     }
2973     else
2974     {
2975         pointer->entityHandler = defaultResourceEHandler;
2976         pointer->entityHandlerCallbackParam = NULL;
2977     }
2978
2979     *handle = pointer;
2980     result = OC_STACK_OK;
2981
2982 #ifdef WITH_PRESENCE
2983     if (presenceResource.handle)
2984     {
2985         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2986         SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
2987     }
2988 #endif
2989 exit:
2990     if (result != OC_STACK_OK)
2991     {
2992         // Deep delete of resource and other dynamic elements that it contains
2993         deleteResource(pointer);
2994     }
2995     return result;
2996 }
2997
2998
2999 OCStackResult OCBindResource(
3000         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3001 {
3002     OCResource *resource = NULL;
3003     uint8_t i = 0;
3004
3005     OC_LOG(INFO, TAG, "Entering OCBindResource");
3006
3007     // Validate parameters
3008     VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3009     VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3010     // Container cannot contain itself
3011     if (collectionHandle == resourceHandle)
3012     {
3013         OC_LOG(ERROR, TAG, "Added handle equals collection handle");
3014         return OC_STACK_INVALID_PARAM;
3015     }
3016
3017     // Use the handle to find the resource in the resource linked list
3018     resource = findResource((OCResource *) collectionHandle);
3019     if (!resource)
3020     {
3021         OC_LOG(ERROR, TAG, "Collection handle not found");
3022         return OC_STACK_INVALID_PARAM;
3023     }
3024
3025     // Look for an open slot to add add the child resource.
3026     // If found, add it and return success
3027     for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
3028     {
3029         if (!resource->rsrcResources[i])
3030         {
3031             resource->rsrcResources[i] = (OCResource *) resourceHandle;
3032             OC_LOG(INFO, TAG, "resource bound");
3033
3034 #ifdef WITH_PRESENCE
3035             if (presenceResource.handle)
3036             {
3037                 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3038                 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3039                         OC_PRESENCE_TRIGGER_CHANGE);
3040             }
3041 #endif
3042             return OC_STACK_OK;
3043
3044         }
3045     }
3046
3047     // Unable to add resourceHandle, so return error
3048     return OC_STACK_ERROR;
3049 }
3050
3051 OCStackResult OCUnBindResource(
3052         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3053 {
3054     OCResource *resource = NULL;
3055     uint8_t i = 0;
3056
3057     OC_LOG(INFO, TAG, "Entering OCUnBindResource");
3058
3059     // Validate parameters
3060     VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3061     VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3062     // Container cannot contain itself
3063     if (collectionHandle == resourceHandle)
3064     {
3065         OC_LOG(ERROR, TAG, "removing handle equals collection handle");
3066         return OC_STACK_INVALID_PARAM;
3067     }
3068
3069     // Use the handle to find the resource in the resource linked list
3070     resource = findResource((OCResource *) collectionHandle);
3071     if (!resource)
3072     {
3073         OC_LOG(ERROR, TAG, "Collection handle not found");
3074         return OC_STACK_INVALID_PARAM;
3075     }
3076
3077     // Look for an open slot to add add the child resource.
3078     // If found, add it and return success
3079     for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
3080     {
3081         if (resourceHandle == resource->rsrcResources[i])
3082         {
3083             resource->rsrcResources[i] = (OCResource *) NULL;
3084             OC_LOG(INFO, TAG, "resource unbound");
3085
3086             // Send notification when resource is unbounded successfully.
3087 #ifdef WITH_PRESENCE
3088             if (presenceResource.handle)
3089             {
3090                 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3091                 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3092                         OC_PRESENCE_TRIGGER_CHANGE);
3093             }
3094 #endif
3095             return OC_STACK_OK;
3096         }
3097     }
3098
3099     OC_LOG(INFO, TAG, "resource not found in collection");
3100
3101     // Unable to add resourceHandle, so return error
3102     return OC_STACK_ERROR;
3103 }
3104
3105 // Precondition is that the parameter has been checked to not equal NULL.
3106 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3107 {
3108     if (resourceItemName[0] < 'a' || resourceItemName[0] > 'z')
3109     {
3110         return false;
3111     }
3112
3113     size_t index = 1;
3114     while (resourceItemName[index] != '\0')
3115     {
3116         if (resourceItemName[index] != '.' &&
3117                 resourceItemName[index] != '-' &&
3118                 (resourceItemName[index] < 'a' || resourceItemName[index] > 'z') &&
3119                 (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3120         {
3121             return false;
3122         }
3123         ++index;
3124     }
3125
3126     return true;
3127 }
3128 OCStackResult BindResourceTypeToResource(OCResource* resource,
3129                                             const char *resourceTypeName)
3130 {
3131     OCResourceType *pointer = NULL;
3132     char *str = NULL;
3133     OCStackResult result = OC_STACK_ERROR;
3134
3135     VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3136
3137     if (!ValidateResourceTypeInterface(resourceTypeName))
3138     {
3139         OC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3140         return OC_STACK_INVALID_PARAM;
3141     }
3142
3143     pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3144     if (!pointer)
3145     {
3146         result = OC_STACK_NO_MEMORY;
3147         goto exit;
3148     }
3149
3150     str = OICStrdup(resourceTypeName);
3151     if (!str)
3152     {
3153         result = OC_STACK_NO_MEMORY;
3154         goto exit;
3155     }
3156     pointer->resourcetypename = str;
3157
3158     insertResourceType(resource, pointer);
3159     result = OC_STACK_OK;
3160
3161     exit:
3162     if (result != OC_STACK_OK)
3163     {
3164         OICFree(pointer);
3165         OICFree(str);
3166     }
3167
3168     return result;
3169 }
3170
3171 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3172         const char *resourceInterfaceName)
3173 {
3174     OCResourceInterface *pointer = NULL;
3175     char *str = NULL;
3176     OCStackResult result = OC_STACK_ERROR;
3177
3178     VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3179
3180     if (!ValidateResourceTypeInterface(resourceInterfaceName))
3181     {
3182         OC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3183         return OC_STACK_INVALID_PARAM;
3184     }
3185
3186     OC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3187
3188     pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3189     if (!pointer)
3190     {
3191         result = OC_STACK_NO_MEMORY;
3192         goto exit;
3193     }
3194
3195     str = OICStrdup(resourceInterfaceName);
3196     if (!str)
3197     {
3198         result = OC_STACK_NO_MEMORY;
3199         goto exit;
3200     }
3201     pointer->name = str;
3202
3203     // Bind the resourceinterface to the resource
3204     insertResourceInterface(resource, pointer);
3205
3206     result = OC_STACK_OK;
3207
3208     exit:
3209     if (result != OC_STACK_OK)
3210     {
3211         OICFree(pointer);
3212         OICFree(str);
3213     }
3214
3215     return result;
3216 }
3217
3218 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3219         const char *resourceTypeName)
3220 {
3221
3222     OCStackResult result = OC_STACK_ERROR;
3223     OCResource *resource = NULL;
3224
3225     resource = findResource((OCResource *) handle);
3226     if (!resource)
3227     {
3228         OC_LOG(ERROR, TAG, "Resource not found");
3229         return OC_STACK_ERROR;
3230     }
3231
3232     result = BindResourceTypeToResource(resource, resourceTypeName);
3233
3234 #ifdef WITH_PRESENCE
3235     if(presenceResource.handle)
3236     {
3237         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3238         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3239     }
3240 #endif
3241
3242     return result;
3243 }
3244
3245 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3246         const char *resourceInterfaceName)
3247 {
3248
3249     OCStackResult result = OC_STACK_ERROR;
3250     OCResource *resource = NULL;
3251
3252     resource = findResource((OCResource *) handle);
3253     if (!resource)
3254     {
3255         OC_LOG(ERROR, TAG, "Resource not found");
3256         return OC_STACK_ERROR;
3257     }
3258
3259     result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3260
3261 #ifdef WITH_PRESENCE
3262     if (presenceResource.handle)
3263     {
3264         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3265         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3266     }
3267 #endif
3268
3269     return result;
3270 }
3271
3272 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3273 {
3274     OCResource *pointer = headResource;
3275
3276     VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3277     *numResources = 0;
3278     while (pointer)
3279     {
3280         *numResources = *numResources + 1;
3281         pointer = pointer->next;
3282     }
3283     return OC_STACK_OK;
3284 }
3285
3286 OCResourceHandle OCGetResourceHandle(uint8_t index)
3287 {
3288     OCResource *pointer = headResource;
3289
3290     for( uint8_t i = 0; i < index && pointer; ++i)
3291     {
3292         pointer = pointer->next;
3293     }
3294     return (OCResourceHandle) pointer;
3295 }
3296
3297 OCStackResult OCDeleteResource(OCResourceHandle handle)
3298 {
3299     if (!handle)
3300     {
3301         OC_LOG(ERROR, TAG, "Invalid handle for deletion");
3302         return OC_STACK_INVALID_PARAM;
3303     }
3304
3305     OCResource *resource = findResource((OCResource *) handle);
3306     if (resource == NULL)
3307     {
3308         OC_LOG(ERROR, TAG, "Resource not found");
3309         return OC_STACK_NO_RESOURCE;
3310     }
3311
3312     if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3313     {
3314         OC_LOG(ERROR, TAG, "Error deleting resource");
3315         return OC_STACK_ERROR;
3316     }
3317
3318     return OC_STACK_OK;
3319 }
3320
3321 const char *OCGetResourceUri(OCResourceHandle handle)
3322 {
3323     OCResource *resource = NULL;
3324
3325     resource = findResource((OCResource *) handle);
3326     if (resource)
3327     {
3328         return resource->uri;
3329     }
3330     return (const char *) NULL;
3331 }
3332
3333 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3334 {
3335     OCResource *resource = NULL;
3336
3337     resource = findResource((OCResource *) handle);
3338     if (resource)
3339     {
3340         return resource->resourceProperties;
3341     }
3342     return (OCResourceProperty)-1;
3343 }
3344
3345 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3346         uint8_t *numResourceTypes)
3347 {
3348     OCResource *resource = NULL;
3349     OCResourceType *pointer = NULL;
3350
3351     VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3352     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3353
3354     *numResourceTypes = 0;
3355
3356     resource = findResource((OCResource *) handle);
3357     if (resource)
3358     {
3359         pointer = resource->rsrcType;
3360         while (pointer)
3361         {
3362             *numResourceTypes = *numResourceTypes + 1;
3363             pointer = pointer->next;
3364         }
3365     }
3366     return OC_STACK_OK;
3367 }
3368
3369 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3370 {
3371     OCResourceType *resourceType = NULL;
3372
3373     resourceType = findResourceTypeAtIndex(handle, index);
3374     if (resourceType)
3375     {
3376         return resourceType->resourcetypename;
3377     }
3378     return (const char *) NULL;
3379 }
3380
3381 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3382         uint8_t *numResourceInterfaces)
3383 {
3384     OCResourceInterface *pointer = NULL;
3385     OCResource *resource = NULL;
3386
3387     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3388     VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3389
3390     *numResourceInterfaces = 0;
3391     resource = findResource((OCResource *) handle);
3392     if (resource)
3393     {
3394         pointer = resource->rsrcInterface;
3395         while (pointer)
3396         {
3397             *numResourceInterfaces = *numResourceInterfaces + 1;
3398             pointer = pointer->next;
3399         }
3400     }
3401     return OC_STACK_OK;
3402 }
3403
3404 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3405 {
3406     OCResourceInterface *resourceInterface = NULL;
3407
3408     resourceInterface = findResourceInterfaceAtIndex(handle, index);
3409     if (resourceInterface)
3410     {
3411         return resourceInterface->name;
3412     }
3413     return (const char *) NULL;
3414 }
3415
3416 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3417         uint8_t index)
3418 {
3419     OCResource *resource = NULL;
3420
3421     if (index >= MAX_CONTAINED_RESOURCES)
3422     {
3423         return NULL;
3424     }
3425
3426     resource = findResource((OCResource *) collectionHandle);
3427     if (!resource)
3428     {
3429         return NULL;
3430     }
3431
3432     return resource->rsrcResources[index];
3433 }
3434
3435 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3436         OCEntityHandler entityHandler,
3437         void* callbackParam)
3438 {
3439     OCResource *resource = NULL;
3440
3441     // Validate parameters
3442     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3443
3444     // Use the handle to find the resource in the resource linked list
3445     resource = findResource((OCResource *)handle);
3446     if (!resource)
3447     {
3448         OC_LOG(ERROR, TAG, "Resource not found");
3449         return OC_STACK_ERROR;
3450     }
3451
3452     // Bind the handler
3453     resource->entityHandler = entityHandler;
3454     resource->entityHandlerCallbackParam = callbackParam;
3455
3456 #ifdef WITH_PRESENCE
3457     if (presenceResource.handle)
3458     {
3459         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3460         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3461     }
3462 #endif
3463
3464     return OC_STACK_OK;
3465 }
3466
3467 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3468 {
3469     OCResource *resource = NULL;
3470
3471     resource = findResource((OCResource *)handle);
3472     if (!resource)
3473     {
3474         OC_LOG(ERROR, TAG, "Resource not found");
3475         return NULL;
3476     }
3477
3478     // Bind the handler
3479     return resource->entityHandler;
3480 }
3481
3482 void incrementSequenceNumber(OCResource * resPtr)
3483 {
3484     // Increment the sequence number
3485     resPtr->sequenceNum += 1;
3486     if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3487     {
3488         resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3489     }
3490     return;
3491 }
3492
3493 #ifdef WITH_PRESENCE
3494 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3495         OCPresenceTrigger trigger)
3496 {
3497     OCResource *resPtr = NULL;
3498     OCStackResult result = OC_STACK_ERROR;
3499     OCMethod method = OC_REST_PRESENCE;
3500     uint32_t maxAge = 0;
3501     resPtr = findResource((OCResource *) presenceResource.handle);
3502     if(NULL == resPtr)
3503     {
3504         return OC_STACK_NO_RESOURCE;
3505     }
3506
3507     if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3508     {
3509         maxAge = presenceResource.presenceTTL;
3510
3511         result = SendAllObserverNotification(method, resPtr, maxAge,
3512                 trigger, resourceType, OC_LOW_QOS);
3513     }
3514
3515     return result;
3516 }
3517
3518 OCStackResult SendStopNotification()
3519 {
3520     OCResource *resPtr = NULL;
3521     OCStackResult result = OC_STACK_ERROR;
3522     OCMethod method = OC_REST_PRESENCE;
3523     resPtr = findResource((OCResource *) presenceResource.handle);
3524     if(NULL == resPtr)
3525     {
3526         return OC_STACK_NO_RESOURCE;
3527     }
3528
3529     // maxAge is 0. ResourceType is NULL.
3530     result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3531             NULL, OC_LOW_QOS);
3532
3533     return result;
3534 }
3535
3536 #endif // WITH_PRESENCE
3537 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3538 {
3539     OCResource *resPtr = NULL;
3540     OCStackResult result = OC_STACK_ERROR;
3541     OCMethod method = OC_REST_NOMETHOD;
3542     uint32_t maxAge = 0;
3543
3544     OC_LOG(INFO, TAG, "Notifying all observers");
3545 #ifdef WITH_PRESENCE
3546     if(handle == presenceResource.handle)
3547     {
3548         return OC_STACK_OK;
3549     }
3550 #endif // WITH_PRESENCE
3551     VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3552
3553     // Verify that the resource exists
3554     resPtr = findResource ((OCResource *) handle);
3555     if (NULL == resPtr)
3556     {
3557         return OC_STACK_NO_RESOURCE;
3558     }
3559     else
3560     {
3561         //only increment in the case of regular observing (not presence)
3562         incrementSequenceNumber(resPtr);
3563         method = OC_REST_OBSERVE;
3564         maxAge = MAX_OBSERVE_AGE;
3565 #ifdef WITH_PRESENCE
3566         result = SendAllObserverNotification (method, resPtr, maxAge,
3567                 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3568 #else
3569         result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3570 #endif
3571         return result;
3572     }
3573 }
3574
3575 OCStackResult
3576 OCNotifyListOfObservers (OCResourceHandle handle,
3577                          OCObservationId  *obsIdList,
3578                          uint8_t          numberOfIds,
3579                          const OCRepPayload       *payload,
3580                          OCQualityOfService qos)
3581 {
3582     OC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
3583
3584     OCResource *resPtr = NULL;
3585     //TODO: we should allow the server to define this
3586     uint32_t maxAge = MAX_OBSERVE_AGE;
3587
3588     VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3589     VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3590     VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
3591
3592     resPtr = findResource ((OCResource *) handle);
3593     if (NULL == resPtr || myStackMode == OC_CLIENT)
3594     {
3595         return OC_STACK_NO_RESOURCE;
3596     }
3597     else
3598     {
3599         incrementSequenceNumber(resPtr);
3600     }
3601     return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3602             payload, maxAge, qos));
3603 }
3604
3605 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3606 {
3607     OCStackResult result = OC_STACK_ERROR;
3608     OCServerRequest *serverRequest = NULL;
3609
3610     OC_LOG(INFO, TAG, "Entering OCDoResponse");
3611
3612     // Validate input parameters
3613     VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3614     VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3615
3616     // Normal response
3617     // Get pointer to request info
3618     serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3619     if(serverRequest)
3620     {
3621         // response handler in ocserverrequest.c. Usually HandleSingleResponse.
3622         result = serverRequest->ehResponseHandler(ehResponse);
3623     }
3624
3625     return result;
3626 }
3627
3628 //-----------------------------------------------------------------------------
3629 // Private internal function definitions
3630 //-----------------------------------------------------------------------------
3631 static OCDoHandle GenerateInvocationHandle()
3632 {
3633     OCDoHandle handle = NULL;
3634     // Generate token here, it will be deleted when the transaction is deleted
3635     handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3636     if (handle)
3637     {
3638         OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3639     }
3640
3641     return handle;
3642 }
3643
3644 #ifdef WITH_PRESENCE
3645 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3646         OCResourceProperty resourceProperties, uint8_t enable)
3647 {
3648     if (!inputProperty)
3649     {
3650         return OC_STACK_INVALID_PARAM;
3651     }
3652     if (resourceProperties
3653             > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
3654     {
3655         OC_LOG(ERROR, TAG, "Invalid property");
3656         return OC_STACK_INVALID_PARAM;
3657     }
3658     if(!enable)
3659     {
3660         *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3661     }
3662     else
3663     {
3664         *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3665     }
3666     return OC_STACK_OK;
3667 }
3668 #endif
3669
3670 OCStackResult initResources()
3671 {
3672     OCStackResult result = OC_STACK_OK;
3673
3674     headResource = NULL;
3675     tailResource = NULL;
3676     // Init Virtual Resources
3677 #ifdef WITH_PRESENCE
3678     presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3679
3680     result = OCCreateResource(&presenceResource.handle,
3681             OC_RSRVD_RESOURCE_TYPE_PRESENCE,
3682             "core.r",
3683             OC_RSRVD_PRESENCE_URI,
3684             NULL,
3685             NULL,
3686             OC_OBSERVABLE);
3687     //make resource inactive
3688     result = OCChangeResourceProperty(
3689             &(((OCResource *) presenceResource.handle)->resourceProperties),
3690             OC_ACTIVE, 0);
3691 #endif
3692
3693     if (result == OC_STACK_OK)
3694     {
3695         result = SRMInitSecureResources();
3696     }
3697
3698     return result;
3699 }
3700
3701 void insertResource(OCResource *resource)
3702 {
3703     if (!headResource)
3704     {
3705         headResource = resource;
3706         tailResource = resource;
3707     }
3708     else
3709     {
3710         tailResource->next = resource;
3711         tailResource = resource;
3712     }
3713     resource->next = NULL;
3714 }
3715
3716 OCResource *findResource(OCResource *resource)
3717 {
3718     OCResource *pointer = headResource;
3719
3720     while (pointer)
3721     {
3722         if (pointer == resource)
3723         {
3724             return resource;
3725         }
3726         pointer = pointer->next;
3727     }
3728     return NULL;
3729 }
3730
3731 void deleteAllResources()
3732 {
3733     OCResource *pointer = headResource;
3734     OCResource *temp = NULL;
3735
3736     while (pointer)
3737     {
3738         temp = pointer->next;
3739 #ifdef WITH_PRESENCE
3740         if (pointer != (OCResource *) presenceResource.handle)
3741         {
3742 #endif // WITH_PRESENCE
3743             deleteResource(pointer);
3744 #ifdef WITH_PRESENCE
3745         }
3746 #endif // WITH_PRESENCE
3747         pointer = temp;
3748     }
3749
3750     SRMDeInitSecureResources();
3751
3752 #ifdef WITH_PRESENCE
3753     // Ensure that the last resource to be deleted is the presence resource. This allows for all
3754     // presence notification attributed to their deletion to be processed.
3755     deleteResource((OCResource *) presenceResource.handle);
3756 #endif // WITH_PRESENCE
3757 }
3758
3759 OCStackResult deleteResource(OCResource *resource)
3760 {
3761     OCResource *prev = NULL;
3762     OCResource *temp = NULL;
3763     if(!resource)
3764     {
3765         OC_LOG(DEBUG,TAG,"resource is NULL");
3766         return OC_STACK_INVALID_PARAM;
3767     }
3768
3769     OC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
3770
3771     temp = headResource;
3772     while (temp)
3773     {
3774         if (temp == resource)
3775         {
3776             // Invalidate all Resource Properties.
3777             resource->resourceProperties = (OCResourceProperty) 0;
3778 #ifdef WITH_PRESENCE
3779             if(resource != (OCResource *) presenceResource.handle)
3780             {
3781 #endif // WITH_PRESENCE
3782                 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
3783 #ifdef WITH_PRESENCE
3784             }
3785
3786             if(presenceResource.handle)
3787             {
3788                 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3789                 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
3790             }
3791 #endif
3792             // Only resource in list.
3793             if (temp == headResource && temp == tailResource)
3794             {
3795                 headResource = NULL;
3796                 tailResource = NULL;
3797             }
3798             // Deleting head.
3799             else if (temp == headResource)
3800             {
3801                 headResource = temp->next;
3802             }
3803             // Deleting tail.
3804             else if (temp == tailResource)
3805             {
3806                 tailResource = prev;
3807                 tailResource->next = NULL;
3808             }
3809             else
3810             {
3811                 prev->next = temp->next;
3812             }
3813
3814             deleteResourceElements(temp);
3815             OICFree(temp);
3816             return OC_STACK_OK;
3817         }
3818         else
3819         {
3820             prev = temp;
3821             temp = temp->next;
3822         }
3823     }
3824
3825     return OC_STACK_ERROR;
3826 }
3827
3828 void deleteResourceElements(OCResource *resource)
3829 {
3830     if (!resource)
3831     {
3832         return;
3833     }
3834
3835     OICFree(resource->uri);
3836     deleteResourceType(resource->rsrcType);
3837     deleteResourceInterface(resource->rsrcInterface);
3838 }
3839
3840 void deleteResourceType(OCResourceType *resourceType)
3841 {
3842     OCResourceType *pointer = resourceType;
3843     OCResourceType *next = NULL;
3844
3845     while (pointer)
3846     {
3847         next = pointer->next;
3848         OICFree(pointer->resourcetypename);
3849         OICFree(pointer);
3850         pointer = next;
3851     }
3852 }
3853
3854 void deleteResourceInterface(OCResourceInterface *resourceInterface)
3855 {
3856     OCResourceInterface *pointer = resourceInterface;
3857     OCResourceInterface *next = NULL;
3858
3859     while (pointer)
3860     {
3861         next = pointer->next;
3862         OICFree(pointer->name);
3863         OICFree(pointer);
3864         pointer = next;
3865     }
3866 }
3867
3868 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
3869 {
3870     OCResourceType *pointer = NULL;
3871     OCResourceType *previous = NULL;
3872     if (!resource || !resourceType)
3873     {
3874         return;
3875     }
3876     // resource type list is empty.
3877     else if (!resource->rsrcType)
3878     {
3879         resource->rsrcType = resourceType;
3880     }
3881     else
3882     {
3883         pointer = resource->rsrcType;
3884
3885         while (pointer)
3886         {
3887             if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
3888             {
3889                 OC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
3890                 OICFree(resourceType->resourcetypename);
3891                 OICFree(resourceType);
3892                 return;
3893             }
3894             previous = pointer;
3895             pointer = pointer->next;
3896         }
3897         previous->next = resourceType;
3898     }
3899     resourceType->next = NULL;
3900
3901     OC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
3902 }
3903
3904 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
3905 {
3906     OCResource *resource = NULL;
3907     OCResourceType *pointer = NULL;
3908
3909     // Find the specified resource
3910     resource = findResource((OCResource *) handle);
3911     if (!resource)
3912     {
3913         return NULL;
3914     }
3915
3916     // Make sure a resource has a resourcetype
3917     if (!resource->rsrcType)
3918     {
3919         return NULL;
3920     }
3921
3922     // Iterate through the list
3923     pointer = resource->rsrcType;
3924     for(uint8_t i = 0; i< index && pointer; ++i)
3925     {
3926         pointer = pointer->next;
3927     }
3928     return pointer;
3929 }
3930
3931 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
3932 {
3933     if(resourceTypeList && resourceTypeName)
3934     {
3935         OCResourceType * rtPointer = resourceTypeList;
3936         while(resourceTypeName && rtPointer)
3937         {
3938             if(rtPointer->resourcetypename &&
3939                     strcmp(resourceTypeName, (const char *)
3940                     (rtPointer->resourcetypename)) == 0)
3941             {
3942                 break;
3943             }
3944             rtPointer = rtPointer->next;
3945         }
3946         return rtPointer;
3947     }
3948     return NULL;
3949 }
3950
3951 /*
3952  * Insert a new interface into interface linked list only if not already present.
3953  * If alredy present, 2nd arg is free'd.
3954  * Default interface will always be first if present.
3955  */
3956 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
3957 {
3958     OCResourceInterface *pointer = NULL;
3959     OCResourceInterface *previous = NULL;
3960
3961     newInterface->next = NULL;
3962
3963     OCResourceInterface **firstInterface = &(resource->rsrcInterface);
3964
3965     if (!*firstInterface)
3966     {
3967         *firstInterface = newInterface;
3968     }
3969     else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
3970     {
3971         if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
3972         {
3973             OICFree(newInterface->name);
3974             OICFree(newInterface);
3975             return;
3976         }
3977         else
3978         {
3979             newInterface->next = *firstInterface;
3980             *firstInterface = newInterface;
3981         }
3982     }
3983     else
3984     {
3985         pointer = *firstInterface;
3986         while (pointer)
3987         {
3988             if (strcmp(newInterface->name, pointer->name) == 0)
3989             {
3990                 OICFree(newInterface->name);
3991                 OICFree(newInterface);
3992                 return;
3993             }
3994             previous = pointer;
3995             pointer = pointer->next;
3996         }
3997         previous->next = newInterface;
3998     }
3999 }
4000
4001 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4002         uint8_t index)
4003 {
4004     OCResource *resource = NULL;
4005     OCResourceInterface *pointer = NULL;
4006
4007     // Find the specified resource
4008     resource = findResource((OCResource *) handle);
4009     if (!resource)
4010     {
4011         return NULL;
4012     }
4013
4014     // Make sure a resource has a resourceinterface
4015     if (!resource->rsrcInterface)
4016     {
4017         return NULL;
4018     }
4019
4020     // Iterate through the list
4021     pointer = resource->rsrcInterface;
4022
4023     for (uint8_t i = 0; i < index && pointer; ++i)
4024     {
4025         pointer = pointer->next;
4026     }
4027     return pointer;
4028 }
4029
4030 /*
4031  * This function splits the uri using the '?' delimiter.
4032  * "uriWithoutQuery" is the block of characters between the beginning
4033  * till the delimiter or '\0' which ever comes first.
4034  * "query" is whatever is to the right of the delimiter if present.
4035  * No delimiter sets the query to NULL.
4036  * If either are present, they will be malloc'ed into the params 2, 3.
4037  * The first param, *uri is left untouched.
4038
4039  * NOTE: This function does not account for whitespace at the end of the uri NOR
4040  *       malformed uri's with '??'. Whitespace at the end will be assumed to be
4041  *       part of the query.
4042  */
4043 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4044 {
4045     if(!uri)
4046     {
4047         return OC_STACK_INVALID_URI;
4048     }
4049     if(!query || !uriWithoutQuery)
4050     {
4051         return OC_STACK_INVALID_PARAM;
4052     }
4053
4054     *query           = NULL;
4055     *uriWithoutQuery = NULL;
4056
4057     size_t uriWithoutQueryLen = 0;
4058     size_t queryLen = 0;
4059     size_t uriLen = strlen(uri);
4060
4061     char *pointerToDelimiter = strstr(uri, "?");
4062
4063     uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4064     queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4065
4066     if (uriWithoutQueryLen)
4067     {
4068         *uriWithoutQuery =  (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4069         if (!*uriWithoutQuery)
4070         {
4071             goto exit;
4072         }
4073         OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4074     }
4075     if (queryLen)
4076     {
4077         *query = (char *) OICCalloc(queryLen + 1, 1);
4078         if (!*query)
4079         {
4080             OICFree(*uriWithoutQuery);
4081             *uriWithoutQuery = NULL;
4082             goto exit;
4083         }
4084         OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4085     }
4086
4087     return OC_STACK_OK;
4088
4089     exit:
4090         return OC_STACK_NO_MEMORY;
4091 }
4092
4093 const OicUuid_t* OCGetServerInstanceID(void)
4094 {
4095     static bool generated = false;
4096     static OicUuid_t sid;
4097     if (generated)
4098     {
4099         return &sid;
4100     }
4101
4102     if (GetDoxmDeviceID(&sid) != OC_STACK_OK)
4103     {
4104         OC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4105         return NULL;
4106     }
4107     generated = true;
4108     return &sid;
4109 }
4110
4111 const char* OCGetServerInstanceIDString(void)
4112 {
4113     static bool generated = false;
4114     static char sidStr[UUID_STRING_SIZE];
4115
4116     if(generated)
4117     {
4118         return sidStr;
4119     }
4120
4121     const OicUuid_t* sid = OCGetServerInstanceID();
4122
4123     if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4124     {
4125         OC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4126         return NULL;
4127     }
4128
4129     generated = true;
4130     return sidStr;
4131 }
4132
4133 CAResult_t OCSelectNetwork()
4134 {
4135     CAResult_t retResult = CA_STATUS_FAILED;
4136     CAResult_t caResult = CA_STATUS_OK;
4137
4138     CATransportAdapter_t connTypes[] = {
4139             CA_ADAPTER_IP,
4140             CA_ADAPTER_RFCOMM_BTEDR,
4141             CA_ADAPTER_GATT_BTLE
4142
4143 #ifdef RA_ADAPTER
4144             ,CA_ADAPTER_REMOTE_ACCESS
4145 #endif
4146         };
4147     int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4148
4149     for(int i = 0; i<numConnTypes; i++)
4150     {
4151         // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
4152         if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
4153         {
4154            caResult = CASelectNetwork(connTypes[i]);
4155            if(caResult == CA_STATUS_OK)
4156            {
4157                retResult = CA_STATUS_OK;
4158            }
4159         }
4160     }
4161
4162     if(retResult != CA_STATUS_OK)
4163     {
4164         return caResult; // Returns error of appropriate transport that failed fatally.
4165     }
4166
4167     return retResult;
4168 }
4169
4170 OCStackResult CAResultToOCResult(CAResult_t caResult)
4171 {
4172     switch (caResult)
4173     {
4174         case CA_STATUS_OK:
4175             return OC_STACK_OK;
4176         case CA_STATUS_INVALID_PARAM:
4177             return OC_STACK_INVALID_PARAM;
4178         case CA_ADAPTER_NOT_ENABLED:
4179             return OC_STACK_ADAPTER_NOT_ENABLED;
4180         case CA_SERVER_STARTED_ALREADY:
4181             return OC_STACK_OK;
4182         case CA_SERVER_NOT_STARTED:
4183             return OC_STACK_ERROR;
4184         case CA_DESTINATION_NOT_REACHABLE:
4185             return OC_STACK_COMM_ERROR;
4186         case CA_SOCKET_OPERATION_FAILED:
4187             return OC_STACK_COMM_ERROR;
4188         case CA_SEND_FAILED:
4189             return OC_STACK_COMM_ERROR;
4190         case CA_RECEIVE_FAILED:
4191             return OC_STACK_COMM_ERROR;
4192         case CA_MEMORY_ALLOC_FAILED:
4193             return OC_STACK_NO_MEMORY;
4194         case CA_REQUEST_TIMEOUT:
4195             return OC_STACK_TIMEOUT;
4196         case CA_DESTINATION_DISCONNECTED:
4197             return OC_STACK_COMM_ERROR;
4198         case CA_STATUS_FAILED:
4199             return OC_STACK_ERROR;
4200         case CA_NOT_SUPPORTED:
4201             return OC_STACK_NOTIMPL;
4202         default:
4203             return OC_STACK_ERROR;
4204     }
4205 }
4206