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