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