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