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