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