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