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