modified coding style for parenthesis for Android JNI
[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     // prepare for response
2646 #ifdef WITH_PRESENCE
2647     if (method == OC_REST_PRESENCE)
2648     {
2649         char *presenceUri = NULL;
2650         result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
2651         if (OC_STACK_OK != result)
2652         {
2653             goto exit;
2654         }
2655
2656         // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2657         // Presence notification will form a canonical uri to
2658         // look for callbacks into the application.
2659         resourceUri = presenceUri;
2660     }
2661 #endif
2662
2663     ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2664     result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2665                             method, devAddr, resourceUri, resourceType, ttl);
2666     if (OC_STACK_OK != result)
2667     {
2668         goto exit;
2669     }
2670
2671     devAddr = NULL;       // Client CB list entry now owns it
2672     resourceUri = NULL;   // Client CB list entry now owns it
2673     resourceType = NULL;  // Client CB list entry now owns it
2674
2675     // send request
2676     result = OCSendRequest(&endpoint, &requestInfo);
2677     if (OC_STACK_OK != result)
2678     {
2679         goto exit;
2680     }
2681
2682     if (handle)
2683     {
2684         *handle = resHandle;
2685     }
2686
2687 exit:
2688     if (result != OC_STACK_OK)
2689     {
2690         OIC_LOG(ERROR, TAG, "OCDoResource error");
2691         FindAndDeleteClientCB(clientCB);
2692         CADestroyToken(token);
2693         if (handle)
2694         {
2695             *handle = NULL;
2696         }
2697         OICFree(resHandle);
2698     }
2699
2700     // This is the owner of the payload object, so we free it
2701     OCPayloadDestroy(payload);
2702     OICFree(requestInfo.info.payload);
2703     OICFree(devAddr);
2704     OICFree(resourceUri);
2705     OICFree(resourceType);
2706     OICFree(requestInfo.info.options);
2707     return result;
2708 }
2709
2710 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2711         uint8_t numOptions)
2712 {
2713     /*
2714      * This ftn is implemented one of two ways in the case of observation:
2715      *
2716      * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2717      *      Remove the callback associated on client side.
2718      *      When the next notification comes in from server,
2719      *      reply with RESET message to server.
2720      *      Keep in mind that the server will react to RESET only
2721      *      if the last notification was sent as CON
2722      *
2723      * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2724      *      and it is associated with an observe request
2725      *      (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2726      *      Send CON Observe request to server with
2727      *      observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2728      *      Remove the callback associated on client side.
2729      */
2730     OCStackResult ret = OC_STACK_OK;
2731     CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2732     CARequestInfo_t requestInfo = {.method = CA_GET};
2733
2734     if(!handle)
2735     {
2736         return OC_STACK_INVALID_PARAM;
2737     }
2738
2739     ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2740     if (!clientCB)
2741     {
2742         OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2743         return OC_STACK_ERROR;
2744     }
2745
2746     switch (clientCB->method)
2747     {
2748         case OC_REST_OBSERVE:
2749         case OC_REST_OBSERVE_ALL:
2750
2751             OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2752
2753             CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2754
2755             if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2756             {
2757                 FindAndDeleteClientCB(clientCB);
2758                 break;
2759             }
2760
2761             OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2762
2763             requestInfo.info.type = qualityOfServiceToMessageType(qos);
2764             requestInfo.info.token = clientCB->token;
2765             requestInfo.info.tokenLength = clientCB->tokenLength;
2766
2767             if (CreateObserveHeaderOption (&(requestInfo.info.options),
2768                     options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2769             {
2770                 return OC_STACK_ERROR;
2771             }
2772             requestInfo.info.numOptions = numOptions + 1;
2773             requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2774
2775
2776             ret = OCSendRequest(&endpoint, &requestInfo);
2777
2778             if (requestInfo.info.options)
2779             {
2780                 OICFree (requestInfo.info.options);
2781             }
2782             if (requestInfo.info.resourceUri)
2783             {
2784                 OICFree (requestInfo.info.resourceUri);
2785             }
2786
2787             break;
2788
2789         case OC_REST_DISCOVER:
2790             OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2791                                            clientCB->requestUri);
2792             FindAndDeleteClientCB(clientCB);
2793             break;
2794
2795 #ifdef WITH_PRESENCE
2796         case OC_REST_PRESENCE:
2797             FindAndDeleteClientCB(clientCB);
2798             break;
2799 #endif
2800
2801         default:
2802             ret = OC_STACK_INVALID_METHOD;
2803             break;
2804     }
2805
2806     return ret;
2807 }
2808
2809 /**
2810  * @brief   Register Persistent storage callback.
2811  * @param   persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2812  * @return
2813  *     OC_STACK_OK    - No errors; Success
2814  *     OC_STACK_INVALID_PARAM - Invalid parameter
2815  */
2816 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2817 {
2818     OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2819     if(!persistentStorageHandler)
2820     {
2821         OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2822         return OC_STACK_INVALID_PARAM;
2823     }
2824     else
2825     {
2826         if( !persistentStorageHandler->open ||
2827                 !persistentStorageHandler->close ||
2828                 !persistentStorageHandler->read ||
2829                 !persistentStorageHandler->unlink ||
2830                 !persistentStorageHandler->write)
2831         {
2832             OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2833             return OC_STACK_INVALID_PARAM;
2834         }
2835     }
2836     return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2837 }
2838
2839 #ifdef WITH_PRESENCE
2840
2841 OCStackResult OCProcessPresence()
2842 {
2843     OCStackResult result = OC_STACK_OK;
2844
2845     // the following line floods the log with messages that are irrelevant
2846     // to most purposes.  Uncomment as needed.
2847     //OIC_LOG(INFO, TAG, "Entering RequestPresence");
2848     ClientCB* cbNode = NULL;
2849     OCClientResponse clientResponse;
2850     OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2851
2852     LL_FOREACH(cbList, cbNode)
2853     {
2854         if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2855         {
2856             continue;
2857         }
2858
2859         uint32_t now = GetTicks(0);
2860         OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
2861                                                 cbNode->presence->TTLlevel);
2862         OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2863
2864         if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
2865         {
2866             goto exit;
2867         }
2868
2869         if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2870         {
2871             OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2872                     cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2873         }
2874         if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2875         {
2876             OIC_LOG(DEBUG, TAG, "No more timeout ticks");
2877
2878             clientResponse.sequenceNumber = 0;
2879             clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2880             clientResponse.devAddr = *cbNode->devAddr;
2881             FixUpClientResponse(&clientResponse);
2882             clientResponse.payload = NULL;
2883
2884             // Increment the TTLLevel (going to a next state), so we don't keep
2885             // sending presence notification to client.
2886             cbNode->presence->TTLlevel++;
2887             OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2888                                         cbNode->presence->TTLlevel);
2889
2890             cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2891             if (cbResult == OC_STACK_DELETE_TRANSACTION)
2892             {
2893                 FindAndDeleteClientCB(cbNode);
2894             }
2895         }
2896
2897         if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2898         {
2899             continue;
2900         }
2901
2902         CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2903         CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
2904         CARequestInfo_t requestInfo = {.method = CA_GET};
2905
2906         OIC_LOG(DEBUG, TAG, "time to test server presence");
2907
2908         CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
2909
2910         requestData.type = CA_MSG_NONCONFIRM;
2911         requestData.token = cbNode->token;
2912         requestData.tokenLength = cbNode->tokenLength;
2913         requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
2914         requestInfo.method = CA_GET;
2915         requestInfo.info = requestData;
2916
2917         result = OCSendRequest(&endpoint, &requestInfo);
2918         if (OC_STACK_OK != result)
2919         {
2920             goto exit;
2921         }
2922
2923         cbNode->presence->TTLlevel++;
2924         OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
2925     }
2926 exit:
2927     if (result != OC_STACK_OK)
2928     {
2929         OIC_LOG(ERROR, TAG, "OCProcessPresence error");
2930     }
2931
2932     return result;
2933 }
2934 #endif // WITH_PRESENCE
2935
2936 OCStackResult OCProcess()
2937 {
2938 #ifdef WITH_PRESENCE
2939     OCProcessPresence();
2940 #endif
2941     CAHandleRequestResponse();
2942
2943 #ifdef ROUTING_GATEWAY
2944     RMProcess();
2945 #endif
2946
2947 #ifdef TCP_ADAPTER
2948     ProcessKeepAlive();
2949 #endif
2950     return OC_STACK_OK;
2951 }
2952
2953 #ifdef WITH_PRESENCE
2954 OCStackResult OCStartPresence(const uint32_t ttl)
2955 {
2956     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2957     OCChangeResourceProperty(
2958             &(((OCResource *)presenceResource.handle)->resourceProperties),
2959             OC_ACTIVE, 1);
2960
2961     if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
2962     {
2963         presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
2964         OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
2965     }
2966     else if (0 == ttl)
2967     {
2968         presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
2969         OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
2970     }
2971     else
2972     {
2973         presenceResource.presenceTTL = ttl;
2974     }
2975     OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
2976
2977     if (OC_PRESENCE_UNINITIALIZED == presenceState)
2978     {
2979         presenceState = OC_PRESENCE_INITIALIZED;
2980
2981         OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
2982
2983         CAToken_t caToken = NULL;
2984         CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
2985         if (caResult != CA_STATUS_OK)
2986         {
2987             OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2988             CADestroyToken(caToken);
2989             return OC_STACK_ERROR;
2990         }
2991
2992         AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
2993                 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
2994         CADestroyToken(caToken);
2995     }
2996
2997     // Each time OCStartPresence is called
2998     // a different random 32-bit integer number is used
2999     ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3000
3001     return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3002             OC_PRESENCE_TRIGGER_CREATE);
3003 }
3004
3005 OCStackResult OCStopPresence()
3006 {
3007     OCStackResult result = OC_STACK_ERROR;
3008
3009     if(presenceResource.handle)
3010     {
3011         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3012
3013     // make resource inactive
3014     result = OCChangeResourceProperty(
3015             &(((OCResource *) presenceResource.handle)->resourceProperties),
3016             OC_ACTIVE, 0);
3017     }
3018
3019     if(result != OC_STACK_OK)
3020     {
3021         OIC_LOG(ERROR, TAG,
3022                       "Changing the presence resource properties to ACTIVE not successful");
3023         return result;
3024     }
3025
3026     return SendStopNotification();
3027 }
3028 #endif
3029
3030 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3031                                             void* callbackParameter)
3032 {
3033     defaultDeviceHandler = entityHandler;
3034     defaultDeviceHandlerCallbackParameter = callbackParameter;
3035
3036     return OC_STACK_OK;
3037 }
3038
3039 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3040 {
3041     OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3042
3043     if(myStackMode ==  OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3044     {
3045         if (validatePlatformInfo(platformInfo))
3046         {
3047             return SavePlatformInfo(platformInfo);
3048         }
3049         else
3050         {
3051             return OC_STACK_INVALID_PARAM;
3052         }
3053     }
3054     else
3055     {
3056         return OC_STACK_ERROR;
3057     }
3058 }
3059
3060 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3061 {
3062     OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3063
3064     if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3065     {
3066         OIC_LOG(ERROR, TAG, "Null or empty device name.");
3067         return OC_STACK_INVALID_PARAM;
3068     }
3069
3070     if (deviceInfo.types)
3071     {
3072         OCStringLL *type =  deviceInfo.types;
3073         OCResource *resource = findResource((OCResource *) deviceResource);
3074         if (!resource)
3075         {
3076             return OC_STACK_INVALID_PARAM;
3077         }
3078         deleteResourceType(resource->rsrcType);
3079         resource->rsrcType = NULL;
3080
3081         while (type)
3082         {
3083             OCBindResourceTypeToResource(deviceResource, type->value);
3084             type = type->next;
3085         }
3086     }
3087     return SaveDeviceInfo(deviceInfo);
3088 }
3089
3090 OCStackResult OCCreateResource(OCResourceHandle *handle,
3091         const char *resourceTypeName,
3092         const char *resourceInterfaceName,
3093         const char *uri, OCEntityHandler entityHandler,
3094         void* callbackParam,
3095         uint8_t resourceProperties)
3096 {
3097
3098     OCResource *pointer = NULL;
3099     OCStackResult result = OC_STACK_ERROR;
3100
3101     OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3102
3103     if(myStackMode == OC_CLIENT)
3104     {
3105         return OC_STACK_INVALID_PARAM;
3106     }
3107     // Validate parameters
3108     if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3109     {
3110         OIC_LOG(ERROR, TAG, "URI is empty or too long");
3111         return OC_STACK_INVALID_URI;
3112     }
3113     // Is it presented during resource discovery?
3114     if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3115     {
3116         OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3117         return OC_STACK_INVALID_PARAM;
3118     }
3119
3120     if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3121     {
3122         resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3123     }
3124
3125     // Make sure resourceProperties bitmask has allowed properties specified
3126     if (resourceProperties
3127             > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3128                OC_EXPLICIT_DISCOVERABLE))
3129     {
3130         OIC_LOG(ERROR, TAG, "Invalid property");
3131         return OC_STACK_INVALID_PARAM;
3132     }
3133
3134     // If the headResource is NULL, then no resources have been created...
3135     pointer = headResource;
3136     if (pointer)
3137     {
3138         // At least one resources is in the resource list, so we need to search for
3139         // repeated URLs, which are not allowed.  If a repeat is found, exit with an error
3140         while (pointer)
3141         {
3142             if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3143             {
3144                 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3145                 return OC_STACK_INVALID_PARAM;
3146             }
3147             pointer = pointer->next;
3148         }
3149     }
3150     // Create the pointer and insert it into the resource list
3151     pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3152     if (!pointer)
3153     {
3154         result = OC_STACK_NO_MEMORY;
3155         goto exit;
3156     }
3157     pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3158
3159     insertResource(pointer);
3160
3161     // Set the uri
3162     pointer->uri = OICStrdup(uri);
3163     if (!pointer->uri)
3164     {
3165         result = OC_STACK_NO_MEMORY;
3166         goto exit;
3167     }
3168
3169     // Set properties.  Set OC_ACTIVE
3170     pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3171             | OC_ACTIVE);
3172
3173     // Add the resourcetype to the resource
3174     result = BindResourceTypeToResource(pointer, resourceTypeName);
3175     if (result != OC_STACK_OK)
3176     {
3177         OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3178         goto exit;
3179     }
3180
3181     // Add the resourceinterface to the resource
3182     result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3183     if (result != OC_STACK_OK)
3184     {
3185         OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3186         goto exit;
3187     }
3188
3189     // If an entity handler has been passed, attach it to the newly created
3190     // resource.  Otherwise, set the default entity handler.
3191     if (entityHandler)
3192     {
3193         pointer->entityHandler = entityHandler;
3194         pointer->entityHandlerCallbackParam = callbackParam;
3195     }
3196     else
3197     {
3198         pointer->entityHandler = defaultResourceEHandler;
3199         pointer->entityHandlerCallbackParam = NULL;
3200     }
3201
3202     // Initialize a pointer indicating child resources in case of collection
3203     pointer->rsrcChildResourcesHead = NULL;
3204
3205     *handle = pointer;
3206     result = OC_STACK_OK;
3207
3208 #ifdef WITH_PRESENCE
3209     if (presenceResource.handle)
3210     {
3211         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3212         SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3213     }
3214 #endif
3215 exit:
3216     if (result != OC_STACK_OK)
3217     {
3218         // Deep delete of resource and other dynamic elements that it contains
3219         deleteResource(pointer);
3220     }
3221     return result;
3222 }
3223
3224 OCStackResult OCBindResource(
3225         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3226 {
3227     OCResource *resource = NULL;
3228     OCChildResource *tempChildResource = NULL;
3229     OCChildResource *newChildResource = NULL;
3230
3231     OIC_LOG(INFO, TAG, "Entering OCBindResource");
3232
3233     // Validate parameters
3234     VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3235     VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3236     // Container cannot contain itself
3237     if (collectionHandle == resourceHandle)
3238     {
3239         OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3240         return OC_STACK_INVALID_PARAM;
3241     }
3242
3243     // Use the handle to find the resource in the resource linked list
3244     resource = findResource((OCResource *) collectionHandle);
3245     if (!resource)
3246     {
3247         OIC_LOG(ERROR, TAG, "Collection handle not found");
3248         return OC_STACK_INVALID_PARAM;
3249     }
3250
3251     // Look for an open slot to add add the child resource.
3252     // If found, add it and return success
3253
3254     tempChildResource = resource->rsrcChildResourcesHead;
3255
3256     while(resource->rsrcChildResourcesHead && tempChildResource->next)
3257     {
3258         // TODO: what if one of child resource was deregistered without unbinding?
3259         tempChildResource = tempChildResource->next;
3260     }
3261
3262     // Do memory allocation for child resource
3263     newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3264     if(!newChildResource)
3265     {
3266         OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3267         return OC_STACK_ERROR;
3268     }
3269
3270     newChildResource->rsrcResource = (OCResource *) resourceHandle;
3271     newChildResource->next = NULL;
3272
3273     if(!resource->rsrcChildResourcesHead)
3274     {
3275         resource->rsrcChildResourcesHead = newChildResource;
3276     }
3277     else {
3278         tempChildResource->next = newChildResource;
3279     }
3280
3281     OIC_LOG(INFO, TAG, "resource bound");
3282
3283 #ifdef WITH_PRESENCE
3284     if (presenceResource.handle)
3285     {
3286         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3287         SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3288                 OC_PRESENCE_TRIGGER_CHANGE);
3289     }
3290 #endif
3291
3292     return OC_STACK_OK;
3293 }
3294
3295 OCStackResult OCUnBindResource(
3296         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3297 {
3298     OCResource *resource = NULL;
3299     OCChildResource *tempChildResource = NULL;
3300     OCChildResource *tempLastChildResource = NULL;
3301
3302     OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3303
3304     // Validate parameters
3305     VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3306     VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3307     // Container cannot contain itself
3308     if (collectionHandle == resourceHandle)
3309     {
3310         OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3311         return OC_STACK_INVALID_PARAM;
3312     }
3313
3314     // Use the handle to find the resource in the resource linked list
3315     resource = findResource((OCResource *) collectionHandle);
3316     if (!resource)
3317     {
3318         OIC_LOG(ERROR, TAG, "Collection handle not found");
3319         return OC_STACK_INVALID_PARAM;
3320     }
3321
3322     // Look for an open slot to add add the child resource.
3323     // If found, add it and return success
3324     if(!resource->rsrcChildResourcesHead)
3325     {
3326         OIC_LOG(INFO, TAG, "resource not found in collection");
3327
3328         // Unable to add resourceHandle, so return error
3329         return OC_STACK_ERROR;
3330
3331     }
3332
3333     tempChildResource = resource->rsrcChildResourcesHead;
3334
3335     while (tempChildResource)
3336     {
3337         if(tempChildResource->rsrcResource == resourceHandle)
3338         {
3339             // if resource going to be unbinded is the head one.
3340             if( tempChildResource == resource->rsrcChildResourcesHead )
3341             {
3342                 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3343                 OICFree(resource->rsrcChildResourcesHead);
3344                 resource->rsrcChildResourcesHead = temp;
3345                 temp = NULL;
3346             }
3347             else
3348             {
3349                 OCChildResource *temp = tempChildResource->next;
3350                 OICFree(tempChildResource);
3351                 tempLastChildResource->next = temp;
3352                 temp = NULL;
3353             }
3354
3355             OIC_LOG(INFO, TAG, "resource unbound");
3356
3357             // Send notification when resource is unbounded successfully.
3358 #ifdef WITH_PRESENCE
3359             if (presenceResource.handle)
3360             {
3361                 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3362                 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3363                         OC_PRESENCE_TRIGGER_CHANGE);
3364             }
3365 #endif
3366             tempChildResource = NULL;
3367             tempLastChildResource = NULL;
3368
3369             return OC_STACK_OK;
3370
3371         }
3372
3373         tempLastChildResource = tempChildResource;
3374         tempChildResource = tempChildResource->next;
3375     }
3376
3377     OIC_LOG(INFO, TAG, "resource not found in collection");
3378
3379     tempChildResource = NULL;
3380     tempLastChildResource = NULL;
3381
3382     // Unable to add resourceHandle, so return error
3383     return OC_STACK_ERROR;
3384 }
3385
3386 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3387 {
3388     if (!resourceItemName)
3389     {
3390         return false;
3391     }
3392     // Per RFC 6690 only registered values must follow the first rule below.
3393     // At this point in time the only values registered begin with "core", and
3394     // all other values are specified as opaque strings where multiple values
3395     // are separated by a space.
3396     if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3397     {
3398         for(size_t index = sizeof(CORESPEC) - 1;  resourceItemName[index]; ++index)
3399         {
3400             if (resourceItemName[index] != '.'
3401                 && resourceItemName[index] != '-'
3402                 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3403                 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3404             {
3405                 return false;
3406             }
3407         }
3408     }
3409     else
3410     {
3411         for (size_t index = 0; resourceItemName[index]; ++index)
3412         {
3413             if (resourceItemName[index] == ' '
3414                 || resourceItemName[index] == '\t'
3415                 || resourceItemName[index] == '\r'
3416                 || resourceItemName[index] == '\n')
3417             {
3418                 return false;
3419             }
3420         }
3421     }
3422
3423     return true;
3424 }
3425
3426 OCStackResult BindResourceTypeToResource(OCResource* resource,
3427                                             const char *resourceTypeName)
3428 {
3429     OCResourceType *pointer = NULL;
3430     char *str = NULL;
3431     OCStackResult result = OC_STACK_ERROR;
3432
3433     VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3434
3435     if (!ValidateResourceTypeInterface(resourceTypeName))
3436     {
3437         OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3438         return OC_STACK_INVALID_PARAM;
3439     }
3440
3441     pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3442     if (!pointer)
3443     {
3444         result = OC_STACK_NO_MEMORY;
3445         goto exit;
3446     }
3447
3448     str = OICStrdup(resourceTypeName);
3449     if (!str)
3450     {
3451         result = OC_STACK_NO_MEMORY;
3452         goto exit;
3453     }
3454     pointer->resourcetypename = str;
3455     pointer->next = NULL;
3456
3457     insertResourceType(resource, pointer);
3458     result = OC_STACK_OK;
3459
3460 exit:
3461     if (result != OC_STACK_OK)
3462     {
3463         OICFree(pointer);
3464         OICFree(str);
3465     }
3466
3467     return result;
3468 }
3469
3470 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3471         const char *resourceInterfaceName)
3472 {
3473     OCResourceInterface *pointer = NULL;
3474     char *str = NULL;
3475     OCStackResult result = OC_STACK_ERROR;
3476
3477     VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3478
3479     if (!ValidateResourceTypeInterface(resourceInterfaceName))
3480     {
3481         OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3482         return OC_STACK_INVALID_PARAM;
3483     }
3484
3485     OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3486
3487     pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3488     if (!pointer)
3489     {
3490         result = OC_STACK_NO_MEMORY;
3491         goto exit;
3492     }
3493
3494     str = OICStrdup(resourceInterfaceName);
3495     if (!str)
3496     {
3497         result = OC_STACK_NO_MEMORY;
3498         goto exit;
3499     }
3500     pointer->name = str;
3501
3502     // Bind the resourceinterface to the resource
3503     insertResourceInterface(resource, pointer);
3504
3505     result = OC_STACK_OK;
3506
3507     exit:
3508     if (result != OC_STACK_OK)
3509     {
3510         OICFree(pointer);
3511         OICFree(str);
3512     }
3513
3514     return result;
3515 }
3516
3517 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3518         const char *resourceTypeName)
3519 {
3520
3521     OCStackResult result = OC_STACK_ERROR;
3522     OCResource *resource = NULL;
3523
3524     resource = findResource((OCResource *) handle);
3525     if (!resource)
3526     {
3527         OIC_LOG(ERROR, TAG, "Resource not found");
3528         return OC_STACK_ERROR;
3529     }
3530
3531     result = BindResourceTypeToResource(resource, resourceTypeName);
3532
3533 #ifdef WITH_PRESENCE
3534     if(presenceResource.handle)
3535     {
3536         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3537         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3538     }
3539 #endif
3540
3541     return result;
3542 }
3543
3544 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3545         const char *resourceInterfaceName)
3546 {
3547
3548     OCStackResult result = OC_STACK_ERROR;
3549     OCResource *resource = NULL;
3550
3551     resource = findResource((OCResource *) handle);
3552     if (!resource)
3553     {
3554         OIC_LOG(ERROR, TAG, "Resource not found");
3555         return OC_STACK_ERROR;
3556     }
3557
3558     result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3559
3560 #ifdef WITH_PRESENCE
3561     if (presenceResource.handle)
3562     {
3563         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3564         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3565     }
3566 #endif
3567
3568     return result;
3569 }
3570
3571 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3572 {
3573     OCResource *pointer = headResource;
3574
3575     VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3576     *numResources = 0;
3577     while (pointer)
3578     {
3579         *numResources = *numResources + 1;
3580         pointer = pointer->next;
3581     }
3582     return OC_STACK_OK;
3583 }
3584
3585 OCResourceHandle OCGetResourceHandle(uint8_t index)
3586 {
3587     OCResource *pointer = headResource;
3588
3589     for( uint8_t i = 0; i < index && pointer; ++i)
3590     {
3591         pointer = pointer->next;
3592     }
3593     return (OCResourceHandle) pointer;
3594 }
3595
3596 OCStackResult OCDeleteResource(OCResourceHandle handle)
3597 {
3598     if (!handle)
3599     {
3600         OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3601         return OC_STACK_INVALID_PARAM;
3602     }
3603
3604     OCResource *resource = findResource((OCResource *) handle);
3605     if (resource == NULL)
3606     {
3607         OIC_LOG(ERROR, TAG, "Resource not found");
3608         return OC_STACK_NO_RESOURCE;
3609     }
3610
3611     if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3612     {
3613         OIC_LOG(ERROR, TAG, "Error deleting resource");
3614         return OC_STACK_ERROR;
3615     }
3616
3617     return OC_STACK_OK;
3618 }
3619
3620 const char *OCGetResourceUri(OCResourceHandle handle)
3621 {
3622     OCResource *resource = NULL;
3623
3624     resource = findResource((OCResource *) handle);
3625     if (resource)
3626     {
3627         return resource->uri;
3628     }
3629     return (const char *) NULL;
3630 }
3631
3632 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3633 {
3634     OCResource *resource = NULL;
3635
3636     resource = findResource((OCResource *) handle);
3637     if (resource)
3638     {
3639         return resource->resourceProperties;
3640     }
3641     return (OCResourceProperty)-1;
3642 }
3643
3644 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3645         uint8_t *numResourceTypes)
3646 {
3647     OCResource *resource = NULL;
3648     OCResourceType *pointer = NULL;
3649
3650     VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3651     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3652
3653     *numResourceTypes = 0;
3654
3655     resource = findResource((OCResource *) handle);
3656     if (resource)
3657     {
3658         pointer = resource->rsrcType;
3659         while (pointer)
3660         {
3661             *numResourceTypes = *numResourceTypes + 1;
3662             pointer = pointer->next;
3663         }
3664     }
3665     return OC_STACK_OK;
3666 }
3667
3668 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3669 {
3670     OCResourceType *resourceType = NULL;
3671
3672     resourceType = findResourceTypeAtIndex(handle, index);
3673     if (resourceType)
3674     {
3675         return resourceType->resourcetypename;
3676     }
3677     return (const char *) NULL;
3678 }
3679
3680 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3681         uint8_t *numResourceInterfaces)
3682 {
3683     OCResourceInterface *pointer = NULL;
3684     OCResource *resource = NULL;
3685
3686     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3687     VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3688
3689     *numResourceInterfaces = 0;
3690     resource = findResource((OCResource *) handle);
3691     if (resource)
3692     {
3693         pointer = resource->rsrcInterface;
3694         while (pointer)
3695         {
3696             *numResourceInterfaces = *numResourceInterfaces + 1;
3697             pointer = pointer->next;
3698         }
3699     }
3700     return OC_STACK_OK;
3701 }
3702
3703 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3704 {
3705     OCResourceInterface *resourceInterface = NULL;
3706
3707     resourceInterface = findResourceInterfaceAtIndex(handle, index);
3708     if (resourceInterface)
3709     {
3710         return resourceInterface->name;
3711     }
3712     return (const char *) NULL;
3713 }
3714
3715 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3716         uint8_t index)
3717 {
3718     OCResource *resource = NULL;
3719     OCChildResource *tempChildResource = NULL;
3720     uint8_t num = 0;
3721
3722     resource = findResource((OCResource *) collectionHandle);
3723     if (!resource)
3724     {
3725         return NULL;
3726     }
3727
3728     tempChildResource = resource->rsrcChildResourcesHead;
3729
3730     while(tempChildResource)
3731     {
3732         if( num == index )
3733         {
3734             return tempChildResource->rsrcResource;
3735         }
3736         num++;
3737         tempChildResource = tempChildResource->next;
3738     }
3739
3740     // In this case, the number of resource handles in the collection exceeds the index
3741     tempChildResource = NULL;
3742     return NULL;
3743 }
3744
3745 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3746         OCEntityHandler entityHandler,
3747         void* callbackParam)
3748 {
3749     OCResource *resource = NULL;
3750
3751     // Validate parameters
3752     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3753
3754     // Use the handle to find the resource in the resource linked list
3755     resource = findResource((OCResource *)handle);
3756     if (!resource)
3757     {
3758         OIC_LOG(ERROR, TAG, "Resource not found");
3759         return OC_STACK_ERROR;
3760     }
3761
3762     // Bind the handler
3763     resource->entityHandler = entityHandler;
3764     resource->entityHandlerCallbackParam = callbackParam;
3765
3766 #ifdef WITH_PRESENCE
3767     if (presenceResource.handle)
3768     {
3769         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3770         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3771     }
3772 #endif
3773
3774     return OC_STACK_OK;
3775 }
3776
3777 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3778 {
3779     OCResource *resource = NULL;
3780
3781     resource = findResource((OCResource *)handle);
3782     if (!resource)
3783     {
3784         OIC_LOG(ERROR, TAG, "Resource not found");
3785         return NULL;
3786     }
3787
3788     // Bind the handler
3789     return resource->entityHandler;
3790 }
3791
3792 void incrementSequenceNumber(OCResource * resPtr)
3793 {
3794     // Increment the sequence number
3795     resPtr->sequenceNum += 1;
3796     if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3797     {
3798         resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3799     }
3800     return;
3801 }
3802
3803 #ifdef WITH_PRESENCE
3804 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3805         OCPresenceTrigger trigger)
3806 {
3807     OCResource *resPtr = NULL;
3808     OCStackResult result = OC_STACK_ERROR;
3809     OCMethod method = OC_REST_PRESENCE;
3810     uint32_t maxAge = 0;
3811     resPtr = findResource((OCResource *) presenceResource.handle);
3812     if(NULL == resPtr)
3813     {
3814         return OC_STACK_NO_RESOURCE;
3815     }
3816
3817     if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3818     {
3819         maxAge = presenceResource.presenceTTL;
3820
3821         result = SendAllObserverNotification(method, resPtr, maxAge,
3822                 trigger, resourceType, OC_LOW_QOS);
3823     }
3824
3825     return result;
3826 }
3827
3828 OCStackResult SendStopNotification()
3829 {
3830     OCResource *resPtr = NULL;
3831     OCStackResult result = OC_STACK_ERROR;
3832     OCMethod method = OC_REST_PRESENCE;
3833     resPtr = findResource((OCResource *) presenceResource.handle);
3834     if(NULL == resPtr)
3835     {
3836         return OC_STACK_NO_RESOURCE;
3837     }
3838
3839     // maxAge is 0. ResourceType is NULL.
3840     result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3841             NULL, OC_LOW_QOS);
3842
3843     return result;
3844 }
3845
3846 #endif // WITH_PRESENCE
3847 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3848 {
3849     OCResource *resPtr = NULL;
3850     OCStackResult result = OC_STACK_ERROR;
3851     OCMethod method = OC_REST_NOMETHOD;
3852     uint32_t maxAge = 0;
3853
3854     OIC_LOG(INFO, TAG, "Notifying all observers");
3855 #ifdef WITH_PRESENCE
3856     if(handle == presenceResource.handle)
3857     {
3858         return OC_STACK_OK;
3859     }
3860 #endif // WITH_PRESENCE
3861     VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3862
3863     // Verify that the resource exists
3864     resPtr = findResource ((OCResource *) handle);
3865     if (NULL == resPtr)
3866     {
3867         return OC_STACK_NO_RESOURCE;
3868     }
3869     else
3870     {
3871         //only increment in the case of regular observing (not presence)
3872         incrementSequenceNumber(resPtr);
3873         method = OC_REST_OBSERVE;
3874         maxAge = MAX_OBSERVE_AGE;
3875 #ifdef WITH_PRESENCE
3876         result = SendAllObserverNotification (method, resPtr, maxAge,
3877                 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3878 #else
3879         result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3880 #endif
3881         return result;
3882     }
3883 }
3884
3885 OCStackResult
3886 OCNotifyListOfObservers (OCResourceHandle handle,
3887                          OCObservationId  *obsIdList,
3888                          uint8_t          numberOfIds,
3889                          const OCRepPayload       *payload,
3890                          OCQualityOfService qos)
3891 {
3892     OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
3893
3894     OCResource *resPtr = NULL;
3895     //TODO: we should allow the server to define this
3896     uint32_t maxAge = MAX_OBSERVE_AGE;
3897
3898     VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3899     VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3900     VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
3901
3902     resPtr = findResource ((OCResource *) handle);
3903     if (NULL == resPtr || myStackMode == OC_CLIENT)
3904     {
3905         return OC_STACK_NO_RESOURCE;
3906     }
3907     else
3908     {
3909         incrementSequenceNumber(resPtr);
3910     }
3911     return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3912             payload, maxAge, qos));
3913 }
3914
3915 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3916 {
3917     OCStackResult result = OC_STACK_ERROR;
3918     OCServerRequest *serverRequest = NULL;
3919
3920     OIC_LOG(INFO, TAG, "Entering OCDoResponse");
3921
3922     // Validate input parameters
3923     VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3924     VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3925
3926     // Normal response
3927     // Get pointer to request info
3928     serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3929     if(serverRequest)
3930     {
3931         // response handler in ocserverrequest.c. Usually HandleSingleResponse.
3932         result = serverRequest->ehResponseHandler(ehResponse);
3933     }
3934
3935     return result;
3936 }
3937
3938 //#ifdef DIRECT_PAIRING
3939 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
3940 {
3941     OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
3942     if(OC_STACK_OK != DPDeviceDiscovery(waittime))
3943     {
3944         OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
3945         return NULL;
3946     }
3947
3948     return (const OCDPDev_t*)DPGetDiscoveredDevices();
3949 }
3950
3951 const OCDPDev_t* OCGetDirectPairedDevices()
3952 {
3953     return (const OCDPDev_t*)DPGetPairedDevices();
3954 }
3955
3956 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
3957                                                      OCDirectPairingCB resultCallback)
3958 {
3959     OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
3960     if(NULL ==  peer || NULL == pinNumber)
3961     {
3962         OIC_LOG(ERROR, TAG, "Invalid parameters");
3963         return OC_STACK_INVALID_PARAM;
3964     }
3965     if (NULL == resultCallback)
3966     {
3967         OIC_LOG(ERROR, TAG, "Invalid callback");
3968         return OC_STACK_INVALID_CALLBACK;
3969     }
3970
3971     return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
3972                                            pinNumber, (OCDirectPairingResultCB)resultCallback);
3973 }
3974 //#endif // DIRECT_PAIRING
3975
3976 //-----------------------------------------------------------------------------
3977 // Private internal function definitions
3978 //-----------------------------------------------------------------------------
3979 static OCDoHandle GenerateInvocationHandle()
3980 {
3981     OCDoHandle handle = NULL;
3982     // Generate token here, it will be deleted when the transaction is deleted
3983     handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3984     if (handle)
3985     {
3986         OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3987     }
3988
3989     return handle;
3990 }
3991
3992 #ifdef WITH_PRESENCE
3993 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3994         OCResourceProperty resourceProperties, uint8_t enable)
3995 {
3996     if (!inputProperty)
3997     {
3998         return OC_STACK_INVALID_PARAM;
3999     }
4000     if (resourceProperties
4001             > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4002     {
4003         OIC_LOG(ERROR, TAG, "Invalid property");
4004         return OC_STACK_INVALID_PARAM;
4005     }
4006     if(!enable)
4007     {
4008         *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4009     }
4010     else
4011     {
4012         *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4013     }
4014     return OC_STACK_OK;
4015 }
4016 #endif
4017
4018 OCStackResult initResources()
4019 {
4020     OCStackResult result = OC_STACK_OK;
4021
4022     headResource = NULL;
4023     tailResource = NULL;
4024     // Init Virtual Resources
4025 #ifdef WITH_PRESENCE
4026     presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4027
4028     result = OCCreateResource(&presenceResource.handle,
4029             OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4030             "core.r",
4031             OC_RSRVD_PRESENCE_URI,
4032             NULL,
4033             NULL,
4034             OC_OBSERVABLE);
4035     //make resource inactive
4036     result = OCChangeResourceProperty(
4037             &(((OCResource *) presenceResource.handle)->resourceProperties),
4038             OC_ACTIVE, 0);
4039 #endif
4040 #ifndef WITH_ARDUINO
4041     if (result == OC_STACK_OK)
4042     {
4043         result = SRMInitSecureResources();
4044     }
4045 #endif
4046
4047     if(result == OC_STACK_OK)
4048     {
4049         result = OCCreateResource(&deviceResource,
4050                                   OC_RSRVD_RESOURCE_TYPE_DEVICE,
4051                                   OC_RSRVD_INTERFACE_DEFAULT,
4052                                   OC_RSRVD_DEVICE_URI,
4053                                   NULL,
4054                                   NULL,
4055                                   OC_DISCOVERABLE);
4056         if(result == OC_STACK_OK)
4057         {
4058             result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4059                                                      OC_RSRVD_INTERFACE_READ);
4060         }
4061     }
4062
4063     if(result == OC_STACK_OK)
4064     {
4065         result = OCCreateResource(&platformResource,
4066                                   OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4067                                   OC_RSRVD_INTERFACE_DEFAULT,
4068                                   OC_RSRVD_PLATFORM_URI,
4069                                   NULL,
4070                                   NULL,
4071                                   OC_DISCOVERABLE);
4072         if(result == OC_STACK_OK)
4073         {
4074             result = BindResourceInterfaceToResource((OCResource *)platformResource,
4075                                                      OC_RSRVD_INTERFACE_READ);
4076         }
4077     }
4078
4079     return result;
4080 }
4081
4082 void insertResource(OCResource *resource)
4083 {
4084     if (!headResource)
4085     {
4086         headResource = resource;
4087         tailResource = resource;
4088     }
4089     else
4090     {
4091         tailResource->next = resource;
4092         tailResource = resource;
4093     }
4094     resource->next = NULL;
4095 }
4096
4097 OCResource *findResource(OCResource *resource)
4098 {
4099     OCResource *pointer = headResource;
4100
4101     while (pointer)
4102     {
4103         if (pointer == resource)
4104         {
4105             return resource;
4106         }
4107         pointer = pointer->next;
4108     }
4109     return NULL;
4110 }
4111
4112 void deleteAllResources()
4113 {
4114     OCResource *pointer = headResource;
4115     OCResource *temp = NULL;
4116
4117     while (pointer)
4118     {
4119         temp = pointer->next;
4120 #ifdef WITH_PRESENCE
4121         if (pointer != (OCResource *) presenceResource.handle)
4122         {
4123 #endif // WITH_PRESENCE
4124             deleteResource(pointer);
4125 #ifdef WITH_PRESENCE
4126         }
4127 #endif // WITH_PRESENCE
4128         pointer = temp;
4129     }
4130
4131     SRMDeInitSecureResources();
4132
4133 #ifdef WITH_PRESENCE
4134     // Ensure that the last resource to be deleted is the presence resource. This allows for all
4135     // presence notification attributed to their deletion to be processed.
4136     deleteResource((OCResource *) presenceResource.handle);
4137 #endif // WITH_PRESENCE
4138 }
4139
4140 OCStackResult deleteResource(OCResource *resource)
4141 {
4142     OCResource *prev = NULL;
4143     OCResource *temp = NULL;
4144     if(!resource)
4145     {
4146         OIC_LOG(DEBUG,TAG,"resource is NULL");
4147         return OC_STACK_INVALID_PARAM;
4148     }
4149
4150     OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4151
4152     temp = headResource;
4153     while (temp)
4154     {
4155         if (temp == resource)
4156         {
4157             // Invalidate all Resource Properties.
4158             resource->resourceProperties = (OCResourceProperty) 0;
4159 #ifdef WITH_PRESENCE
4160             if(resource != (OCResource *) presenceResource.handle)
4161             {
4162 #endif // WITH_PRESENCE
4163                 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4164 #ifdef WITH_PRESENCE
4165             }
4166
4167             if(presenceResource.handle)
4168             {
4169                 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4170                 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4171             }
4172 #endif
4173             // Only resource in list.
4174             if (temp == headResource && temp == tailResource)
4175             {
4176                 headResource = NULL;
4177                 tailResource = NULL;
4178             }
4179             // Deleting head.
4180             else if (temp == headResource)
4181             {
4182                 headResource = temp->next;
4183             }
4184             // Deleting tail.
4185             else if (temp == tailResource)
4186             {
4187                 tailResource = prev;
4188                 tailResource->next = NULL;
4189             }
4190             else
4191             {
4192                 prev->next = temp->next;
4193             }
4194
4195             deleteResourceElements(temp);
4196             OICFree(temp);
4197             return OC_STACK_OK;
4198         }
4199         else
4200         {
4201             prev = temp;
4202             temp = temp->next;
4203         }
4204     }
4205
4206     return OC_STACK_ERROR;
4207 }
4208
4209 void deleteResourceElements(OCResource *resource)
4210 {
4211     if (!resource)
4212     {
4213         return;
4214     }
4215
4216     OICFree(resource->uri);
4217     deleteResourceType(resource->rsrcType);
4218     deleteResourceInterface(resource->rsrcInterface);
4219 }
4220
4221 void deleteResourceType(OCResourceType *resourceType)
4222 {
4223     OCResourceType *pointer = resourceType;
4224     OCResourceType *next = NULL;
4225
4226     while (pointer)
4227     {
4228         next = pointer->next;
4229         OICFree(pointer->resourcetypename);
4230         OICFree(pointer);
4231         pointer = next;
4232     }
4233 }
4234
4235 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4236 {
4237     OCResourceInterface *pointer = resourceInterface;
4238     OCResourceInterface *next = NULL;
4239
4240     while (pointer)
4241     {
4242         next = pointer->next;
4243         OICFree(pointer->name);
4244         OICFree(pointer);
4245         pointer = next;
4246     }
4247 }
4248
4249 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4250 {
4251     OCResourceType *pointer = NULL;
4252     OCResourceType *previous = NULL;
4253     if (!resource || !resourceType)
4254     {
4255         return;
4256     }
4257     // resource type list is empty.
4258     else if (!resource->rsrcType)
4259     {
4260         resource->rsrcType = resourceType;
4261     }
4262     else
4263     {
4264         pointer = resource->rsrcType;
4265
4266         while (pointer)
4267         {
4268             if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4269             {
4270                 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4271                 OICFree(resourceType->resourcetypename);
4272                 OICFree(resourceType);
4273                 return;
4274             }
4275             previous = pointer;
4276             pointer = pointer->next;
4277         }
4278
4279         if (previous)
4280         {
4281             previous->next = resourceType;
4282         }
4283     }
4284     resourceType->next = NULL;
4285
4286     OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4287 }
4288
4289 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4290 {
4291     OCResource *resource = NULL;
4292     OCResourceType *pointer = NULL;
4293
4294     // Find the specified resource
4295     resource = findResource((OCResource *) handle);
4296     if (!resource)
4297     {
4298         return NULL;
4299     }
4300
4301     // Make sure a resource has a resourcetype
4302     if (!resource->rsrcType)
4303     {
4304         return NULL;
4305     }
4306
4307     // Iterate through the list
4308     pointer = resource->rsrcType;
4309     for(uint8_t i = 0; i< index && pointer; ++i)
4310     {
4311         pointer = pointer->next;
4312     }
4313     return pointer;
4314 }
4315
4316 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4317 {
4318     if(resourceTypeList && resourceTypeName)
4319     {
4320         OCResourceType * rtPointer = resourceTypeList;
4321         while(resourceTypeName && rtPointer)
4322         {
4323             if(rtPointer->resourcetypename &&
4324                     strcmp(resourceTypeName, (const char *)
4325                     (rtPointer->resourcetypename)) == 0)
4326             {
4327                 break;
4328             }
4329             rtPointer = rtPointer->next;
4330         }
4331         return rtPointer;
4332     }
4333     return NULL;
4334 }
4335
4336 /*
4337  * Insert a new interface into interface linked list only if not already present.
4338  * If alredy present, 2nd arg is free'd.
4339  * Default interface will always be first if present.
4340  */
4341 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4342 {
4343     OCResourceInterface *pointer = NULL;
4344     OCResourceInterface *previous = NULL;
4345
4346     newInterface->next = NULL;
4347
4348     OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4349
4350     if (!*firstInterface)
4351     {
4352         // If first interface is not oic.if.baseline, by default add it as first interface type.
4353         if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4354         {
4355             *firstInterface = newInterface;
4356         }
4357         else
4358         {
4359             OCStackResult result = BindResourceInterfaceToResource(resource, OC_RSRVD_INTERFACE_DEFAULT);
4360             if (result != OC_STACK_OK)
4361             {
4362                 OICFree(newInterface->name);
4363                 OICFree(newInterface);
4364                 return;
4365             }
4366             if (*firstInterface)
4367             {
4368                 (*firstInterface)->next = newInterface;
4369             }
4370         }
4371     }
4372     // If once add oic.if.baseline, later too below code take care of freeing memory.
4373     else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4374     {
4375         if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4376         {
4377             OICFree(newInterface->name);
4378             OICFree(newInterface);
4379             return;
4380         }
4381         // This code will not hit anymore, keeping
4382         else
4383         {
4384             newInterface->next = *firstInterface;
4385             *firstInterface = newInterface;
4386         }
4387     }
4388     else
4389     {
4390         pointer = *firstInterface;
4391         while (pointer)
4392         {
4393             if (strcmp(newInterface->name, pointer->name) == 0)
4394             {
4395                 OICFree(newInterface->name);
4396                 OICFree(newInterface);
4397                 return;
4398             }
4399             previous = pointer;
4400             pointer = pointer->next;
4401         }
4402
4403         if (previous)
4404         {
4405             previous->next = newInterface;
4406         }
4407     }
4408 }
4409
4410 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4411         uint8_t index)
4412 {
4413     OCResource *resource = NULL;
4414     OCResourceInterface *pointer = NULL;
4415
4416     // Find the specified resource
4417     resource = findResource((OCResource *) handle);
4418     if (!resource)
4419     {
4420         return NULL;
4421     }
4422
4423     // Make sure a resource has a resourceinterface
4424     if (!resource->rsrcInterface)
4425     {
4426         return NULL;
4427     }
4428
4429     // Iterate through the list
4430     pointer = resource->rsrcInterface;
4431
4432     for (uint8_t i = 0; i < index && pointer; ++i)
4433     {
4434         pointer = pointer->next;
4435     }
4436     return pointer;
4437 }
4438
4439 /*
4440  * This function splits the uri using the '?' delimiter.
4441  * "uriWithoutQuery" is the block of characters between the beginning
4442  * till the delimiter or '\0' which ever comes first.
4443  * "query" is whatever is to the right of the delimiter if present.
4444  * No delimiter sets the query to NULL.
4445  * If either are present, they will be malloc'ed into the params 2, 3.
4446  * The first param, *uri is left untouched.
4447
4448  * NOTE: This function does not account for whitespace at the end of the uri NOR
4449  *       malformed uri's with '??'. Whitespace at the end will be assumed to be
4450  *       part of the query.
4451  */
4452 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4453 {
4454     if(!uri)
4455     {
4456         return OC_STACK_INVALID_URI;
4457     }
4458     if(!query || !uriWithoutQuery)
4459     {
4460         return OC_STACK_INVALID_PARAM;
4461     }
4462
4463     *query           = NULL;
4464     *uriWithoutQuery = NULL;
4465
4466     size_t uriWithoutQueryLen = 0;
4467     size_t queryLen = 0;
4468     size_t uriLen = strlen(uri);
4469
4470     char *pointerToDelimiter = strstr(uri, "?");
4471
4472     uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4473     queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4474
4475     if (uriWithoutQueryLen)
4476     {
4477         *uriWithoutQuery =  (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4478         if (!*uriWithoutQuery)
4479         {
4480             goto exit;
4481         }
4482         OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4483     }
4484     if (queryLen)
4485     {
4486         *query = (char *) OICCalloc(queryLen + 1, 1);
4487         if (!*query)
4488         {
4489             OICFree(*uriWithoutQuery);
4490             *uriWithoutQuery = NULL;
4491             goto exit;
4492         }
4493         OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4494     }
4495
4496     return OC_STACK_OK;
4497
4498     exit:
4499         return OC_STACK_NO_MEMORY;
4500 }
4501
4502 static const OicUuid_t* OCGetServerInstanceID(void)
4503 {
4504     static bool generated = false;
4505     static OicUuid_t sid;
4506     if (generated)
4507     {
4508         return &sid;
4509     }
4510
4511     if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4512     {
4513         OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4514         return NULL;
4515     }
4516     generated = true;
4517     return &sid;
4518 }
4519
4520 const char* OCGetServerInstanceIDString(void)
4521 {
4522     static bool generated = false;
4523     static char sidStr[UUID_STRING_SIZE];
4524
4525     if(generated)
4526     {
4527         return sidStr;
4528     }
4529
4530     const OicUuid_t *sid = OCGetServerInstanceID();
4531     if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4532     {
4533         OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4534         return NULL;
4535     }
4536
4537     generated = true;
4538     return sidStr;
4539 }
4540
4541 CAResult_t OCSelectNetwork()
4542 {
4543     CAResult_t retResult = CA_STATUS_FAILED;
4544     CAResult_t caResult = CA_STATUS_OK;
4545
4546     CATransportAdapter_t connTypes[] = {
4547             CA_ADAPTER_IP,
4548             CA_ADAPTER_RFCOMM_BTEDR,
4549             CA_ADAPTER_GATT_BTLE,
4550             CA_ADAPTER_NFC
4551 #ifdef RA_ADAPTER
4552             ,CA_ADAPTER_REMOTE_ACCESS
4553 #endif
4554
4555 #ifdef TCP_ADAPTER
4556             ,CA_ADAPTER_TCP
4557 #endif
4558         };
4559     int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4560
4561     for(int i = 0; i<numConnTypes; i++)
4562     {
4563         // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
4564         if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
4565         {
4566            caResult = CASelectNetwork(connTypes[i]);
4567            if(caResult == CA_STATUS_OK)
4568            {
4569                retResult = CA_STATUS_OK;
4570            }
4571         }
4572     }
4573
4574     if(retResult != CA_STATUS_OK)
4575     {
4576         return caResult; // Returns error of appropriate transport that failed fatally.
4577     }
4578
4579     return retResult;
4580 }
4581
4582 OCStackResult CAResultToOCResult(CAResult_t caResult)
4583 {
4584     switch (caResult)
4585     {
4586         case CA_STATUS_OK:
4587             return OC_STACK_OK;
4588         case CA_STATUS_INVALID_PARAM:
4589             return OC_STACK_INVALID_PARAM;
4590         case CA_ADAPTER_NOT_ENABLED:
4591             return OC_STACK_ADAPTER_NOT_ENABLED;
4592         case CA_SERVER_STARTED_ALREADY:
4593             return OC_STACK_OK;
4594         case CA_SERVER_NOT_STARTED:
4595             return OC_STACK_ERROR;
4596         case CA_DESTINATION_NOT_REACHABLE:
4597             return OC_STACK_COMM_ERROR;
4598         case CA_SOCKET_OPERATION_FAILED:
4599             return OC_STACK_COMM_ERROR;
4600         case CA_SEND_FAILED:
4601             return OC_STACK_COMM_ERROR;
4602         case CA_RECEIVE_FAILED:
4603             return OC_STACK_COMM_ERROR;
4604         case CA_MEMORY_ALLOC_FAILED:
4605             return OC_STACK_NO_MEMORY;
4606         case CA_REQUEST_TIMEOUT:
4607             return OC_STACK_TIMEOUT;
4608         case CA_DESTINATION_DISCONNECTED:
4609             return OC_STACK_COMM_ERROR;
4610         case CA_STATUS_FAILED:
4611             return OC_STACK_ERROR;
4612         case CA_NOT_SUPPORTED:
4613             return OC_STACK_NOTIMPL;
4614         default:
4615             return OC_STACK_ERROR;
4616     }
4617 }