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