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