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