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