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