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