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