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