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