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