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