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