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