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