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