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