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