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