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