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