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