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