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