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