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