Fix for server request with duplicate token issue
[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         return OC_STACK_DUPLICATE_REQUEST;
2025     }
2026
2027     if(request->requestComplete)
2028     {
2029         OIC_LOG(INFO, TAG, "This Server Request is complete");
2030         ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
2031         OCResource *resource = NULL;
2032         result = DetermineResourceHandling (request, &resHandling, &resource);
2033         if (result == OC_STACK_OK)
2034         {
2035             result = ProcessRequest(resHandling, resource, request);
2036         }
2037     }
2038     else
2039     {
2040         OIC_LOG(INFO, TAG, "This Server Request is incomplete");
2041         result = OC_STACK_CONTINUE;
2042     }
2043     return result;
2044 }
2045
2046 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2047 {
2048     OIC_TRACE_MARK(%s:OCHandleRequests:%s, TAG, requestInfo->info.resourceUri);
2049     OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
2050
2051     OCStackResult requestResult = OC_STACK_ERROR;
2052
2053     if(myStackMode == OC_CLIENT)
2054     {
2055         //TODO: should the client be responding to requests?
2056         return;
2057     }
2058
2059     OCServerProtocolRequest serverRequest = {0};
2060
2061     OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
2062
2063     char * uriWithoutQuery = NULL;
2064     char * query  = NULL;
2065
2066     requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
2067
2068     if (requestResult != OC_STACK_OK || !uriWithoutQuery)
2069     {
2070         OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
2071         return;
2072     }
2073     OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
2074     OIC_LOG_V(INFO, TAG, "Query : %s", query);
2075
2076     if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
2077     {
2078         OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
2079         OICFree(uriWithoutQuery);
2080     }
2081     else
2082     {
2083         OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
2084         OICFree(uriWithoutQuery);
2085         OICFree(query);
2086         return;
2087     }
2088
2089     if(query)
2090     {
2091         if(strlen(query) < MAX_QUERY_LENGTH)
2092         {
2093             OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
2094             OICFree(query);
2095         }
2096         else
2097         {
2098             OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
2099             OICFree(query);
2100             return;
2101         }
2102     }
2103
2104     if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
2105     {
2106         serverRequest.reqTotalSize = requestInfo->info.payloadSize;
2107         serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
2108         if (!serverRequest.payload)
2109         {
2110             OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
2111             return;
2112         }
2113         memcpy (serverRequest.payload, requestInfo->info.payload,
2114                 requestInfo->info.payloadSize);
2115     }
2116     else
2117     {
2118         serverRequest.reqTotalSize = 0;
2119     }
2120
2121     switch (requestInfo->method)
2122     {
2123         case CA_GET:
2124             serverRequest.method = OC_REST_GET;
2125             break;
2126         case CA_PUT:
2127             serverRequest.method = OC_REST_PUT;
2128             break;
2129         case CA_POST:
2130             serverRequest.method = OC_REST_POST;
2131             break;
2132         case CA_DELETE:
2133             serverRequest.method = OC_REST_DELETE;
2134             break;
2135         default:
2136             OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
2137             SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
2138                         requestInfo->info.type, requestInfo->info.numOptions,
2139                         requestInfo->info.options, requestInfo->info.token,
2140                         requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2141                         CA_RESPONSE_DATA);
2142             OICFree(serverRequest.payload);
2143             return;
2144     }
2145
2146     OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
2147             requestInfo->info.tokenLength);
2148
2149     serverRequest.tokenLength = requestInfo->info.tokenLength;
2150     if (serverRequest.tokenLength) {
2151         // Non empty token
2152         serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
2153
2154         if (!serverRequest.requestToken)
2155         {
2156             OIC_LOG(FATAL, TAG, "Allocation for token failed.");
2157             SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
2158                     requestInfo->info.type, requestInfo->info.numOptions,
2159                     requestInfo->info.options, requestInfo->info.token,
2160                     requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2161                     CA_RESPONSE_DATA);
2162             OICFree(serverRequest.payload);
2163             return;
2164         }
2165         memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
2166     }
2167
2168     switch (requestInfo->info.acceptFormat)
2169     {
2170         case CA_FORMAT_APPLICATION_CBOR:
2171             serverRequest.acceptFormat = OC_FORMAT_CBOR;
2172             break;
2173         case CA_FORMAT_UNDEFINED:
2174             serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
2175             break;
2176         default:
2177             serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
2178     }
2179
2180     if (requestInfo->info.type == CA_MSG_CONFIRM)
2181     {
2182         serverRequest.qos = OC_HIGH_QOS;
2183     }
2184     else
2185     {
2186         serverRequest.qos = OC_LOW_QOS;
2187     }
2188     // CA does not need the following field
2189     // Are we sure CA does not need them? how is it responding to multicast
2190     serverRequest.delayedResNeeded = 0;
2191
2192     serverRequest.coapID = requestInfo->info.messageId;
2193
2194     CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
2195
2196     // copy vendor specific header options
2197     uint8_t tempNum = (requestInfo->info.numOptions);
2198
2199     // Assume no observation requested and it is a pure GET.
2200     // If obs registration/de-registration requested it'll be fetched from the
2201     // options in GetObserveHeaderOption()
2202     serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
2203
2204     GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
2205     if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
2206     {
2207         OIC_LOG(ERROR, TAG,
2208                 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
2209         SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
2210                 requestInfo->info.type, requestInfo->info.numOptions,
2211                 requestInfo->info.options, requestInfo->info.token,
2212                 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2213                 CA_RESPONSE_DATA);
2214         OICFree(serverRequest.payload);
2215         OICFree(serverRequest.requestToken);
2216         return;
2217     }
2218
2219     serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
2220     if (serverRequest.numRcvdVendorSpecificHeaderOptions && requestInfo->info.options)
2221     {
2222         serverRequest.rcvdVendorSpecificHeaderOptions = (OCHeaderOption*) OICCalloc(tempNum, sizeof(OCHeaderOption));
2223         if (NULL == serverRequest.rcvdVendorSpecificHeaderOptions)
2224         {
2225             OIC_LOG(ERROR, TAG, "Failed to allocated memory to vnd header options!");
2226             OICFree(serverRequest.payload);
2227             OICFree(serverRequest.requestToken);
2228             return;
2229         }
2230
2231         memcpy (serverRequest.rcvdVendorSpecificHeaderOptions, requestInfo->info.options,
2232             sizeof(CAHeaderOption_t)*tempNum);
2233     }
2234
2235     requestResult = HandleStackRequests (&serverRequest);
2236
2237     // Send ACK to client as precursor to slow response
2238     if (requestResult == OC_STACK_SLOW_RESOURCE)
2239     {
2240         if (requestInfo->info.type == CA_MSG_CONFIRM)
2241         {
2242             SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
2243                                     CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
2244                                     CA_RESPONSE_DATA);
2245         }
2246     }
2247 #ifndef __TIZENRT__
2248     if (requestResult == OC_STACK_RESOURCE_ERROR
2249             && serverRequest.observationOption == OC_OBSERVE_REGISTER)
2250     {
2251         OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2252     }
2253 #else
2254     if (serverRequest.observationOption == OC_OBSERVE_REGISTER)
2255     {
2256         if (requestResult == OC_STACK_RESOURCE_ERROR)
2257         {
2258             OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2259         }
2260         else if (!OCResultToSuccess(requestResult))
2261         {
2262             DeleteObserverUsingToken(requestInfo->info.token, requestInfo->info.tokenLength);
2263         }
2264     }
2265 #endif
2266     else if(!OCResultToSuccess(requestResult))
2267     {
2268         OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
2269
2270         // Delete observer node if it is OBSERVE failure from app
2271         if (serverRequest.observationOption == OC_OBSERVE_REGISTER)
2272         {
2273             DeleteObserverUsingToken(requestInfo->info.token, requestInfo->info.tokenLength);
2274         }
2275
2276         CAResponseResult_t stackResponse =
2277             OCToCAStackResult(requestResult, serverRequest.method);
2278
2279         SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
2280                 requestInfo->info.type, requestInfo->info.numOptions,
2281                 requestInfo->info.options, requestInfo->info.token,
2282                 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2283                 CA_RESPONSE_DATA);
2284     }
2285     // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
2286     // The token is copied in there, and is thus still owned by this function.
2287     OICFree(serverRequest.payload);
2288     OICFree(serverRequest.requestToken);
2289     OICFree(serverRequest.rcvdVendorSpecificHeaderOptions);
2290     OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
2291 }
2292
2293 //This function will be called back by CA layer when a request is received
2294 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2295 {
2296     OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2297     OIC_TRACE_BEGIN(%s:HandleCARequests, TAG);
2298     if(!endPoint)
2299     {
2300         OIC_LOG(ERROR, TAG, "endPoint is NULL");
2301         OIC_TRACE_END();
2302         return;
2303     }
2304
2305     if(!requestInfo)
2306     {
2307         OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2308         OIC_TRACE_END();
2309         return;
2310     }
2311
2312 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2313 #ifdef ROUTING_GATEWAY
2314     bool needRIHandling = false;
2315     bool isEmptyMsg = false;
2316     /*
2317      * Routing manager is going to update either of endpoint or request or both.
2318      * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2319      * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2320      * destination. It can also remove "RM" coap header option before passing request / response to
2321      * RI as this option will make no sense to either RI or application.
2322      */
2323     OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2324                                         &needRIHandling, &isEmptyMsg);
2325     if(OC_STACK_OK != ret || !needRIHandling)
2326     {
2327         OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2328         OIC_TRACE_END();
2329         return;
2330     }
2331 #endif
2332
2333     /*
2334      * Put source in sender endpoint so that the next packet from application can be routed to
2335      * proper destination and remove RM header option.
2336      */
2337     RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2338                  (uint8_t *) &(requestInfo->info.numOptions),
2339                  (CAEndpoint_t *) endPoint);
2340
2341 #ifdef ROUTING_GATEWAY
2342     if (isEmptyMsg)
2343     {
2344         /*
2345          * In Gateways, the MSGType in route option is used to check if the actual
2346          * response is EMPTY message(4 bytes CoAP Header).  In case of Client, the
2347          * EMPTY response is sent in the form of POST request which need to be changed
2348          * to a EMPTY response by RM.  This translation is done in this part of the code.
2349          */
2350         OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2351         CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2352                                      .info.messageId = requestInfo->info.messageId,
2353                                      .info.type = CA_MSG_ACKNOWLEDGE};
2354         OCHandleResponse(endPoint, &respInfo);
2355     }
2356     else
2357 #endif
2358 #endif
2359     {
2360         // Normal handling of the packet
2361         OCHandleRequests(endPoint, requestInfo);
2362     }
2363     OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2364     OIC_TRACE_END();
2365 }
2366
2367 //-----------------------------------------------------------------------------
2368 // Public APIs
2369 //-----------------------------------------------------------------------------
2370 #ifdef RA_ADAPTER
2371 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2372 {
2373     if (!raInfo           ||
2374         !raInfo->username ||
2375         !raInfo->hostname ||
2376         !raInfo->xmpp_domain)
2377     {
2378
2379         return OC_STACK_INVALID_PARAM;
2380     }
2381     OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2382     gRASetInfo = (result == OC_STACK_OK)? true : false;
2383
2384     return result;
2385 }
2386 #endif
2387
2388 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2389 {
2390     (void) ipAddr;
2391     (void) port;
2392     return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2393 }
2394
2395 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2396 {
2397     OC_UNUSED(serverFlags);
2398     OC_UNUSED(clientFlags);
2399
2400     OIC_LOG(DEBUG, TAG, "call OCInit1");
2401     return OCInit2(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS, OC_DEFAULT_ADAPTER);
2402 }
2403
2404 OCStackResult OCInit2(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags,
2405                       OCTransportAdapter transportType)
2406 {
2407     if(stackState == OC_STACK_INITIALIZED)
2408     {
2409         OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2410                 OCStop() between them are ignored.");
2411         return OC_STACK_OK;
2412     }
2413
2414 #ifndef ROUTING_GATEWAY
2415     if (OC_GATEWAY == mode)
2416     {
2417         OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2418         return OC_STACK_INVALID_PARAM;
2419     }
2420 #endif
2421
2422 #ifdef RA_ADAPTER
2423     if(!gRASetInfo)
2424     {
2425         OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2426         return OC_STACK_ERROR;
2427     }
2428 #endif
2429
2430     OCStackResult result = OC_STACK_ERROR;
2431     OIC_LOG(INFO, TAG, "Entering OCInit");
2432
2433     // Validate mode
2434     if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2435         || (mode == OC_GATEWAY)))
2436     {
2437         OIC_LOG(ERROR, TAG, "Invalid mode");
2438         return OC_STACK_ERROR;
2439     }
2440     myStackMode = mode;
2441
2442     if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2443     {
2444         caglobals.client = true;
2445     }
2446     if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2447     {
2448         caglobals.server = true;
2449     }
2450
2451     caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2452     if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2453     {
2454         caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2455     }
2456     caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2457     if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2458     {
2459         caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2460     }
2461
2462     defaultDeviceHandler = NULL;
2463     defaultDeviceHandlerCallbackParameter = NULL;
2464
2465     result = InitializeScheduleResourceList();
2466     VERIFY_SUCCESS(result, OC_STACK_OK);
2467
2468     result = CAResultToOCResult(CAInitialize((CATransportAdapter_t)transportType));
2469     VERIFY_SUCCESS(result, OC_STACK_OK);
2470
2471     result = CAResultToOCResult(OCSelectNetwork(transportType));
2472     VERIFY_SUCCESS(result, OC_STACK_OK);
2473
2474     result = CAResultToOCResult(CARegisterNetworkMonitorHandler(
2475       OCDefaultAdapterStateChangedHandler, OCDefaultConnectionStateChangedHandler));
2476     VERIFY_SUCCESS(result, OC_STACK_OK);
2477
2478     switch (myStackMode)
2479     {
2480         case OC_CLIENT:
2481             CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2482             result = CAResultToOCResult(CAStartDiscoveryServer());
2483             OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2484             break;
2485         case OC_SERVER:
2486             SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2487             result = CAResultToOCResult(CAStartListeningServer());
2488             OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2489             break;
2490         case OC_CLIENT_SERVER:
2491         case OC_GATEWAY:
2492             SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2493             result = CAResultToOCResult(CAStartListeningServer());
2494             if(result == OC_STACK_OK)
2495             {
2496                 result = CAResultToOCResult(CAStartDiscoveryServer());
2497             }
2498             break;
2499     }
2500     VERIFY_SUCCESS(result, OC_STACK_OK);
2501
2502 #ifdef TCP_ADAPTER
2503     CARegisterKeepAliveHandler(OCHandleKeepAliveConnCB);
2504 #endif
2505
2506 #ifdef WITH_PRESENCE
2507     PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2508 #endif // WITH_PRESENCE
2509
2510     //Update Stack state to initialized
2511     stackState = OC_STACK_INITIALIZED;
2512
2513     // Initialize resource
2514     if(myStackMode != OC_CLIENT)
2515     {
2516         result = initResources();
2517     }
2518
2519     // Initialize the SRM Policy Engine
2520     if(result == OC_STACK_OK)
2521     {
2522         result = SRMInitPolicyEngine();
2523         // TODO after BeachHead delivery: consolidate into single SRMInit()
2524     }
2525 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2526     RMSetStackMode(mode);
2527 #ifdef ROUTING_GATEWAY
2528     if (OC_GATEWAY == myStackMode)
2529     {
2530         result = RMInitialize();
2531     }
2532 #endif
2533 #endif
2534
2535 #ifdef TCP_ADAPTER
2536     if (result == OC_STACK_OK)
2537     {
2538         result = OCInitializeKeepAlive(myStackMode);
2539     }
2540 #endif
2541
2542     InitializeObserverList();
2543
2544 exit:
2545     if(result != OC_STACK_OK)
2546     {
2547         OIC_LOG(ERROR, TAG, "Stack initialization error");
2548         TerminateScheduleResourceList();
2549         deleteAllResources();
2550         CATerminate();
2551         stackState = OC_STACK_UNINITIALIZED;
2552     }
2553     return result;
2554 }
2555
2556 OCStackResult OCStop()
2557 {
2558     OIC_LOG(INFO, TAG, "Entering OCStop");
2559
2560     if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2561     {
2562         OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2563         return OC_STACK_OK;
2564     }
2565     else if (stackState != OC_STACK_INITIALIZED)
2566     {
2567         OIC_LOG(INFO, TAG, "Stack not initialized");
2568         return OC_STACK_ERROR;
2569     }
2570
2571     // unset cautil config
2572     CAUtilConfig_t configs = {(CATransportBTFlags_t)CA_DEFAULT_BT_FLAGS};
2573     CAUtilSetBTConfigure(configs);
2574
2575     stackState = OC_STACK_UNINIT_IN_PROGRESS;
2576
2577     CAUnregisterNetworkMonitorHandler(OCDefaultAdapterStateChangedHandler,
2578                                       OCDefaultConnectionStateChangedHandler);
2579
2580 #ifdef WITH_PRESENCE
2581     // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2582     // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2583     presenceResource.presenceTTL = 0;
2584     presenceState = OC_PRESENCE_UNINITIALIZED;
2585 #endif // WITH_PRESENCE
2586
2587 #ifdef ROUTING_GATEWAY
2588     if (OC_GATEWAY == myStackMode)
2589     {
2590         RMTerminate();
2591     }
2592 #endif
2593
2594 #ifdef TCP_ADAPTER
2595     OCTerminateKeepAlive(myStackMode);
2596 #endif
2597
2598     TerminateScheduleResourceList();
2599     // Remove all observers
2600     DeleteObserverList();
2601     // Free memory dynamically allocated for resources
2602     deleteAllResources();
2603     // Remove all the client callbacks
2604     DeleteClientCBList();
2605     // Terminate connectivity-abstraction layer.
2606     CATerminate();
2607
2608     // De-init the SRM Policy Engine
2609     // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2610     SRMDeInitPolicyEngine();
2611
2612     // Destroy Observer List Mutex
2613     TerminateObserverList();
2614
2615     stackState = OC_STACK_UNINITIALIZED;
2616     return OC_STACK_OK;
2617 }
2618
2619 OCStackResult OCStartMulticastServer()
2620 {
2621     if(stackState != OC_STACK_INITIALIZED)
2622     {
2623         OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2624         return OC_STACK_ERROR;
2625     }
2626     CAResult_t ret = CAStartListeningServer();
2627     if (CA_STATUS_OK != ret)
2628     {
2629         OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2630         return OC_STACK_ERROR;
2631     }
2632     return OC_STACK_OK;
2633 }
2634
2635 OCStackResult OCStopMulticastServer()
2636 {
2637     CAResult_t ret = CAStopListeningServer();
2638     if (CA_STATUS_OK != ret)
2639     {
2640         OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2641         return OC_STACK_ERROR;
2642     }
2643     return OC_STACK_OK;
2644 }
2645
2646 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2647 {
2648     switch (qos)
2649     {
2650         case OC_HIGH_QOS:
2651             return CA_MSG_CONFIRM;
2652         case OC_LOW_QOS:
2653         case OC_MEDIUM_QOS:
2654         case OC_NA_QOS:
2655         default:
2656             return CA_MSG_NONCONFIRM;
2657     }
2658 }
2659
2660 OCStackResult ParseRequestUri(const char *fullUri,
2661                               OCTransportAdapter adapter,
2662                               OCTransportFlags flags,
2663                               OCDevAddr **devAddr,
2664                               char **resourceUri,
2665                               char **resourceType)
2666 {
2667     VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2668
2669     OCStackResult result = OC_STACK_OK;
2670     OCDevAddr *da = NULL;
2671     char *colon = NULL;
2672     char *end;
2673
2674     // provide defaults for all returned values
2675     if (devAddr)
2676     {
2677         *devAddr = NULL;
2678     }
2679     if (resourceUri)
2680     {
2681         *resourceUri = NULL;
2682     }
2683     if (resourceType)
2684     {
2685         *resourceType = NULL;
2686     }
2687
2688     // delimit url prefix, if any
2689     const char *start = fullUri;
2690     char *slash2 = strstr(start, "//");
2691     if (slash2)
2692     {
2693         start = slash2 + 2;
2694     }
2695     char *slash = strchr(start, '/');
2696     if (!slash)
2697     {
2698         return OC_STACK_INVALID_URI;
2699     }
2700
2701     // process url scheme
2702     size_t prefixLen = slash2 - fullUri;
2703     bool istcp = false;
2704     if (prefixLen)
2705     {
2706         if (((prefixLen == sizeof(COAP_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAP_TCP_SCHEME, prefixLen)))
2707         || ((prefixLen == sizeof(COAPS_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAPS_TCP_SCHEME, prefixLen))))
2708         {
2709             istcp = true;
2710         }
2711     }
2712
2713     // TODO: this logic should come in with unit tests exercising the various strings
2714     // processs url prefix, if any
2715     size_t urlLen = slash - start;
2716     // port
2717     uint16_t port = 0;
2718     size_t len = 0;
2719     if (urlLen && devAddr)
2720     {   // construct OCDevAddr
2721         if (start[0] == '[')
2722         {   // ipv6 address
2723             char *close = strchr(++start, ']');
2724             if (!close || close > slash)
2725             {
2726                 return OC_STACK_INVALID_URI;
2727             }
2728             end = close;
2729             if (close[1] == ':')
2730             {
2731                 colon = close + 1;
2732             }
2733
2734             if (istcp)
2735             {
2736                 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2737             }
2738             else
2739             {
2740                 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2741             }
2742             flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2743         }
2744         else
2745         {
2746             char *dot = strchr(start, '.');
2747             if (dot && dot < slash)
2748             {   // ipv4 address
2749                 colon = strchr(start, ':');
2750                 end = (colon && colon < slash) ? colon : slash;
2751
2752                 if (istcp)
2753                 {
2754                     // coap over tcp
2755                     adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2756                 }
2757                 else
2758                 {
2759                     adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2760                 }
2761                 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2762             }
2763             else
2764             {   // MAC address
2765                 end = slash;
2766             }
2767         }
2768         len = end - start;
2769         if (len >= sizeof(da->addr))
2770         {
2771             return OC_STACK_INVALID_URI;
2772         }
2773         // collect port, if any
2774         if (colon && colon < slash)
2775         {
2776             for (colon++; colon < slash; colon++)
2777             {
2778                 char c = colon[0];
2779                 if (c < '0' || c > '9')
2780                 {
2781                     return OC_STACK_INVALID_URI;
2782                 }
2783                 port = 10 * port + c - '0';
2784             }
2785         }
2786
2787         len = end - start;
2788         if (len >= sizeof(da->addr))
2789         {
2790             return OC_STACK_INVALID_URI;
2791         }
2792
2793         da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2794         if (!da)
2795         {
2796             return OC_STACK_NO_MEMORY;
2797         }
2798
2799         // Decode address per RFC 6874.
2800         result = OCDecodeAddressForRFC6874(da->addr, sizeof(da->addr), start, end);
2801         if (result != OC_STACK_OK)
2802         {
2803              OICFree(*devAddr);
2804              return result;
2805         }
2806
2807         da->port = port;
2808         da->adapter = adapter;
2809         da->flags = flags;
2810         if (!strncmp(fullUri, "coaps", 5))
2811         {
2812             da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2813         }
2814         *devAddr = da;
2815     }
2816
2817     // process resource uri, if any
2818     if (slash)
2819     {   // request uri and query
2820         size_t ulen = strlen(slash); // resource uri length
2821         size_t tlen = 0;      // resource type length
2822         char *type = NULL;
2823
2824         static const char strPresence[] = "/oic/ad?rt=";
2825         static const size_t lenPresence = sizeof(strPresence) - 1;
2826         if (!strncmp(slash, strPresence, lenPresence))
2827         {
2828             type = slash + lenPresence;
2829             tlen = ulen - lenPresence;
2830         }
2831         // resource uri
2832         if (resourceUri)
2833         {
2834             *resourceUri = (char *)OICMalloc(ulen + 1);
2835             if (!*resourceUri)
2836             {
2837                 result = OC_STACK_NO_MEMORY;
2838                 goto error;
2839             }
2840             OICStrcpy(*resourceUri, (ulen + 1), slash);
2841         }
2842         // resource type
2843         if (type && resourceType)
2844         {
2845             *resourceType = (char *)OICMalloc(tlen + 1);
2846             if (!*resourceType)
2847             {
2848                 result = OC_STACK_NO_MEMORY;
2849                 goto error;
2850             }
2851
2852             OICStrcpy(*resourceType, (tlen+1), type);
2853         }
2854     }
2855
2856     return OC_STACK_OK;
2857
2858 error:
2859     // free all returned values
2860     if (devAddr)
2861     {
2862         OICFree(*devAddr);
2863     }
2864     if (resourceUri)
2865     {
2866         OICFree(*resourceUri);
2867     }
2868     if (resourceType)
2869     {
2870         OICFree(*resourceType);
2871     }
2872     return result;
2873 }
2874
2875 #ifdef WITH_PRESENCE
2876 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2877                                        char **requestUri,
2878                                        bool isMulticast)
2879 {
2880     char uri[CA_MAX_URI_LENGTH];
2881
2882     FormCanonicalPresenceUri(endpoint, uri, isMulticast);
2883
2884     *requestUri = OICStrdup(uri);
2885     if (!*requestUri)
2886     {
2887         return OC_STACK_NO_MEMORY;
2888     }
2889
2890     return OC_STACK_OK;
2891 }
2892 #endif // WITH_PRESENCE
2893
2894 /**
2895  * Discover or Perform requests on a specified resource
2896  */
2897 OCStackResult OCDoResource(OCDoHandle *handle,
2898                             OCMethod method,
2899                             const char *requestUri,
2900                             const OCDevAddr *destination,
2901                             OCPayload* payload,
2902                             OCConnectivityType connectivityType,
2903                             OCQualityOfService qos,
2904                             OCCallbackData *cbData,
2905                             OCHeaderOption *options,
2906                             uint8_t numOptions)
2907 {
2908     OCStackResult ret = OCDoRequest(handle, method, requestUri,destination, payload,
2909                 connectivityType, qos, cbData, options, numOptions);
2910
2911     // This is the owner of the payload object, so we free it
2912     OCPayloadDestroy(payload);
2913     return ret;
2914 }
2915
2916 /**
2917  * Discover or Perform requests on a specified resource
2918  */
2919 OCStackResult OCDoRequest(OCDoHandle *handle,
2920                             OCMethod method,
2921                             const char *requestUri,
2922                             const OCDevAddr *destination,
2923                             OCPayload* payload,
2924                             OCConnectivityType connectivityType,
2925                             OCQualityOfService qos,
2926                             OCCallbackData *cbData,
2927                             OCHeaderOption *options,
2928                             uint8_t numOptions)
2929 {
2930     OIC_LOG(INFO, TAG, "Entering OCDoResource");
2931     OIC_TRACE_BEGIN(%s:OCDoRequest, TAG);
2932
2933     // Validate input parameters
2934     VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2935     VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2936
2937     OCStackResult result = OC_STACK_ERROR;
2938     CAResult_t caResult;
2939     CAToken_t token = NULL;
2940     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2941     ClientCB *clientCB = NULL;
2942     OCDoHandle resHandle = NULL;
2943     CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2944     OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2945     uint32_t ttl = 0;
2946     OCTransportAdapter adapter;
2947     OCTransportFlags flags;
2948     // the request contents are put here
2949     CARequestInfo_t requestInfo = {.method = CA_GET};
2950     // requestUri  will be parsed into the following three variables
2951     OCDevAddr *devAddr = NULL;
2952     char *resourceUri = NULL;
2953     char *resourceType = NULL;
2954
2955     /*
2956      * Support original behavior with address on resourceUri argument.
2957      */
2958     adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2959     flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2960
2961     if (requestUri)
2962     {
2963         result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2964         if (result != OC_STACK_OK)
2965         {
2966             OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2967             goto exit;
2968         }
2969     }
2970     else if (!checkProxyUri(options, numOptions))
2971     {
2972         OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
2973         goto exit;
2974     }
2975
2976     switch (method)
2977     {
2978     case OC_REST_GET:
2979     case OC_REST_OBSERVE:
2980     case OC_REST_OBSERVE_ALL:
2981         requestInfo.method = CA_GET;
2982         break;
2983     case OC_REST_PUT:
2984         requestInfo.method = CA_PUT;
2985         break;
2986     case OC_REST_POST:
2987         requestInfo.method = CA_POST;
2988         break;
2989     case OC_REST_DELETE:
2990         requestInfo.method = CA_DELETE;
2991         break;
2992     case OC_REST_DISCOVER:
2993 #ifdef WITH_PRESENCE
2994     case OC_REST_PRESENCE:
2995 #endif
2996         if (destination || devAddr)
2997         {
2998             requestInfo.isMulticast = false;
2999         }
3000         else
3001         {
3002             tmpDevAddr.adapter = adapter;
3003             tmpDevAddr.flags = flags;
3004             destination = &tmpDevAddr;
3005             requestInfo.isMulticast = true;
3006             qos = OC_LOW_QOS;
3007         }
3008         // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
3009         // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
3010         //                   replacing method type with GET.
3011         requestInfo.method = CA_GET;
3012         break;
3013     default:
3014         result = OC_STACK_INVALID_METHOD;
3015         goto exit;
3016     }
3017
3018     if (!devAddr && !destination)
3019     {
3020         OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
3021         result = OC_STACK_INVALID_PARAM;
3022         goto exit;
3023     }
3024
3025     /* If not original behavior, use destination argument */
3026     if (destination && !devAddr)
3027     {
3028         devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
3029         if (!devAddr)
3030         {
3031             result = OC_STACK_NO_MEMORY;
3032             goto exit;
3033         }
3034         OIC_LOG(DEBUG, TAG, "devAddr is set as destination");
3035         *devAddr = *destination;
3036     }
3037
3038     if (devAddr)
3039     {
3040         OIC_LOG_V(INFO_PRIVATE, TAG, "remoteId of devAddr : %s", devAddr->remoteId);
3041         if (!requestInfo.isMulticast)
3042         {
3043             OIC_LOG_V(DEBUG, TAG, "remoteAddr of devAddr : [%s]:[%d]",
3044                       devAddr->addr, devAddr->port);
3045         }
3046     }
3047
3048     resHandle = GenerateInvocationHandle();
3049     if (!resHandle)
3050     {
3051         result = OC_STACK_NO_MEMORY;
3052         goto exit;
3053     }
3054
3055     caResult = CAGenerateToken(&token, tokenLength);
3056     if (caResult != CA_STATUS_OK)
3057     {
3058         OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3059         result= OC_STACK_ERROR;
3060         goto exit;
3061     }
3062
3063     // fill in request data
3064     requestInfo.info.type = qualityOfServiceToMessageType(qos);
3065     requestInfo.info.token = token;
3066     requestInfo.info.tokenLength = tokenLength;
3067
3068     if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
3069     {
3070         result = CreateObserveHeaderOption (&(requestInfo.info.options),
3071                                     options, numOptions, OC_OBSERVE_REGISTER);
3072         if (result != OC_STACK_OK)
3073         {
3074             goto exit;
3075         }
3076         requestInfo.info.numOptions = numOptions + 1;
3077     }
3078     else
3079     {
3080         requestInfo.info.numOptions = numOptions;
3081         requestInfo.info.options =
3082             (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
3083         memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
3084                numOptions * sizeof(CAHeaderOption_t));
3085     }
3086
3087     CopyDevAddrToEndpoint(devAddr, &endpoint);
3088
3089     if(payload)
3090     {
3091         if((result =
3092             OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
3093                 != OC_STACK_OK)
3094         {
3095             OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
3096             goto exit;
3097         }
3098         requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
3099     }
3100     else
3101     {
3102         requestInfo.info.payload = NULL;
3103         requestInfo.info.payloadSize = 0;
3104         requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
3105     }
3106
3107     // prepare for response
3108 #ifdef WITH_PRESENCE
3109     if (method == OC_REST_PRESENCE)
3110     {
3111         char *presenceUri = NULL;
3112         result = OCPreparePresence(&endpoint, &presenceUri,
3113                                    requestInfo.isMulticast);
3114         if (OC_STACK_OK != result)
3115         {
3116             goto exit;
3117         }
3118
3119         // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
3120         // Presence notification will form a canonical uri to
3121         // look for callbacks into the application.
3122         if (resourceUri)
3123         {
3124             OICFree(resourceUri);
3125         }
3126         resourceUri = presenceUri;
3127     }
3128 #endif
3129
3130     // update resourceUri onto requestInfo after check presence uri
3131     requestInfo.info.resourceUri = resourceUri;
3132
3133     ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
3134     result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
3135                             method, devAddr, resourceUri, resourceType, ttl);
3136     if (OC_STACK_OK != result)
3137     {
3138         goto exit;
3139     }
3140
3141     cbData = NULL;        // Client CB list entry now owns it
3142     token = NULL;         // Client CB list entry now owns it
3143     devAddr = NULL;       // Client CB list entry now owns it
3144     resourceUri = NULL;   // Client CB list entry now owns it
3145     resourceType = NULL;  // Client CB list entry now owns it
3146
3147 #ifdef WITH_PRESENCE
3148     if (method == OC_REST_PRESENCE)
3149     {
3150         OIC_LOG(ERROR, TAG, "AddClientCB for presence done.");
3151
3152         if (handle)
3153         {
3154             *handle = resHandle;
3155         }
3156 #ifdef WITH_PROCESS_EVENT
3157         OCSendProcessEventSignal();
3158 #endif // WITH_PROCESS_EVENT
3159
3160         goto exit;
3161     }
3162 #endif
3163
3164     // send request
3165     result = OCSendRequest(&endpoint, &requestInfo);
3166     if (OC_STACK_OK != result)
3167     {
3168         goto exit;
3169     }
3170
3171     if (handle)
3172     {
3173         *handle = resHandle;
3174     }
3175
3176 exit:
3177     if (result != OC_STACK_OK)
3178     {
3179         OIC_LOG(ERROR, TAG, "OCDoResource error");
3180         if (NULL != cbData && NULL != cbData->cd)
3181         {
3182             cbData->cd(cbData->context);
3183         }
3184         FindAndDeleteClientCB(clientCB);
3185         CADestroyToken(token);
3186         if (handle)
3187         {
3188             *handle = NULL;
3189         }
3190         OICFree(resHandle);
3191     }
3192
3193     OICFree(requestInfo.info.payload);
3194     OICFree(devAddr);
3195     OICFree(resourceUri);
3196     OICFree(resourceType);
3197     OICFree(requestInfo.info.options);
3198     OIC_TRACE_END();
3199     return result;
3200 }
3201
3202 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
3203         uint8_t numOptions)
3204 {
3205     /*
3206      * This ftn is implemented one of two ways in the case of observation:
3207      *
3208      * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
3209      *      Remove the callback associated on client side.
3210      *      When the next notification comes in from server,
3211      *      reply with RESET message to server.
3212      *      Keep in mind that the server will react to RESET only
3213      *      if the last notification was sent as CON
3214      *
3215      * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
3216      *      and it is associated with an observe request
3217      *      (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
3218      *      Send CON Observe request to server with
3219      *      observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
3220      *      Remove the callback associated on client side.
3221      */
3222     OCStackResult ret = OC_STACK_OK;
3223     CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3224     CARequestInfo_t requestInfo = {.method = CA_GET};
3225
3226     if(!handle)
3227     {
3228         return OC_STACK_INVALID_PARAM;
3229     }
3230
3231     ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
3232     if (!clientCB)
3233     {
3234         OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
3235         return OC_STACK_ERROR;
3236     }
3237
3238     switch (clientCB->method)
3239     {
3240         case OC_REST_OBSERVE:
3241         case OC_REST_OBSERVE_ALL:
3242
3243             OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
3244
3245             CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
3246
3247             if (((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS) ||
3248                     ((endpoint.adapter & CA_ADAPTER_TCP) && OC_LOW_QOS_WITH_TCP == qos))
3249             {
3250                 OIC_LOG_V(INFO, TAG, "the %s observe callback is removed", clientCB->requestUri);
3251                 FindAndDeleteClientCB(clientCB);
3252                 break;
3253             }
3254
3255             OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
3256
3257             requestInfo.info.type = qualityOfServiceToMessageType(qos);
3258             requestInfo.info.token = clientCB->token;
3259             requestInfo.info.tokenLength = clientCB->tokenLength;
3260
3261             if (CreateObserveHeaderOption (&(requestInfo.info.options),
3262                     options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
3263             {
3264                 return OC_STACK_ERROR;
3265             }
3266             requestInfo.info.numOptions = numOptions + 1;
3267             requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
3268
3269
3270             ret = OCSendRequest(&endpoint, &requestInfo);
3271
3272             if (requestInfo.info.options)
3273             {
3274                 OICFree (requestInfo.info.options);
3275             }
3276             if (requestInfo.info.resourceUri)
3277             {
3278                 OICFree (requestInfo.info.resourceUri);
3279             }
3280
3281             break;
3282
3283         case OC_REST_DISCOVER:
3284             OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
3285                                            clientCB->requestUri);
3286             FindAndDeleteClientCB(clientCB);
3287             break;
3288
3289 #ifdef WITH_PRESENCE
3290         case OC_REST_PRESENCE:
3291             FindAndDeleteClientCB(clientCB);
3292             break;
3293 #endif
3294         case OC_REST_GET:
3295         case OC_REST_PUT:
3296         case OC_REST_POST:
3297         case OC_REST_DELETE:
3298             OIC_LOG_V(INFO, TAG, "Cancelling request callback for resource %s",
3299                                            clientCB->requestUri);
3300             FindAndDeleteClientCB(clientCB);
3301             break;
3302
3303         default:
3304             ret = OC_STACK_INVALID_METHOD;
3305             break;
3306     }
3307
3308     return ret;
3309 }
3310
3311 /**
3312  * @brief   Register Persistent storage callback.
3313  * @param   persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
3314  * @return
3315  *     OC_STACK_OK    - No errors; Success
3316  *     OC_STACK_INVALID_PARAM - Invalid parameter
3317  */
3318 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
3319 {
3320     OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
3321     if(!persistentStorageHandler)
3322     {
3323         OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3324         return OC_STACK_INVALID_PARAM;
3325     }
3326     else
3327     {
3328         if( !persistentStorageHandler->open ||
3329                 !persistentStorageHandler->close ||
3330                 !persistentStorageHandler->read ||
3331                 !persistentStorageHandler->unlink ||
3332                 !persistentStorageHandler->write)
3333         {
3334             OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3335             return OC_STACK_INVALID_PARAM;
3336         }
3337     }
3338     return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
3339 }
3340
3341 #ifdef WITH_PRESENCE
3342
3343 #ifdef WITH_PROCESS_EVENT
3344 OCStackResult OCProcessPresence(uint32_t *nextEventTime)
3345 #else   // WITH_PROCESS_EVENT
3346 OCStackResult OCProcessPresence(void)
3347 #endif  // !WITH_PROCESS_EVENT
3348 {
3349     OCStackResult result = OC_STACK_OK;
3350
3351     // the following line floods the log with messages that are irrelevant
3352     // to most purposes.  Uncomment as needed.
3353     //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3354     ClientCB* cbNode = NULL;
3355     ClientCB* tempcbNode = NULL;
3356     OCClientResponse clientResponse;
3357     OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3358
3359     LL_FOREACH_SAFE(cbList, cbNode, tempcbNode)
3360     {
3361         if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3362         {
3363             continue;
3364         }
3365
3366         uint32_t now = GetTicks(0);
3367         OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3368                                                 cbNode->presence->TTLlevel);
3369         OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3370
3371         if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3372         {
3373             goto exit;
3374         }
3375
3376         if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3377         {
3378             OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3379                     cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3380         }
3381         if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3382         {
3383             OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3384
3385             clientResponse.sequenceNumber = 0;
3386             clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3387             clientResponse.devAddr = *cbNode->devAddr;
3388             FixUpClientResponse(&clientResponse);
3389             clientResponse.payload = NULL;
3390
3391             // Increment the TTLLevel (going to a next state), so we don't keep
3392             // sending presence notification to client.
3393             cbNode->presence->TTLlevel++;
3394             OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3395                                         cbNode->presence->TTLlevel);
3396
3397             OIC_LOG(INFO, TAG, "Before calling into application address space for presence timeout");
3398             cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3399             OIC_LOG(INFO, TAG, "After calling into application address space for presence timeout");
3400
3401             if (cbResult == OC_STACK_DELETE_TRANSACTION)
3402             {
3403                 FindAndDeleteClientCB(cbNode);
3404             }
3405             continue;
3406         }
3407
3408         uint32_t timeout = cbNode->presence->timeOut[cbNode->presence->TTLlevel];
3409         if (now < timeout)
3410         {
3411 #ifdef WITH_PROCESS_EVENT
3412             if (nextEventTime && (timeout - now) < *nextEventTime)
3413             {
3414                 *nextEventTime = timeout - now;
3415             }
3416 #endif // WITH_PROCESS_EVENT
3417             continue;
3418         }
3419
3420         CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3421         CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3422         CARequestInfo_t requestInfo = {.method = CA_GET};
3423
3424         OIC_LOG(DEBUG, TAG, "time to test server presence");
3425
3426         CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3427
3428         requestData.type = CA_MSG_NONCONFIRM;
3429         requestData.token = cbNode->token;
3430         requestData.tokenLength = cbNode->tokenLength;
3431         requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3432         requestInfo.method = CA_GET;
3433         requestInfo.info = requestData;
3434
3435         result = OCSendRequest(&endpoint, &requestInfo);
3436         if (OC_STACK_OK != result)
3437         {
3438             goto exit;
3439         }
3440
3441         cbNode->presence->TTLlevel++;
3442         OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3443     }
3444 exit:
3445     if (result != OC_STACK_OK)
3446     {
3447         OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3448     }
3449
3450     return result;
3451 }
3452 #endif // WITH_PRESENCE
3453
3454 #ifdef WITH_PROCESS_EVENT
3455 OCStackResult OCProcess(void)
3456 {
3457     uint32_t nextEventTime;
3458     return OCProcessEvent(&nextEventTime);
3459 }
3460
3461 OCStackResult OCProcessEvent(uint32_t *nextEventTime)
3462 {
3463     if (stackState == OC_STACK_UNINITIALIZED)
3464     {
3465         OIC_LOG(ERROR, TAG, "OCProcess has failed. ocstack is not initialized");
3466         return OC_STACK_ERROR;
3467     }
3468
3469     *nextEventTime = UINT32_MAX;
3470
3471 #ifdef WITH_PRESENCE
3472     OCProcessPresence(nextEventTime);
3473     OIC_LOG_V(INFO, TAG, "OCProcessPresence next event time : %u", *nextEventTime);
3474 #endif
3475     CAHandleRequestResponse();
3476
3477 // TODO
3478 #ifdef ROUTING_GATEWAY
3479     RMProcess(nextEventTime);
3480 #endif
3481
3482 #ifdef TCP_ADAPTER
3483     OCProcessKeepAlive(nextEventTime);
3484     OIC_LOG_V(INFO, TAG, "OCProcessKeepAlive next event time : %u", *nextEventTime);
3485 #endif
3486     return OC_STACK_OK;
3487 }
3488
3489 void OCRegisterProcessEvent(oc_event event)
3490 {
3491     g_ocProcessEvent = event;
3492     CARegisterProcessEvent(event);
3493 }
3494
3495 void OCSendProcessEventSignal(void)
3496 {
3497     if (g_ocProcessEvent)
3498     {
3499         oc_event_signal(g_ocProcessEvent);
3500     }
3501 }
3502 #else // WITH_PROCESS_EVENT
3503
3504 OCStackResult OCProcess()
3505 {
3506     if (stackState == OC_STACK_UNINITIALIZED)
3507     {
3508         OIC_LOG(ERROR, TAG, "OCProcess has failed. ocstack is not initialized");
3509         return OC_STACK_ERROR;
3510     }
3511 #ifdef WITH_PRESENCE
3512     OCProcessPresence();
3513 #endif
3514     CAHandleRequestResponse();
3515
3516 #ifdef ROUTING_GATEWAY
3517     RMProcess();
3518 #endif
3519
3520 #ifdef TCP_ADAPTER
3521     OCProcessKeepAlive();
3522 #endif
3523     return OC_STACK_OK;
3524 }
3525 #endif // !WITH_PROCESS_EVENT
3526
3527 #ifdef WITH_PRESENCE
3528 OCStackResult OCStartPresence(const uint32_t ttl)
3529 {
3530     OIC_LOG(INFO, TAG, "Entering OCStartPresence");
3531     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3532     OCChangeResourceProperty(
3533             &(((OCResource *)presenceResource.handle)->resourceProperties),
3534             OC_ACTIVE, 1);
3535
3536     if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3537     {
3538         presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3539         OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3540     }
3541     else if (0 == ttl)
3542     {
3543         presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3544         OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3545     }
3546     else
3547     {
3548         presenceResource.presenceTTL = ttl;
3549     }
3550 #ifndef __TIZENRT__
3551     OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3552 #endif
3553
3554     if (OC_PRESENCE_UNINITIALIZED == presenceState)
3555     {
3556         presenceState = OC_PRESENCE_INITIALIZED;
3557
3558         OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3559
3560         CAToken_t caToken = NULL;
3561         CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3562         if (caResult != CA_STATUS_OK)
3563         {
3564             OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3565             CADestroyToken(caToken);
3566             return OC_STACK_ERROR;
3567         }
3568
3569         AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3570                 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3571         CADestroyToken(caToken);
3572     }
3573
3574     // Each time OCStartPresence is called
3575     // a different random 32-bit integer number is used
3576     ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3577
3578     return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3579             OC_PRESENCE_TRIGGER_CREATE);
3580 }
3581
3582 OCStackResult OCStopPresence()
3583 {
3584     OIC_LOG(INFO, TAG, "Entering OCStopPresence");
3585     OCStackResult result = OC_STACK_ERROR;
3586
3587     if(presenceResource.handle)
3588     {
3589         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3590
3591     // make resource inactive
3592     result = OCChangeResourceProperty(
3593             &(((OCResource *) presenceResource.handle)->resourceProperties),
3594             OC_ACTIVE, 0);
3595     }
3596
3597     if(result != OC_STACK_OK)
3598     {
3599         OIC_LOG(ERROR, TAG,
3600                       "Changing the presence resource properties to ACTIVE not successful");
3601         return result;
3602     }
3603
3604     return SendStopNotification();
3605 }
3606 #endif
3607
3608 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3609                                             void* callbackParameter)
3610 {
3611     defaultDeviceHandler = entityHandler;
3612     defaultDeviceHandlerCallbackParameter = callbackParameter;
3613
3614     return OC_STACK_OK;
3615 }
3616
3617 OCStackResult OCCreateResource(OCResourceHandle *handle,
3618         const char *resourceTypeName,
3619         const char *resourceInterfaceName,
3620         const char *uri, OCEntityHandler entityHandler,
3621         void* callbackParam,
3622         uint8_t resourceProperties)
3623 {
3624
3625     OCResource *pointer = NULL;
3626     OCStackResult result = OC_STACK_ERROR;
3627
3628     OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3629
3630     if(myStackMode == OC_CLIENT)
3631     {
3632         return OC_STACK_INVALID_PARAM;
3633     }
3634     // Validate parameters
3635     if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3636     {
3637         OIC_LOG(ERROR, TAG, "URI is empty or too long");
3638         return OC_STACK_INVALID_URI;
3639     }
3640     // Is it presented during resource discovery?
3641     if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3642     {
3643         OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3644         return OC_STACK_INVALID_PARAM;
3645     }
3646
3647     if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3648     {
3649         resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3650     }
3651
3652 #ifdef MQ_PUBLISHER
3653     resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3654 #endif
3655     // Make sure resourceProperties bitmask has allowed properties specified
3656     if (resourceProperties
3657             > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3658                OC_EXPLICIT_DISCOVERABLE
3659 #ifdef MQ_PUBLISHER
3660                | OC_MQ_PUBLISHER
3661 #endif
3662 #ifdef MQ_BROKER
3663                | OC_MQ_BROKER
3664 #endif
3665                ))
3666     {
3667         OIC_LOG(ERROR, TAG, "Invalid property");
3668         return OC_STACK_INVALID_PARAM;
3669     }
3670
3671     // If the headResource is NULL, then no resources have been created...
3672     pointer = headResource;
3673     if (pointer)
3674     {
3675         // At least one resources is in the resource list, so we need to search for
3676         // repeated URLs, which are not allowed.  If a repeat is found, exit with an error
3677         while (pointer)
3678         {
3679             if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3680             {
3681                 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3682                 return OC_STACK_INVALID_PARAM;
3683             }
3684             pointer = pointer->next;
3685         }
3686     }
3687     // Create the pointer and insert it into the resource list
3688     pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3689     if (!pointer)
3690     {
3691         result = OC_STACK_NO_MEMORY;
3692         goto exit;
3693     }
3694     pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3695
3696     insertResource(pointer);
3697
3698     // Set the uri
3699     pointer->uri = OICStrdup(uri);
3700     if (!pointer->uri)
3701     {
3702         result = OC_STACK_NO_MEMORY;
3703         goto exit;
3704     }
3705
3706     // Set properties.  Set OC_ACTIVE
3707     pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3708             | OC_ACTIVE);
3709
3710     // Add the resourcetype to the resource
3711     result = BindResourceTypeToResource(pointer, resourceTypeName);
3712     if (result != OC_STACK_OK)
3713     {
3714         OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3715         goto exit;
3716     }
3717
3718     // Add the resourceinterface to the resource
3719     result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3720     if (result != OC_STACK_OK)
3721     {
3722         OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3723         goto exit;
3724     }
3725
3726     // If an entity handler has been passed, attach it to the newly created
3727     // resource.  Otherwise, set the default entity handler.
3728     if (entityHandler)
3729     {
3730         pointer->entityHandler = entityHandler;
3731         pointer->entityHandlerCallbackParam = callbackParam;
3732     }
3733     else
3734     {
3735         pointer->entityHandler = defaultResourceEHandler;
3736         pointer->entityHandlerCallbackParam = NULL;
3737     }
3738
3739     // Initialize a pointer indicating child resources in case of collection
3740     pointer->rsrcChildResourcesHead = NULL;
3741
3742     *handle = pointer;
3743     result = OC_STACK_OK;
3744
3745 #ifdef WITH_PRESENCE
3746     if (presenceResource.handle)
3747     {
3748         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3749         SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3750     }
3751 #endif
3752 exit:
3753     if (result != OC_STACK_OK)
3754     {
3755         // Deep delete of resource and other dynamic elements that it contains
3756         deleteResource(pointer);
3757     }
3758     return result;
3759 }
3760
3761 OCStackResult OCBindResource(
3762         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3763 {
3764     OCResource *resource = NULL;
3765     OCChildResource *tempChildResource = NULL;
3766     OCChildResource *newChildResource = NULL;
3767
3768     OIC_LOG(INFO, TAG, "Entering OCBindResource");
3769
3770     // Validate parameters
3771     VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3772     VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3773     // Container cannot contain itself
3774     if (collectionHandle == resourceHandle)
3775     {
3776         OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3777         return OC_STACK_INVALID_PARAM;
3778     }
3779
3780     // Use the handle to find the resource in the resource linked list
3781     resource = findResource((OCResource *) collectionHandle);
3782     if (!resource)
3783     {
3784         OIC_LOG(ERROR, TAG, "Collection handle not found");
3785         return OC_STACK_INVALID_PARAM;
3786     }
3787
3788     // Look for an open slot to add add the child resource.
3789     // If found, add it and return success
3790
3791     tempChildResource = resource->rsrcChildResourcesHead;
3792
3793     while(resource->rsrcChildResourcesHead && tempChildResource->next)
3794     {
3795         // TODO: what if one of child resource was deregistered without unbinding?
3796         tempChildResource = tempChildResource->next;
3797     }
3798
3799     // Do memory allocation for child resource
3800     newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3801     if(!newChildResource)
3802     {
3803         OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3804         return OC_STACK_ERROR;
3805     }
3806
3807     newChildResource->rsrcResource = (OCResource *) resourceHandle;
3808     newChildResource->next = NULL;
3809
3810     if(!resource->rsrcChildResourcesHead)
3811     {
3812         resource->rsrcChildResourcesHead = newChildResource;
3813     }
3814     else {
3815         tempChildResource->next = newChildResource;
3816     }
3817
3818     OIC_LOG(INFO, TAG, "resource bound");
3819
3820 #ifdef WITH_PRESENCE
3821     if (presenceResource.handle)
3822     {
3823         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3824         SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3825                 OC_PRESENCE_TRIGGER_CHANGE);
3826     }
3827 #endif
3828
3829     return OC_STACK_OK;
3830 }
3831
3832 OCStackResult OCUnBindResource(
3833         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3834 {
3835     OCResource *resource = NULL;
3836     OCChildResource *tempChildResource = NULL;
3837     OCChildResource *tempLastChildResource = NULL;
3838
3839     OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3840
3841     // Validate parameters
3842     VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3843     VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3844     // Container cannot contain itself
3845     if (collectionHandle == resourceHandle)
3846     {
3847         OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3848         return OC_STACK_INVALID_PARAM;
3849     }
3850
3851     // Use the handle to find the resource in the resource linked list
3852     resource = findResource((OCResource *) collectionHandle);
3853     if (!resource)
3854     {
3855         OIC_LOG(ERROR, TAG, "Collection handle not found");
3856         return OC_STACK_INVALID_PARAM;
3857     }
3858
3859     // Look for an open slot to add add the child resource.
3860     // If found, add it and return success
3861     if(!resource->rsrcChildResourcesHead)
3862     {
3863         OIC_LOG(INFO, TAG, "resource not found in collection");
3864
3865         // Unable to add resourceHandle, so return error
3866         return OC_STACK_ERROR;
3867
3868     }
3869
3870     tempChildResource = resource->rsrcChildResourcesHead;
3871
3872     while (tempChildResource)
3873     {
3874         if(tempChildResource->rsrcResource == resourceHandle)
3875         {
3876             // if resource going to be unbinded is the head one.
3877             if( tempChildResource == resource->rsrcChildResourcesHead )
3878             {
3879                 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3880                 OICFree(resource->rsrcChildResourcesHead);
3881                 resource->rsrcChildResourcesHead = temp;
3882                 temp = NULL;
3883             }
3884             else
3885             {
3886                 OCChildResource *temp = tempChildResource->next;
3887                 OICFree(tempChildResource);
3888                 if (tempLastChildResource)
3889                 {
3890                     tempLastChildResource->next = temp;
3891                     temp = NULL;
3892                 }
3893             }
3894
3895             OIC_LOG(INFO, TAG, "resource unbound");
3896
3897             // Send notification when resource is unbounded successfully.
3898 #ifdef WITH_PRESENCE
3899             if (presenceResource.handle)
3900             {
3901                 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3902                 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3903                         OC_PRESENCE_TRIGGER_CHANGE);
3904             }
3905 #endif
3906             tempChildResource = NULL;
3907             tempLastChildResource = NULL;
3908
3909             return OC_STACK_OK;
3910
3911         }
3912
3913         tempLastChildResource = tempChildResource;
3914         tempChildResource = tempChildResource->next;
3915     }
3916
3917     OIC_LOG(INFO, TAG, "resource not found in collection");
3918
3919     tempChildResource = NULL;
3920     tempLastChildResource = NULL;
3921
3922     // Unable to add resourceHandle, so return error
3923     return OC_STACK_ERROR;
3924 }
3925
3926 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3927 {
3928     if (!resourceItemName)
3929     {
3930         return false;
3931     }
3932     // Per RFC 6690 only registered values must follow the first rule below.
3933     // At this point in time the only values registered begin with "core", and
3934     // all other values are specified as opaque strings where multiple values
3935     // are separated by a space.
3936     if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3937     {
3938         for(size_t index = sizeof(CORESPEC) - 1;  resourceItemName[index]; ++index)
3939         {
3940             if (resourceItemName[index] != '.'
3941                 && resourceItemName[index] != '-'
3942                 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3943                 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3944             {
3945                 return false;
3946             }
3947         }
3948     }
3949     else
3950     {
3951         for (size_t index = 0; resourceItemName[index]; ++index)
3952         {
3953             if (resourceItemName[index] == ' '
3954                 || resourceItemName[index] == '\t'
3955                 || resourceItemName[index] == '\r'
3956                 || resourceItemName[index] == '\n')
3957             {
3958                 return false;
3959             }
3960         }
3961     }
3962
3963     return true;
3964 }
3965
3966 OCStackResult BindResourceTypeToResource(OCResource* resource,
3967                                             const char *resourceTypeName)
3968 {
3969     OCResourceType *pointer = NULL;
3970     char *str = NULL;
3971     OCStackResult result = OC_STACK_ERROR;
3972
3973     VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3974
3975     if (!ValidateResourceTypeInterface(resourceTypeName))
3976     {
3977         OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3978         return OC_STACK_INVALID_PARAM;
3979     }
3980
3981     pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3982     if (!pointer)
3983     {
3984         result = OC_STACK_NO_MEMORY;
3985         goto exit;
3986     }
3987
3988     str = OICStrdup(resourceTypeName);
3989     if (!str)
3990     {
3991         result = OC_STACK_NO_MEMORY;
3992         goto exit;
3993     }
3994     pointer->resourcetypename = str;
3995     pointer->next = NULL;
3996
3997     insertResourceType(resource, pointer);
3998     result = OC_STACK_OK;
3999
4000 exit:
4001     if (result != OC_STACK_OK)
4002     {
4003         OICFree(pointer);
4004         OICFree(str);
4005     }
4006
4007     return result;
4008 }
4009
4010 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
4011         const char *resourceInterfaceName)
4012 {
4013     OCResourceInterface *pointer = NULL;
4014     char *str = NULL;
4015     OCStackResult result = OC_STACK_ERROR;
4016
4017     VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
4018
4019     if (!ValidateResourceTypeInterface(resourceInterfaceName))
4020     {
4021         OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
4022         return OC_STACK_INVALID_PARAM;
4023     }
4024
4025     OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
4026
4027     pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
4028     if (!pointer)
4029     {
4030         result = OC_STACK_NO_MEMORY;
4031         goto exit;
4032     }
4033
4034     str = OICStrdup(resourceInterfaceName);
4035     if (!str)
4036     {
4037         result = OC_STACK_NO_MEMORY;
4038         goto exit;
4039     }
4040     pointer->name = str;
4041
4042     // Bind the resourceinterface to the resource
4043     insertResourceInterface(resource, pointer);
4044
4045     result = OC_STACK_OK;
4046
4047     exit:
4048     if (result != OC_STACK_OK)
4049     {
4050         OICFree(pointer);
4051         OICFree(str);
4052     }
4053
4054     return result;
4055 }
4056
4057 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
4058         const char *resourceTypeName)
4059 {
4060
4061     OCStackResult result = OC_STACK_ERROR;
4062     OCResource *resource = NULL;
4063
4064     resource = findResource((OCResource *) handle);
4065     if (!resource)
4066     {
4067         OIC_LOG(ERROR, TAG, "Resource not found");
4068         return OC_STACK_ERROR;
4069     }
4070
4071     result = BindResourceTypeToResource(resource, resourceTypeName);
4072
4073 #ifdef WITH_PRESENCE
4074     if(presenceResource.handle)
4075     {
4076         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4077         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4078     }
4079 #endif
4080
4081     return result;
4082 }
4083
4084 OCStackResult OCResetResourceTypes(OCResourceHandle handle,
4085                                    const char *newResourceType)
4086 {
4087     OCStackResult result = OC_STACK_ERROR;
4088     OCResource *resource = NULL;
4089
4090     resource = findResource((OCResource *) handle);
4091     if (!resource)
4092     {
4093         OIC_LOG(ERROR, TAG, "Resource not found");
4094         return OC_STACK_ERROR;
4095     }
4096
4097     // Clear all bound resource types
4098     deleteResourceType(resource->rsrcType);
4099     resource->rsrcType = NULL;
4100
4101     // Bind new resource type to resource
4102     result = BindResourceTypeToResource(resource, newResourceType);
4103
4104 #ifdef WITH_PRESENCE
4105     if(presenceResource.handle)
4106     {
4107         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4108         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4109     }
4110 #endif
4111
4112     return result;
4113 }
4114
4115 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
4116         const char *resourceInterfaceName)
4117 {
4118
4119     OCStackResult result = OC_STACK_ERROR;
4120     OCResource *resource = NULL;
4121
4122     resource = findResource((OCResource *) handle);
4123     if (!resource)
4124     {
4125         OIC_LOG(ERROR, TAG, "Resource not found");
4126         return OC_STACK_ERROR;
4127     }
4128
4129     result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
4130
4131 #ifdef WITH_PRESENCE
4132     if (presenceResource.handle)
4133     {
4134         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4135         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4136     }
4137 #endif
4138
4139     return result;
4140 }
4141
4142 OCStackResult OCResetResourceInterfaces(OCResourceHandle handle,
4143                                         const char *newResourceInterface)
4144 {
4145     OCStackResult result = OC_STACK_ERROR;
4146     OCResource *resource = NULL;
4147
4148     resource = findResource((OCResource *) handle);
4149     if (!resource)
4150     {
4151         OIC_LOG(ERROR, TAG, "Resource not found");
4152         return OC_STACK_ERROR;
4153     }
4154
4155     // Clear all bound interface
4156     deleteResourceInterface(resource->rsrcInterface);
4157     resource->rsrcInterface = NULL;
4158
4159     // Bind new interface to resource
4160     result = BindResourceInterfaceToResource(resource, newResourceInterface);
4161
4162 #ifdef WITH_PRESENCE
4163     if (presenceResource.handle)
4164     {
4165         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4166         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4167     }
4168 #endif
4169
4170     return result;
4171 }
4172
4173 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
4174 {
4175     OCResource *pointer = headResource;
4176
4177     VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
4178     *numResources = 0;
4179     while (pointer)
4180     {
4181         *numResources = *numResources + 1;
4182         pointer = pointer->next;
4183     }
4184     return OC_STACK_OK;
4185 }
4186
4187 OCResourceHandle OCGetResourceHandle(uint8_t index)
4188 {
4189     OCResource *pointer = headResource;
4190
4191     for( uint8_t i = 0; i < index && pointer; ++i)
4192     {
4193         pointer = pointer->next;
4194     }
4195     return (OCResourceHandle) pointer;
4196 }
4197
4198 OCStackResult OCDeleteResource(OCResourceHandle handle)
4199 {
4200     if (!handle)
4201     {
4202         OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
4203         return OC_STACK_INVALID_PARAM;
4204     }
4205
4206     OCResource *resource = findResource((OCResource *) handle);
4207     if (resource == NULL)
4208     {
4209         OIC_LOG(ERROR, TAG, "Resource not found");
4210         return OC_STACK_NO_RESOURCE;
4211     }
4212
4213     if (deleteResource((OCResource *) handle) != OC_STACK_OK)
4214     {
4215         OIC_LOG(ERROR, TAG, "Error deleting resource");
4216         return OC_STACK_ERROR;
4217     }
4218
4219     return OC_STACK_OK;
4220 }
4221
4222 const char *OCGetResourceUri(OCResourceHandle handle)
4223 {
4224     OCResource *resource = NULL;
4225
4226     resource = findResource((OCResource *) handle);
4227     if (resource)
4228     {
4229         return resource->uri;
4230     }
4231     return (const char *) NULL;
4232 }
4233
4234 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
4235 {
4236     OCResource *resource = NULL;
4237
4238     resource = findResource((OCResource *) handle);
4239     if (resource)
4240     {
4241         return resource->resourceProperties;
4242     }
4243     return (OCResourceProperty)-1;
4244 }
4245
4246 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
4247         uint8_t *numResourceTypes)
4248 {
4249     OCResource *resource = NULL;
4250     OCResourceType *pointer = NULL;
4251
4252     VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
4253     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4254
4255     *numResourceTypes = 0;
4256
4257     resource = findResource((OCResource *) handle);
4258     if (resource)
4259     {
4260         pointer = resource->rsrcType;
4261         while (pointer)
4262         {
4263             *numResourceTypes = *numResourceTypes + 1;
4264             pointer = pointer->next;
4265         }
4266     }
4267     return OC_STACK_OK;
4268 }
4269
4270 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
4271 {
4272     OCResourceType *resourceType = NULL;
4273
4274     resourceType = findResourceTypeAtIndex(handle, index);
4275     if (resourceType)
4276     {
4277         return resourceType->resourcetypename;
4278     }
4279     return (const char *) NULL;
4280 }
4281
4282 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
4283         uint8_t *numResourceInterfaces)
4284 {
4285     OCResourceInterface *pointer = NULL;
4286     OCResource *resource = NULL;
4287
4288     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4289     VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
4290
4291     *numResourceInterfaces = 0;
4292     resource = findResource((OCResource *) handle);
4293     if (resource)
4294     {
4295         pointer = resource->rsrcInterface;
4296         while (pointer)
4297         {
4298             *numResourceInterfaces = *numResourceInterfaces + 1;
4299             pointer = pointer->next;
4300         }
4301     }
4302     return OC_STACK_OK;
4303 }
4304
4305 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
4306 {
4307     OCResourceInterface *resourceInterface = NULL;
4308
4309     resourceInterface = findResourceInterfaceAtIndex(handle, index);
4310     if (resourceInterface)
4311     {
4312         return resourceInterface->name;
4313     }
4314     return (const char *) NULL;
4315 }
4316
4317 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
4318         uint8_t index)
4319 {
4320     OCResource *resource = NULL;
4321     OCChildResource *tempChildResource = NULL;
4322     uint8_t num = 0;
4323
4324     resource = findResource((OCResource *) collectionHandle);
4325     if (!resource)
4326     {
4327         return NULL;
4328     }
4329
4330     tempChildResource = resource->rsrcChildResourcesHead;
4331
4332     while(tempChildResource)
4333     {
4334         if( num == index )
4335         {
4336             return tempChildResource->rsrcResource;
4337         }
4338         num++;
4339         tempChildResource = tempChildResource->next;
4340     }
4341
4342     // In this case, the number of resource handles in the collection exceeds the index
4343     tempChildResource = NULL;
4344     return NULL;
4345 }
4346
4347 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
4348         OCEntityHandler entityHandler,
4349         void* callbackParam)
4350 {
4351     OCResource *resource = NULL;
4352
4353     // Validate parameters
4354     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4355
4356     // Use the handle to find the resource in the resource linked list
4357     resource = findResource((OCResource *)handle);
4358     if (!resource)
4359     {
4360         OIC_LOG(ERROR, TAG, "Resource not found");
4361         return OC_STACK_ERROR;
4362     }
4363
4364     // Bind the handler
4365     resource->entityHandler = entityHandler;
4366     resource->entityHandlerCallbackParam = callbackParam;
4367
4368 #ifdef WITH_PRESENCE
4369     if (presenceResource.handle)
4370     {
4371         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4372         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
4373     }
4374 #endif
4375
4376     return OC_STACK_OK;
4377 }
4378
4379 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
4380 {
4381     OCResource *resource = NULL;
4382
4383     resource = findResource((OCResource *)handle);
4384     if (!resource)
4385     {
4386         OIC_LOG(ERROR, TAG, "Resource not found");
4387         return NULL;
4388     }
4389
4390     // Bind the handler
4391     return resource->entityHandler;
4392 }
4393
4394 void incrementSequenceNumber(OCResource * resPtr)
4395 {
4396     // Increment the sequence number
4397     resPtr->sequenceNum += 1;
4398     if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
4399     {
4400         resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
4401     }
4402     return;
4403 }
4404
4405 #ifdef WITH_PRESENCE
4406 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
4407         OCPresenceTrigger trigger)
4408 {
4409     OIC_LOG(INFO, TAG, "SendPresenceNotification");
4410     OCResource *resPtr = NULL;
4411     OCStackResult result = OC_STACK_ERROR;
4412     OCMethod method = OC_REST_PRESENCE;
4413     uint32_t maxAge = 0;
4414     resPtr = findResource((OCResource *) presenceResource.handle);
4415     if(NULL == resPtr)
4416     {
4417         return OC_STACK_NO_RESOURCE;
4418     }
4419
4420     if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
4421     {
4422         maxAge = presenceResource.presenceTTL;
4423
4424         result = SendAllObserverNotification(method, resPtr, maxAge,
4425                 trigger, resourceType, OC_LOW_QOS);
4426     }
4427
4428     return result;
4429 }
4430
4431 OCStackResult SendStopNotification()
4432 {
4433     OIC_LOG(INFO, TAG, "SendStopNotification");
4434     OCResource *resPtr = NULL;
4435     OCStackResult result = OC_STACK_ERROR;
4436     OCMethod method = OC_REST_PRESENCE;
4437     resPtr = findResource((OCResource *) presenceResource.handle);
4438     if(NULL == resPtr)
4439     {
4440         return OC_STACK_NO_RESOURCE;
4441     }
4442
4443     // maxAge is 0. ResourceType is NULL.
4444     result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
4445             NULL, OC_LOW_QOS);
4446
4447     return result;
4448 }
4449
4450 #endif // WITH_PRESENCE
4451 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
4452 {
4453     OCResource *resPtr = NULL;
4454     OCStackResult result = OC_STACK_ERROR;
4455     OCMethod method = OC_REST_NOMETHOD;
4456     uint32_t maxAge = 0;
4457
4458     OIC_LOG(INFO, TAG, "Notifying all observers");
4459 #ifdef WITH_PRESENCE
4460     if(handle == presenceResource.handle)
4461     {
4462         return OC_STACK_OK;
4463     }
4464 #endif // WITH_PRESENCE
4465     VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4466
4467     // Verify that the resource exists
4468     resPtr = findResource ((OCResource *) handle);
4469     if (NULL == resPtr)
4470     {
4471         return OC_STACK_NO_RESOURCE;
4472     }
4473     else
4474     {
4475         //only increment in the case of regular observing (not presence)
4476         incrementSequenceNumber(resPtr);
4477         method = OC_REST_OBSERVE;
4478         maxAge = MAX_OBSERVE_AGE;
4479 #ifdef WITH_PRESENCE
4480         result = SendAllObserverNotification (method, resPtr, maxAge,
4481                 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4482 #else
4483         result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4484 #endif
4485         return result;
4486     }
4487 }
4488
4489 OCStackResult
4490 OCNotifyListOfObservers (OCResourceHandle handle,
4491                          OCObservationId  *obsIdList,
4492                          uint8_t          numberOfIds,
4493                          const OCRepPayload       *payload,
4494                          OCQualityOfService qos)
4495 {
4496     OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4497
4498     OCResource *resPtr = NULL;
4499     //TODO: we should allow the server to define this
4500     uint32_t maxAge = MAX_OBSERVE_AGE;
4501
4502     VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4503     VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4504     VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4505
4506     resPtr = findResource ((OCResource *) handle);
4507     if (NULL == resPtr || myStackMode == OC_CLIENT)
4508     {
4509         return OC_STACK_NO_RESOURCE;
4510     }
4511     else
4512     {
4513         incrementSequenceNumber(resPtr);
4514     }
4515     return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4516             payload, maxAge, qos));
4517 }
4518
4519 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4520 {
4521     OIC_TRACE_BEGIN(%s:OCDoResponse, TAG);
4522     OCStackResult result = OC_STACK_ERROR;
4523     OCServerRequest *serverRequest = NULL;
4524
4525     OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4526
4527     // Validate input parameters
4528     VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4529     VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4530
4531     // Normal response
4532     // Get pointer to request info
4533     serverRequest = GetServerRequestUsingHandle(ehResponse->requestHandle);
4534     if(serverRequest)
4535     {
4536         // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4537         result = serverRequest->ehResponseHandler(ehResponse);
4538     }
4539
4540     OIC_TRACE_END();
4541     return result;
4542 }
4543
4544 //#ifdef DIRECT_PAIRING
4545 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4546 {
4547     OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4548     if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4549     {
4550         OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4551         return NULL;
4552     }
4553
4554     return (const OCDPDev_t*)DPGetDiscoveredDevices();
4555 }
4556
4557 const OCDPDev_t* OCGetDirectPairedDevices()
4558 {
4559     return (const OCDPDev_t*)DPGetPairedDevices();
4560 }
4561
4562 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4563                                                      OCDirectPairingCB resultCallback)
4564 {
4565     OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4566     if(NULL ==  peer || NULL == pinNumber)
4567     {
4568         OIC_LOG(ERROR, TAG, "Invalid parameters");
4569         return OC_STACK_INVALID_PARAM;
4570     }
4571     if (NULL == resultCallback)
4572     {
4573         OIC_LOG(ERROR, TAG, "Invalid callback");
4574         return OC_STACK_INVALID_CALLBACK;
4575     }
4576
4577     return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4578                                            pinNumber, (OCDirectPairingResultCB)resultCallback);
4579 }
4580 //#endif // DIRECT_PAIRING
4581
4582 //-----------------------------------------------------------------------------
4583 // Private internal function definitions
4584 //-----------------------------------------------------------------------------
4585 static OCDoHandle GenerateInvocationHandle()
4586 {
4587     OCDoHandle handle = NULL;
4588     // Generate token here, it will be deleted when the transaction is deleted
4589     handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4590     if (handle)
4591     {
4592         OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4593     }
4594
4595     return handle;
4596 }
4597
4598 #ifdef WITH_PRESENCE
4599 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4600         OCResourceProperty resourceProperties, uint8_t enable)
4601 {
4602     if (!inputProperty)
4603     {
4604         return OC_STACK_INVALID_PARAM;
4605     }
4606     if (resourceProperties
4607             > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4608     {
4609         OIC_LOG(ERROR, TAG, "Invalid property");
4610         return OC_STACK_INVALID_PARAM;
4611     }
4612     if(!enable)
4613     {
4614         *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4615     }
4616     else
4617     {
4618         *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4619     }
4620     return OC_STACK_OK;
4621 }
4622 #endif
4623
4624 OCStackResult initResources()
4625 {
4626     OCStackResult result = OC_STACK_OK;
4627
4628     headResource = NULL;
4629     tailResource = NULL;
4630     // Init Virtual Resources
4631 #ifdef WITH_PRESENCE
4632     presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4633
4634     result = OCCreateResource(&presenceResource.handle,
4635             OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4636             "core.r",
4637             OC_RSRVD_PRESENCE_URI,
4638             NULL,
4639             NULL,
4640             OC_OBSERVABLE);
4641     //make resource inactive
4642     result = OCChangeResourceProperty(
4643             &(((OCResource *) presenceResource.handle)->resourceProperties),
4644             OC_ACTIVE, 0);
4645 #endif
4646 #ifndef WITH_ARDUINO
4647     if (result == OC_STACK_OK)
4648     {
4649         result = SRMInitSecureResources();
4650     }
4651 #endif
4652
4653     if(result == OC_STACK_OK)
4654     {
4655         CreateResetProfile();
4656         result = OCCreateResource(&deviceResource,
4657                                   OC_RSRVD_RESOURCE_TYPE_DEVICE,
4658                                   OC_RSRVD_INTERFACE_DEFAULT,
4659                                   OC_RSRVD_DEVICE_URI,
4660                                   NULL,
4661                                   NULL,
4662                                   OC_DISCOVERABLE);
4663         if(result == OC_STACK_OK)
4664         {
4665             result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4666                                                      OC_RSRVD_INTERFACE_READ);
4667         }
4668     }
4669
4670     if(result == OC_STACK_OK)
4671     {
4672         result = OCCreateResource(&platformResource,
4673                                   OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4674                                   OC_RSRVD_INTERFACE_DEFAULT,
4675                                   OC_RSRVD_PLATFORM_URI,
4676                                   NULL,
4677                                   NULL,
4678                                   OC_DISCOVERABLE);
4679         if(result == OC_STACK_OK)
4680         {
4681             result = BindResourceInterfaceToResource((OCResource *)platformResource,
4682                                                      OC_RSRVD_INTERFACE_READ);
4683         }
4684     }
4685
4686     return result;
4687 }
4688
4689 void insertResource(OCResource *resource)
4690 {
4691     if (!headResource)
4692     {
4693         headResource = resource;
4694         tailResource = resource;
4695     }
4696     else
4697     {
4698         tailResource->next = resource;
4699         tailResource = resource;
4700     }
4701     resource->next = NULL;
4702 }
4703
4704 OCResource *findResource(OCResource *resource)
4705 {
4706     OCResource *pointer = headResource;
4707
4708     while (pointer)
4709     {
4710         if (pointer == resource)
4711         {
4712             return resource;
4713         }
4714         pointer = pointer->next;
4715     }
4716     return NULL;
4717 }
4718
4719 void deleteAllResources()
4720 {
4721     OCResource *pointer = headResource;
4722     OCResource *temp = NULL;
4723
4724     while (pointer)
4725     {
4726         temp = pointer->next;
4727 #ifdef WITH_PRESENCE
4728         if (pointer != (OCResource *) presenceResource.handle)
4729         {
4730 #endif // WITH_PRESENCE
4731             deleteResource(pointer);
4732 #ifdef WITH_PRESENCE
4733         }
4734 #endif // WITH_PRESENCE
4735         pointer = temp;
4736     }
4737     memset(&platformResource, 0, sizeof(platformResource));
4738     memset(&deviceResource, 0, sizeof(deviceResource));
4739 #ifdef MQ_BROKER
4740     memset(&brokerResource, 0, sizeof(brokerResource));
4741 #endif
4742
4743     SRMDeInitSecureResources();
4744
4745 #ifdef WITH_PRESENCE
4746     // Ensure that the last resource to be deleted is the presence resource. This allows for all
4747     // presence notification attributed to their deletion to be processed.
4748     deleteResource((OCResource *) presenceResource.handle);
4749     memset(&presenceResource, 0, sizeof(presenceResource));
4750 #endif // WITH_PRESENCE
4751 }
4752
4753 OCStackResult deleteResource(OCResource *resource)
4754 {
4755     OCResource *prev = NULL;
4756     OCResource *temp = NULL;
4757     if(!resource)
4758     {
4759         OIC_LOG(DEBUG,TAG,"resource is NULL");
4760         return OC_STACK_INVALID_PARAM;
4761     }
4762
4763     OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4764
4765     temp = headResource;
4766     while (temp)
4767     {
4768         if (temp == resource)
4769         {
4770             // Invalidate all Resource Properties.
4771             resource->resourceProperties = (OCResourceProperty) 0;
4772 #ifdef WITH_PRESENCE
4773             if(resource != (OCResource *) presenceResource.handle)
4774             {
4775 #endif // WITH_PRESENCE
4776                 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4777 #ifdef WITH_PRESENCE
4778             }
4779
4780             if(presenceResource.handle)
4781             {
4782                 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4783                 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4784             }
4785 #endif
4786             // Delete resource's all observers
4787             DeleteObserverUsingResource(resource);
4788
4789             // Only resource in list.
4790             if (temp == headResource && temp == tailResource)
4791             {
4792                 headResource = NULL;
4793                 tailResource = NULL;
4794             }
4795             // Deleting head.
4796             else if (temp == headResource)
4797             {
4798                 headResource = temp->next;
4799             }
4800             // Deleting tail.
4801             else if (temp == tailResource && prev)
4802             {
4803                 tailResource = prev;
4804                 tailResource->next = NULL;
4805             }
4806             else if (prev)
4807             {
4808                 prev->next = temp->next;
4809             }
4810
4811             deleteResourceElements(temp);
4812             OICFree(temp);
4813             return OC_STACK_OK;
4814         }
4815         else
4816         {
4817             prev = temp;
4818             temp = temp->next;
4819         }
4820     }
4821
4822     return OC_STACK_ERROR;
4823 }
4824
4825 void deleteResourceElements(OCResource *resource)
4826 {
4827     if (!resource)
4828     {
4829         return;
4830     }
4831
4832     if (resource->uri)
4833     {
4834         OICFree(resource->uri);
4835         resource->uri = NULL;
4836     }
4837     if (resource->rsrcType)
4838     {
4839         deleteResourceType(resource->rsrcType);
4840         resource->rsrcType = NULL;
4841     }
4842     if (resource->rsrcInterface)
4843     {
4844         deleteResourceInterface(resource->rsrcInterface);
4845         resource->rsrcInterface = NULL;
4846     }
4847     if (resource->rsrcChildResourcesHead)
4848     {
4849         unbindChildResources(resource->rsrcChildResourcesHead);
4850         resource->rsrcChildResourcesHead = NULL;
4851     }
4852     if (resource->rsrcAttributes)
4853     {
4854         OCDeleteResourceAttributes(resource->rsrcAttributes);
4855         resource->rsrcAttributes = NULL;
4856     }
4857
4858     resource->entityHandler = NULL;
4859     resource = NULL;
4860 }
4861
4862 void deleteResourceType(OCResourceType *resourceType)
4863 {
4864     OCResourceType *next = NULL;
4865
4866     for (OCResourceType *pointer = resourceType; pointer; pointer = next)
4867     {
4868         next = pointer->next ? pointer->next : NULL;
4869         if (pointer->resourcetypename)
4870         {
4871             OICFree(pointer->resourcetypename);
4872             pointer->resourcetypename = NULL;
4873         }
4874         OICFree(pointer);
4875     }
4876 }
4877
4878 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4879 {
4880     OCResourceInterface *next = NULL;
4881     for (OCResourceInterface *pointer = resourceInterface; pointer; pointer = next)
4882     {
4883         next = pointer->next ? pointer->next : NULL;
4884         if (pointer->name)
4885         {
4886             OICFree(pointer->name);
4887             pointer->name = NULL;
4888         }
4889         OICFree(pointer);
4890     }
4891 }
4892
4893 void unbindChildResources(OCChildResource *head)
4894 {
4895     OCChildResource *next = NULL;
4896     for (OCChildResource *current = head; current; current = next)
4897     {
4898         next = current->next;
4899         OICFree(current);
4900     }
4901 }
4902
4903 void OCDeleteResourceAttributes(OCAttribute *rsrcAttributes)
4904 {
4905     OCAttribute *next = NULL;
4906     for (OCAttribute *pointer = rsrcAttributes; pointer; pointer = next)
4907     {
4908         next = pointer->next ? pointer->next : NULL;
4909         if (pointer->attrName && 0 == strcmp(OC_RSRVD_DATA_MODEL_VERSION, pointer->attrName))
4910         {
4911             OCFreeOCStringLL((OCStringLL *)pointer->attrValue);
4912             pointer->attrValue = NULL;
4913         }
4914         else if (pointer->attrValue)
4915         {
4916             OICFree(pointer->attrValue);
4917             pointer->attrValue = NULL;
4918         }
4919         if (pointer->attrName)
4920         {
4921             OICFree(pointer->attrName);
4922             pointer->attrName = NULL;
4923         }
4924         OICFree(pointer);
4925     }
4926 }
4927
4928 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4929 {
4930     OCResourceType *pointer = NULL;
4931     OCResourceType *previous = NULL;
4932     if (!resource || !resourceType)
4933     {
4934         return;
4935     }
4936     // resource type list is empty.
4937     else if (!resource->rsrcType)
4938     {
4939         resource->rsrcType = resourceType;
4940     }
4941     else
4942     {
4943         pointer = resource->rsrcType;
4944
4945         while (pointer)
4946         {
4947             if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4948             {
4949                 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4950                 OICFree(resourceType->resourcetypename);
4951                 OICFree(resourceType);
4952                 return;
4953             }
4954             previous = pointer;
4955             pointer = pointer->next;
4956         }
4957
4958         if (previous)
4959         {
4960             previous->next = resourceType;
4961         }
4962     }
4963     resourceType->next = NULL;
4964
4965     OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4966 }
4967
4968 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4969 {
4970     OCResource *resource = NULL;
4971     OCResourceType *pointer = NULL;
4972
4973     // Find the specified resource
4974     resource = findResource((OCResource *) handle);
4975     if (!resource)
4976     {
4977         return NULL;
4978     }
4979
4980     // Make sure a resource has a resourcetype
4981     if (!resource->rsrcType)
4982     {
4983         return NULL;
4984     }
4985
4986     // Iterate through the list
4987     pointer = resource->rsrcType;
4988     for(uint8_t i = 0; i< index && pointer; ++i)
4989     {
4990         pointer = pointer->next;
4991     }
4992     return pointer;
4993 }
4994
4995 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4996 {
4997     if(resourceTypeList && resourceTypeName)
4998     {
4999         OCResourceType * rtPointer = resourceTypeList;
5000         while(resourceTypeName && rtPointer)
5001         {
5002             OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
5003             if(rtPointer->resourcetypename &&
5004                     strcmp(resourceTypeName, (const char *)
5005                     (rtPointer->resourcetypename)) == 0)
5006             {
5007                 break;
5008             }
5009             rtPointer = rtPointer->next;
5010         }
5011         return rtPointer;
5012     }
5013     return NULL;
5014 }
5015
5016 /*
5017  * Insert a new interface into interface linked list only if not already present.
5018  * If alredy present, 2nd arg is free'd.
5019  * Default interface will always be first if present.
5020  */
5021 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
5022 {
5023     OCResourceInterface *pointer = NULL;
5024     OCResourceInterface *previous = NULL;
5025
5026     newInterface->next = NULL;
5027
5028     OCResourceInterface **firstInterface = &(resource->rsrcInterface);
5029
5030     if (!*firstInterface)
5031     {
5032         // If first interface is not oic.if.baseline, by default add it as first interface type.
5033         if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
5034         {
5035             *firstInterface = newInterface;
5036         }
5037         else
5038         {
5039             OCStackResult result = BindResourceInterfaceToResource(resource,
5040                                                                     OC_RSRVD_INTERFACE_DEFAULT);
5041             if (result != OC_STACK_OK)
5042             {
5043                 OICFree(newInterface->name);
5044                 OICFree(newInterface);
5045                 return;
5046             }
5047             if (*firstInterface)
5048             {
5049                 (*firstInterface)->next = newInterface;
5050             }
5051         }
5052     }
5053     // If once add oic.if.baseline, later too below code take care of freeing memory.
5054     else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
5055     {
5056         if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
5057         {
5058             OICFree(newInterface->name);
5059             OICFree(newInterface);
5060             return;
5061         }
5062         // This code will not hit anymore, keeping
5063         else
5064         {
5065             newInterface->next = *firstInterface;
5066             *firstInterface = newInterface;
5067         }
5068     }
5069     else
5070     {
5071         pointer = *firstInterface;
5072         while (pointer)
5073         {
5074             if (strcmp(newInterface->name, pointer->name) == 0)
5075             {
5076                 OICFree(newInterface->name);
5077                 OICFree(newInterface);
5078                 return;
5079             }
5080             previous = pointer;
5081             pointer = pointer->next;
5082         }
5083
5084         if (previous)
5085         {
5086             previous->next = newInterface;
5087         }
5088     }
5089 }
5090
5091 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
5092         uint8_t index)
5093 {
5094     OCResource *resource = NULL;
5095     OCResourceInterface *pointer = NULL;
5096
5097     // Find the specified resource
5098     resource = findResource((OCResource *) handle);
5099     if (!resource)
5100     {
5101         return NULL;
5102     }
5103
5104     // Make sure a resource has a resourceinterface
5105     if (!resource->rsrcInterface)
5106     {
5107         return NULL;
5108     }
5109
5110     // Iterate through the list
5111     pointer = resource->rsrcInterface;
5112
5113     for (uint8_t i = 0; i < index && pointer; ++i)
5114     {
5115         pointer = pointer->next;
5116     }
5117     return pointer;
5118 }
5119
5120 /*
5121  * This function splits the uri using the '?' delimiter.
5122  * "uriWithoutQuery" is the block of characters between the beginning
5123  * till the delimiter or '\0' which ever comes first.
5124  * "query" is whatever is to the right of the delimiter if present.
5125  * No delimiter sets the query to NULL.
5126  * If either are present, they will be malloc'ed into the params 2, 3.
5127  * The first param, *uri is left untouched.
5128
5129  * NOTE: This function does not account for whitespace at the end of the uri NOR
5130  *       malformed uri's with '??'. Whitespace at the end will be assumed to be
5131  *       part of the query.
5132  */
5133 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
5134 {
5135     if(!uri)
5136     {
5137         return OC_STACK_INVALID_URI;
5138     }
5139     if(!query || !uriWithoutQuery)
5140     {
5141         return OC_STACK_INVALID_PARAM;
5142     }
5143
5144     *query           = NULL;
5145     *uriWithoutQuery = NULL;
5146
5147     size_t uriWithoutQueryLen = 0;
5148     size_t queryLen = 0;
5149     size_t uriLen = strlen(uri);
5150
5151     char *pointerToDelimiter = strstr(uri, "?");
5152
5153     uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
5154     queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
5155
5156     if (uriWithoutQueryLen)
5157     {
5158         *uriWithoutQuery =  (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
5159         if (!*uriWithoutQuery)
5160         {
5161             goto exit;
5162         }
5163         OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
5164     }
5165     if (queryLen)
5166     {
5167         *query = (char *) OICCalloc(queryLen + 1, 1);
5168         if (!*query)
5169         {
5170             OICFree(*uriWithoutQuery);
5171             *uriWithoutQuery = NULL;
5172             goto exit;
5173         }
5174         OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
5175     }
5176
5177     return OC_STACK_OK;
5178
5179     exit:
5180         return OC_STACK_NO_MEMORY;
5181 }
5182
5183 const char* OCGetServerInstanceIDString(void)
5184 {
5185     static char sidStr[UUID_STRING_SIZE];
5186     OicUuid_t sid;
5187     if (OC_STACK_OK != GetDoxmDeviceID(&sid))
5188     {
5189         OIC_LOG(FATAL, TAG, "GetDoxmDeviceID failed!");
5190         return NULL;
5191     }
5192
5193     if (OCConvertUuidToString(sid.id, sidStr) != RAND_UUID_OK)
5194     {
5195         OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
5196         return NULL;
5197     }
5198
5199     return sidStr;
5200 }
5201
5202 CAResult_t OCSelectNetwork(OCTransportAdapter transportType)
5203 {
5204     OIC_LOG_V(DEBUG, TAG, "OCSelectNetwork [%d]", transportType);
5205     CAResult_t retResult = CA_STATUS_FAILED;
5206     CAResult_t caResult = CA_STATUS_OK;
5207
5208     CATransportAdapter_t connTypes[] = {
5209             CA_ADAPTER_IP,
5210             CA_ADAPTER_RFCOMM_BTEDR,
5211             CA_ADAPTER_GATT_BTLE,
5212             CA_ADAPTER_NFC
5213 #ifdef RA_ADAPTER
5214             ,CA_ADAPTER_REMOTE_ACCESS
5215 #endif
5216
5217 #ifdef TCP_ADAPTER
5218             ,CA_ADAPTER_TCP
5219 #endif
5220         };
5221     int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
5222
5223     for(int i = 0; i < numConnTypes; i++)
5224     {
5225         // If CA status is not initialized, CASelectNetwork() will not be called.
5226         if (caResult != CA_STATUS_NOT_INITIALIZED)
5227         {
5228             if ((connTypes[i] & transportType) || (OC_DEFAULT_ADAPTER == transportType))
5229             {
5230                 OIC_LOG_V(DEBUG, TAG, "call CASelectNetwork [%d]", connTypes[i]);
5231                 caResult = CASelectNetwork(connTypes[i]);
5232                 if (caResult == CA_STATUS_OK)
5233                 {
5234                     retResult = CA_STATUS_OK;
5235                 }
5236             }
5237             else
5238             {
5239                 OIC_LOG_V(DEBUG, TAG, "there is no transport type [%d]", connTypes[i]);
5240             }
5241         }
5242     }
5243
5244     if (retResult != CA_STATUS_OK)
5245     {
5246         return caResult; // Returns error of appropriate transport that failed fatally.
5247     }
5248
5249     return retResult;
5250 }
5251
5252 OCStackResult CAResultToOCResult(CAResult_t caResult)
5253 {
5254     switch (caResult)
5255     {
5256         case CA_STATUS_OK:
5257             return OC_STACK_OK;
5258         case CA_STATUS_INVALID_PARAM:
5259             return OC_STACK_INVALID_PARAM;
5260         case CA_ADAPTER_NOT_ENABLED:
5261             return OC_STACK_ADAPTER_NOT_ENABLED;
5262         case CA_SERVER_STARTED_ALREADY:
5263             return OC_STACK_OK;
5264         case CA_SERVER_NOT_STARTED:
5265             return OC_STACK_ERROR;
5266         case CA_DESTINATION_NOT_REACHABLE:
5267             return OC_STACK_COMM_ERROR;
5268         case CA_SOCKET_OPERATION_FAILED:
5269             return OC_STACK_COMM_ERROR;
5270         case CA_SEND_FAILED:
5271             return OC_STACK_COMM_ERROR;
5272         case CA_RECEIVE_FAILED:
5273             return OC_STACK_COMM_ERROR;
5274         case CA_MEMORY_ALLOC_FAILED:
5275             return OC_STACK_NO_MEMORY;
5276         case CA_REQUEST_TIMEOUT:
5277             return OC_STACK_TIMEOUT;
5278         case CA_DESTINATION_DISCONNECTED:
5279             return OC_STACK_COMM_ERROR;
5280         case CA_STATUS_FAILED:
5281             return OC_STACK_ERROR;
5282         case CA_NOT_SUPPORTED:
5283             return OC_STACK_NOTIMPL;
5284         default:
5285             return OC_STACK_ERROR;
5286     }
5287 }
5288
5289 bool OCResultToSuccess(OCStackResult ocResult)
5290 {
5291     switch (ocResult)
5292     {
5293         case OC_STACK_OK:
5294         case OC_STACK_RESOURCE_CREATED:
5295         case OC_STACK_RESOURCE_DELETED:
5296         case OC_STACK_CONTINUE:
5297         case OC_STACK_RESOURCE_CHANGED:
5298         case OC_STACK_SLOW_RESOURCE:
5299             return true;
5300         default:
5301             return false;
5302     }
5303 }
5304
5305 #ifdef WITH_CHPROXY
5306 OCStackResult OCSetProxyURI(const char *uri)
5307 {
5308     return CAResultToOCResult(CASetProxyUri(uri));
5309 }
5310 #endif
5311
5312 #if defined(RD_CLIENT) || defined(RD_SERVER)
5313 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, int64_t ins)
5314 {
5315     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5316
5317     OCResource *resource = NULL;
5318
5319     resource = findResource((OCResource *) handle);
5320     if (!resource)
5321     {
5322         OIC_LOG(ERROR, TAG, "Resource not found");
5323         return OC_STACK_ERROR;
5324     }
5325
5326     resource->ins = ins;
5327
5328     return OC_STACK_OK;
5329 }
5330
5331
5332 OCStackResult OCUpdateResourceInsWithResponse(const char *requestUri,
5333                                               const OCClientResponse *response)
5334 {
5335     // Validate input parameters
5336     VERIFY_NON_NULL(requestUri, ERROR, OC_STACK_INVALID_PARAM);
5337     VERIFY_NON_NULL(response, ERROR, OC_STACK_INVALID_PARAM);
5338
5339     char *targetUri = (char *) OICMalloc(strlen(requestUri) + 1);
5340     if (!targetUri)
5341     {
5342         return OC_STACK_NO_MEMORY;
5343     }
5344     strncpy(targetUri, requestUri, strlen(requestUri) + 1);
5345
5346     if (response->result == OC_STACK_RESOURCE_CHANGED) // publish message
5347     {
5348         OIC_LOG(DEBUG, TAG, "update the ins of published resource");
5349
5350         char rdPubUri[MAX_URI_LENGTH] = { 0 };
5351         snprintf(rdPubUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
5352                  OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
5353
5354         if (strcmp(rdPubUri, targetUri) == 0)
5355         {
5356             // Update resource unique id in stack.
5357             if (response)
5358             {
5359                 if (response->payload)
5360                 {
5361                     OCRepPayload *rdPayload = (OCRepPayload *) response->payload;
5362                     OCRepPayload **links = NULL;
5363                     size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
5364                     if (OCRepPayloadGetPropObjectArray(rdPayload, OC_RSRVD_LINKS,
5365                                                        &links, dimensions))
5366                     {
5367                         size_t i = 0;
5368                         for (; i < dimensions[0]; i++)
5369                         {
5370                             char *uri = NULL;
5371                             if (OCRepPayloadGetPropString(links[i], OC_RSRVD_HREF, &uri))
5372                             {
5373                                 OCResourceHandle handle = OCGetResourceHandleAtUri(uri);
5374                                 int64_t ins = 0;
5375                                 if (OCRepPayloadGetPropInt(links[i], OC_RSRVD_INS, &ins))
5376                                 {
5377                                     OCBindResourceInsToResource(handle, ins);
5378                                 }
5379
5380                                 OICFree(uri);
5381                                 uri = NULL;
5382                             }
5383                         }
5384
5385                         // Free links
5386                         size_t count = calcDimTotal(dimensions);
5387                         for (size_t k = 0; k < count; k++)
5388                         {
5389                             OCRepPayloadDestroy(links[k]);
5390                         }
5391                         OICFree(links);
5392                     }
5393                 }
5394             }
5395         }
5396     }
5397     else if (response->result == OC_STACK_RESOURCE_DELETED) // delete message
5398     {
5399         OIC_LOG(DEBUG, TAG, "update the ins of deleted resource with 0");
5400
5401         uint8_t numResources = 0;
5402         OCGetNumberOfResources(&numResources);
5403
5404         char *ins = strstr(targetUri, OC_RSRVD_INS);
5405         if (!ins)
5406         {
5407             for (uint8_t i = 0; i < numResources; i++)
5408             {
5409                 OCResourceHandle resHandle = OCGetResourceHandle(i);
5410                 if (resHandle)
5411                 {
5412                     OCBindResourceInsToResource(resHandle, 0);
5413                 }
5414             }
5415         }
5416         else
5417         {
5418             const char *token = "&";
5419             char *iterTokenPtr = NULL;
5420             char *start = strtok_r(targetUri, token, &iterTokenPtr);
5421
5422              while (start != NULL)
5423              {
5424                  char *query = start;
5425                  query = strstr(query, OC_RSRVD_INS);
5426                  if (query)
5427                  {
5428                      int64_t queryIns = atoi(query + 4);
5429                      for (uint8_t i = 0; i < numResources; i++)
5430                      {
5431                          OCResourceHandle resHandle = OCGetResourceHandle(i);
5432                          if (resHandle)
5433                          {
5434                              int64_t resIns = 0;
5435                              OCGetResourceIns(resHandle, &resIns);
5436                              if (queryIns && queryIns == resIns)
5437                              {
5438                                  OCBindResourceInsToResource(resHandle, 0);
5439                                  break;
5440                              }
5441                          }
5442                      }
5443                  }
5444                  start = strtok_r(NULL, token, &iterTokenPtr);
5445              }
5446         }
5447     }
5448
5449     OICFree(targetUri);
5450     return OC_STACK_OK;
5451 }
5452
5453 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
5454 {
5455     if (!uri)
5456     {
5457         OIC_LOG(ERROR, TAG, "Resource uri is NULL");
5458         return NULL;
5459     }
5460
5461     OCResource *pointer = headResource;
5462
5463     while (pointer)
5464     {
5465         if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
5466         {
5467             OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
5468             return pointer;
5469         }
5470         pointer = pointer->next;
5471     }
5472     return NULL;
5473 }
5474
5475 OCStackResult OCGetResourceIns(OCResourceHandle handle, int64_t *ins)
5476 {
5477     OCResource *resource = NULL;
5478
5479     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
5480     VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
5481
5482     resource = findResource((OCResource *) handle);
5483     if (resource)
5484     {
5485         *ins = resource->ins;
5486         return OC_STACK_OK;
5487     }
5488     return OC_STACK_ERROR;
5489 }
5490 #endif
5491
5492 OCStackResult OCSetHeaderOption(OCHeaderOption* ocHdrOpt, size_t* numOptions, uint16_t optionID,
5493                                 const void* optionData, size_t optionDataLength)
5494 {
5495     if (!ocHdrOpt)
5496     {
5497         OIC_LOG (INFO, TAG, "Header options are NULL");
5498         return OC_STACK_INVALID_PARAM;
5499     }
5500
5501     if (!optionData)
5502     {
5503         OIC_LOG (INFO, TAG, "optionData are NULL");
5504         return OC_STACK_INVALID_PARAM;
5505     }
5506
5507     if (!numOptions)
5508     {
5509         OIC_LOG (INFO, TAG, "numOptions is NULL");
5510         return OC_STACK_INVALID_PARAM;
5511     }
5512
5513     if (*numOptions >= MAX_HEADER_OPTIONS)
5514     {
5515         OIC_LOG (INFO, TAG, "Exceeding MAX_HEADER_OPTIONS");
5516         return OC_STACK_NO_MEMORY;
5517     }
5518
5519     ocHdrOpt += *numOptions;
5520     ocHdrOpt->protocolID = OC_COAP_ID;
5521     ocHdrOpt->optionID = optionID;
5522     ocHdrOpt->optionLength =
5523             optionDataLength < MAX_HEADER_OPTION_DATA_LENGTH ?
5524                     optionDataLength : MAX_HEADER_OPTION_DATA_LENGTH;
5525     memcpy(ocHdrOpt->optionData, (const void*) optionData, ocHdrOpt->optionLength);
5526     *numOptions += 1;
5527
5528     return OC_STACK_OK;
5529 }
5530
5531 OCStackResult OCGetHeaderOption(OCHeaderOption* ocHdrOpt, size_t numOptions, uint16_t optionID,
5532                                 void* optionData, size_t optionDataLength, uint16_t* receivedDataLength)
5533 {
5534     if (!ocHdrOpt || !numOptions)
5535     {
5536         OIC_LOG (INFO, TAG, "No options present");
5537         return OC_STACK_OK;
5538     }
5539
5540     if (!optionData)
5541     {
5542         OIC_LOG (INFO, TAG, "optionData are NULL");
5543         return OC_STACK_INVALID_PARAM;
5544     }
5545
5546     if (!receivedDataLength)
5547     {
5548         OIC_LOG (INFO, TAG, "receivedDataLength is NULL");
5549         return OC_STACK_INVALID_PARAM;
5550     }
5551
5552     for (uint8_t i = 0; i < numOptions; i++)
5553     {
5554         if (ocHdrOpt[i].optionID == optionID)
5555         {
5556             if (optionDataLength >= ocHdrOpt->optionLength)
5557             {
5558                 memcpy(optionData, ocHdrOpt->optionData, ocHdrOpt->optionLength);
5559                 *receivedDataLength = ocHdrOpt->optionLength;
5560                 return OC_STACK_OK;
5561             }
5562             else
5563             {
5564                 OIC_LOG (ERROR, TAG, "optionDataLength is less than the length of received data");
5565                 return OC_STACK_ERROR;
5566             }
5567         }
5568     }
5569     return OC_STACK_OK;
5570 }
5571
5572 void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
5573 {
5574     OIC_LOG(DEBUG, TAG, "OCDefaultAdapterStateChangedHandler");
5575
5576     OC_UNUSED(adapter);
5577     OC_UNUSED(enabled);
5578 }
5579
5580 void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected)
5581 {
5582     OIC_LOG(DEBUG, TAG, "OCDefaultConnectionStateChangedHandler");
5583
5584     /*
5585      * If the client observes one or more resources over a reliable connection,
5586      * then the CoAP server (or intermediary in the role of the CoAP server)
5587      * MUST remove all entries associated with the client endpoint from the lists
5588      * of observers when the connection is either closed or times out.
5589      */
5590     if (!isConnected)
5591     {
5592         OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
5593         CopyEndpointToDevAddr(info, &devAddr);
5594
5595         // remove observer list with remote device address.
5596         DeleteObserverUsingDevAddr(&devAddr);
5597     }
5598 }
5599
5600 OCStackResult OCGetDeviceId(OCUUIdentity *deviceId)
5601 {
5602     OicUuid_t oicUuid;
5603     OCStackResult ret = OC_STACK_ERROR;
5604
5605     ret = GetDoxmDeviceID(&oicUuid);
5606     if (OC_STACK_OK == ret)
5607     {
5608         memcpy(deviceId, &oicUuid, UUID_IDENTITY_SIZE);
5609     }
5610     else
5611     {
5612         OIC_LOG(ERROR, TAG, "Device ID Get error");
5613     }
5614     return ret;
5615 }
5616
5617 OCStackResult OCSetDeviceId(const OCUUIdentity *deviceId)
5618 {
5619     OicUuid_t oicUuid;
5620     OCStackResult ret = OC_STACK_ERROR;
5621
5622     memcpy(&oicUuid, deviceId, UUID_LENGTH);
5623     for (int i = 0; i < UUID_LENGTH; i++)
5624     {
5625         OIC_LOG_V(INFO, TAG, "Set Device Id %x", oicUuid.id[i]);
5626     }
5627     ret = SetDoxmDeviceID(&oicUuid);
5628     return ret;
5629 }
5630
5631 OCStackResult OCGetDeviceOwnedState(bool *isOwned)
5632 {
5633     bool isDeviceOwned = true;
5634     OCStackResult ret = OC_STACK_ERROR;
5635
5636     ret = GetDoxmIsOwned(&isDeviceOwned);
5637     if (OC_STACK_OK == ret)
5638     {
5639         *isOwned = isDeviceOwned;
5640     }
5641     else
5642     {
5643         OIC_LOG(ERROR, TAG, "Device Owned State Get error");
5644     }
5645     return ret;
5646 }
5647
5648 OCStackResult OCGetDeviceOperationalState(bool* isOp)
5649 {
5650     if(NULL != isOp)
5651     {
5652         *isOp = GetPstatIsop();
5653         return OC_STACK_OK;
5654     }
5655
5656     return OC_STACK_ERROR;
5657 }
5658
5659 void OCClearCallBackList()
5660 {
5661     DeleteClientCBList();
5662 }
5663
5664 void OCClearObserverlist()
5665 {
5666     DeleteObserverList();
5667 }
5668
5669 int OCEncrypt(const unsigned char *pt, size_t pt_len,
5670         unsigned char **ct, size_t *ct_len)
5671 {
5672 #ifndef __SECURE_PSI__
5673     OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5674     return 0;
5675 #else
5676     OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5677
5678     return psiEncrypt(pt, pt_len, ct, ct_len);
5679 #endif // __SECURE_PSI__
5680 }
5681
5682 int OCDecrypt(const unsigned char *ct, size_t ct_len,
5683         unsigned char **pt, size_t *pt_len)
5684 {
5685 #ifndef __SECURE_PSI__
5686     OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5687     return 0;
5688 #else
5689     OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5690
5691     return psiDecrypt(ct, ct_len, pt, pt_len);
5692 #endif // __SECURE_PSI__
5693 }
5694
5695 OCStackResult OCSetKey(const unsigned char* key)
5696 {
5697 #ifndef __SECURE_PSI__
5698     OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5699     return OC_STACK_OK;
5700 #else
5701     OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5702
5703     return psiSetKey(key);
5704 #endif // __SECURE_PSI__
5705 }
5706
5707 OCStackResult OCGetKey(unsigned char* key)
5708 {
5709 #ifndef __SECURE_PSI__
5710     OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5711     return OC_STACK_OK;
5712 #else
5713     OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5714
5715     return psiGetKey(key);
5716 #endif // __SECURE_PSI__
5717 }
5718
5719 OCStackResult OCSetSecurePSI(const unsigned char *key, const OCPersistentStorage *psPlain,
5720         const OCPersistentStorage *psEnc, const OCPersistentStorage *psRescue)
5721 {
5722 #ifndef __SECURE_PSI__
5723     OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5724     return OC_STACK_OK;
5725 #else
5726     OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5727
5728     return setSecurePSI(key, psPlain, psEnc, psRescue);
5729 #endif // __SECURE_PSI__
5730 }
5731
5732 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5733 static void OtmEventHandler(const char *addr, uint16_t port, const char *uuid, int event)
5734 {
5735     if (g_otmEventHandler.cb)
5736     {
5737         g_otmEventHandler.cb(g_otmEventHandler.ctx, addr, port, uuid, event);
5738     }
5739 }
5740
5741 /* TODO Work-around
5742  * It is already declared in srmutility.h.
5743  * We can't include the header file, because of "redefined VERIFY_NON_NULL"
5744  */
5745 typedef void (*OicSecOtmEventHandler_t)(const char* addr, uint16_t port,
5746         const char* uuid, int event);
5747 void SetOtmEventHandler(OicSecOtmEventHandler_t otmEventHandler);
5748 #endif
5749
5750 OCStackResult OCSetOtmEventHandler(void *ctx, OCOtmEventHandler cb)
5751 {
5752 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
5753     OIC_LOG_V(DEBUG, TAG, "%s", __func__);
5754
5755     g_otmEventHandler.cb = cb;
5756     g_otmEventHandler.ctx = ctx;
5757
5758     if (g_otmEventHandler.cb)
5759     {
5760         OIC_LOG(DEBUG, TAG, "SET OCOtmEventHandler");
5761         SetOtmEventHandler(OtmEventHandler);
5762     }
5763     else
5764     {
5765         OIC_LOG(DEBUG, TAG, "UNSET OCOtmEventHandler");
5766         SetOtmEventHandler(NULL);
5767     }
5768 #else
5769     OIC_LOG_V(DEBUG, TAG, "Not Supported : %s", __func__);
5770     OC_UNUSED(ctx);
5771     OC_UNUSED(cb);
5772 #endif
5773     return OC_STACK_OK;
5774 }