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