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