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