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