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