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