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