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