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