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