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