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