12adb2f4c64b6b576f8faee86fc4e8b77e322d9e
[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     OCPayloadDestroy(response.payload);
1000     return result;
1001 }
1002
1003 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1004 {
1005     VERIFY_NON_NULL_NR(endPoint, FATAL);
1006     VERIFY_NON_NULL_NR(responseInfo, FATAL);
1007
1008     OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
1009
1010     if(responseInfo->info.resourceUri &&
1011         strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1012     {
1013         HandlePresenceResponse(endPoint, responseInfo);
1014         return;
1015     }
1016
1017     ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1018             responseInfo->info.tokenLength, NULL, NULL);
1019
1020     ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1021             responseInfo->info.tokenLength);
1022
1023     if(cbNode)
1024     {
1025         OC_LOG(INFO, TAG, PCF("There is a cbNode associated with the response token"));
1026         if(responseInfo->result == CA_EMPTY)
1027         {
1028             OC_LOG(INFO, TAG, PCF("Receiving A ACK/RESET for this token"));
1029             // We do not have a case for the client to receive a RESET
1030             if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1031             {
1032                 //This is the case of receiving an ACK on a request to a slow resource!
1033                 OC_LOG(INFO, TAG, PCF("This is a pure ACK"));
1034                 //TODO: should we inform the client
1035                 //      app that at least the request was received at the server?
1036             }
1037         }
1038         else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1039         {
1040             OC_LOG(INFO, TAG, PCF("Receiving A Timeout for this token"));
1041             OC_LOG(INFO, TAG, PCF("Calling into application address space"));
1042
1043             OCClientResponse response = {};
1044             CopyEndpointToDevAddr(endPoint, &response.devAddr);
1045             FixUpClientResponse(&response);
1046             response.resourceUri = responseInfo->info.resourceUri;
1047
1048             response.result = CAToOCStackResult(responseInfo->result);
1049             cbNode->callBack(cbNode->context,
1050                     cbNode->handle, &response);
1051             FindAndDeleteClientCB(cbNode);
1052         }
1053         else
1054         {
1055             OC_LOG(INFO, TAG, PCF("This is a regular response, A client call back is found"));
1056             OC_LOG(INFO, TAG, PCF("Calling into application address space"));
1057
1058             OCClientResponse response = {};
1059             response.sequenceNumber = OC_OBSERVE_NO_OPTION;
1060             CopyEndpointToDevAddr(endPoint, &response.devAddr);
1061             FixUpClientResponse(&response);
1062             response.resourceUri = responseInfo->info.resourceUri;
1063
1064             response.result = CAToOCStackResult(responseInfo->result);
1065             if(responseInfo->info.payload &&
1066                responseInfo->info.payloadSize &&
1067                OC_STACK_OK != OCParsePayload(&response.payload, responseInfo->info.payload,
1068                                            responseInfo->info.payloadSize))
1069             {
1070                 OC_LOG(ERROR, TAG, PCF("Error converting payload"));
1071                 OCPayloadDestroy(response.payload);
1072                 return;
1073             }
1074
1075             response.numRcvdVendorSpecificHeaderOptions = 0;
1076             if(responseInfo->info.numOptions > 0)
1077             {
1078                 int start = 0;
1079                 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1080                 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1081                 {
1082                     memcpy (&(response.sequenceNumber),
1083                             &(responseInfo->info.options[0].optionData), sizeof(uint32_t));
1084                     response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1085                     start = 1;
1086                 }
1087                 else
1088                 {
1089                     response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1090                 }
1091
1092                 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1093                 {
1094                     OC_LOG(ERROR, TAG, PCF("#header options are more than MAX_HEADER_OPTIONS"));
1095                     OCPayloadDestroy(response.payload);
1096                     return;
1097                 }
1098
1099                 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1100                 {
1101                     memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1102                             &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1103                 }
1104             }
1105
1106             if (cbNode->method == OC_REST_OBSERVE &&
1107                 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1108                 response.sequenceNumber <= cbNode->sequenceNumber)
1109             {
1110                 OC_LOG_V(INFO, TAG, PCF("Received stale notification. Number :%d"),
1111                                                  response.sequenceNumber);
1112             }
1113             else
1114             {
1115                 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1116                                                                         cbNode->handle,
1117                                                                         &response);
1118                 cbNode->sequenceNumber = response.sequenceNumber;
1119
1120                 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1121                 {
1122                     FindAndDeleteClientCB(cbNode);
1123                 }
1124                 else
1125                 {
1126                     // To keep discovery callbacks active.
1127                     cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1128                                             MILLISECONDS_PER_SECOND);
1129                 }
1130             }
1131
1132             //Need to send ACK when the response is CON
1133             if(responseInfo->info.type == CA_MSG_CONFIRM)
1134             {
1135                 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1136                         CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0);
1137             }
1138
1139             OCPayloadDestroy(response.payload);
1140         }
1141         return;
1142     }
1143
1144     if(observer)
1145     {
1146         OC_LOG(INFO, TAG, PCF("There is an observer associated with the response token"));
1147         if(responseInfo->result == CA_EMPTY)
1148         {
1149             OC_LOG(INFO, TAG, PCF("Receiving A ACK/RESET for this token"));
1150             if(responseInfo->info.type == CA_MSG_RESET)
1151             {
1152                 OC_LOG(INFO, TAG, PCF("This is a RESET"));
1153                 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1154                         OC_OBSERVER_NOT_INTERESTED);
1155             }
1156             else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1157             {
1158                 OC_LOG(INFO, TAG, PCF("This is a pure ACK"));
1159                 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1160                         OC_OBSERVER_STILL_INTERESTED);
1161             }
1162         }
1163         else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1164         {
1165             OC_LOG(INFO, TAG, PCF("Receiving Time Out for an observer"));
1166             OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1167                     OC_OBSERVER_FAILED_COMM);
1168         }
1169         return;
1170     }
1171
1172     if(!cbNode && !observer)
1173     {
1174         if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER)
1175         {
1176             OC_LOG(INFO, TAG, PCF("This is a client, but no cbNode was found for token"));
1177             if(responseInfo->result == CA_EMPTY)
1178             {
1179                 OC_LOG(INFO, TAG, PCF("Receiving CA_EMPTY in the ocstack"));
1180             }
1181             else
1182             {
1183                 OC_LOG(INFO, TAG, PCF("Received a message without callbacks. Sending RESET"));
1184                 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1185                         CA_MSG_RESET, 0, NULL, NULL, 0);
1186             }
1187         }
1188
1189         if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER)
1190         {
1191             OC_LOG(INFO, TAG, PCF("This is a server, but no observer was found for token"));
1192             if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1193             {
1194                 OC_LOG_V(INFO, TAG, PCF("Received ACK at server for messageId : %d"),
1195                                             responseInfo->info.messageId);
1196             }
1197             if (responseInfo->info.type == CA_MSG_RESET)
1198             {
1199                 OC_LOG_V(INFO, TAG, PCF("Received RESET at server for messageId : %d"),
1200                                             responseInfo->info.messageId);
1201             }
1202         }
1203
1204         return;
1205     }
1206
1207     OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses"));
1208 }
1209
1210 /*
1211  * This function handles error response from CA
1212  * code shall be added to handle the errors
1213  */
1214 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errrorInfo)
1215 {
1216     OC_LOG(INFO, TAG, PCF("Enter HandleCAErrorResponse"));
1217
1218     if(NULL == endPoint)
1219     {
1220         OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
1221         return;
1222     }
1223
1224     if(NULL == errrorInfo)
1225     {
1226         OC_LOG(ERROR, TAG, PCF("errrorInfo is NULL"));
1227         return;
1228     }
1229     OC_LOG(INFO, TAG, PCF("Exit HandleCAErrorResponse"));
1230 }
1231
1232 /*
1233  * This function sends out Direct Stack Responses. These are responses that are not coming
1234  * from the application entity handler. These responses have no payload and are usually ACKs,
1235  * RESETs or some error conditions that were caught by the stack.
1236  */
1237 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1238         const CAResponseResult_t responseResult, const CAMessageType_t type,
1239         const uint8_t numOptions, const CAHeaderOption_t *options,
1240         CAToken_t token, uint8_t tokenLength)
1241 {
1242     CAResponseInfo_t respInfo = {};
1243     respInfo.result = responseResult;
1244     respInfo.info.messageId = coapID;
1245     respInfo.info.numOptions = numOptions;
1246     respInfo.info.options = (CAHeaderOption_t*)options;
1247     respInfo.info.payload = NULL;
1248     respInfo.info.token = token;
1249     respInfo.info.tokenLength = tokenLength;
1250     respInfo.info.type = type;
1251
1252     CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1253     if(caResult != CA_STATUS_OK)
1254     {
1255         OC_LOG(ERROR, TAG, PCF("CASendResponse error"));
1256         return OC_STACK_ERROR;
1257     }
1258     return OC_STACK_OK;
1259 }
1260
1261 //This function will be called back by CA layer when a request is received
1262 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1263 {
1264     OC_LOG(INFO, TAG, PCF("Enter HandleCARequests"));
1265     if(!endPoint)
1266     {
1267         OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
1268         return;
1269     }
1270
1271     if(!requestInfo)
1272     {
1273         OC_LOG(ERROR, TAG, PCF("requestInfo is NULL"));
1274         return;
1275     }
1276
1277     OCStackResult requestResult = OC_STACK_ERROR;
1278
1279     if(myStackMode == OC_CLIENT)
1280     {
1281         //TODO: should the client be responding to requests?
1282         return;
1283     }
1284
1285     OCServerProtocolRequest serverRequest = {};
1286
1287     OC_LOG_V(INFO, TAG, PCF("Endpoint URI : %s"), requestInfo->info.resourceUri);
1288
1289     char * uriWithoutQuery = NULL;
1290     char * query  = NULL;
1291
1292     requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1293
1294     if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1295     {
1296         OC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1297         return;
1298     }
1299     OC_LOG_V(INFO, TAG, PCF("URI without query: %s"), uriWithoutQuery);
1300     OC_LOG_V(INFO, TAG, PCF("Query : %s"), query);
1301
1302     if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1303     {
1304         OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1305         OICFree(uriWithoutQuery);
1306     }
1307     else
1308     {
1309         OC_LOG(ERROR, TAG, PCF("URI length exceeds MAX_URI_LENGTH."));
1310         OICFree(uriWithoutQuery);
1311         OICFree(query);
1312         return;
1313     }
1314
1315     if(query)
1316     {
1317         if(strlen(query) < MAX_QUERY_LENGTH)
1318         {
1319             OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1320             OICFree(query);
1321         }
1322         else
1323         {
1324             OC_LOG(ERROR, TAG, PCF("Query length exceeds MAX_QUERY_LENGTH."));
1325             OICFree(query);
1326             return;
1327         }
1328     }
1329
1330     if (requestInfo->info.payload)
1331     {
1332         serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1333         memcpy (&(serverRequest.payload), requestInfo->info.payload,
1334                 requestInfo->info.payloadSize);
1335     }
1336     else
1337     {
1338         serverRequest.reqTotalSize = 0;
1339     }
1340
1341     switch (requestInfo->method)
1342     {
1343         case CA_GET:
1344             serverRequest.method = OC_REST_GET;
1345             break;
1346         case CA_PUT:
1347             serverRequest.method = OC_REST_PUT;
1348             break;
1349         case CA_POST:
1350             serverRequest.method = OC_REST_POST;
1351             break;
1352         case CA_DELETE:
1353             serverRequest.method = OC_REST_DELETE;
1354             break;
1355         default:
1356             OC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1357             SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1358                         requestInfo->info.type, requestInfo->info.numOptions,
1359                         requestInfo->info.options, requestInfo->info.token,
1360                         requestInfo->info.tokenLength);
1361             return;
1362     }
1363
1364     OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1365             requestInfo->info.tokenLength);
1366     serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1367     serverRequest.tokenLength = requestInfo->info.tokenLength;
1368
1369     if (!serverRequest.requestToken)
1370     {
1371         OC_LOG(FATAL, TAG, "Allocation for token failed.");
1372         SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1373                 requestInfo->info.type, requestInfo->info.numOptions,
1374                 requestInfo->info.options, requestInfo->info.token,
1375                 requestInfo->info.tokenLength);
1376         return;
1377     }
1378     memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1379
1380     if (requestInfo->info.type == CA_MSG_CONFIRM)
1381     {
1382         serverRequest.qos = OC_HIGH_QOS;
1383     }
1384     else
1385     {
1386         serverRequest.qos = OC_LOW_QOS;
1387     }
1388     // CA does not need the following field
1389     // Are we sure CA does not need them? how is it responding to multicast
1390     serverRequest.delayedResNeeded = 0;
1391
1392     serverRequest.coapID = requestInfo->info.messageId;
1393
1394     CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1395
1396     // copy vendor specific header options
1397     uint8_t tempNum = (requestInfo->info.numOptions);
1398     GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1399     if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1400     {
1401         OC_LOG(ERROR, TAG,
1402                 PCF("The request info numOptions is greater than MAX_HEADER_OPTIONS"));
1403         SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1404                 requestInfo->info.type, requestInfo->info.numOptions,
1405                 requestInfo->info.options, requestInfo->info.token,
1406                 requestInfo->info.tokenLength);
1407         OICFree(serverRequest.requestToken);
1408         return;
1409     }
1410     serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1411     if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1412     {
1413         memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1414             sizeof(CAHeaderOption_t)*tempNum);
1415     }
1416
1417     requestResult = HandleStackRequests (&serverRequest);
1418
1419     // Send ACK to client as precursor to slow response
1420     if(requestResult == OC_STACK_SLOW_RESOURCE)
1421     {
1422         SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1423                     CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0);
1424     }
1425     else if(requestResult != OC_STACK_OK)
1426     {
1427         OC_LOG_V(ERROR, TAG, PCF("HandleStackRequests failed. error: %d"), requestResult);
1428
1429         CAResponseResult_t stackResponse = OCToCAStackResult(requestResult);
1430
1431         SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1432                 requestInfo->info.type, requestInfo->info.numOptions,
1433                 requestInfo->info.options, requestInfo->info.token,
1434                 requestInfo->info.tokenLength);
1435     }
1436     // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1437     // The token is copied in there, and is thus still owned by this function.
1438     OICFree(serverRequest.requestToken);
1439     OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
1440 }
1441
1442 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1443 {
1444     OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
1445     OCStackResult result = OC_STACK_ERROR;
1446     ResourceHandling resHandling;
1447     OCResource *resource;
1448     if(!protocolRequest)
1449     {
1450         OC_LOG(ERROR, TAG, PCF("protocolRequest is NULL"));
1451         return OC_STACK_INVALID_PARAM;
1452     }
1453
1454     OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1455             protocolRequest->tokenLength);
1456     if(!request)
1457     {
1458         OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
1459         result = AddServerRequest(&request, protocolRequest->coapID,
1460                 protocolRequest->delayedResNeeded, 0,
1461                 protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
1462                 protocolRequest->observationOption, protocolRequest->qos,
1463                 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1464                 protocolRequest->payload, protocolRequest->requestToken,
1465                 protocolRequest->tokenLength,
1466                 protocolRequest->resourceUrl, protocolRequest->reqTotalSize,
1467                 &protocolRequest->devAddr);
1468         if (OC_STACK_OK != result)
1469         {
1470             OC_LOG(ERROR, TAG, PCF("Error adding server request"));
1471             return result;
1472         }
1473
1474         if(!request)
1475         {
1476             OC_LOG(ERROR, TAG, PCF("Out of Memory"));
1477             return OC_STACK_NO_MEMORY;
1478         }
1479
1480         if(!protocolRequest->reqMorePacket)
1481         {
1482             request->requestComplete = 1;
1483         }
1484     }
1485     else
1486     {
1487         OC_LOG(INFO, TAG, PCF("This is either a repeated or blocked Server Request"));
1488     }
1489
1490     if(request->requestComplete)
1491     {
1492         OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
1493         result = DetermineResourceHandling (request, &resHandling, &resource);
1494         if (result == OC_STACK_OK)
1495         {
1496             result = ProcessRequest(resHandling, resource, request);
1497         }
1498     }
1499     else
1500     {
1501         OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
1502         result = OC_STACK_CONTINUE;
1503     }
1504     return result;
1505 }
1506
1507 bool validatePlatformInfo(OCPlatformInfo info)
1508 {
1509
1510     if (!info.platformID)
1511     {
1512         OC_LOG(ERROR, TAG, PCF("No platform ID found."));
1513         return false;
1514     }
1515
1516     if (info.manufacturerName)
1517     {
1518         size_t lenManufacturerName = strlen(info.manufacturerName);
1519
1520         if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
1521         {
1522             OC_LOG(ERROR, TAG, PCF("Manufacturer name fails length requirements."));
1523             return false;
1524         }
1525     }
1526     else
1527     {
1528         OC_LOG(ERROR, TAG, PCF("No manufacturer name present"));
1529         return false;
1530     }
1531
1532     if (info.manufacturerUrl)
1533     {
1534         if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
1535         {
1536             OC_LOG(ERROR, TAG, PCF("Manufacturer url fails length requirements."));
1537             return false;
1538         }
1539     }
1540     return true;
1541 }
1542
1543 //-----------------------------------------------------------------------------
1544 // Public APIs
1545 //-----------------------------------------------------------------------------
1546 #ifdef RA_ADAPTER
1547 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
1548 {
1549     if (!raInfo           ||
1550         !raInfo->username ||
1551         !raInfo->hostname ||
1552         !raInfo->xmpp_domain)
1553     {
1554
1555         return OC_STACK_INVALID_PARAM;
1556     }
1557     OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
1558     gRASetInfo = (result == OC_STACK_OK)? true : false;
1559
1560     return result;
1561 }
1562 #endif
1563
1564 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1565 {
1566     (void) ipAddr;
1567     (void) port;
1568 #ifdef RA_ADAPTER
1569     if(!gRASetInfo)
1570     {
1571         OC_LOG(ERROR, TAG, PCF("Need to call OCSetRAInfo before calling OCInit"));
1572         return OC_STACK_ERROR;
1573     }
1574 #endif
1575     return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
1576 }
1577
1578 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
1579 {
1580     if(stackState == OC_STACK_INITIALIZED)
1581     {
1582         OC_LOG(INFO, TAG, PCF("Subsequent calls to OCInit() without calling \
1583                 OCStop() between them are ignored."));
1584         return OC_STACK_OK;
1585     }
1586
1587     OCStackResult result = OC_STACK_ERROR;
1588     OC_LOG(INFO, TAG, PCF("Entering OCInit"));
1589
1590     // Validate mode
1591     if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)))
1592     {
1593         OC_LOG(ERROR, TAG, PCF("Invalid mode"));
1594         return OC_STACK_ERROR;
1595     }
1596     myStackMode = mode;
1597
1598     if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER)
1599     {
1600         caglobals.client = true;
1601     }
1602     if (mode == OC_SERVER || mode == OC_CLIENT_SERVER)
1603     {
1604         caglobals.server = true;
1605     }
1606
1607     caglobals.serverFlags = (CATransportFlags_t)serverFlags;
1608     if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
1609     {
1610         caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4);
1611     }
1612     caglobals.clientFlags = (CATransportFlags_t)clientFlags;
1613     if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
1614     {
1615         caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4);
1616     }
1617
1618     defaultDeviceHandler = NULL;
1619     defaultDeviceHandlerCallbackParameter = NULL;
1620     OCSeedRandom();
1621
1622     result = CAResultToOCResult(CAInitialize());
1623     VERIFY_SUCCESS(result, OC_STACK_OK);
1624
1625     result = CAResultToOCResult(OCSelectNetwork());
1626     VERIFY_SUCCESS(result, OC_STACK_OK);
1627
1628     switch (myStackMode)
1629     {
1630         case OC_CLIENT:
1631                         CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1632             result = CAResultToOCResult(CAStartDiscoveryServer());
1633             OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
1634             break;
1635         case OC_SERVER:
1636                         SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1637             result = CAResultToOCResult(CAStartListeningServer());
1638             OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
1639             break;
1640         case OC_CLIENT_SERVER:
1641                         SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1642             result = CAResultToOCResult(CAStartListeningServer());
1643             if(result == OC_STACK_OK)
1644             {
1645                 result = CAResultToOCResult(CAStartDiscoveryServer());
1646             }
1647             break;
1648     }
1649     VERIFY_SUCCESS(result, OC_STACK_OK);
1650
1651 #ifdef WITH_PRESENCE
1652     PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
1653 #endif // WITH_PRESENCE
1654
1655     //Update Stack state to initialized
1656     stackState = OC_STACK_INITIALIZED;
1657
1658     // Initialize resource
1659     if(myStackMode != OC_CLIENT)
1660     {
1661         result = initResources();
1662     }
1663
1664     // Initialize the SRM Policy Engine
1665     if(result == OC_STACK_OK)
1666     {
1667         result = SRMInitPolicyEngine();
1668         // TODO after BeachHead delivery: consolidate into single SRMInit()
1669     }
1670
1671 exit:
1672     if(result != OC_STACK_OK)
1673     {
1674         OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
1675         deleteAllResources();
1676         CATerminate();
1677         stackState = OC_STACK_UNINITIALIZED;
1678     }
1679     return result;
1680 }
1681
1682 OCStackResult OCStop()
1683 {
1684     OC_LOG(INFO, TAG, PCF("Entering OCStop"));
1685
1686     if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1687     {
1688         OC_LOG(DEBUG, TAG, PCF("Stack already stopping, exiting"));
1689         return OC_STACK_OK;
1690     }
1691     else if (stackState != OC_STACK_INITIALIZED)
1692     {
1693         OC_LOG(ERROR, TAG, PCF("Stack not initialized"));
1694         return OC_STACK_ERROR;
1695     }
1696
1697     stackState = OC_STACK_UNINIT_IN_PROGRESS;
1698
1699     #ifdef WITH_PRESENCE
1700     // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1701     // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1702     presenceResource.presenceTTL = 0;
1703     #endif // WITH_PRESENCE
1704
1705     // Free memory dynamically allocated for resources
1706     deleteAllResources();
1707     DeleteDeviceInfo();
1708     DeletePlatformInfo();
1709     CATerminate();
1710     // Remove all observers
1711     DeleteObserverList();
1712     // Remove all the client callbacks
1713     DeleteClientCBList();
1714
1715         // De-init the SRM Policy Engine
1716     // TODO after BeachHead delivery: consolidate into single SRMDeInit()
1717     SRMDeInitPolicyEngine();
1718
1719
1720     stackState = OC_STACK_UNINITIALIZED;
1721     return OC_STACK_OK;
1722 }
1723
1724 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
1725 {
1726     switch (qos)
1727     {
1728         case OC_HIGH_QOS:
1729             return CA_MSG_CONFIRM;
1730         case OC_LOW_QOS:
1731         case OC_MEDIUM_QOS:
1732         case OC_NA_QOS:
1733         default:
1734             return CA_MSG_NONCONFIRM;
1735     }
1736 }
1737
1738 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
1739 {
1740     char *query;
1741
1742     query = strchr (inputUri, '?');
1743
1744     if (query != NULL)
1745     {
1746         if((query - inputUri) > MAX_URI_LENGTH)
1747         {
1748             return OC_STACK_INVALID_URI;
1749         }
1750
1751         if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
1752         {
1753             return OC_STACK_INVALID_QUERY;
1754         }
1755     }
1756     else if(uriLen > MAX_URI_LENGTH)
1757     {
1758         return OC_STACK_INVALID_URI;
1759     }
1760     return OC_STACK_OK;
1761 }
1762
1763 /**
1764  *  A request uri consists of the following components in order:
1765  *                              example
1766  *  optional prefix             "coap://"
1767  *  optionally one of
1768  *      IPv6 address            "[1234::5678]"
1769  *      IPv4 address            "192.168.1.1"
1770  *  optional port               ":5683"
1771  *  resource uri                "/oc/core..."
1772  *
1773  *  for PRESENCE requests, extract resource type.
1774  */
1775 static OCStackResult ParseRequestUri(const char *fullUri,
1776                                         OCTransportAdapter adapter,
1777                                         OCTransportFlags flags,
1778                                         OCDevAddr **devAddr,
1779                                         char **resourceUri,
1780                                         char **resourceType)
1781 {
1782     VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
1783
1784     OCStackResult result = OC_STACK_OK;
1785     OCDevAddr *da = NULL;
1786     char *colon = NULL;
1787     char *end;
1788
1789     // provide defaults for all returned values
1790     if (devAddr)
1791     {
1792         *devAddr = NULL;
1793     }
1794     if (resourceUri)
1795     {
1796         *resourceUri = NULL;
1797     }
1798     if (resourceType)
1799     {
1800         *resourceType = NULL;
1801     }
1802
1803     // delimit url prefix, if any
1804     const char *start = fullUri;
1805     char *slash2 = strstr(start, "//");
1806     if (slash2)
1807     {
1808         start = slash2 + 2;
1809     }
1810     char *slash = strchr(start, '/');
1811     if (!slash)
1812     {
1813         return OC_STACK_INVALID_URI;
1814     }
1815
1816     // processs url prefix, if any
1817     size_t urlLen = slash - start;
1818     // port
1819     uint16_t port = 0;
1820     size_t len = 0;
1821     if (urlLen && devAddr)
1822     {   // construct OCDevAddr
1823         if (OC_ADAPTER_IP == adapter)
1824         {
1825             if (start[0] == '[')
1826             {   // ipv6 address
1827                 char *close = strchr(++start, ']');
1828                 if (!close || close > slash)
1829                 {
1830                     return OC_STACK_INVALID_URI;
1831                 }
1832                 end = close;
1833                 if (close[1] == ':')
1834                 {
1835                     colon = close + 1;
1836                 }
1837             }
1838             else
1839             {   // ipv4 address
1840                 end = slash;
1841                 colon = strchr(start, ':');
1842                 end = (colon && colon < slash) ? colon : slash;
1843             }
1844             len = end - start;
1845             if (len >= sizeof(da->addr))
1846             {
1847                 return OC_STACK_INVALID_URI;
1848             }
1849             // collect port, if any
1850             if (colon && colon < slash)
1851             {
1852                 for (colon++; colon < slash; colon++)
1853                 {
1854                     char c = colon[0];
1855                     if (c < '0' || c > '9')
1856                     {
1857                         return OC_STACK_INVALID_URI;
1858                     }
1859                     port = 10 * port + c - '0';
1860                 }
1861             }
1862         }
1863         else
1864         {
1865             /**
1866              * This is for Non-IP adapters(EDR and BLE).
1867              * The address will be between "//" and "/" in the request URI.
1868              * [Ex. coap://AB:BC:CD:DE:EF:FG/resource_uri]
1869              */
1870             end = slash;
1871         }
1872
1873         len = end - start;
1874         if (len >= sizeof(da->addr))
1875         {
1876             return OC_STACK_INVALID_URI;
1877         }
1878
1879         da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
1880         if (!da)
1881         {
1882             return OC_STACK_NO_MEMORY;
1883         }
1884         OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
1885         da->port = port;
1886         da->adapter = adapter;
1887         da->flags = flags;
1888         if (!strncmp(fullUri, "coaps:", 6))
1889         {
1890             da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
1891         }
1892         *devAddr = da;
1893     }
1894
1895     // process resource uri, if any
1896     if (slash)
1897     {   // request uri and query
1898         size_t ulen = strlen(slash); // resource uri length
1899         size_t tlen = 0;      // resource type length
1900         char *type = NULL;
1901
1902         static const char strPresence[] = "/oic/ad?rt=";
1903         static const size_t lenPresence = sizeof(strPresence) - 1;
1904         if (!strncmp(slash, strPresence, lenPresence))
1905         {
1906             type = slash + lenPresence;
1907             tlen = ulen - lenPresence;
1908         }
1909         // resource uri
1910         if (resourceUri)
1911         {
1912             *resourceUri = (char *)OICMalloc(ulen + 1);
1913             if (!*resourceUri)
1914             {
1915                 result = OC_STACK_NO_MEMORY;
1916                 goto error;
1917             }
1918             strcpy(*resourceUri, slash);
1919         }
1920         // resource type
1921         if (type && resourceType)
1922         {
1923             *resourceType = (char *)OICMalloc(tlen + 1);
1924             if (!*resourceType)
1925             {
1926                 result = OC_STACK_NO_MEMORY;
1927                 goto error;
1928             }
1929
1930             OICStrcpy(*resourceType, (tlen+1), type);
1931         }
1932     }
1933
1934     return OC_STACK_OK;
1935
1936 error:
1937     // free all returned values
1938     if (devAddr)
1939     {
1940         OICFree(*devAddr);
1941     }
1942     if (resourceUri)
1943     {
1944         OICFree(*resourceUri);
1945     }
1946     if (resourceType)
1947     {
1948         OICFree(*resourceType);
1949     }
1950     return result;
1951 }
1952
1953 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
1954                                         char *resourceUri, char **requestUri)
1955 {
1956     char uri[CA_MAX_URI_LENGTH];
1957
1958     FormCanonicalPresenceUri(endpoint, resourceUri, uri);
1959
1960     *requestUri = OICStrdup(uri);
1961     if (!*requestUri)
1962     {
1963         return OC_STACK_NO_MEMORY;
1964     }
1965
1966     return OC_STACK_OK;
1967 }
1968
1969 /**
1970  * Discover or Perform requests on a specified resource
1971  */
1972 OCStackResult OCDoResource(OCDoHandle *handle,
1973                             OCMethod method,
1974                             const char *requestUri,
1975                             const OCDevAddr *destination,
1976                             OCPayload* payload,
1977                             OCConnectivityType connectivityType,
1978                             OCQualityOfService qos,
1979                             OCCallbackData *cbData,
1980                             OCHeaderOption *options,
1981                             uint8_t numOptions)
1982 {
1983     OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
1984
1985     // Validate input parameters
1986     VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
1987     VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
1988     VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
1989
1990     OCStackResult result = OC_STACK_ERROR;
1991     CAResult_t caResult;
1992     CAToken_t token = NULL;
1993     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
1994     ClientCB *clientCB = NULL;
1995     OCDoHandle resHandle = NULL;
1996     CAEndpoint_t *endpoint = NULL;
1997     OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
1998     uint32_t ttl = 0;
1999     OCTransportAdapter adapter;
2000     OCTransportFlags flags;
2001     // the request contents are put here
2002     CARequestInfo_t requestInfo = { CA_GET };
2003     // requestUri  will be parsed into the following three variables
2004     OCDevAddr *devAddr = NULL;
2005     char *resourceUri = NULL;
2006     char *resourceType = NULL;
2007
2008     // To track if memory is allocated for additional header options
2009     uint8_t hdrOptionMemAlloc = 0;
2010
2011     // This validation is broken, but doesn't cause harm
2012     size_t uriLen = strlen(requestUri );
2013     if ((result = verifyUriQueryLength(requestUri , uriLen)) != OC_STACK_OK)
2014     {
2015         goto exit;
2016     }
2017
2018     /*
2019      * Support original behavior with address on resourceUri argument.
2020      */
2021     adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2022     flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2023
2024     result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2025
2026     if (result != OC_STACK_OK)
2027     {
2028         OC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2029         goto exit;
2030     }
2031
2032     switch (method)
2033     {
2034     case OC_REST_GET:
2035     case OC_REST_OBSERVE:
2036     case OC_REST_OBSERVE_ALL:
2037     case OC_REST_CANCEL_OBSERVE:
2038         requestInfo.method = CA_GET;
2039         break;
2040     case OC_REST_PUT:
2041         requestInfo.method = CA_PUT;
2042         break;
2043     case OC_REST_POST:
2044         requestInfo.method = CA_POST;
2045         break;
2046     case OC_REST_DELETE:
2047         requestInfo.method = CA_DELETE;
2048         break;
2049     case OC_REST_DISCOVER:
2050         qos = OC_LOW_QOS;
2051         if (destination || devAddr)
2052         {
2053             requestInfo.isMulticast = false;
2054         }
2055         else
2056         {
2057             destination = &tmpDevAddr;
2058             requestInfo.isMulticast = true;
2059         }
2060         // CA_DISCOVER will become GET and isMulticast
2061         requestInfo.method = CA_GET;
2062         break;
2063     #ifdef WITH_PRESENCE
2064     case OC_REST_PRESENCE:
2065         // Replacing method type with GET because "presence"
2066         // is a stack layer only implementation.
2067         requestInfo.method = CA_GET;
2068         break;
2069     #endif
2070     default:
2071         result = OC_STACK_INVALID_METHOD;
2072         goto exit;
2073     }
2074
2075     if (!devAddr && !destination)
2076     {
2077         OC_LOG_V(DEBUG, TAG, "no devAddr and no destination");
2078         result = OC_STACK_INVALID_PARAM;
2079         goto exit;
2080     }
2081
2082     /* If not original behavior, use destination argument */
2083     if (destination && !devAddr)
2084     {
2085         devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2086         if (!devAddr)
2087         {
2088             result = OC_STACK_NO_MEMORY;
2089             goto exit;
2090         }
2091         *devAddr = *destination;
2092     }
2093
2094     resHandle = GenerateInvocationHandle();
2095     if (!resHandle)
2096     {
2097         result = OC_STACK_NO_MEMORY;
2098         goto exit;
2099     }
2100
2101     caResult = CAGenerateToken(&token, tokenLength);
2102     if (caResult != CA_STATUS_OK)
2103     {
2104         OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
2105         result= OC_STACK_ERROR;
2106         goto exit;
2107     }
2108
2109     // fill in request data
2110     requestInfo.info.type = qualityOfServiceToMessageType(qos);
2111     requestInfo.info.token = token;
2112     requestInfo.info.tokenLength = tokenLength;
2113     requestInfo.info.resourceUri = resourceUri;
2114
2115     if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2116     {
2117         result = CreateObserveHeaderOption (&(requestInfo.info.options),
2118                                     options, numOptions, OC_OBSERVE_REGISTER);
2119         if (result != OC_STACK_OK)
2120         {
2121             goto exit;
2122         }
2123         hdrOptionMemAlloc = 1;
2124         requestInfo.info.numOptions = numOptions + 1;
2125     }
2126     else
2127     {
2128         requestInfo.info.options = (CAHeaderOption_t*)options;
2129         requestInfo.info.numOptions = numOptions;
2130     }
2131
2132     // create remote endpoint
2133     result = OCCreateEndpoint(devAddr, &endpoint);
2134     if(payload)
2135     {
2136         if((result =
2137             OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2138                 != OC_STACK_OK)
2139         {
2140             OC_LOG(ERROR, TAG, PCF("Failed to create CBOR Payload"));
2141             goto exit;
2142         }
2143     }
2144     else
2145     {
2146         requestInfo.info.payload = NULL;
2147         requestInfo.info.payloadSize = 0;
2148     }
2149
2150
2151
2152     if (result != OC_STACK_OK)
2153     {
2154         OC_LOG(ERROR, TAG, PCF("CACreateEndpoint error"));
2155         goto exit;
2156     }
2157
2158     // prepare for response
2159     #ifdef WITH_PRESENCE
2160     if (method == OC_REST_PRESENCE)
2161     {
2162         char *presenceUri = NULL;
2163         result = OCPreparePresence(endpoint, resourceUri, &presenceUri);
2164         if (OC_STACK_OK != result)
2165         {
2166             goto exit;
2167         }
2168
2169         // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2170         // Presence notification will form a canonical uri to
2171         // look for callbacks into the application.
2172         resourceUri = presenceUri;
2173     }
2174     #endif
2175
2176     ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2177     result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2178                             method, devAddr, resourceUri, resourceType, ttl);
2179     if (OC_STACK_OK != result)
2180     {
2181         goto exit;
2182     }
2183
2184     devAddr = NULL;       // Client CB list entry now owns it
2185     resourceUri = NULL;   // Client CB list entry now owns it
2186     resourceType = NULL;  // Client CB list entry now owns it
2187
2188     // send request
2189     caResult = CASendRequest(endpoint, &requestInfo);
2190     if (caResult != CA_STATUS_OK)
2191     {
2192         OC_LOG(ERROR, TAG, PCF("CASendRequest"));
2193         result = OC_STACK_COMM_ERROR;
2194         goto exit;
2195     }
2196
2197     if (handle)
2198     {
2199         *handle = resHandle;
2200     }
2201
2202 exit:
2203     if (result != OC_STACK_OK)
2204     {
2205         OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
2206         FindAndDeleteClientCB(clientCB);
2207         CADestroyToken(token);
2208         if (handle)
2209         {
2210             *handle = NULL;
2211         }
2212         OICFree(resHandle);
2213     }
2214
2215     // This is the owner of the payload object, so we free it
2216     OCPayloadDestroy(payload);
2217     OICFree(requestInfo.info.payload);
2218     OICFree(devAddr);
2219     OICFree(resourceUri);
2220     OICFree(resourceType);
2221     OICFree(endpoint);
2222     if (hdrOptionMemAlloc)
2223     {
2224         OICFree(requestInfo.info.options);
2225     }
2226     return result;
2227 }
2228
2229 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2230         uint8_t numOptions)
2231 {
2232     /*
2233      * This ftn is implemented one of two ways in the case of observation:
2234      *
2235      * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2236      *      Remove the callback associated on client side.
2237      *      When the next notification comes in from server,
2238      *      reply with RESET message to server.
2239      *      Keep in mind that the server will react to RESET only
2240      *      if the last notification was sent as CON
2241      *
2242      * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2243      *      and it is associated with an observe request
2244      *      (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2245      *      Send CON Observe request to server with
2246      *      observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2247      *      Remove the callback associated on client side.
2248      */
2249     OCStackResult ret = OC_STACK_OK;
2250     CAEndpoint_t* endpoint = NULL;
2251     CAResult_t caResult;
2252     CAInfo_t requestData = {};
2253     CARequestInfo_t requestInfo = {};
2254
2255     if(!handle)
2256     {
2257         return OC_STACK_INVALID_PARAM;
2258     }
2259
2260     ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2261     if (!clientCB)
2262     {
2263         OC_LOG(ERROR, TAG, PCF("Client callback not found. Called OCCancel twice?"));
2264         goto Error;
2265     }
2266
2267     switch (clientCB->method)
2268     {
2269         case OC_REST_OBSERVE:
2270         case OC_REST_OBSERVE_ALL:
2271             OC_LOG_V(INFO, TAG, "Canceling observation for resource %s",
2272                                         clientCB->requestUri);
2273             if (qos != OC_HIGH_QOS)
2274             {
2275                 FindAndDeleteClientCB(clientCB);
2276                 break;
2277             }
2278             else
2279             {
2280                 OC_LOG(INFO, TAG, PCF("Cancelling observation as CONFIRMABLE"));
2281             }
2282
2283             requestData.type = qualityOfServiceToMessageType(qos);
2284             requestData.token = clientCB->token;
2285             requestData.tokenLength = clientCB->tokenLength;
2286             if (CreateObserveHeaderOption (&(requestData.options),
2287                     options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2288             {
2289                 return OC_STACK_ERROR;
2290             }
2291             requestData.numOptions = numOptions + 1;
2292             requestData.resourceUri = OICStrdup (clientCB->requestUri);
2293
2294             requestInfo.method = CA_GET;
2295             requestInfo.info = requestData;
2296
2297             ret = OCCreateEndpoint(clientCB->devAddr, &endpoint);
2298             if (ret != OC_STACK_OK)
2299             {
2300                 OC_LOG(ERROR, TAG, PCF("CACreateEndpoint error"));
2301                 goto Error;
2302             }
2303
2304             // send request
2305             caResult = CASendRequest(endpoint, &requestInfo);
2306             if (caResult != CA_STATUS_OK)
2307             {
2308                 OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
2309                 ret = OC_STACK_ERROR;
2310             }
2311             ret = CAResultToOCResult (caResult);
2312             break;
2313
2314         #ifdef WITH_PRESENCE
2315         case OC_REST_PRESENCE:
2316             FindAndDeleteClientCB(clientCB);
2317             break;
2318         #endif
2319
2320         default:
2321             ret = OC_STACK_INVALID_METHOD;
2322             break;
2323     }
2324
2325 Error:
2326     OCDestroyEndpoint(endpoint);
2327     if (requestData.numOptions > 0)
2328     {
2329         OICFree(requestData.options);
2330     }
2331     if (requestData.resourceUri)
2332     {
2333         OICFree (requestData.resourceUri);
2334     }
2335
2336     return ret;
2337 }
2338
2339 /**
2340  * @brief   Register Persistent storage callback.
2341  * @param   persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2342  * @return
2343  *     OC_STACK_OK    - No errors; Success
2344  *     OC_STACK_INVALID_PARAM - Invalid parameter
2345  */
2346 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2347 {
2348     OC_LOG(INFO, TAG, PCF("RegisterPersistentStorageHandler !!"));
2349     if(!persistentStorageHandler)
2350     {
2351         OC_LOG(ERROR, TAG, PCF("The persistent storage handler is invalid"));
2352         return OC_STACK_INVALID_PARAM;
2353     }
2354     else
2355     {
2356         if( !persistentStorageHandler->open ||
2357                 !persistentStorageHandler->close ||
2358                 !persistentStorageHandler->read ||
2359                 !persistentStorageHandler->unlink ||
2360                 !persistentStorageHandler->write)
2361         {
2362             OC_LOG(ERROR, TAG, PCF("The persistent storage handler is invalid"));
2363             return OC_STACK_INVALID_PARAM;
2364         }
2365     }
2366     return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2367 }
2368
2369 #ifdef WITH_PRESENCE
2370
2371 OCStackResult OCProcessPresence()
2372 {
2373     OCStackResult result = OC_STACK_OK;
2374
2375     // the following line floods the log with messages that are irrelevant
2376     // to most purposes.  Uncomment as needed.
2377     //OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
2378     ClientCB* cbNode = NULL;
2379     OCClientResponse clientResponse;
2380     OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2381
2382     LL_FOREACH(cbList, cbNode)
2383     {
2384         if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2385         {
2386             continue;
2387         }
2388
2389         uint32_t now = GetTicks(0);
2390         OC_LOG_V(DEBUG, TAG, "this TTL level %d",
2391                                                 cbNode->presence->TTLlevel);
2392         OC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2393
2394         if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
2395         {
2396             goto exit;
2397         }
2398
2399         if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2400         {
2401             OC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2402                     cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2403         }
2404
2405         if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2406         {
2407             OC_LOG(DEBUG, TAG, PCF("No more timeout ticks"));
2408
2409             clientResponse.sequenceNumber = 0;
2410             clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2411             clientResponse.devAddr = *cbNode->devAddr;
2412             FixUpClientResponse(&clientResponse);
2413             clientResponse.payload = NULL;
2414
2415             // Increment the TTLLevel (going to a next state), so we don't keep
2416             // sending presence notification to client.
2417             cbNode->presence->TTLlevel++;
2418             OC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2419                                         cbNode->presence->TTLlevel);
2420
2421             cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2422             if (cbResult == OC_STACK_DELETE_TRANSACTION)
2423             {
2424                 FindAndDeleteClientCB(cbNode);
2425             }
2426         }
2427
2428         if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2429         {
2430             continue;
2431         }
2432
2433         CAResult_t caResult = CA_STATUS_OK;
2434         CAEndpoint_t* endpoint = NULL;
2435         CAInfo_t requestData ={};
2436         CARequestInfo_t requestInfo = {};
2437
2438         OC_LOG(DEBUG, TAG, PCF("time to test server presence"));
2439
2440         result = OCCreateEndpoint(cbNode->devAddr, &endpoint);
2441         if (result != OC_STACK_OK)
2442         {
2443             OC_LOG(ERROR, TAG, PCF("CACreateEndpoint error"));
2444             goto exit;
2445         }
2446
2447         requestData.type = CA_MSG_NONCONFIRM;
2448         requestData.token = cbNode->token;
2449         requestData.tokenLength = cbNode->tokenLength;
2450         requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
2451         requestInfo.method = CA_GET;
2452         requestInfo.info = requestData;
2453
2454         caResult = CASendRequest(endpoint, &requestInfo);
2455         OCDestroyEndpoint(endpoint);
2456
2457         if (caResult != CA_STATUS_OK)
2458         {
2459             OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
2460             goto exit;
2461         }
2462
2463         cbNode->presence->TTLlevel++;
2464         OC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
2465     }
2466 exit:
2467     if (result != OC_STACK_OK)
2468     {
2469         OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
2470     }
2471     return result;
2472 }
2473 #endif // WITH_PRESENCE
2474
2475 OCStackResult OCProcess()
2476 {
2477     #ifdef WITH_PRESENCE
2478     OCProcessPresence();
2479     #endif
2480     CAHandleRequestResponse();
2481
2482     return OC_STACK_OK;
2483 }
2484
2485 #ifdef WITH_PRESENCE
2486 OCStackResult OCStartPresence(const uint32_t ttl)
2487 {
2488     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2489     OCChangeResourceProperty(
2490             &(((OCResource *)presenceResource.handle)->resourceProperties),
2491             OC_ACTIVE, 1);
2492
2493     if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
2494     {
2495         presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
2496         OC_LOG(INFO, TAG, PCF("Setting Presence TTL to max value"));
2497     }
2498     else if (0 == ttl)
2499     {
2500         presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
2501         OC_LOG(INFO, TAG, PCF("Setting Presence TTL to default value"));
2502     }
2503     else
2504     {
2505         presenceResource.presenceTTL = ttl;
2506     }
2507     OC_LOG_V(DEBUG, TAG, "Presence TTL is %lu seconds", presenceResource.presenceTTL);
2508
2509     if (OC_PRESENCE_UNINITIALIZED == presenceState)
2510     {
2511         presenceState = OC_PRESENCE_INITIALIZED;
2512
2513         OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
2514         OICStrcpy(devAddr.addr, sizeof(devAddr.addr), OC_MULTICAST_IP);
2515         devAddr.port = OC_MULTICAST_PORT;
2516
2517         CAToken_t caToken = NULL;
2518         CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
2519         if (caResult != CA_STATUS_OK)
2520         {
2521             OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
2522             CADestroyToken(caToken);
2523             return OC_STACK_ERROR;
2524         }
2525
2526         AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
2527                 (OCResource *)presenceResource.handle, OC_LOW_QOS, &devAddr);
2528         CADestroyToken(caToken);
2529     }
2530
2531     // Each time OCStartPresence is called
2532     // a different random 32-bit integer number is used
2533     ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2534
2535     return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
2536             OC_PRESENCE_TRIGGER_CREATE);
2537 }
2538
2539 OCStackResult OCStopPresence()
2540 {
2541     OCStackResult result = OC_STACK_ERROR;
2542
2543     if(presenceResource.handle)
2544     {
2545         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2546
2547     // make resource inactive
2548     result = OCChangeResourceProperty(
2549             &(((OCResource *) presenceResource.handle)->resourceProperties),
2550             OC_ACTIVE, 0);
2551     }
2552
2553     if(result != OC_STACK_OK)
2554     {
2555         OC_LOG(ERROR, TAG,
2556                       PCF("Changing the presence resource properties to ACTIVE not successful"));
2557         return result;
2558     }
2559
2560     return SendStopNotification();
2561 }
2562 #endif
2563
2564 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
2565                                             void* callbackParameter)
2566 {
2567     defaultDeviceHandler = entityHandler;
2568     defaultDeviceHandlerCallbackParameter = callbackParameter;
2569
2570     return OC_STACK_OK;
2571 }
2572
2573 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
2574 {
2575     OC_LOG(INFO, TAG, PCF("Entering OCSetPlatformInfo"));
2576
2577     if(myStackMode ==  OC_SERVER || myStackMode == OC_CLIENT_SERVER)
2578     {
2579         if (validatePlatformInfo(platformInfo))
2580         {
2581             return SavePlatformInfo(platformInfo);
2582         }
2583         else
2584         {
2585             return OC_STACK_INVALID_PARAM;
2586         }
2587     }
2588     else
2589     {
2590         return OC_STACK_ERROR;
2591     }
2592 }
2593
2594 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
2595 {
2596     OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
2597
2598     if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
2599     {
2600         OC_LOG(ERROR, TAG, PCF("Null or empty device name."));
2601         return OC_STACK_INVALID_PARAM;
2602     }
2603
2604     return SaveDeviceInfo(deviceInfo);
2605 }
2606
2607 OCStackResult OCCreateResource(OCResourceHandle *handle,
2608         const char *resourceTypeName,
2609         const char *resourceInterfaceName,
2610         const char *uri, OCEntityHandler entityHandler,
2611         void* callbackParam,
2612         uint8_t resourceProperties)
2613 {
2614
2615     OCResource *pointer = NULL;
2616     char *str = NULL;
2617     OCStackResult result = OC_STACK_ERROR;
2618
2619     OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
2620
2621     if(myStackMode == OC_CLIENT)
2622     {
2623         return OC_STACK_INVALID_PARAM;
2624     }
2625     // Validate parameters
2626     if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
2627     {
2628         OC_LOG(ERROR, TAG, PCF("URI is empty or too long"));
2629         return OC_STACK_INVALID_URI;
2630     }
2631     // Is it presented during resource discovery?
2632     if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
2633     {
2634         OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
2635         return OC_STACK_INVALID_PARAM;
2636     }
2637
2638     if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
2639     {
2640         resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
2641     }
2642
2643     // Make sure resourceProperties bitmask has allowed properties specified
2644     if (resourceProperties
2645             > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
2646                OC_EXPLICIT_DISCOVERABLE))
2647     {
2648         OC_LOG(ERROR, TAG, PCF("Invalid property"));
2649         return OC_STACK_INVALID_PARAM;
2650     }
2651
2652     // If the headResource is NULL, then no resources have been created...
2653     pointer = headResource;
2654     if (pointer)
2655     {
2656         // At least one resources is in the resource list, so we need to search for
2657         // repeated URLs, which are not allowed.  If a repeat is found, exit with an error
2658         while (pointer)
2659         {
2660             if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
2661             {
2662                 OC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
2663                 return OC_STACK_INVALID_PARAM;
2664             }
2665             pointer = pointer->next;
2666         }
2667     }
2668     // Create the pointer and insert it into the resource list
2669     pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
2670     if (!pointer)
2671     {
2672         result = OC_STACK_NO_MEMORY;
2673         goto exit;
2674     }
2675     pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
2676
2677     insertResource(pointer);
2678
2679     // Set the uri
2680     str = OICStrdup(uri);
2681     if (!str)
2682     {
2683         result = OC_STACK_NO_MEMORY;
2684         goto exit;
2685     }
2686     pointer->uri = str;
2687
2688     // Set properties.  Set OC_ACTIVE
2689     pointer->resourceProperties = (OCResourceProperty) (resourceProperties
2690             | OC_ACTIVE);
2691
2692     // Add the resourcetype to the resource
2693     result = BindResourceTypeToResource(pointer, resourceTypeName);
2694     if (result != OC_STACK_OK)
2695     {
2696         OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
2697         goto exit;
2698     }
2699
2700     // Add the resourceinterface to the resource
2701     result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
2702     if (result != OC_STACK_OK)
2703     {
2704         OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
2705         goto exit;
2706     }
2707
2708     // If an entity handler has been passed, attach it to the newly created
2709     // resource.  Otherwise, set the default entity handler.
2710     if (entityHandler)
2711     {
2712         pointer->entityHandler = entityHandler;
2713         pointer->entityHandlerCallbackParam = callbackParam;
2714     }
2715     else
2716     {
2717         pointer->entityHandler = defaultResourceEHandler;
2718         pointer->entityHandlerCallbackParam = NULL;
2719     }
2720
2721     *handle = pointer;
2722     result = OC_STACK_OK;
2723
2724     #ifdef WITH_PRESENCE
2725     if(presenceResource.handle)
2726     {
2727         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2728         SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
2729     }
2730     #endif
2731 exit:
2732     if (result != OC_STACK_OK)
2733     {
2734         // Deep delete of resource and other dynamic elements that it contains
2735         deleteResource(pointer);
2736         OICFree(str);
2737     }
2738     return result;
2739 }
2740
2741
2742 OCStackResult OCBindResource(
2743         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
2744 {
2745     OCResource *resource = NULL;
2746     uint8_t i = 0;
2747
2748     OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
2749
2750     // Validate parameters
2751     VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2752     VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2753     // Container cannot contain itself
2754     if (collectionHandle == resourceHandle)
2755     {
2756         OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle"));
2757         return OC_STACK_INVALID_PARAM;
2758     }
2759
2760     // Use the handle to find the resource in the resource linked list
2761     resource = findResource((OCResource *) collectionHandle);
2762     if (!resource)
2763     {
2764         OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2765         return OC_STACK_INVALID_PARAM;
2766     }
2767
2768     // Look for an open slot to add add the child resource.
2769     // If found, add it and return success
2770     for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
2771     {
2772         if (!resource->rsrcResources[i])
2773         {
2774             resource->rsrcResources[i] = (OCResource *) resourceHandle;
2775             OC_LOG(INFO, TAG, PCF("resource bound"));
2776
2777             #ifdef WITH_PRESENCE
2778             if(presenceResource.handle)
2779             {
2780                 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2781                 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
2782                         OC_PRESENCE_TRIGGER_CHANGE);
2783             }
2784             #endif
2785             return OC_STACK_OK;
2786
2787         }
2788     }
2789
2790     // Unable to add resourceHandle, so return error
2791     return OC_STACK_ERROR;
2792 }
2793
2794 OCStackResult OCUnBindResource(
2795         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
2796 {
2797     OCResource *resource = NULL;
2798     uint8_t i = 0;
2799
2800     OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
2801
2802     // Validate parameters
2803     VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
2804     VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
2805     // Container cannot contain itself
2806     if (collectionHandle == resourceHandle)
2807     {
2808         OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
2809         return OC_STACK_INVALID_PARAM;
2810     }
2811
2812     // Use the handle to find the resource in the resource linked list
2813     resource = findResource((OCResource *) collectionHandle);
2814     if (!resource)
2815     {
2816         OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
2817         return OC_STACK_INVALID_PARAM;
2818     }
2819
2820     // Look for an open slot to add add the child resource.
2821     // If found, add it and return success
2822     for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
2823     {
2824         if (resourceHandle == resource->rsrcResources[i])
2825         {
2826             resource->rsrcResources[i] = (OCResource *) NULL;
2827             OC_LOG(INFO, TAG, PCF("resource unbound"));
2828
2829             // Send notification when resource is unbounded successfully.
2830             #ifdef WITH_PRESENCE
2831             if(presenceResource.handle)
2832             {
2833                 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2834                 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
2835                         OC_PRESENCE_TRIGGER_CHANGE);
2836             }
2837             #endif
2838             return OC_STACK_OK;
2839         }
2840     }
2841
2842     OC_LOG(INFO, TAG, PCF("resource not found in collection"));
2843
2844     // Unable to add resourceHandle, so return error
2845     return OC_STACK_ERROR;
2846 }
2847
2848 OCStackResult BindResourceTypeToResource(OCResource* resource,
2849                                             const char *resourceTypeName)
2850 {
2851     OCResourceType *pointer = NULL;
2852     char *str = NULL;
2853     OCStackResult result = OC_STACK_ERROR;
2854
2855     VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
2856
2857     pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
2858     if (!pointer)
2859     {
2860         result = OC_STACK_NO_MEMORY;
2861         goto exit;
2862     }
2863
2864     str = OICStrdup(resourceTypeName);
2865     if (!str)
2866     {
2867         result = OC_STACK_NO_MEMORY;
2868         goto exit;
2869     }
2870     pointer->resourcetypename = str;
2871
2872     insertResourceType(resource, pointer);
2873     result = OC_STACK_OK;
2874
2875     exit:
2876     if (result != OC_STACK_OK)
2877     {
2878         OICFree(pointer);
2879         OICFree(str);
2880     }
2881
2882     return result;
2883 }
2884
2885 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
2886         const char *resourceInterfaceName)
2887 {
2888     OCResourceInterface *pointer = NULL;
2889     char *str = NULL;
2890     OCStackResult result = OC_STACK_ERROR;
2891
2892     VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
2893
2894     OC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
2895
2896     pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
2897     if (!pointer)
2898     {
2899         result = OC_STACK_NO_MEMORY;
2900         goto exit;
2901     }
2902
2903     str = OICStrdup(resourceInterfaceName);
2904     if (!str)
2905     {
2906         result = OC_STACK_NO_MEMORY;
2907         goto exit;
2908     }
2909     pointer->name = str;
2910
2911     // Bind the resourceinterface to the resource
2912     insertResourceInterface(resource, pointer);
2913
2914     result = OC_STACK_OK;
2915
2916     exit:
2917     if (result != OC_STACK_OK)
2918     {
2919         OICFree(pointer);
2920         OICFree(str);
2921     }
2922
2923     return result;
2924 }
2925
2926 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
2927         const char *resourceTypeName)
2928 {
2929
2930     OCStackResult result = OC_STACK_ERROR;
2931     OCResource *resource = NULL;
2932
2933     resource = findResource((OCResource *) handle);
2934     if (!resource)
2935     {
2936         OC_LOG(ERROR, TAG, PCF("Resource not found"));
2937         return OC_STACK_ERROR;
2938     }
2939
2940     result = BindResourceTypeToResource(resource, resourceTypeName);
2941
2942     #ifdef WITH_PRESENCE
2943     if(presenceResource.handle)
2944     {
2945         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2946         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
2947     }
2948     #endif
2949
2950     return result;
2951 }
2952
2953 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
2954         const char *resourceInterfaceName)
2955 {
2956
2957     OCStackResult result = OC_STACK_ERROR;
2958     OCResource *resource = NULL;
2959
2960     resource = findResource((OCResource *) handle);
2961     if (!resource)
2962     {
2963         OC_LOG(ERROR, TAG, PCF("Resource not found"));
2964         return OC_STACK_ERROR;
2965     }
2966
2967     result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
2968
2969     #ifdef WITH_PRESENCE
2970     if(presenceResource.handle)
2971     {
2972         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2973         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
2974     }
2975     #endif
2976
2977     return result;
2978 }
2979
2980 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
2981 {
2982     OCResource *pointer = headResource;
2983
2984     VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
2985     *numResources = 0;
2986     while (pointer)
2987     {
2988         *numResources = *numResources + 1;
2989         pointer = pointer->next;
2990     }
2991     return OC_STACK_OK;
2992 }
2993
2994 OCResourceHandle OCGetResourceHandle(uint8_t index)
2995 {
2996     OCResource *pointer = headResource;
2997
2998     for( uint8_t i = 0; i < index && pointer; ++i)
2999     {
3000         pointer = pointer->next;
3001     }
3002     return (OCResourceHandle) pointer;
3003 }
3004
3005 OCStackResult OCDeleteResource(OCResourceHandle handle)
3006 {
3007     if (!handle)
3008     {
3009         OC_LOG(ERROR, TAG, PCF("Invalid handle for deletion"));
3010         return OC_STACK_INVALID_PARAM;
3011     }
3012
3013     OCResource *resource = findResource((OCResource *) handle);
3014     if (resource == NULL)
3015     {
3016         OC_LOG(ERROR, TAG, PCF("Resource not found"));
3017         return OC_STACK_NO_RESOURCE;
3018     }
3019
3020     if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3021     {
3022         OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
3023         return OC_STACK_ERROR;
3024     }
3025
3026     return OC_STACK_OK;
3027 }
3028
3029 const char *OCGetResourceUri(OCResourceHandle handle)
3030 {
3031     OCResource *resource = NULL;
3032
3033     resource = findResource((OCResource *) handle);
3034     if (resource)
3035     {
3036         return resource->uri;
3037     }
3038     return (const char *) NULL;
3039 }
3040
3041 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3042 {
3043     OCResource *resource = NULL;
3044
3045     resource = findResource((OCResource *) handle);
3046     if (resource)
3047     {
3048         return resource->resourceProperties;
3049     }
3050     return (OCResourceProperty)-1;
3051 }
3052
3053 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3054         uint8_t *numResourceTypes)
3055 {
3056     OCResource *resource = NULL;
3057     OCResourceType *pointer = NULL;
3058
3059     VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3060     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3061
3062     *numResourceTypes = 0;
3063
3064     resource = findResource((OCResource *) handle);
3065     if (resource)
3066     {
3067         pointer = resource->rsrcType;
3068         while (pointer)
3069         {
3070             *numResourceTypes = *numResourceTypes + 1;
3071             pointer = pointer->next;
3072         }
3073     }
3074     return OC_STACK_OK;
3075 }
3076
3077 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3078 {
3079     OCResourceType *resourceType = NULL;
3080
3081     resourceType = findResourceTypeAtIndex(handle, index);
3082     if (resourceType)
3083     {
3084         return resourceType->resourcetypename;
3085     }
3086     return (const char *) NULL;
3087 }
3088
3089 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3090         uint8_t *numResourceInterfaces)
3091 {
3092     OCResourceInterface *pointer = NULL;
3093     OCResource *resource = NULL;
3094
3095     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3096     VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3097
3098     *numResourceInterfaces = 0;
3099     resource = findResource((OCResource *) handle);
3100     if (resource)
3101     {
3102         pointer = resource->rsrcInterface;
3103         while (pointer)
3104         {
3105             *numResourceInterfaces = *numResourceInterfaces + 1;
3106             pointer = pointer->next;
3107         }
3108     }
3109     return OC_STACK_OK;
3110 }
3111
3112 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3113 {
3114     OCResourceInterface *resourceInterface = NULL;
3115
3116     resourceInterface = findResourceInterfaceAtIndex(handle, index);
3117     if (resourceInterface)
3118     {
3119         return resourceInterface->name;
3120     }
3121     return (const char *) NULL;
3122 }
3123
3124 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3125         uint8_t index)
3126 {
3127     OCResource *resource = NULL;
3128
3129     if (index >= MAX_CONTAINED_RESOURCES)
3130     {
3131         return NULL;
3132     }
3133
3134     resource = findResource((OCResource *) collectionHandle);
3135     if (!resource)
3136     {
3137         return NULL;
3138     }
3139
3140     return resource->rsrcResources[index];
3141 }
3142
3143 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3144         OCEntityHandler entityHandler,
3145         void* callbackParam)
3146 {
3147     OCResource *resource = NULL;
3148
3149     // Validate parameters
3150     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3151
3152     // Use the handle to find the resource in the resource linked list
3153     resource = findResource((OCResource *)handle);
3154     if (!resource)
3155     {
3156         OC_LOG(ERROR, TAG, PCF("Resource not found"));
3157         return OC_STACK_ERROR;
3158     }
3159
3160     // Bind the handler
3161     resource->entityHandler = entityHandler;
3162     resource->entityHandlerCallbackParam = callbackParam;
3163
3164     #ifdef WITH_PRESENCE
3165     if(presenceResource.handle)
3166     {
3167         ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3168         SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3169     }
3170     #endif
3171
3172     return OC_STACK_OK;
3173 }
3174
3175 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3176 {
3177     OCResource *resource = NULL;
3178
3179     resource = findResource((OCResource *)handle);
3180     if (!resource)
3181     {
3182         OC_LOG(ERROR, TAG, PCF("Resource not found"));
3183         return NULL;
3184     }
3185
3186     // Bind the handler
3187     return resource->entityHandler;
3188 }
3189
3190 void incrementSequenceNumber(OCResource * resPtr)
3191 {
3192     // Increment the sequence number
3193     resPtr->sequenceNum += 1;
3194     if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3195     {
3196         resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3197     }
3198     return;
3199 }
3200
3201 #ifdef WITH_PRESENCE
3202 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3203         OCPresenceTrigger trigger)
3204 {
3205     OCResource *resPtr = NULL;
3206     OCStackResult result = OC_STACK_ERROR;
3207     OCMethod method = OC_REST_PRESENCE;
3208     uint32_t maxAge = 0;
3209     resPtr = findResource((OCResource *) presenceResource.handle);
3210     if(NULL == resPtr)
3211     {
3212         return OC_STACK_NO_RESOURCE;
3213     }
3214
3215     if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3216     {
3217         maxAge = presenceResource.presenceTTL;
3218
3219         result = SendAllObserverNotification(method, resPtr, maxAge,
3220                 trigger, resourceType, OC_LOW_QOS);
3221     }
3222
3223     return result;
3224 }
3225
3226 OCStackResult SendStopNotification()
3227 {
3228     OCResource *resPtr = NULL;
3229     OCStackResult result = OC_STACK_ERROR;
3230     OCMethod method = OC_REST_PRESENCE;
3231     resPtr = findResource((OCResource *) presenceResource.handle);
3232     if(NULL == resPtr)
3233     {
3234         return OC_STACK_NO_RESOURCE;
3235     }
3236
3237     // maxAge is 0. ResourceType is NULL.
3238     result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3239             NULL, OC_LOW_QOS);
3240
3241     return result;
3242 }
3243
3244 #endif // WITH_PRESENCE
3245 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3246 {
3247     OCResource *resPtr = NULL;
3248     OCStackResult result = OC_STACK_ERROR;
3249     OCMethod method = OC_REST_NOMETHOD;
3250     uint32_t maxAge = 0;
3251
3252     OC_LOG(INFO, TAG, PCF("Notifying all observers"));
3253     #ifdef WITH_PRESENCE
3254     if(handle == presenceResource.handle)
3255     {
3256         return OC_STACK_OK;
3257     }
3258     #endif // WITH_PRESENCE
3259     VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3260
3261     // Verify that the resource exists
3262     resPtr = findResource ((OCResource *) handle);
3263     if (NULL == resPtr)
3264     {
3265         return OC_STACK_NO_RESOURCE;
3266     }
3267     else
3268     {
3269         //only increment in the case of regular observing (not presence)
3270         incrementSequenceNumber(resPtr);
3271         method = OC_REST_OBSERVE;
3272         maxAge = MAX_OBSERVE_AGE;
3273         #ifdef WITH_PRESENCE
3274         result = SendAllObserverNotification (method, resPtr, maxAge,
3275                 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3276         #else
3277         result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3278         #endif
3279         return result;
3280     }
3281 }
3282
3283 OCStackResult
3284 OCNotifyListOfObservers (OCResourceHandle handle,
3285                          OCObservationId  *obsIdList,
3286                          uint8_t          numberOfIds,
3287                          const OCRepPayload       *payload,
3288                          OCQualityOfService qos)
3289 {
3290     OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
3291
3292     OCResource *resPtr = NULL;
3293     //TODO: we should allow the server to define this
3294     uint32_t maxAge = MAX_OBSERVE_AGE;
3295
3296     VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3297     VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3298     VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
3299
3300     resPtr = findResource ((OCResource *) handle);
3301     if (NULL == resPtr || myStackMode == OC_CLIENT)
3302     {
3303         return OC_STACK_NO_RESOURCE;
3304     }
3305     else
3306     {
3307         incrementSequenceNumber(resPtr);
3308     }
3309     return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3310             payload, maxAge, qos));
3311 }
3312
3313 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3314 {
3315     OCStackResult result = OC_STACK_ERROR;
3316     OCServerRequest *serverRequest = NULL;
3317
3318     OC_LOG(INFO, TAG, PCF("Entering OCDoResponse"));
3319
3320     // Validate input parameters
3321     VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3322     VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3323
3324     // Normal response
3325     // Get pointer to request info
3326     serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3327     if(serverRequest)
3328     {
3329         // response handler in ocserverrequest.c. Usually HandleSingleResponse.
3330         result = serverRequest->ehResponseHandler(ehResponse);
3331     }
3332
3333     return result;
3334 }
3335
3336 //-----------------------------------------------------------------------------
3337 // Private internal function definitions
3338 //-----------------------------------------------------------------------------
3339 static OCDoHandle GenerateInvocationHandle()
3340 {
3341     OCDoHandle handle = NULL;
3342     // Generate token here, it will be deleted when the transaction is deleted
3343     handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3344     if (handle)
3345     {
3346         OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3347     }
3348
3349     return handle;
3350 }
3351
3352 #ifdef WITH_PRESENCE
3353 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3354         OCResourceProperty resourceProperties, uint8_t enable)
3355 {
3356     if (!inputProperty)
3357     {
3358         return OC_STACK_INVALID_PARAM;
3359     }
3360     if (resourceProperties
3361             > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
3362     {
3363         OC_LOG(ERROR, TAG, PCF("Invalid property"));
3364         return OC_STACK_INVALID_PARAM;
3365     }
3366     if(!enable)
3367     {
3368         *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3369     }
3370     else
3371     {
3372         *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3373     }
3374     return OC_STACK_OK;
3375 }
3376 #endif
3377
3378 OCStackResult initResources()
3379 {
3380     OCStackResult result = OC_STACK_OK;
3381
3382     headResource = NULL;
3383     tailResource = NULL;
3384     // Init Virtual Resources
3385     #ifdef WITH_PRESENCE
3386     presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3387
3388     result = OCCreateResource(&presenceResource.handle,
3389             OC_RSRVD_RESOURCE_TYPE_PRESENCE,
3390             "core.r",
3391             OC_RSRVD_PRESENCE_URI,
3392             NULL,
3393             NULL,
3394             OC_OBSERVABLE);
3395     //make resource inactive
3396     result = OCChangeResourceProperty(
3397             &(((OCResource *) presenceResource.handle)->resourceProperties),
3398             OC_ACTIVE, 0);
3399     #endif
3400
3401     if (result == OC_STACK_OK)
3402     {
3403         result = SRMInitSecureResources();
3404     }
3405
3406     return result;
3407 }
3408
3409 void insertResource(OCResource *resource)
3410 {
3411     if (!headResource)
3412     {
3413         headResource = resource;
3414         tailResource = resource;
3415     }
3416     else
3417     {
3418         tailResource->next = resource;
3419         tailResource = resource;
3420     }
3421     resource->next = NULL;
3422 }
3423
3424 OCResource *findResource(OCResource *resource)
3425 {
3426     OCResource *pointer = headResource;
3427
3428     while (pointer)
3429     {
3430         if (pointer == resource)
3431         {
3432             return resource;
3433         }
3434         pointer = pointer->next;
3435     }
3436     return NULL;
3437 }
3438
3439 void deleteAllResources()
3440 {
3441     OCResource *pointer = headResource;
3442     OCResource *temp = NULL;
3443
3444     while (pointer)
3445     {
3446         temp = pointer->next;
3447         #ifdef WITH_PRESENCE
3448         if(pointer != (OCResource *) presenceResource.handle)
3449         {
3450         #endif // WITH_PRESENCE
3451             deleteResource(pointer);
3452         #ifdef WITH_PRESENCE
3453         }
3454         #endif // WITH_PRESENCE
3455         pointer = temp;
3456     }
3457
3458     SRMDeInitSecureResources();
3459
3460     #ifdef WITH_PRESENCE
3461     // Ensure that the last resource to be deleted is the presence resource. This allows for all
3462     // presence notification attributed to their deletion to be processed.
3463     deleteResource((OCResource *) presenceResource.handle);
3464     #endif // WITH_PRESENCE
3465 }
3466
3467 OCStackResult deleteResource(OCResource *resource)
3468 {
3469     OCResource *prev = NULL;
3470     OCResource *temp = NULL;
3471     if(!resource)
3472     {
3473         OC_LOG_V(DEBUG,TAG,"resource is NULL");
3474         return OC_STACK_INVALID_PARAM;
3475     }
3476
3477     OC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
3478
3479     temp = headResource;
3480     while (temp)
3481     {
3482         if (temp == resource)
3483         {
3484             // Invalidate all Resource Properties.
3485             resource->resourceProperties = (OCResourceProperty) 0;
3486             #ifdef WITH_PRESENCE
3487             if(resource != (OCResource *) presenceResource.handle)
3488             {
3489             #endif // WITH_PRESENCE
3490                 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
3491             #ifdef WITH_PRESENCE
3492             }
3493
3494             if(presenceResource.handle)
3495             {
3496                 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3497                 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
3498             }
3499             #endif
3500             // Only resource in list.
3501             if (temp == headResource && temp == tailResource)
3502             {
3503                 headResource = NULL;
3504                 tailResource = NULL;
3505             }
3506             // Deleting head.
3507             else if (temp == headResource)
3508             {
3509                 headResource = temp->next;
3510             }
3511             // Deleting tail.
3512             else if (temp == tailResource)
3513             {
3514                 tailResource = prev;
3515                 tailResource->next = NULL;
3516             }
3517             else
3518             {
3519                 prev->next = temp->next;
3520             }
3521
3522             deleteResourceElements(temp);
3523             OICFree(temp);
3524             return OC_STACK_OK;
3525         }
3526         else
3527         {
3528             prev = temp;
3529             temp = temp->next;
3530         }
3531     }
3532
3533     return OC_STACK_ERROR;
3534 }
3535
3536 void deleteResourceElements(OCResource *resource)
3537 {
3538     if (!resource)
3539     {
3540         return;
3541     }
3542
3543     OICFree(resource->uri);
3544     deleteResourceType(resource->rsrcType);
3545     deleteResourceInterface(resource->rsrcInterface);
3546 }
3547
3548 void deleteResourceType(OCResourceType *resourceType)
3549 {
3550     OCResourceType *pointer = resourceType;
3551     OCResourceType *next = NULL;
3552
3553     while (pointer)
3554     {
3555         next = pointer->next;
3556         OICFree(pointer->resourcetypename);
3557         OICFree(pointer);
3558         pointer = next;
3559     }
3560 }
3561
3562 void deleteResourceInterface(OCResourceInterface *resourceInterface)
3563 {
3564     OCResourceInterface *pointer = resourceInterface;
3565     OCResourceInterface *next = NULL;
3566
3567     while (pointer)
3568     {
3569         next = pointer->next;
3570         OICFree(pointer->name);
3571         OICFree(pointer);
3572         pointer = next;
3573     }
3574 }
3575
3576 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
3577 {
3578     OCResourceType *pointer = NULL;
3579     OCResourceType *previous = NULL;
3580     if (!resource || !resourceType)
3581     {
3582         return;
3583     }
3584     // resource type list is empty.
3585     else if (!resource->rsrcType)
3586     {
3587         resource->rsrcType = resourceType;
3588     }
3589     else
3590     {
3591         pointer = resource->rsrcType;
3592
3593         while (pointer)
3594         {
3595             if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
3596             {
3597                 OC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
3598                 OICFree(resourceType->resourcetypename);
3599                 OICFree(resourceType);
3600                 return;
3601             }
3602             previous = pointer;
3603             pointer = pointer->next;
3604         }
3605         previous->next = resourceType;
3606     }
3607     resourceType->next = NULL;
3608
3609     OC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
3610 }
3611
3612 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
3613 {
3614     OCResource *resource = NULL;
3615     OCResourceType *pointer = NULL;
3616
3617     // Find the specified resource
3618     resource = findResource((OCResource *) handle);
3619     if (!resource)
3620     {
3621         return NULL;
3622     }
3623
3624     // Make sure a resource has a resourcetype
3625     if (!resource->rsrcType)
3626     {
3627         return NULL;
3628     }
3629
3630     // Iterate through the list
3631     pointer = resource->rsrcType;
3632     for(uint8_t i = 0; i< index && pointer; ++i)
3633     {
3634         pointer = pointer->next;
3635     }
3636     return pointer;
3637 }
3638
3639 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
3640 {
3641     if(resourceTypeList && resourceTypeName)
3642     {
3643         OCResourceType * rtPointer = resourceTypeList;
3644         while(resourceTypeName && rtPointer)
3645         {
3646             if(rtPointer->resourcetypename &&
3647                     strcmp(resourceTypeName, (const char *)
3648                     (rtPointer->resourcetypename)) == 0)
3649             {
3650                 break;
3651             }
3652             rtPointer = rtPointer->next;
3653         }
3654         return rtPointer;
3655     }
3656     return NULL;
3657 }
3658
3659 /*
3660  * Insert a new interface into interface linked list only if not already present.
3661  * If alredy present, 2nd arg is free'd.
3662  * Default interface will always be first if present.
3663  */
3664 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
3665 {
3666     OCResourceInterface *pointer = NULL;
3667     OCResourceInterface *previous = NULL;
3668
3669     newInterface->next = NULL;
3670
3671     OCResourceInterface **firstInterface = &(resource->rsrcInterface);
3672
3673     if (!*firstInterface)
3674     {
3675         *firstInterface = newInterface;
3676     }
3677     else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
3678     {
3679         if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
3680         {
3681             OICFree(newInterface->name);
3682             OICFree(newInterface);
3683             return;
3684         }
3685         else
3686         {
3687             newInterface->next = *firstInterface;
3688             *firstInterface = newInterface;
3689         }
3690     }
3691     else
3692     {
3693         pointer = *firstInterface;
3694         while (pointer)
3695         {
3696             if (strcmp(newInterface->name, pointer->name) == 0)
3697             {
3698                 OICFree(newInterface->name);
3699                 OICFree(newInterface);
3700                 return;
3701             }
3702             previous = pointer;
3703             pointer = pointer->next;
3704         }
3705         previous->next = newInterface;
3706     }
3707 }
3708
3709 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
3710         uint8_t index)
3711 {
3712     OCResource *resource = NULL;
3713     OCResourceInterface *pointer = NULL;
3714
3715     // Find the specified resource
3716     resource = findResource((OCResource *) handle);
3717     if (!resource)
3718     {
3719         return NULL;
3720     }
3721
3722     // Make sure a resource has a resourceinterface
3723     if (!resource->rsrcInterface)
3724     {
3725         return NULL;
3726     }
3727
3728     // Iterate through the list
3729     pointer = resource->rsrcInterface;
3730
3731     for (uint8_t i = 0; i < index && pointer; ++i)
3732     {
3733         pointer = pointer->next;
3734     }
3735     return pointer;
3736 }
3737
3738 /*
3739  * This function splits the uri using the '?' delimiter.
3740  * "uriWithoutQuery" is the block of characters between the beginning
3741  * till the delimiter or '\0' which ever comes first.
3742  * "query" is whatever is to the right of the delimiter if present.
3743  * No delimiter sets the query to NULL.
3744  * If either are present, they will be malloc'ed into the params 2, 3.
3745  * The first param, *uri is left untouched.
3746
3747  * NOTE: This function does not account for whitespace at the end of the uri NOR
3748  *       malformed uri's with '??'. Whitespace at the end will be assumed to be
3749  *       part of the query.
3750  */
3751 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
3752 {
3753     if(!uri)
3754     {
3755         return OC_STACK_INVALID_URI;
3756     }
3757     if(!query || !uriWithoutQuery)
3758     {
3759         return OC_STACK_INVALID_PARAM;
3760     }
3761
3762     *query           = NULL;
3763     *uriWithoutQuery = NULL;
3764
3765     size_t uriWithoutQueryLen = 0;
3766     size_t queryLen = 0;
3767     size_t uriLen = strlen(uri);
3768
3769     char *pointerToDelimiter = strstr(uri, "?");
3770
3771     uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : pointerToDelimiter - uri;
3772     queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
3773
3774     if (uriWithoutQueryLen)
3775     {
3776         *uriWithoutQuery =  (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
3777         if (!*uriWithoutQuery)
3778         {
3779             goto exit;
3780         }
3781         OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
3782     }
3783     if (queryLen)
3784     {
3785         *query = (char *) OICCalloc(queryLen + 1, 1);
3786         if (!*query)
3787         {
3788             OICFree(*uriWithoutQuery);
3789             *uriWithoutQuery = NULL;
3790             goto exit;
3791         }
3792         OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
3793     }
3794
3795     return OC_STACK_OK;
3796
3797     exit:
3798         return OC_STACK_NO_MEMORY;
3799 }
3800
3801 const uint8_t* OCGetServerInstanceID(void)
3802 {
3803     static bool generated = false;
3804     static ServerID sid;
3805     if(generated)
3806     {
3807         return sid;
3808     }
3809
3810     if (OCGenerateUuid(sid) != RAND_UUID_OK)
3811     {
3812         OC_LOG(FATAL, TAG, PCF("Generate UUID for Server Instance failed!"));
3813         return NULL;
3814     }
3815     generated = true;
3816     return sid;
3817 }
3818
3819 const char* OCGetServerInstanceIDString(void)
3820 {
3821     static bool generated = false;
3822     static char sidStr[UUID_STRING_SIZE];
3823
3824     if(generated)
3825     {
3826         return sidStr;
3827     }
3828
3829     const uint8_t* sid = OCGetServerInstanceID();
3830
3831     if(OCConvertUuidToString(sid, sidStr) != RAND_UUID_OK)
3832     {
3833         OC_LOG(FATAL, TAG, PCF("Generate UUID String for Server Instance failed!"));
3834         return NULL;
3835     }
3836
3837     generated = true;
3838     return sidStr;
3839 }
3840
3841 CAResult_t OCSelectNetwork()
3842 {
3843     CAResult_t retResult = CA_STATUS_FAILED;
3844     CAResult_t caResult = CA_STATUS_OK;
3845
3846     CATransportAdapter_t connTypes[] = {
3847             CA_ADAPTER_IP,
3848             CA_ADAPTER_RFCOMM_BTEDR,
3849             CA_ADAPTER_GATT_BTLE
3850
3851             #ifdef RA_ADAPTER
3852             ,CA_ADAPTER_REMOTE_ACCESS
3853             #endif
3854         };
3855     int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
3856
3857     for(int i = 0; i<numConnTypes; i++)
3858     {
3859         // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
3860         if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
3861         {
3862            caResult = CASelectNetwork(connTypes[i]);
3863            if(caResult == CA_STATUS_OK)
3864            {
3865                retResult = CA_STATUS_OK;
3866            }
3867         }
3868     }
3869
3870     if(retResult != CA_STATUS_OK)
3871     {
3872         return caResult; // Returns error of appropriate transport that failed fatally.
3873     }
3874
3875     return retResult;
3876 }
3877
3878 OCStackResult CAResultToOCResult(CAResult_t caResult)
3879 {
3880     switch (caResult)
3881     {
3882         case CA_STATUS_OK:
3883             return OC_STACK_OK;
3884         case CA_STATUS_INVALID_PARAM:
3885             return OC_STACK_INVALID_PARAM;
3886         case CA_ADAPTER_NOT_ENABLED:
3887             return OC_STACK_ADAPTER_NOT_ENABLED;
3888         case CA_SERVER_STARTED_ALREADY:
3889             return OC_STACK_OK;
3890         case CA_SERVER_NOT_STARTED:
3891             return OC_STACK_ERROR;
3892         case CA_DESTINATION_NOT_REACHABLE:
3893             return OC_STACK_COMM_ERROR;
3894         case CA_SOCKET_OPERATION_FAILED:
3895             return OC_STACK_COMM_ERROR;
3896         case CA_SEND_FAILED:
3897             return OC_STACK_COMM_ERROR;
3898         case CA_RECEIVE_FAILED:
3899             return OC_STACK_COMM_ERROR;
3900         case CA_MEMORY_ALLOC_FAILED:
3901             return OC_STACK_NO_MEMORY;
3902         case CA_REQUEST_TIMEOUT:
3903             return OC_STACK_TIMEOUT;
3904         case CA_DESTINATION_DISCONNECTED:
3905             return OC_STACK_COMM_ERROR;
3906         case CA_STATUS_FAILED:
3907             return OC_STACK_ERROR;
3908         case CA_NOT_SUPPORTED:
3909             return OC_STACK_NOTIMPL;
3910         default:
3911             return OC_STACK_ERROR;
3912     }
3913 }