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