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