Imported Upstream version 1.1.0
[platform/upstream/iotivity.git] / resource / csdk / stack / src / ocstack.c
1 //******************************************************************
2 //
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
4 //
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
6 //
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
10 //
11 //      http://www.apache.org/licenses/LICENSE-2.0
12 //
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18 //
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20
21
22 //-----------------------------------------------------------------------------
23 // Includes
24 //-----------------------------------------------------------------------------
25
26 // Defining _POSIX_C_SOURCE macro with 200112L (or greater) as value
27 // causes header files to expose definitions
28 // corresponding to the POSIX.1-2001 base
29 // specification (excluding the XSI extension).
30 // For POSIX.1-2001 base specification,
31 // Refer http://pubs.opengroup.org/onlinepubs/009695399/
32 #define _POSIX_C_SOURCE 200112L
33 #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         memcpy (serverRequest.payload, requestInfo->info.payload,
1680                 requestInfo->info.payloadSize);
1681     }
1682     else
1683     {
1684         serverRequest.reqTotalSize = 0;
1685     }
1686
1687     switch (requestInfo->method)
1688     {
1689         case CA_GET:
1690             serverRequest.method = OC_REST_GET;
1691             break;
1692         case CA_PUT:
1693             serverRequest.method = OC_REST_PUT;
1694             break;
1695         case CA_POST:
1696             serverRequest.method = OC_REST_POST;
1697             break;
1698         case CA_DELETE:
1699             serverRequest.method = OC_REST_DELETE;
1700             break;
1701         default:
1702             OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1703             SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1704                         requestInfo->info.type, requestInfo->info.numOptions,
1705                         requestInfo->info.options, requestInfo->info.token,
1706                         requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1707             OICFree(serverRequest.payload);
1708             return;
1709     }
1710
1711     OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1712             requestInfo->info.tokenLength);
1713
1714     serverRequest.tokenLength = requestInfo->info.tokenLength;
1715     if (serverRequest.tokenLength) {
1716         // Non empty token
1717         serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1718
1719         if (!serverRequest.requestToken)
1720         {
1721             OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1722             SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1723                     requestInfo->info.type, requestInfo->info.numOptions,
1724                     requestInfo->info.options, requestInfo->info.token,
1725                     requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1726             OICFree(serverRequest.payload);
1727             return;
1728         }
1729         memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1730     }
1731
1732     switch (requestInfo->info.acceptFormat)
1733     {
1734         case CA_FORMAT_APPLICATION_CBOR:
1735             serverRequest.acceptFormat = OC_FORMAT_CBOR;
1736             break;
1737         case CA_FORMAT_UNDEFINED:
1738             serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1739             break;
1740         default:
1741             serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1742     }
1743
1744     if (requestInfo->info.type == CA_MSG_CONFIRM)
1745     {
1746         serverRequest.qos = OC_HIGH_QOS;
1747     }
1748     else
1749     {
1750         serverRequest.qos = OC_LOW_QOS;
1751     }
1752     // CA does not need the following field
1753     // Are we sure CA does not need them? how is it responding to multicast
1754     serverRequest.delayedResNeeded = 0;
1755
1756     serverRequest.coapID = requestInfo->info.messageId;
1757
1758     CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1759
1760     // copy vendor specific header options
1761     uint8_t tempNum = (requestInfo->info.numOptions);
1762
1763     // Assume no observation requested and it is a pure GET.
1764     // If obs registration/de-registration requested it'll be fetched from the
1765     // options in GetObserveHeaderOption()
1766     serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1767
1768     GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1769     if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1770     {
1771         OIC_LOG(ERROR, TAG,
1772                 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1773         SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1774                 requestInfo->info.type, requestInfo->info.numOptions,
1775                 requestInfo->info.options, requestInfo->info.token,
1776                 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1777         OICFree(serverRequest.payload);
1778         OICFree(serverRequest.requestToken);
1779         return;
1780     }
1781     serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1782     if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1783     {
1784         memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1785             sizeof(CAHeaderOption_t)*tempNum);
1786     }
1787
1788     requestResult = HandleStackRequests (&serverRequest);
1789
1790     // Send ACK to client as precursor to slow response
1791     if (requestResult == OC_STACK_SLOW_RESOURCE)
1792     {
1793         if (requestInfo->info.type == CA_MSG_CONFIRM)
1794         {
1795             SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1796                                     CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL);
1797         }
1798     }
1799     else if(requestResult != OC_STACK_OK)
1800     {
1801         OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1802
1803         CAResponseResult_t stackResponse =
1804             OCToCAStackResult(requestResult, serverRequest.method);
1805
1806         SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1807                 requestInfo->info.type, requestInfo->info.numOptions,
1808                 requestInfo->info.options, requestInfo->info.token,
1809                 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1810     }
1811     // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1812     // The token is copied in there, and is thus still owned by this function.
1813     OICFree(serverRequest.payload);
1814     OICFree(serverRequest.requestToken);
1815     OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
1816 }
1817
1818 //This function will be called back by CA layer when a request is received
1819 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1820 {
1821     OIC_LOG(INFO, TAG, "Enter HandleCARequests");
1822     if(!endPoint)
1823     {
1824         OIC_LOG(ERROR, TAG, "endPoint is NULL");
1825         return;
1826     }
1827
1828     if(!requestInfo)
1829     {
1830         OIC_LOG(ERROR, TAG, "requestInfo is NULL");
1831         return;
1832     }
1833
1834 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1835 #ifdef ROUTING_GATEWAY
1836     bool needRIHandling = false;
1837     bool isEmptyMsg = false;
1838     /*
1839      * Routing manager is going to update either of endpoint or request or both.
1840      * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
1841      * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1842      * destination. It can also remove "RM" coap header option before passing request / response to
1843      * RI as this option will make no sense to either RI or application.
1844      */
1845     OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
1846                                         &needRIHandling, &isEmptyMsg);
1847     if(OC_STACK_OK != ret || !needRIHandling)
1848     {
1849         OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1850         return;
1851     }
1852 #endif
1853
1854     /*
1855      * Put source in sender endpoint so that the next packet from application can be routed to
1856      * proper destination and remove RM header option.
1857      */
1858     RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
1859                  (uint8_t *) &(requestInfo->info.numOptions),
1860                  (CAEndpoint_t *) endPoint);
1861
1862 #ifdef ROUTING_GATEWAY
1863     if (isEmptyMsg)
1864     {
1865         /*
1866          * In Gateways, the MSGType in route option is used to check if the actual
1867          * response is EMPTY message(4 bytes CoAP Header).  In case of Client, the
1868          * EMPTY response is sent in the form of POST request which need to be changed
1869          * to a EMPTY response by RM.  This translation is done in this part of the code.
1870          */
1871         OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
1872         CAResponseInfo_t respInfo = {.result = CA_EMPTY,
1873                                      .info.messageId = requestInfo->info.messageId,
1874                                      .info.type = CA_MSG_ACKNOWLEDGE};
1875         OCHandleResponse(endPoint, &respInfo);
1876     }
1877     else
1878 #endif
1879 #endif
1880     {
1881         // Normal handling of the packet
1882         OCHandleRequests(endPoint, requestInfo);
1883     }
1884     OIC_LOG(INFO, TAG, "Exit HandleCARequests");
1885 }
1886
1887 bool validatePlatformInfo(OCPlatformInfo info)
1888 {
1889
1890     if (!info.platformID)
1891     {
1892         OIC_LOG(ERROR, TAG, "No platform ID found.");
1893         return false;
1894     }
1895
1896     if (info.manufacturerName)
1897     {
1898         size_t lenManufacturerName = strlen(info.manufacturerName);
1899
1900         if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
1901         {
1902             OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
1903             return false;
1904         }
1905     }
1906     else
1907     {
1908         OIC_LOG(ERROR, TAG, "No manufacturer name present");
1909         return false;
1910     }
1911
1912     if (info.manufacturerUrl)
1913     {
1914         if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
1915         {
1916             OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
1917             return false;
1918         }
1919     }
1920     return true;
1921 }
1922
1923 //-----------------------------------------------------------------------------
1924 // Public APIs
1925 //-----------------------------------------------------------------------------
1926 #ifdef RA_ADAPTER
1927 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
1928 {
1929     if (!raInfo           ||
1930         !raInfo->username ||
1931         !raInfo->hostname ||
1932         !raInfo->xmpp_domain)
1933     {
1934
1935         return OC_STACK_INVALID_PARAM;
1936     }
1937     OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
1938     gRASetInfo = (result == OC_STACK_OK)? true : false;
1939
1940     return result;
1941 }
1942 #endif
1943
1944 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1945 {
1946     (void) ipAddr;
1947     (void) port;
1948     return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
1949 }
1950
1951 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
1952 {
1953     if(stackState == OC_STACK_INITIALIZED)
1954     {
1955         OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
1956                 OCStop() between them are ignored.");
1957         return OC_STACK_OK;
1958     }
1959
1960 #ifndef ROUTING_GATEWAY
1961     if (OC_GATEWAY == mode)
1962     {
1963         OIC_LOG(ERROR, TAG, "Routing Manager not supported");
1964         return OC_STACK_INVALID_PARAM;
1965     }
1966 #endif
1967
1968 #ifdef RA_ADAPTER
1969     if(!gRASetInfo)
1970     {
1971         OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
1972         return OC_STACK_ERROR;
1973     }
1974 #endif
1975
1976     OCStackResult result = OC_STACK_ERROR;
1977     OIC_LOG(INFO, TAG, "Entering OCInit");
1978
1979     // Validate mode
1980     if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
1981         || (mode == OC_GATEWAY)))
1982     {
1983         OIC_LOG(ERROR, TAG, "Invalid mode");
1984         return OC_STACK_ERROR;
1985     }
1986     myStackMode = mode;
1987
1988     if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
1989     {
1990         caglobals.client = true;
1991     }
1992     if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
1993     {
1994         caglobals.server = true;
1995     }
1996
1997     caglobals.serverFlags = (CATransportFlags_t)serverFlags;
1998     if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
1999     {
2000         caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2001     }
2002     caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2003     if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2004     {
2005         caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2006     }
2007
2008     defaultDeviceHandler = NULL;
2009     defaultDeviceHandlerCallbackParameter = NULL;
2010
2011     result = CAResultToOCResult(CAInitialize());
2012     VERIFY_SUCCESS(result, OC_STACK_OK);
2013
2014     result = CAResultToOCResult(OCSelectNetwork());
2015     VERIFY_SUCCESS(result, OC_STACK_OK);
2016
2017     switch (myStackMode)
2018     {
2019         case OC_CLIENT:
2020             CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2021             result = CAResultToOCResult(CAStartDiscoveryServer());
2022             OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2023             break;
2024         case OC_SERVER:
2025             SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2026             result = CAResultToOCResult(CAStartListeningServer());
2027             OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2028             break;
2029         case OC_CLIENT_SERVER:
2030         case OC_GATEWAY:
2031             SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2032             result = CAResultToOCResult(CAStartListeningServer());
2033             if(result == OC_STACK_OK)
2034             {
2035                 result = CAResultToOCResult(CAStartDiscoveryServer());
2036             }
2037             break;
2038     }
2039     VERIFY_SUCCESS(result, OC_STACK_OK);
2040
2041 #ifdef TCP_ADAPTER
2042     CARegisterKeepAliveHandler(HandleKeepAliveConnCB, HandleKeepAliveDisconnCB);
2043 #endif
2044
2045 #ifdef WITH_PRESENCE
2046     PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2047 #endif // WITH_PRESENCE
2048
2049     //Update Stack state to initialized
2050     stackState = OC_STACK_INITIALIZED;
2051
2052     // Initialize resource
2053     if(myStackMode != OC_CLIENT)
2054     {
2055         result = initResources();
2056     }
2057
2058     // Initialize the SRM Policy Engine
2059     if(result == OC_STACK_OK)
2060     {
2061         result = SRMInitPolicyEngine();
2062         // TODO after BeachHead delivery: consolidate into single SRMInit()
2063     }
2064 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2065     RMSetStackMode(mode);
2066 #ifdef ROUTING_GATEWAY
2067     if (OC_GATEWAY == myStackMode)
2068     {
2069         result = RMInitialize();
2070     }
2071 #endif
2072 #endif
2073
2074 #ifdef TCP_ADAPTER
2075     if(result == OC_STACK_OK)
2076     {
2077         result = InitializeKeepAlive(myStackMode);
2078     }
2079 #endif
2080
2081 exit:
2082     if(result != OC_STACK_OK)
2083     {
2084         OIC_LOG(ERROR, TAG, "Stack initialization error");
2085         deleteAllResources();
2086         CATerminate();
2087         stackState = OC_STACK_UNINITIALIZED;
2088     }
2089     return result;
2090 }
2091
2092 OCStackResult OCStop()
2093 {
2094     OIC_LOG(INFO, TAG, "Entering OCStop");
2095
2096     if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2097     {
2098         OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2099         return OC_STACK_OK;
2100     }
2101     else if (stackState != OC_STACK_INITIALIZED)
2102     {
2103         OIC_LOG(ERROR, TAG, "Stack not initialized");
2104         return OC_STACK_ERROR;
2105     }
2106
2107     stackState = OC_STACK_UNINIT_IN_PROGRESS;
2108
2109 #ifdef WITH_PRESENCE
2110     // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2111     // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2112     presenceResource.presenceTTL = 0;
2113 #endif // WITH_PRESENCE
2114
2115 #ifdef ROUTING_GATEWAY
2116     if (OC_GATEWAY == myStackMode)
2117     {
2118         RMTerminate();
2119     }
2120 #endif
2121
2122 #ifdef TCP_ADAPTER
2123     TerminateKeepAlive(myStackMode);
2124 #endif
2125
2126     // Free memory dynamically allocated for resources
2127     deleteAllResources();
2128     DeleteDeviceInfo();
2129     DeletePlatformInfo();
2130     CATerminate();
2131     // Remove all observers
2132     DeleteObserverList();
2133     // Remove all the client callbacks
2134     DeleteClientCBList();
2135
2136     // De-init the SRM Policy Engine
2137     // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2138     SRMDeInitPolicyEngine();
2139
2140
2141     stackState = OC_STACK_UNINITIALIZED;
2142     return OC_STACK_OK;
2143 }
2144
2145 OCStackResult OCStartMulticastServer()
2146 {
2147     if(stackState != OC_STACK_INITIALIZED)
2148     {
2149         OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2150         return OC_STACK_ERROR;
2151     }
2152     CAResult_t ret = CAStartListeningServer();
2153     if (CA_STATUS_OK != ret)
2154     {
2155         OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2156         return OC_STACK_ERROR;
2157     }
2158     return OC_STACK_OK;
2159 }
2160
2161 OCStackResult OCStopMulticastServer()
2162 {
2163     CAResult_t ret = CAStopListeningServer();
2164     if (CA_STATUS_OK != ret)
2165     {
2166         OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2167         return OC_STACK_ERROR;
2168     }
2169     return OC_STACK_OK;
2170 }
2171
2172 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2173 {
2174     switch (qos)
2175     {
2176         case OC_HIGH_QOS:
2177             return CA_MSG_CONFIRM;
2178         case OC_LOW_QOS:
2179         case OC_MEDIUM_QOS:
2180         case OC_NA_QOS:
2181         default:
2182             return CA_MSG_NONCONFIRM;
2183     }
2184 }
2185
2186 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
2187 {
2188     char *query;
2189
2190     query = strchr (inputUri, '?');
2191
2192     if (query != NULL)
2193     {
2194         if((query - inputUri) > MAX_URI_LENGTH)
2195         {
2196             return OC_STACK_INVALID_URI;
2197         }
2198
2199         if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
2200         {
2201             return OC_STACK_INVALID_QUERY;
2202         }
2203     }
2204     else if(uriLen > MAX_URI_LENGTH)
2205     {
2206         return OC_STACK_INVALID_URI;
2207     }
2208     return OC_STACK_OK;
2209 }
2210
2211 /**
2212  *  A request uri consists of the following components in order:
2213  *                              example
2214  *  optionally one of
2215  *      CoAP over UDP prefix    "coap://"
2216  *      CoAP over TCP prefix    "coap+tcp://"
2217  *  optionally one of
2218  *      IPv6 address            "[1234::5678]"
2219  *      IPv4 address            "192.168.1.1"
2220  *  optional port               ":5683"
2221  *  resource uri                "/oc/core..."
2222  *
2223  *  for PRESENCE requests, extract resource type.
2224  */
2225 static OCStackResult ParseRequestUri(const char *fullUri,
2226                                         OCTransportAdapter adapter,
2227                                         OCTransportFlags flags,
2228                                         OCDevAddr **devAddr,
2229                                         char **resourceUri,
2230                                         char **resourceType)
2231 {
2232     VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2233
2234     OCStackResult result = OC_STACK_OK;
2235     OCDevAddr *da = NULL;
2236     char *colon = NULL;
2237     char *end;
2238
2239     // provide defaults for all returned values
2240     if (devAddr)
2241     {
2242         *devAddr = NULL;
2243     }
2244     if (resourceUri)
2245     {
2246         *resourceUri = NULL;
2247     }
2248     if (resourceType)
2249     {
2250         *resourceType = NULL;
2251     }
2252
2253     // delimit url prefix, if any
2254     const char *start = fullUri;
2255     char *slash2 = strstr(start, "//");
2256     if (slash2)
2257     {
2258         start = slash2 + 2;
2259     }
2260     char *slash = strchr(start, '/');
2261     if (!slash)
2262     {
2263         return OC_STACK_INVALID_URI;
2264     }
2265
2266     // process url scheme
2267     size_t prefixLen = slash2 - fullUri;
2268     bool istcp = false;
2269     if (prefixLen)
2270     {
2271         if ((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
2272         {
2273             istcp = true;
2274         }
2275     }
2276
2277     // TODO: this logic should come in with unit tests exercising the various strings
2278     // processs url prefix, if any
2279     size_t urlLen = slash - start;
2280     // port
2281     uint16_t port = 0;
2282     size_t len = 0;
2283     if (urlLen && devAddr)
2284     {   // construct OCDevAddr
2285         if (start[0] == '[')
2286         {   // ipv6 address
2287             char *close = strchr(++start, ']');
2288             if (!close || close > slash)
2289             {
2290                 return OC_STACK_INVALID_URI;
2291             }
2292             end = close;
2293             if (close[1] == ':')
2294             {
2295                 colon = close + 1;
2296             }
2297             adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2298             flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2299         }
2300         else
2301         {
2302             char *dot = strchr(start, '.');
2303             if (dot && dot < slash)
2304             {   // ipv4 address
2305                 colon = strchr(start, ':');
2306                 end = (colon && colon < slash) ? colon : slash;
2307
2308                 if (istcp)
2309                 {   // coap over tcp
2310                     adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2311                 }
2312                 else
2313                 {
2314                     adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2315                     flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2316                 }
2317             }
2318             else
2319             {   // MAC address
2320                 end = slash;
2321             }
2322         }
2323         len = end - start;
2324         if (len >= sizeof(da->addr))
2325         {
2326             return OC_STACK_INVALID_URI;
2327         }
2328         // collect port, if any
2329         if (colon && colon < slash)
2330         {
2331             for (colon++; colon < slash; colon++)
2332             {
2333                 char c = colon[0];
2334                 if (c < '0' || c > '9')
2335                 {
2336                     return OC_STACK_INVALID_URI;
2337                 }
2338                 port = 10 * port + c - '0';
2339             }
2340         }
2341
2342         len = end - start;
2343         if (len >= sizeof(da->addr))
2344         {
2345             return OC_STACK_INVALID_URI;
2346         }
2347
2348         da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2349         if (!da)
2350         {
2351             return OC_STACK_NO_MEMORY;
2352         }
2353         OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2354         da->port = port;
2355         da->adapter = adapter;
2356         da->flags = flags;
2357         if (!strncmp(fullUri, "coaps:", 6))
2358         {
2359             da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2360         }
2361         *devAddr = da;
2362     }
2363
2364     // process resource uri, if any
2365     if (slash)
2366     {   // request uri and query
2367         size_t ulen = strlen(slash); // resource uri length
2368         size_t tlen = 0;      // resource type length
2369         char *type = NULL;
2370
2371         static const char strPresence[] = "/oic/ad?rt=";
2372         static const size_t lenPresence = sizeof(strPresence) - 1;
2373         if (!strncmp(slash, strPresence, lenPresence))
2374         {
2375             type = slash + lenPresence;
2376             tlen = ulen - lenPresence;
2377         }
2378         // resource uri
2379         if (resourceUri)
2380         {
2381             *resourceUri = (char *)OICMalloc(ulen + 1);
2382             if (!*resourceUri)
2383             {
2384                 result = OC_STACK_NO_MEMORY;
2385                 goto error;
2386             }
2387             strcpy(*resourceUri, slash);
2388         }
2389         // resource type
2390         if (type && resourceType)
2391         {
2392             *resourceType = (char *)OICMalloc(tlen + 1);
2393             if (!*resourceType)
2394             {
2395                 result = OC_STACK_NO_MEMORY;
2396                 goto error;
2397             }
2398
2399             OICStrcpy(*resourceType, (tlen+1), type);
2400         }
2401     }
2402
2403     return OC_STACK_OK;
2404
2405 error:
2406     // free all returned values
2407     if (devAddr)
2408     {
2409         OICFree(*devAddr);
2410     }
2411     if (resourceUri)
2412     {
2413         OICFree(*resourceUri);
2414     }
2415     if (resourceType)
2416     {
2417         OICFree(*resourceType);
2418     }
2419     return result;
2420 }
2421
2422 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2423                                         char *resourceUri, char **requestUri)
2424 {
2425     char uri[CA_MAX_URI_LENGTH];
2426
2427     FormCanonicalPresenceUri(endpoint, resourceUri, uri);
2428
2429     *requestUri = OICStrdup(uri);
2430     if (!*requestUri)
2431     {
2432         return OC_STACK_NO_MEMORY;
2433     }
2434
2435     return OC_STACK_OK;
2436 }
2437
2438 /**
2439  * Discover or Perform requests on a specified resource
2440  */
2441 OCStackResult OCDoResource(OCDoHandle *handle,
2442                             OCMethod method,
2443                             const char *requestUri,
2444                             const OCDevAddr *destination,
2445                             OCPayload* payload,
2446                             OCConnectivityType connectivityType,
2447                             OCQualityOfService qos,
2448                             OCCallbackData *cbData,
2449                             OCHeaderOption *options,
2450                             uint8_t numOptions)
2451 {
2452     OIC_LOG(INFO, TAG, "Entering OCDoResource");
2453
2454     // Validate input parameters
2455     VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2456     VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2457     VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
2458
2459     OCStackResult result = OC_STACK_ERROR;
2460     CAResult_t caResult;
2461     CAToken_t token = NULL;
2462     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2463     ClientCB *clientCB = NULL;
2464     OCDoHandle resHandle = NULL;
2465     CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2466     OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2467     uint32_t ttl = 0;
2468     OCTransportAdapter adapter;
2469     OCTransportFlags flags;
2470     // the request contents are put here
2471     CARequestInfo_t requestInfo = {.method = CA_GET};
2472     // requestUri  will be parsed into the following three variables
2473     OCDevAddr *devAddr = NULL;
2474     char *resourceUri = NULL;
2475     char *resourceType = NULL;
2476
2477     /*
2478      * Support original behavior with address on resourceUri argument.
2479      */
2480     adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2481     flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2482
2483     result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2484
2485     if (result != OC_STACK_OK)
2486     {
2487         OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2488         goto exit;
2489     }
2490
2491     switch (method)
2492     {
2493     case OC_REST_GET:
2494     case OC_REST_OBSERVE:
2495     case OC_REST_OBSERVE_ALL:
2496     case OC_REST_CANCEL_OBSERVE:
2497         requestInfo.method = CA_GET;
2498         break;
2499     case OC_REST_PUT:
2500         requestInfo.method = CA_PUT;
2501         break;
2502     case OC_REST_POST:
2503         requestInfo.method = CA_POST;
2504         break;
2505     case OC_REST_DELETE:
2506         requestInfo.method = CA_DELETE;
2507         break;
2508     case OC_REST_DISCOVER:
2509         qos = OC_LOW_QOS;
2510         if (destination || devAddr)
2511         {
2512             requestInfo.isMulticast = false;
2513         }
2514         else
2515         {
2516             tmpDevAddr.adapter = adapter;
2517             tmpDevAddr.flags = flags;
2518             destination = &tmpDevAddr;
2519             requestInfo.isMulticast = true;
2520         }
2521         // CA_DISCOVER will become GET and isMulticast
2522         requestInfo.method = CA_GET;
2523         break;
2524 #ifdef WITH_PRESENCE
2525     case OC_REST_PRESENCE:
2526         // Replacing method type with GET because "presence"
2527         // is a stack layer only implementation.
2528         requestInfo.method = CA_GET;
2529         break;
2530 #endif
2531     default:
2532         result = OC_STACK_INVALID_METHOD;
2533         goto exit;
2534     }
2535
2536     if (!devAddr && !destination)
2537     {
2538         OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2539         result = OC_STACK_INVALID_PARAM;
2540         goto exit;
2541     }
2542
2543     /* If not original behavior, use destination argument */
2544     if (destination && !devAddr)
2545     {
2546         devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2547         if (!devAddr)
2548         {
2549             result = OC_STACK_NO_MEMORY;
2550             goto exit;
2551         }
2552         *devAddr = *destination;
2553     }
2554
2555     resHandle = GenerateInvocationHandle();
2556     if (!resHandle)
2557     {
2558         result = OC_STACK_NO_MEMORY;
2559         goto exit;
2560     }
2561
2562     caResult = CAGenerateToken(&token, tokenLength);
2563     if (caResult != CA_STATUS_OK)
2564     {
2565         OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2566         result= OC_STACK_ERROR;
2567         goto exit;
2568     }
2569
2570     // fill in request data
2571     requestInfo.info.type = qualityOfServiceToMessageType(qos);
2572     requestInfo.info.token = token;
2573     requestInfo.info.tokenLength = tokenLength;
2574     requestInfo.info.resourceUri = resourceUri;
2575
2576     if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2577     {
2578         result = CreateObserveHeaderOption (&(requestInfo.info.options),
2579                                     options, numOptions, OC_OBSERVE_REGISTER);
2580         if (result != OC_STACK_OK)
2581         {
2582             goto exit;
2583         }
2584         requestInfo.info.numOptions = numOptions + 1;
2585     }
2586     else
2587     {
2588         requestInfo.info.numOptions = numOptions;
2589         requestInfo.info.options =
2590             (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2591         memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2592                numOptions * sizeof(CAHeaderOption_t));
2593     }
2594
2595     CopyDevAddrToEndpoint(devAddr, &endpoint);
2596
2597     if(payload)
2598     {
2599         if((result =
2600             OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2601                 != OC_STACK_OK)
2602         {
2603             OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2604             goto exit;
2605         }
2606         requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2607     }
2608     else
2609     {
2610         requestInfo.info.payload = NULL;
2611         requestInfo.info.payloadSize = 0;
2612         requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2613     }
2614
2615     if (result != OC_STACK_OK)
2616     {
2617         OIC_LOG(ERROR, TAG, "CACreateEndpoint error");
2618         goto exit;
2619     }
2620
2621     // prepare for response
2622 #ifdef WITH_PRESENCE
2623     if (method == OC_REST_PRESENCE)
2624     {
2625         char *presenceUri = NULL;
2626         result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
2627         if (OC_STACK_OK != result)
2628         {
2629             goto exit;
2630         }
2631
2632         // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2633         // Presence notification will form a canonical uri to
2634         // look for callbacks into the application.
2635         resourceUri = presenceUri;
2636     }
2637 #endif
2638
2639     ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2640     result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2641                             method, devAddr, resourceUri, resourceType, ttl);
2642     if (OC_STACK_OK != result)
2643     {
2644         goto exit;
2645     }
2646
2647     devAddr = NULL;       // Client CB list entry now owns it
2648     resourceUri = NULL;   // Client CB list entry now owns it
2649     resourceType = NULL;  // Client CB list entry now owns it
2650
2651     // send request
2652     result = OCSendRequest(&endpoint, &requestInfo);
2653     if (OC_STACK_OK != result)
2654     {
2655         goto exit;
2656     }
2657
2658     if (handle)
2659     {
2660         *handle = resHandle;
2661     }
2662
2663 exit:
2664     if (result != OC_STACK_OK)
2665     {
2666         OIC_LOG(ERROR, TAG, "OCDoResource error");
2667         FindAndDeleteClientCB(clientCB);
2668         CADestroyToken(token);
2669         if (handle)
2670         {
2671             *handle = NULL;
2672         }
2673         OICFree(resHandle);
2674     }
2675
2676     // This is the owner of the payload object, so we free it
2677     OCPayloadDestroy(payload);
2678     OICFree(requestInfo.info.payload);
2679     OICFree(devAddr);
2680     OICFree(resourceUri);
2681     OICFree(resourceType);
2682     OICFree(requestInfo.info.options);
2683     return result;
2684 }
2685
2686 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2687         uint8_t numOptions)
2688 {
2689     /*
2690      * This ftn is implemented one of two ways in the case of observation:
2691      *
2692      * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2693      *      Remove the callback associated on client side.
2694      *      When the next notification comes in from server,
2695      *      reply with RESET message to server.
2696      *      Keep in mind that the server will react to RESET only
2697      *      if the last notification was sent as CON
2698      *
2699      * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2700      *      and it is associated with an observe request
2701      *      (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2702      *      Send CON Observe request to server with
2703      *      observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2704      *      Remove the callback associated on client side.
2705      */
2706     OCStackResult ret = OC_STACK_OK;
2707     CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2708     CARequestInfo_t requestInfo = {.method = CA_GET};
2709
2710     if(!handle)
2711     {
2712         return OC_STACK_INVALID_PARAM;
2713     }
2714
2715     ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2716     if (!clientCB)
2717     {
2718         OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2719         return OC_STACK_ERROR;
2720     }
2721
2722     switch (clientCB->method)
2723     {
2724         case OC_REST_OBSERVE:
2725         case OC_REST_OBSERVE_ALL:
2726
2727             OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s",
2728                                         clientCB->requestUri);
2729             if (qos != OC_HIGH_QOS)
2730             {
2731                 FindAndDeleteClientCB(clientCB);
2732                 break;
2733             }
2734
2735             OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2736
2737             requestInfo.info.type = qualityOfServiceToMessageType(qos);
2738             requestInfo.info.token = clientCB->token;
2739             requestInfo.info.tokenLength = clientCB->tokenLength;
2740
2741             if (CreateObserveHeaderOption (&(requestInfo.info.options),
2742                     options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2743             {
2744                 return OC_STACK_ERROR;
2745             }
2746             requestInfo.info.numOptions = numOptions + 1;
2747             requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2748
2749             CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2750
2751             ret = OCSendRequest(&endpoint, &requestInfo);
2752
2753             if (requestInfo.info.options)
2754             {
2755                 OICFree (requestInfo.info.options);
2756             }
2757             if (requestInfo.info.resourceUri)
2758             {
2759                 OICFree (requestInfo.info.resourceUri);
2760             }
2761
2762             break;
2763
2764         case OC_REST_DISCOVER:
2765             OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2766                                            clientCB->requestUri);
2767             FindAndDeleteClientCB(clientCB);
2768             break;
2769
2770 #ifdef WITH_PRESENCE
2771         case OC_REST_PRESENCE:
2772             FindAndDeleteClientCB(clientCB);
2773             break;
2774 #endif
2775
2776         default:
2777             ret = OC_STACK_INVALID_METHOD;
2778             break;
2779     }
2780
2781     return ret;
2782 }
2783
2784 /**
2785  * @brief   Register Persistent storage callback.
2786  * @param   persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2787  * @return
2788  *     OC_STACK_OK    - No errors; Success
2789  *     OC_STACK_INVALID_PARAM - Invalid parameter
2790  */
2791 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2792 {
2793     OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2794     if(!persistentStorageHandler)
2795     {
2796         OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2797         return OC_STACK_INVALID_PARAM;
2798     }
2799     else
2800     {
2801         if( !persistentStorageHandler->open ||
2802                 !persistentStorageHandler->close ||
2803                 !persistentStorageHandler->read ||
2804                 !persistentStorageHandler->unlink ||
2805                 !persistentStorageHandler->write)
2806         {
2807             OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2808             return OC_STACK_INVALID_PARAM;
2809         }
2810     }
2811     return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2812 }
2813
2814 #ifdef WITH_PRESENCE
2815
2816 OCStackResult OCProcessPresence()
2817 {
2818     OCStackResult result = OC_STACK_OK;
2819
2820     // the following line floods the log with messages that are irrelevant
2821     // to most purposes.  Uncomment as needed.
2822     //OIC_LOG(INFO, TAG, "Entering RequestPresence");
2823     ClientCB* cbNode = NULL;
2824     OCClientResponse clientResponse;
2825     OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2826
2827     LL_FOREACH(cbList, cbNode)
2828     {
2829         if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2830         {
2831             continue;
2832         }
2833
2834         uint32_t now = GetTicks(0);
2835         OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
2836                                                 cbNode->presence->TTLlevel);
2837         OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2838
2839         if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
2840         {
2841             goto exit;
2842         }
2843
2844         if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2845         {
2846             OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2847                     cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2848         }
2849         if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2850         {
2851             OIC_LOG(DEBUG, TAG, "No more timeout ticks");
2852
2853             clientResponse.sequenceNumber = 0;
2854             clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2855             clientResponse.devAddr = *cbNode->devAddr;
2856             FixUpClientResponse(&clientResponse);
2857             clientResponse.payload = NULL;
2858
2859             // Increment the TTLLevel (going to a next state), so we don't keep
2860             // sending presence notification to client.
2861             cbNode->presence->TTLlevel++;
2862             OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2863                                         cbNode->presence->TTLlevel);
2864
2865             cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2866             if (cbResult == OC_STACK_DELETE_TRANSACTION)
2867             {
2868                 FindAndDeleteClientCB(cbNode);
2869             }
2870         }
2871
2872         if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2873         {
2874             continue;
2875         }
2876
2877         CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2878         CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
2879         CARequestInfo_t requestInfo = {.method = CA_GET};
2880
2881         OIC_LOG(DEBUG, TAG, "time to test server presence");
2882
2883         CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
2884
2885         requestData.type = CA_MSG_NONCONFIRM;
2886         requestData.token = cbNode->token;
2887         requestData.tokenLength = cbNode->tokenLength;
2888         requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
2889         requestInfo.method = CA_GET;
2890         requestInfo.info = requestData;
2891
2892         result = OCSendRequest(&endpoint, &requestInfo);
2893         if (OC_STACK_OK != result)
2894         {
2895             goto exit;
2896         }
2897
2898         cbNode->presence->TTLlevel++;
2899         OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
2900     }
2901 exit:
2902     if (result != OC_STACK_OK)
2903     {
2904         OIC_LOG(ERROR, TAG, "OCProcessPresence error");
2905     }
2906
2907     return result;
2908 }
2909 #endif // WITH_PRESENCE
2910
2911 OCStackResult OCProcess()
2912 {
2913 #ifdef WITH_PRESENCE
2914     OCProcessPresence();
2915 #endif
2916     CAHandleRequestResponse();
2917
2918 #ifdef ROUTING_GATEWAY
2919     RMProcess();
2920 #endif
2921
2922 #ifdef TCP_ADAPTER
2923     ProcessKeepAlive();
2924 #endif
2925     return OC_STACK_OK;
2926 }
2927
2928 #ifdef WITH_PRESENCE
2929 OCStackResult OCStartPresence(const uint32_t ttl)
2930 {
2931     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2932     OCChangeResourceProperty(
2933             &(((OCResource *)presenceResource.handle)->resourceProperties),
2934             OC_ACTIVE, 1);
2935
2936     if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
2937     {
2938         presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
2939         OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
2940     }
2941     else if (0 == ttl)
2942     {
2943         presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
2944         OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
2945     }
2946     else
2947     {
2948         presenceResource.presenceTTL = ttl;
2949     }
2950     OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
2951
2952     if (OC_PRESENCE_UNINITIALIZED == presenceState)
2953     {
2954         presenceState = OC_PRESENCE_INITIALIZED;
2955
2956         OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
2957
2958         CAToken_t caToken = NULL;
2959         CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
2960         if (caResult != CA_STATUS_OK)
2961         {
2962             OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2963             CADestroyToken(caToken);
2964             return OC_STACK_ERROR;
2965         }
2966
2967         AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
2968                 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
2969         CADestroyToken(caToken);
2970     }
2971
2972     // Each time OCStartPresence is called
2973     // a different random 32-bit integer number is used
2974     ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2975
2976     return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
2977             OC_PRESENCE_TRIGGER_CREATE);
2978 }
2979
2980 OCStackResult OCStopPresence()
2981 {
2982     OCStackResult result = OC_STACK_ERROR;
2983
2984     if(presenceResource.handle)
2985     {
2986         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2987
2988     // make resource inactive
2989     result = OCChangeResourceProperty(
2990             &(((OCResource *) presenceResource.handle)->resourceProperties),
2991             OC_ACTIVE, 0);
2992     }
2993
2994     if(result != OC_STACK_OK)
2995     {
2996         OIC_LOG(ERROR, TAG,
2997                       "Changing the presence resource properties to ACTIVE not successful");
2998         return result;
2999     }
3000
3001     return SendStopNotification();
3002 }
3003 #endif
3004
3005 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3006                                             void* callbackParameter)
3007 {
3008     defaultDeviceHandler = entityHandler;
3009     defaultDeviceHandlerCallbackParameter = callbackParameter;
3010
3011     return OC_STACK_OK;
3012 }
3013
3014 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3015 {
3016     OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3017
3018     if(myStackMode ==  OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3019     {
3020         if (validatePlatformInfo(platformInfo))
3021         {
3022             return SavePlatformInfo(platformInfo);
3023         }
3024         else
3025         {
3026             return OC_STACK_INVALID_PARAM;
3027         }
3028     }
3029     else
3030     {
3031         return OC_STACK_ERROR;
3032     }
3033 }
3034
3035 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3036 {
3037     OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3038
3039     if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3040     {
3041         OIC_LOG(ERROR, TAG, "Null or empty device name.");
3042         return OC_STACK_INVALID_PARAM;
3043     }
3044
3045     if (deviceInfo.types)
3046     {
3047         OCStringLL *type =  deviceInfo.types;
3048         OCResource *resource = findResource((OCResource *) deviceResource);
3049         if (!resource)
3050         {
3051             return OC_STACK_INVALID_PARAM;
3052         }
3053         deleteResourceType(resource->rsrcType);
3054         resource->rsrcType = NULL;
3055
3056         while (type)
3057         {
3058             OCBindResourceTypeToResource(deviceResource, type->value);
3059             type = type->next;
3060         }
3061     }
3062     return SaveDeviceInfo(deviceInfo);
3063 }
3064
3065 OCStackResult OCCreateResource(OCResourceHandle *handle,
3066         const char *resourceTypeName,
3067         const char *resourceInterfaceName,
3068         const char *uri, OCEntityHandler entityHandler,
3069         void* callbackParam,
3070         uint8_t resourceProperties)
3071 {
3072
3073     OCResource *pointer = NULL;
3074     OCStackResult result = OC_STACK_ERROR;
3075
3076     OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3077
3078     if(myStackMode == OC_CLIENT)
3079     {
3080         return OC_STACK_INVALID_PARAM;
3081     }
3082     // Validate parameters
3083     if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3084     {
3085         OIC_LOG(ERROR, TAG, "URI is empty or too long");
3086         return OC_STACK_INVALID_URI;
3087     }
3088     // Is it presented during resource discovery?
3089     if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3090     {
3091         OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3092         return OC_STACK_INVALID_PARAM;
3093     }
3094
3095     if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3096     {
3097         resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3098     }
3099
3100     // Make sure resourceProperties bitmask has allowed properties specified
3101     if (resourceProperties
3102             > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3103                OC_EXPLICIT_DISCOVERABLE))
3104     {
3105         OIC_LOG(ERROR, TAG, "Invalid property");
3106         return OC_STACK_INVALID_PARAM;
3107     }
3108
3109     // If the headResource is NULL, then no resources have been created...
3110     pointer = headResource;
3111     if (pointer)
3112     {
3113         // At least one resources is in the resource list, so we need to search for
3114         // repeated URLs, which are not allowed.  If a repeat is found, exit with an error
3115         while (pointer)
3116         {
3117             if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3118             {
3119                 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3120                 return OC_STACK_INVALID_PARAM;
3121             }
3122             pointer = pointer->next;
3123         }
3124     }
3125     // Create the pointer and insert it into the resource list
3126     pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3127     if (!pointer)
3128     {
3129         result = OC_STACK_NO_MEMORY;
3130         goto exit;
3131     }
3132     pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3133
3134     insertResource(pointer);
3135
3136     // Set the uri
3137     pointer->uri = OICStrdup(uri);
3138     if (!pointer->uri)
3139     {
3140         result = OC_STACK_NO_MEMORY;
3141         goto exit;
3142     }
3143
3144     // Set properties.  Set OC_ACTIVE
3145     pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3146             | OC_ACTIVE);
3147
3148     // Add the resourcetype to the resource
3149     result = BindResourceTypeToResource(pointer, resourceTypeName);
3150     if (result != OC_STACK_OK)
3151     {
3152         OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3153         goto exit;
3154     }
3155
3156     // Add the resourceinterface to the resource
3157     result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3158     if (result != OC_STACK_OK)
3159     {
3160         OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3161         goto exit;
3162     }
3163
3164     // If an entity handler has been passed, attach it to the newly created
3165     // resource.  Otherwise, set the default entity handler.
3166     if (entityHandler)
3167     {
3168         pointer->entityHandler = entityHandler;
3169         pointer->entityHandlerCallbackParam = callbackParam;
3170     }
3171     else
3172     {
3173         pointer->entityHandler = defaultResourceEHandler;
3174         pointer->entityHandlerCallbackParam = NULL;
3175     }
3176
3177     // Initialize a pointer indicating child resources in case of collection
3178     pointer->rsrcChildResourcesHead = NULL;
3179
3180     *handle = pointer;
3181     result = OC_STACK_OK;
3182
3183 #ifdef WITH_PRESENCE
3184     if (presenceResource.handle)
3185     {
3186         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3187         SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3188     }
3189 #endif
3190 exit:
3191     if (result != OC_STACK_OK)
3192     {
3193         // Deep delete of resource and other dynamic elements that it contains
3194         deleteResource(pointer);
3195     }
3196     return result;
3197 }
3198
3199 OCStackResult OCBindResource(
3200         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3201 {
3202     OCResource *resource = NULL;
3203     OCChildResource *tempChildResource = NULL;
3204     OCChildResource *newChildResource = NULL;
3205
3206     OIC_LOG(INFO, TAG, "Entering OCBindResource");
3207
3208     // Validate parameters
3209     VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3210     VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3211     // Container cannot contain itself
3212     if (collectionHandle == resourceHandle)
3213     {
3214         OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3215         return OC_STACK_INVALID_PARAM;
3216     }
3217
3218     // Use the handle to find the resource in the resource linked list
3219     resource = findResource((OCResource *) collectionHandle);
3220     if (!resource)
3221     {
3222         OIC_LOG(ERROR, TAG, "Collection handle not found");
3223         return OC_STACK_INVALID_PARAM;
3224     }
3225
3226     // Look for an open slot to add add the child resource.
3227     // If found, add it and return success
3228
3229     tempChildResource = resource->rsrcChildResourcesHead;
3230
3231     while(resource->rsrcChildResourcesHead && tempChildResource->next)
3232     {
3233         // TODO: what if one of child resource was deregistered without unbinding?
3234         tempChildResource = tempChildResource->next;
3235     }
3236
3237     // Do memory allocation for child resource
3238     newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3239     if(!newChildResource)
3240     {
3241         OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3242         return OC_STACK_ERROR;
3243     }
3244
3245     newChildResource->rsrcResource = (OCResource *) resourceHandle;
3246     newChildResource->next = NULL;
3247
3248     if(!resource->rsrcChildResourcesHead)
3249     {
3250         resource->rsrcChildResourcesHead = newChildResource;
3251     }
3252     else {
3253         tempChildResource->next = newChildResource;
3254     }
3255
3256     OIC_LOG(INFO, TAG, "resource bound");
3257
3258 #ifdef WITH_PRESENCE
3259     if (presenceResource.handle)
3260     {
3261         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3262         SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3263                 OC_PRESENCE_TRIGGER_CHANGE);
3264     }
3265 #endif
3266
3267     return OC_STACK_OK;
3268 }
3269
3270 OCStackResult OCUnBindResource(
3271         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3272 {
3273     OCResource *resource = NULL;
3274     OCChildResource *tempChildResource = NULL;
3275     OCChildResource *tempLastChildResource = NULL;
3276
3277     OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3278
3279     // Validate parameters
3280     VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3281     VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3282     // Container cannot contain itself
3283     if (collectionHandle == resourceHandle)
3284     {
3285         OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3286         return OC_STACK_INVALID_PARAM;
3287     }
3288
3289     // Use the handle to find the resource in the resource linked list
3290     resource = findResource((OCResource *) collectionHandle);
3291     if (!resource)
3292     {
3293         OIC_LOG(ERROR, TAG, "Collection handle not found");
3294         return OC_STACK_INVALID_PARAM;
3295     }
3296
3297     // Look for an open slot to add add the child resource.
3298     // If found, add it and return success
3299     if(!resource->rsrcChildResourcesHead)
3300     {
3301         OIC_LOG(INFO, TAG, "resource not found in collection");
3302
3303         // Unable to add resourceHandle, so return error
3304         return OC_STACK_ERROR;
3305
3306     }
3307
3308     tempChildResource = resource->rsrcChildResourcesHead;
3309
3310     while (tempChildResource)
3311     {
3312         if(tempChildResource->rsrcResource == resourceHandle)
3313         {
3314             // if resource going to be unbinded is the head one.
3315             if( tempChildResource == resource->rsrcChildResourcesHead )
3316             {
3317                 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3318                 OICFree(resource->rsrcChildResourcesHead);
3319                 resource->rsrcChildResourcesHead = temp;
3320                 temp = NULL;
3321             }
3322             else
3323             {
3324                 OCChildResource *temp = tempChildResource->next;
3325                 OICFree(tempChildResource);
3326                 tempLastChildResource->next = temp;
3327                 temp = NULL;
3328             }
3329
3330             OIC_LOG(INFO, TAG, "resource unbound");
3331
3332             // Send notification when resource is unbounded successfully.
3333 #ifdef WITH_PRESENCE
3334             if (presenceResource.handle)
3335             {
3336                 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3337                 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3338                         OC_PRESENCE_TRIGGER_CHANGE);
3339             }
3340 #endif
3341             tempChildResource = NULL;
3342             tempLastChildResource = NULL;
3343
3344             return OC_STACK_OK;
3345
3346         }
3347
3348         tempLastChildResource = tempChildResource;
3349         tempChildResource = tempChildResource->next;
3350     }
3351
3352     OIC_LOG(INFO, TAG, "resource not found in collection");
3353
3354     tempChildResource = NULL;
3355     tempLastChildResource = NULL;
3356
3357     // Unable to add resourceHandle, so return error
3358     return OC_STACK_ERROR;
3359 }
3360
3361 // Precondition is that the parameter has been checked to not equal NULL.
3362 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3363 {
3364     if (resourceItemName[0] < 'a' || resourceItemName[0] > 'z')
3365     {
3366         return false;
3367     }
3368
3369     size_t index = 1;
3370     while (resourceItemName[index] != '\0')
3371     {
3372         if (resourceItemName[index] != '.' &&
3373                 resourceItemName[index] != '-' &&
3374                 (resourceItemName[index] < 'a' || resourceItemName[index] > 'z') &&
3375                 (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3376         {
3377             return false;
3378         }
3379         ++index;
3380     }
3381
3382     return true;
3383 }
3384 OCStackResult BindResourceTypeToResource(OCResource* resource,
3385                                             const char *resourceTypeName)
3386 {
3387     OCResourceType *pointer = NULL;
3388     char *str = NULL;
3389     OCStackResult result = OC_STACK_ERROR;
3390
3391     VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3392
3393     if (!ValidateResourceTypeInterface(resourceTypeName))
3394     {
3395         OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3396         return OC_STACK_INVALID_PARAM;
3397     }
3398
3399     pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3400     if (!pointer)
3401     {
3402         result = OC_STACK_NO_MEMORY;
3403         goto exit;
3404     }
3405
3406     str = OICStrdup(resourceTypeName);
3407     if (!str)
3408     {
3409         result = OC_STACK_NO_MEMORY;
3410         goto exit;
3411     }
3412     pointer->resourcetypename = str;
3413     pointer->next = NULL;
3414
3415     insertResourceType(resource, pointer);
3416     result = OC_STACK_OK;
3417
3418 exit:
3419     if (result != OC_STACK_OK)
3420     {
3421         OICFree(pointer);
3422         OICFree(str);
3423     }
3424
3425     return result;
3426 }
3427
3428 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3429         const char *resourceInterfaceName)
3430 {
3431     OCResourceInterface *pointer = NULL;
3432     char *str = NULL;
3433     OCStackResult result = OC_STACK_ERROR;
3434
3435     VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3436
3437     if (!ValidateResourceTypeInterface(resourceInterfaceName))
3438     {
3439         OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3440         return OC_STACK_INVALID_PARAM;
3441     }
3442
3443     OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3444
3445     pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3446     if (!pointer)
3447     {
3448         result = OC_STACK_NO_MEMORY;
3449         goto exit;
3450     }
3451
3452     str = OICStrdup(resourceInterfaceName);
3453     if (!str)
3454     {
3455         result = OC_STACK_NO_MEMORY;
3456         goto exit;
3457     }
3458     pointer->name = str;
3459
3460     // Bind the resourceinterface to the resource
3461     insertResourceInterface(resource, pointer);
3462
3463     result = OC_STACK_OK;
3464
3465     exit:
3466     if (result != OC_STACK_OK)
3467     {
3468         OICFree(pointer);
3469         OICFree(str);
3470     }
3471
3472     return result;
3473 }
3474
3475 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3476         const char *resourceTypeName)
3477 {
3478
3479     OCStackResult result = OC_STACK_ERROR;
3480     OCResource *resource = NULL;
3481
3482     resource = findResource((OCResource *) handle);
3483     if (!resource)
3484     {
3485         OIC_LOG(ERROR, TAG, "Resource not found");
3486         return OC_STACK_ERROR;
3487     }
3488
3489     result = BindResourceTypeToResource(resource, resourceTypeName);
3490
3491 #ifdef WITH_PRESENCE
3492     if(presenceResource.handle)
3493     {
3494         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3495         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3496     }
3497 #endif
3498
3499     return result;
3500 }
3501
3502 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3503         const char *resourceInterfaceName)
3504 {
3505
3506     OCStackResult result = OC_STACK_ERROR;
3507     OCResource *resource = NULL;
3508
3509     resource = findResource((OCResource *) handle);
3510     if (!resource)
3511     {
3512         OIC_LOG(ERROR, TAG, "Resource not found");
3513         return OC_STACK_ERROR;
3514     }
3515
3516     result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3517
3518 #ifdef WITH_PRESENCE
3519     if (presenceResource.handle)
3520     {
3521         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3522         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3523     }
3524 #endif
3525
3526     return result;
3527 }
3528
3529 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3530 {
3531     OCResource *pointer = headResource;
3532
3533     VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3534     *numResources = 0;
3535     while (pointer)
3536     {
3537         *numResources = *numResources + 1;
3538         pointer = pointer->next;
3539     }
3540     return OC_STACK_OK;
3541 }
3542
3543 OCResourceHandle OCGetResourceHandle(uint8_t index)
3544 {
3545     OCResource *pointer = headResource;
3546
3547     for( uint8_t i = 0; i < index && pointer; ++i)
3548     {
3549         pointer = pointer->next;
3550     }
3551     return (OCResourceHandle) pointer;
3552 }
3553
3554 OCStackResult OCDeleteResource(OCResourceHandle handle)
3555 {
3556     if (!handle)
3557     {
3558         OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3559         return OC_STACK_INVALID_PARAM;
3560     }
3561
3562     OCResource *resource = findResource((OCResource *) handle);
3563     if (resource == NULL)
3564     {
3565         OIC_LOG(ERROR, TAG, "Resource not found");
3566         return OC_STACK_NO_RESOURCE;
3567     }
3568
3569     if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3570     {
3571         OIC_LOG(ERROR, TAG, "Error deleting resource");
3572         return OC_STACK_ERROR;
3573     }
3574
3575     return OC_STACK_OK;
3576 }
3577
3578 const char *OCGetResourceUri(OCResourceHandle handle)
3579 {
3580     OCResource *resource = NULL;
3581
3582     resource = findResource((OCResource *) handle);
3583     if (resource)
3584     {
3585         return resource->uri;
3586     }
3587     return (const char *) NULL;
3588 }
3589
3590 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3591 {
3592     OCResource *resource = NULL;
3593
3594     resource = findResource((OCResource *) handle);
3595     if (resource)
3596     {
3597         return resource->resourceProperties;
3598     }
3599     return (OCResourceProperty)-1;
3600 }
3601
3602 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3603         uint8_t *numResourceTypes)
3604 {
3605     OCResource *resource = NULL;
3606     OCResourceType *pointer = NULL;
3607
3608     VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3609     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3610
3611     *numResourceTypes = 0;
3612
3613     resource = findResource((OCResource *) handle);
3614     if (resource)
3615     {
3616         pointer = resource->rsrcType;
3617         while (pointer)
3618         {
3619             *numResourceTypes = *numResourceTypes + 1;
3620             pointer = pointer->next;
3621         }
3622     }
3623     return OC_STACK_OK;
3624 }
3625
3626 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3627 {
3628     OCResourceType *resourceType = NULL;
3629
3630     resourceType = findResourceTypeAtIndex(handle, index);
3631     if (resourceType)
3632     {
3633         return resourceType->resourcetypename;
3634     }
3635     return (const char *) NULL;
3636 }
3637
3638 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3639         uint8_t *numResourceInterfaces)
3640 {
3641     OCResourceInterface *pointer = NULL;
3642     OCResource *resource = NULL;
3643
3644     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3645     VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3646
3647     *numResourceInterfaces = 0;
3648     resource = findResource((OCResource *) handle);
3649     if (resource)
3650     {
3651         pointer = resource->rsrcInterface;
3652         while (pointer)
3653         {
3654             *numResourceInterfaces = *numResourceInterfaces + 1;
3655             pointer = pointer->next;
3656         }
3657     }
3658     return OC_STACK_OK;
3659 }
3660
3661 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3662 {
3663     OCResourceInterface *resourceInterface = NULL;
3664
3665     resourceInterface = findResourceInterfaceAtIndex(handle, index);
3666     if (resourceInterface)
3667     {
3668         return resourceInterface->name;
3669     }
3670     return (const char *) NULL;
3671 }
3672
3673 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3674         uint8_t index)
3675 {
3676     OCResource *resource = NULL;
3677     OCChildResource *tempChildResource = NULL;
3678     uint8_t num = 0;
3679
3680     resource = findResource((OCResource *) collectionHandle);
3681     if (!resource)
3682     {
3683         return NULL;
3684     }
3685
3686     tempChildResource = resource->rsrcChildResourcesHead;
3687
3688     while(tempChildResource)
3689     {
3690         if( num == index )
3691         {
3692             return tempChildResource->rsrcResource;
3693         }
3694         num++;
3695         tempChildResource = tempChildResource->next;
3696     }
3697
3698     // In this case, the number of resource handles in the collection exceeds the index
3699     tempChildResource = NULL;
3700     return NULL;
3701 }
3702
3703 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3704         OCEntityHandler entityHandler,
3705         void* callbackParam)
3706 {
3707     OCResource *resource = NULL;
3708
3709     // Validate parameters
3710     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3711
3712     // Use the handle to find the resource in the resource linked list
3713     resource = findResource((OCResource *)handle);
3714     if (!resource)
3715     {
3716         OIC_LOG(ERROR, TAG, "Resource not found");
3717         return OC_STACK_ERROR;
3718     }
3719
3720     // Bind the handler
3721     resource->entityHandler = entityHandler;
3722     resource->entityHandlerCallbackParam = callbackParam;
3723
3724 #ifdef WITH_PRESENCE
3725     if (presenceResource.handle)
3726     {
3727         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3728         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3729     }
3730 #endif
3731
3732     return OC_STACK_OK;
3733 }
3734
3735 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3736 {
3737     OCResource *resource = NULL;
3738
3739     resource = findResource((OCResource *)handle);
3740     if (!resource)
3741     {
3742         OIC_LOG(ERROR, TAG, "Resource not found");
3743         return NULL;
3744     }
3745
3746     // Bind the handler
3747     return resource->entityHandler;
3748 }
3749
3750 void incrementSequenceNumber(OCResource * resPtr)
3751 {
3752     // Increment the sequence number
3753     resPtr->sequenceNum += 1;
3754     if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3755     {
3756         resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3757     }
3758     return;
3759 }
3760
3761 #ifdef WITH_PRESENCE
3762 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3763         OCPresenceTrigger trigger)
3764 {
3765     OCResource *resPtr = NULL;
3766     OCStackResult result = OC_STACK_ERROR;
3767     OCMethod method = OC_REST_PRESENCE;
3768     uint32_t maxAge = 0;
3769     resPtr = findResource((OCResource *) presenceResource.handle);
3770     if(NULL == resPtr)
3771     {
3772         return OC_STACK_NO_RESOURCE;
3773     }
3774
3775     if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3776     {
3777         maxAge = presenceResource.presenceTTL;
3778
3779         result = SendAllObserverNotification(method, resPtr, maxAge,
3780                 trigger, resourceType, OC_LOW_QOS);
3781     }
3782
3783     return result;
3784 }
3785
3786 OCStackResult SendStopNotification()
3787 {
3788     OCResource *resPtr = NULL;
3789     OCStackResult result = OC_STACK_ERROR;
3790     OCMethod method = OC_REST_PRESENCE;
3791     resPtr = findResource((OCResource *) presenceResource.handle);
3792     if(NULL == resPtr)
3793     {
3794         return OC_STACK_NO_RESOURCE;
3795     }
3796
3797     // maxAge is 0. ResourceType is NULL.
3798     result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3799             NULL, OC_LOW_QOS);
3800
3801     return result;
3802 }
3803
3804 #endif // WITH_PRESENCE
3805 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3806 {
3807     OCResource *resPtr = NULL;
3808     OCStackResult result = OC_STACK_ERROR;
3809     OCMethod method = OC_REST_NOMETHOD;
3810     uint32_t maxAge = 0;
3811
3812     OIC_LOG(INFO, TAG, "Notifying all observers");
3813 #ifdef WITH_PRESENCE
3814     if(handle == presenceResource.handle)
3815     {
3816         return OC_STACK_OK;
3817     }
3818 #endif // WITH_PRESENCE
3819     VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3820
3821     // Verify that the resource exists
3822     resPtr = findResource ((OCResource *) handle);
3823     if (NULL == resPtr)
3824     {
3825         return OC_STACK_NO_RESOURCE;
3826     }
3827     else
3828     {
3829         //only increment in the case of regular observing (not presence)
3830         incrementSequenceNumber(resPtr);
3831         method = OC_REST_OBSERVE;
3832         maxAge = MAX_OBSERVE_AGE;
3833 #ifdef WITH_PRESENCE
3834         result = SendAllObserverNotification (method, resPtr, maxAge,
3835                 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3836 #else
3837         result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3838 #endif
3839         return result;
3840     }
3841 }
3842
3843 OCStackResult
3844 OCNotifyListOfObservers (OCResourceHandle handle,
3845                          OCObservationId  *obsIdList,
3846                          uint8_t          numberOfIds,
3847                          const OCRepPayload       *payload,
3848                          OCQualityOfService qos)
3849 {
3850     OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
3851
3852     OCResource *resPtr = NULL;
3853     //TODO: we should allow the server to define this
3854     uint32_t maxAge = MAX_OBSERVE_AGE;
3855
3856     VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3857     VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3858     VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
3859
3860     resPtr = findResource ((OCResource *) handle);
3861     if (NULL == resPtr || myStackMode == OC_CLIENT)
3862     {
3863         return OC_STACK_NO_RESOURCE;
3864     }
3865     else
3866     {
3867         incrementSequenceNumber(resPtr);
3868     }
3869     return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3870             payload, maxAge, qos));
3871 }
3872
3873 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3874 {
3875     OCStackResult result = OC_STACK_ERROR;
3876     OCServerRequest *serverRequest = NULL;
3877
3878     OIC_LOG(INFO, TAG, "Entering OCDoResponse");
3879
3880     // Validate input parameters
3881     VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3882     VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3883
3884     // Normal response
3885     // Get pointer to request info
3886     serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3887     if(serverRequest)
3888     {
3889         // response handler in ocserverrequest.c. Usually HandleSingleResponse.
3890         result = serverRequest->ehResponseHandler(ehResponse);
3891     }
3892
3893     return result;
3894 }
3895
3896 //#ifdef DIRECT_PAIRING
3897 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
3898 {
3899     OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
3900     if(OC_STACK_OK != DPDeviceDiscovery(waittime))
3901     {
3902         OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
3903         return NULL;
3904     }
3905
3906     return (const OCDPDev_t*)DPGetDiscoveredDevices();
3907 }
3908
3909 const OCDPDev_t* OCGetDirectPairedDevices()
3910 {
3911     return (const OCDPDev_t*)DPGetPairedDevices();
3912 }
3913
3914 void DirectPairingCB (OCDirectPairingDev_t * peer, OCStackResult result)
3915 {
3916     if (gDirectpairingCallback)
3917     {
3918         gDirectpairingCallback((OCDPDev_t*)peer, result);
3919         gDirectpairingCallback = NULL;
3920     }
3921 }
3922
3923 OCStackResult OCDoDirectPairing(OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
3924                                                      OCDirectPairingCB resultCallback)
3925 {
3926     OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
3927     if(NULL ==  peer || NULL == pinNumber)
3928     {
3929         OIC_LOG(ERROR, TAG, "Invalid parameters");
3930         return OC_STACK_INVALID_PARAM;
3931     }
3932     if(NULL == resultCallback)
3933     {
3934         OIC_LOG(ERROR, TAG, "Invalid callback");
3935         return OC_STACK_INVALID_CALLBACK;
3936     }
3937
3938     gDirectpairingCallback = resultCallback;
3939     return DPDirectPairing((OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
3940                                            pinNumber, DirectPairingCB);
3941 }
3942 //#endif // DIRECT_PAIRING
3943
3944 //-----------------------------------------------------------------------------
3945 // Private internal function definitions
3946 //-----------------------------------------------------------------------------
3947 static OCDoHandle GenerateInvocationHandle()
3948 {
3949     OCDoHandle handle = NULL;
3950     // Generate token here, it will be deleted when the transaction is deleted
3951     handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3952     if (handle)
3953     {
3954         OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3955     }
3956
3957     return handle;
3958 }
3959
3960 #ifdef WITH_PRESENCE
3961 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3962         OCResourceProperty resourceProperties, uint8_t enable)
3963 {
3964     if (!inputProperty)
3965     {
3966         return OC_STACK_INVALID_PARAM;
3967     }
3968     if (resourceProperties
3969             > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
3970     {
3971         OIC_LOG(ERROR, TAG, "Invalid property");
3972         return OC_STACK_INVALID_PARAM;
3973     }
3974     if(!enable)
3975     {
3976         *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3977     }
3978     else
3979     {
3980         *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3981     }
3982     return OC_STACK_OK;
3983 }
3984 #endif
3985
3986 OCStackResult initResources()
3987 {
3988     OCStackResult result = OC_STACK_OK;
3989
3990     headResource = NULL;
3991     tailResource = NULL;
3992     // Init Virtual Resources
3993 #ifdef WITH_PRESENCE
3994     presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3995
3996     result = OCCreateResource(&presenceResource.handle,
3997             OC_RSRVD_RESOURCE_TYPE_PRESENCE,
3998             "core.r",
3999             OC_RSRVD_PRESENCE_URI,
4000             NULL,
4001             NULL,
4002             OC_OBSERVABLE);
4003     //make resource inactive
4004     result = OCChangeResourceProperty(
4005             &(((OCResource *) presenceResource.handle)->resourceProperties),
4006             OC_ACTIVE, 0);
4007 #endif
4008 #ifndef WITH_ARDUINO
4009     if (result == OC_STACK_OK)
4010     {
4011         result = SRMInitSecureResources();
4012     }
4013 #endif
4014
4015     if(result == OC_STACK_OK)
4016     {
4017         result = OCCreateResource(&deviceResource,
4018                                   OC_RSRVD_RESOURCE_TYPE_DEVICE,
4019                                   OC_RSRVD_INTERFACE_DEFAULT,
4020                                   OC_RSRVD_DEVICE_URI,
4021                                   NULL,
4022                                   NULL,
4023                                   OC_DISCOVERABLE);
4024         if(result == OC_STACK_OK)
4025         {
4026             result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4027                                                      OC_RSRVD_INTERFACE_READ);
4028         }
4029     }
4030
4031     if(result == OC_STACK_OK)
4032     {
4033         result = OCCreateResource(&platformResource,
4034                                   OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4035                                   OC_RSRVD_INTERFACE_DEFAULT,
4036                                   OC_RSRVD_PLATFORM_URI,
4037                                   NULL,
4038                                   NULL,
4039                                   OC_DISCOVERABLE);
4040         if(result == OC_STACK_OK)
4041         {
4042             result = BindResourceInterfaceToResource((OCResource *)platformResource,
4043                                                      OC_RSRVD_INTERFACE_READ);
4044         }
4045     }
4046
4047     return result;
4048 }
4049
4050 void insertResource(OCResource *resource)
4051 {
4052     if (!headResource)
4053     {
4054         headResource = resource;
4055         tailResource = resource;
4056     }
4057     else
4058     {
4059         tailResource->next = resource;
4060         tailResource = resource;
4061     }
4062     resource->next = NULL;
4063 }
4064
4065 OCResource *findResource(OCResource *resource)
4066 {
4067     OCResource *pointer = headResource;
4068
4069     while (pointer)
4070     {
4071         if (pointer == resource)
4072         {
4073             return resource;
4074         }
4075         pointer = pointer->next;
4076     }
4077     return NULL;
4078 }
4079
4080 void deleteAllResources()
4081 {
4082     OCResource *pointer = headResource;
4083     OCResource *temp = NULL;
4084
4085     while (pointer)
4086     {
4087         temp = pointer->next;
4088 #ifdef WITH_PRESENCE
4089         if (pointer != (OCResource *) presenceResource.handle)
4090         {
4091 #endif // WITH_PRESENCE
4092             deleteResource(pointer);
4093 #ifdef WITH_PRESENCE
4094         }
4095 #endif // WITH_PRESENCE
4096         pointer = temp;
4097     }
4098
4099     SRMDeInitSecureResources();
4100
4101 #ifdef WITH_PRESENCE
4102     // Ensure that the last resource to be deleted is the presence resource. This allows for all
4103     // presence notification attributed to their deletion to be processed.
4104     deleteResource((OCResource *) presenceResource.handle);
4105 #endif // WITH_PRESENCE
4106 }
4107
4108 OCStackResult deleteResource(OCResource *resource)
4109 {
4110     OCResource *prev = NULL;
4111     OCResource *temp = NULL;
4112     if(!resource)
4113     {
4114         OIC_LOG(DEBUG,TAG,"resource is NULL");
4115         return OC_STACK_INVALID_PARAM;
4116     }
4117
4118     OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4119
4120     temp = headResource;
4121     while (temp)
4122     {
4123         if (temp == resource)
4124         {
4125             // Invalidate all Resource Properties.
4126             resource->resourceProperties = (OCResourceProperty) 0;
4127 #ifdef WITH_PRESENCE
4128             if(resource != (OCResource *) presenceResource.handle)
4129             {
4130 #endif // WITH_PRESENCE
4131                 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4132 #ifdef WITH_PRESENCE
4133             }
4134
4135             if(presenceResource.handle)
4136             {
4137                 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4138                 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4139             }
4140 #endif
4141             // Only resource in list.
4142             if (temp == headResource && temp == tailResource)
4143             {
4144                 headResource = NULL;
4145                 tailResource = NULL;
4146             }
4147             // Deleting head.
4148             else if (temp == headResource)
4149             {
4150                 headResource = temp->next;
4151             }
4152             // Deleting tail.
4153             else if (temp == tailResource)
4154             {
4155                 tailResource = prev;
4156                 tailResource->next = NULL;
4157             }
4158             else
4159             {
4160                 prev->next = temp->next;
4161             }
4162
4163             deleteResourceElements(temp);
4164             OICFree(temp);
4165             return OC_STACK_OK;
4166         }
4167         else
4168         {
4169             prev = temp;
4170             temp = temp->next;
4171         }
4172     }
4173
4174     return OC_STACK_ERROR;
4175 }
4176
4177 void deleteResourceElements(OCResource *resource)
4178 {
4179     if (!resource)
4180     {
4181         return;
4182     }
4183
4184     OICFree(resource->uri);
4185     deleteResourceType(resource->rsrcType);
4186     deleteResourceInterface(resource->rsrcInterface);
4187 }
4188
4189 void deleteResourceType(OCResourceType *resourceType)
4190 {
4191     OCResourceType *pointer = resourceType;
4192     OCResourceType *next = NULL;
4193
4194     while (pointer)
4195     {
4196         next = pointer->next;
4197         OICFree(pointer->resourcetypename);
4198         OICFree(pointer);
4199         pointer = next;
4200     }
4201 }
4202
4203 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4204 {
4205     OCResourceInterface *pointer = resourceInterface;
4206     OCResourceInterface *next = NULL;
4207
4208     while (pointer)
4209     {
4210         next = pointer->next;
4211         OICFree(pointer->name);
4212         OICFree(pointer);
4213         pointer = next;
4214     }
4215 }
4216
4217 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4218 {
4219     OCResourceType *pointer = NULL;
4220     OCResourceType *previous = NULL;
4221     if (!resource || !resourceType)
4222     {
4223         return;
4224     }
4225     // resource type list is empty.
4226     else if (!resource->rsrcType)
4227     {
4228         resource->rsrcType = resourceType;
4229     }
4230     else
4231     {
4232         pointer = resource->rsrcType;
4233
4234         while (pointer)
4235         {
4236             if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4237             {
4238                 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4239                 OICFree(resourceType->resourcetypename);
4240                 OICFree(resourceType);
4241                 return;
4242             }
4243             previous = pointer;
4244             pointer = pointer->next;
4245         }
4246         previous->next = resourceType;
4247     }
4248     resourceType->next = NULL;
4249
4250     OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4251 }
4252
4253 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4254 {
4255     OCResource *resource = NULL;
4256     OCResourceType *pointer = NULL;
4257
4258     // Find the specified resource
4259     resource = findResource((OCResource *) handle);
4260     if (!resource)
4261     {
4262         return NULL;
4263     }
4264
4265     // Make sure a resource has a resourcetype
4266     if (!resource->rsrcType)
4267     {
4268         return NULL;
4269     }
4270
4271     // Iterate through the list
4272     pointer = resource->rsrcType;
4273     for(uint8_t i = 0; i< index && pointer; ++i)
4274     {
4275         pointer = pointer->next;
4276     }
4277     return pointer;
4278 }
4279
4280 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4281 {
4282     if(resourceTypeList && resourceTypeName)
4283     {
4284         OCResourceType * rtPointer = resourceTypeList;
4285         while(resourceTypeName && rtPointer)
4286         {
4287             if(rtPointer->resourcetypename &&
4288                     strcmp(resourceTypeName, (const char *)
4289                     (rtPointer->resourcetypename)) == 0)
4290             {
4291                 break;
4292             }
4293             rtPointer = rtPointer->next;
4294         }
4295         return rtPointer;
4296     }
4297     return NULL;
4298 }
4299
4300 /*
4301  * Insert a new interface into interface linked list only if not already present.
4302  * If alredy present, 2nd arg is free'd.
4303  * Default interface will always be first if present.
4304  */
4305 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4306 {
4307     OCResourceInterface *pointer = NULL;
4308     OCResourceInterface *previous = NULL;
4309
4310     newInterface->next = NULL;
4311
4312     OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4313
4314     if (!*firstInterface)
4315     {
4316         // If first interface is not oic.if.baseline, by default add it as first interface type.
4317         if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4318         {
4319             *firstInterface = newInterface;
4320         }
4321         else
4322         {
4323             OCStackResult result = BindResourceInterfaceToResource(resource, OC_RSRVD_INTERFACE_DEFAULT);
4324             if (result != OC_STACK_OK)
4325             {
4326                 OICFree(newInterface->name);
4327                 OICFree(newInterface);
4328                 return;
4329             }
4330             if (*firstInterface)
4331             {
4332                 (*firstInterface)->next = newInterface;
4333             }
4334         }
4335     }
4336     // If once add oic.if.baseline, later too below code take care of freeing memory.
4337     else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4338     {
4339         if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4340         {
4341             OICFree(newInterface->name);
4342             OICFree(newInterface);
4343             return;
4344         }
4345         // This code will not hit anymore, keeping
4346         else
4347         {
4348             newInterface->next = *firstInterface;
4349             *firstInterface = newInterface;
4350         }
4351     }
4352     else
4353     {
4354         pointer = *firstInterface;
4355         while (pointer)
4356         {
4357             if (strcmp(newInterface->name, pointer->name) == 0)
4358             {
4359                 OICFree(newInterface->name);
4360                 OICFree(newInterface);
4361                 return;
4362             }
4363             previous = pointer;
4364             pointer = pointer->next;
4365         }
4366         previous->next = newInterface;
4367     }
4368 }
4369
4370 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4371         uint8_t index)
4372 {
4373     OCResource *resource = NULL;
4374     OCResourceInterface *pointer = NULL;
4375
4376     // Find the specified resource
4377     resource = findResource((OCResource *) handle);
4378     if (!resource)
4379     {
4380         return NULL;
4381     }
4382
4383     // Make sure a resource has a resourceinterface
4384     if (!resource->rsrcInterface)
4385     {
4386         return NULL;
4387     }
4388
4389     // Iterate through the list
4390     pointer = resource->rsrcInterface;
4391
4392     for (uint8_t i = 0; i < index && pointer; ++i)
4393     {
4394         pointer = pointer->next;
4395     }
4396     return pointer;
4397 }
4398
4399 /*
4400  * This function splits the uri using the '?' delimiter.
4401  * "uriWithoutQuery" is the block of characters between the beginning
4402  * till the delimiter or '\0' which ever comes first.
4403  * "query" is whatever is to the right of the delimiter if present.
4404  * No delimiter sets the query to NULL.
4405  * If either are present, they will be malloc'ed into the params 2, 3.
4406  * The first param, *uri is left untouched.
4407
4408  * NOTE: This function does not account for whitespace at the end of the uri NOR
4409  *       malformed uri's with '??'. Whitespace at the end will be assumed to be
4410  *       part of the query.
4411  */
4412 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4413 {
4414     if(!uri)
4415     {
4416         return OC_STACK_INVALID_URI;
4417     }
4418     if(!query || !uriWithoutQuery)
4419     {
4420         return OC_STACK_INVALID_PARAM;
4421     }
4422
4423     *query           = NULL;
4424     *uriWithoutQuery = NULL;
4425
4426     size_t uriWithoutQueryLen = 0;
4427     size_t queryLen = 0;
4428     size_t uriLen = strlen(uri);
4429
4430     char *pointerToDelimiter = strstr(uri, "?");
4431
4432     uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4433     queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4434
4435     if (uriWithoutQueryLen)
4436     {
4437         *uriWithoutQuery =  (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4438         if (!*uriWithoutQuery)
4439         {
4440             goto exit;
4441         }
4442         OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4443     }
4444     if (queryLen)
4445     {
4446         *query = (char *) OICCalloc(queryLen + 1, 1);
4447         if (!*query)
4448         {
4449             OICFree(*uriWithoutQuery);
4450             *uriWithoutQuery = NULL;
4451             goto exit;
4452         }
4453         OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4454     }
4455
4456     return OC_STACK_OK;
4457
4458     exit:
4459         return OC_STACK_NO_MEMORY;
4460 }
4461
4462 static const OicUuid_t* OCGetServerInstanceID(void)
4463 {
4464     static bool generated = false;
4465     static OicUuid_t sid;
4466     if (generated)
4467     {
4468         return &sid;
4469     }
4470
4471     if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4472     {
4473         OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4474         return NULL;
4475     }
4476     generated = true;
4477     return &sid;
4478 }
4479
4480 const char* OCGetServerInstanceIDString(void)
4481 {
4482     static bool generated = false;
4483     static char sidStr[UUID_STRING_SIZE];
4484
4485     if(generated)
4486     {
4487         return sidStr;
4488     }
4489
4490     const OicUuid_t *sid = OCGetServerInstanceID();
4491     if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4492     {
4493         OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4494         return NULL;
4495     }
4496
4497     generated = true;
4498     return sidStr;
4499 }
4500
4501 CAResult_t OCSelectNetwork()
4502 {
4503     CAResult_t retResult = CA_STATUS_FAILED;
4504     CAResult_t caResult = CA_STATUS_OK;
4505
4506     CATransportAdapter_t connTypes[] = {
4507             CA_ADAPTER_IP,
4508             CA_ADAPTER_RFCOMM_BTEDR,
4509             CA_ADAPTER_GATT_BTLE,
4510             CA_ADAPTER_NFC
4511 #ifdef RA_ADAPTER
4512             ,CA_ADAPTER_REMOTE_ACCESS
4513 #endif
4514
4515 #ifdef TCP_ADAPTER
4516             ,CA_ADAPTER_TCP
4517 #endif
4518         };
4519     int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4520
4521     for(int i = 0; i<numConnTypes; i++)
4522     {
4523         // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
4524         if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
4525         {
4526            caResult = CASelectNetwork(connTypes[i]);
4527            if(caResult == CA_STATUS_OK)
4528            {
4529                retResult = CA_STATUS_OK;
4530            }
4531         }
4532     }
4533
4534     if(retResult != CA_STATUS_OK)
4535     {
4536         return caResult; // Returns error of appropriate transport that failed fatally.
4537     }
4538
4539     return retResult;
4540 }
4541
4542 OCStackResult CAResultToOCResult(CAResult_t caResult)
4543 {
4544     switch (caResult)
4545     {
4546         case CA_STATUS_OK:
4547             return OC_STACK_OK;
4548         case CA_STATUS_INVALID_PARAM:
4549             return OC_STACK_INVALID_PARAM;
4550         case CA_ADAPTER_NOT_ENABLED:
4551             return OC_STACK_ADAPTER_NOT_ENABLED;
4552         case CA_SERVER_STARTED_ALREADY:
4553             return OC_STACK_OK;
4554         case CA_SERVER_NOT_STARTED:
4555             return OC_STACK_ERROR;
4556         case CA_DESTINATION_NOT_REACHABLE:
4557             return OC_STACK_COMM_ERROR;
4558         case CA_SOCKET_OPERATION_FAILED:
4559             return OC_STACK_COMM_ERROR;
4560         case CA_SEND_FAILED:
4561             return OC_STACK_COMM_ERROR;
4562         case CA_RECEIVE_FAILED:
4563             return OC_STACK_COMM_ERROR;
4564         case CA_MEMORY_ALLOC_FAILED:
4565             return OC_STACK_NO_MEMORY;
4566         case CA_REQUEST_TIMEOUT:
4567             return OC_STACK_TIMEOUT;
4568         case CA_DESTINATION_DISCONNECTED:
4569             return OC_STACK_COMM_ERROR;
4570         case CA_STATUS_FAILED:
4571             return OC_STACK_ERROR;
4572         case CA_NOT_SUPPORTED:
4573             return OC_STACK_NOTIMPL;
4574         default:
4575             return OC_STACK_ERROR;
4576     }
4577 }