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