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