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