Including observer endpoint information in ObservationInfo structure.
[platform/upstream/iotivity.git] / resource / src / InProcServerWrapper.cpp
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 #include <random>
22 #include <cstring>
23 #include <cstdlib>
24 #include <iostream>
25 #include <algorithm>
26 #include <map>
27 #include <sstream>
28 #include <string>
29
30 #include <InProcServerWrapper.h>
31 #include <InitializeException.h>
32 #include <OCResourceRequest.h>
33 #include <OCResourceResponse.h>
34 #include <ocstack.h>
35 #include <OCApi.h>
36 #include <oic_malloc.h>
37 #include <OCPlatform.h>
38 #include <OCUtilities.h>
39
40 using namespace std;
41 using namespace OC;
42
43 namespace OC
44 {
45     namespace details
46     {
47         std::mutex serverWrapperLock;
48         std::map <OCResourceHandle, OC::EntityHandler>  entityHandlerMap;
49         std::map <OCResourceHandle, std::string> resourceUriMap;
50         EntityHandler defaultDeviceEntityHandler = 0;
51     }
52 }
53
54 void formResourceRequest(OCEntityHandlerFlag flag,
55                          OCEntityHandlerRequest * entityHandlerRequest,
56                          std::shared_ptr<OCResourceRequest> pRequest)
57 {
58     if(pRequest && entityHandlerRequest)
59     {
60         pRequest->setRequestHandle(entityHandlerRequest->requestHandle);
61         pRequest->setResourceHandle(entityHandlerRequest->resource);
62     }
63
64     if(flag & OC_REQUEST_FLAG)
65     {
66         pRequest->setRequestHandlerFlag(OC::RequestHandlerFlag::RequestFlag);
67
68         if(entityHandlerRequest)
69         {
70             if(entityHandlerRequest->query)
71             {
72                 OC::Utilities::QueryParamsKeyVal qp = OC::Utilities::getQueryParams(
73                         entityHandlerRequest->query);
74
75                 if(qp.size() > 0)
76                 {
77                     pRequest->setQueryParams(qp);
78                 }
79             }
80             if(entityHandlerRequest->numRcvdVendorSpecificHeaderOptions != 0)
81             {
82                 //Set the header options here.
83                 uint16_t optionID;
84                 std::string optionData;
85                 HeaderOptions headerOptions;
86
87                 for(int i = 0;
88                     i < entityHandlerRequest->numRcvdVendorSpecificHeaderOptions;
89                     i++)
90                 {
91                     optionID = entityHandlerRequest->rcvdVendorSpecificHeaderOptions[i].optionID;
92                     optionData = reinterpret_cast<const char*>
93                              (entityHandlerRequest->rcvdVendorSpecificHeaderOptions[i].optionData);
94                     HeaderOption::OCHeaderOption headerOption(optionID, optionData);
95                     headerOptions.push_back(headerOption);
96                 }
97                 pRequest->setHeaderOptions(headerOptions);
98             }
99
100             if(OC_REST_GET == entityHandlerRequest->method)
101             {
102                 pRequest->setRequestType(OC::PlatformCommands::GET);
103             }
104             else if(OC_REST_PUT == entityHandlerRequest->method)
105             {
106                 pRequest->setRequestType(OC::PlatformCommands::PUT);
107                 pRequest->setPayload(entityHandlerRequest->payload);
108             }
109             else if(OC_REST_POST == entityHandlerRequest->method)
110             {
111                 pRequest->setRequestType(OC::PlatformCommands::POST);
112                 pRequest->setPayload(entityHandlerRequest->payload);
113             }
114             else if(OC_REST_DELETE == entityHandlerRequest->method)
115             {
116                 pRequest->setRequestType(OC::PlatformCommands::DELETE);
117             }
118         }
119     }
120
121     if(flag & OC_OBSERVE_FLAG)
122     {
123         pRequest->setRequestHandlerFlag(
124                    OC::RequestHandlerFlag::RequestFlag | OC::RequestHandlerFlag::ObserverFlag);
125
126         if(entityHandlerRequest)
127         {
128             OC::ObservationInfo observationInfo;
129             observationInfo.action = (OC::ObserveAction) entityHandlerRequest->obsInfo.action;
130             observationInfo.obsId = entityHandlerRequest->obsInfo.obsId;
131
132             observationInfo.connectivityType = static_cast<OCConnectivityType>(
133                     (entityHandlerRequest->devAddr.adapter << CT_ADAPTER_SHIFT) |
134                     (entityHandlerRequest->devAddr.flags & CT_MASK_FLAGS));
135             observationInfo.address = entityHandlerRequest->devAddr.addr;
136             observationInfo.port = entityHandlerRequest->devAddr.port;
137             pRequest->setObservationInfo(observationInfo);
138         }
139     }
140 }
141
142 OCEntityHandlerResult DefaultEntityHandlerWrapper(OCEntityHandlerFlag flag,
143                                                   OCEntityHandlerRequest * entityHandlerRequest,
144                                                   char* uri,
145                                                   void * /*callbackParam*/)
146 {
147     OCEntityHandlerResult result = OC_EH_ERROR;
148
149     OC::oclog() << "In Default device entity handler wrapper";
150
151     if(NULL == entityHandlerRequest)
152     {
153         oclog() << "Entity handler request is NULL.";
154         return OC_EH_ERROR;
155     }
156
157     auto pRequest = std::make_shared<OC::OCResourceRequest>();
158
159     formResourceRequest(flag, entityHandlerRequest, pRequest);
160
161     pRequest->setResourceUri(std::string(uri));
162
163     EntityHandler defHandler;
164     {
165         std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
166         defHandler = OC::details::defaultDeviceEntityHandler;
167     }
168
169     if(defHandler)
170     {
171         result = defHandler(pRequest);
172     }
173     else
174     {
175         oclog() << "Default device entity handler was not set.";
176         return OC_EH_ERROR;
177     }
178
179     return result;
180 }
181
182
183 OCEntityHandlerResult EntityHandlerWrapper(OCEntityHandlerFlag flag,
184                                            OCEntityHandlerRequest * entityHandlerRequest,
185                                            void* /*callbackParam*/)
186 {
187     OCEntityHandlerResult result = OC_EH_ERROR;
188
189     oclog() << "\nIn entity handler wrapper: " << endl;
190
191     if(NULL == entityHandlerRequest)
192     {
193         oclog() << "Entity handler request is NULL."  << endl;
194         return OC_EH_ERROR;
195     }
196
197     auto pRequest = std::make_shared<OC::OCResourceRequest>();
198
199     formResourceRequest(flag, entityHandlerRequest, pRequest);
200
201     std::map <OCResourceHandle, std::string>::iterator resourceUriEntry;
202     std::map <OCResourceHandle, std::string>::iterator resourceUriEnd;
203     {
204         std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
205         resourceUriEntry = OC::details::resourceUriMap.find(entityHandlerRequest->resource);
206         resourceUriEnd = OC::details::resourceUriMap.end();
207     }
208     // Finding the corresponding URI for a resource handle and set the URI in the request
209     if(resourceUriEntry != resourceUriEnd)
210     {
211         pRequest->setResourceUri(resourceUriEntry->second);
212     }
213     else
214     {
215         oclog() << "Resource handle not found; Resource URI not set in request";
216         return OC_EH_ERROR;
217     }
218
219     std::map <OCResourceHandle, OC::EntityHandler>::iterator entityHandlerEntry;
220     std::map <OCResourceHandle, OC::EntityHandler>::iterator entityHandlerEnd;
221     {
222         // Finding the corresponding CPP Application entityHandler for a given resource
223         std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
224         entityHandlerEntry = OC::details::entityHandlerMap.find(entityHandlerRequest->resource);
225         entityHandlerEnd = OC::details::entityHandlerMap.end();
226     }
227
228     if(entityHandlerEntry != entityHandlerEnd)
229     {
230         // Call CPP Application Entity Handler
231         if(entityHandlerEntry->second)
232         {
233             result = entityHandlerEntry->second(pRequest);
234         }
235         else
236         {
237             oclog() << "C stack should not call again for parent resource\n";
238             return OC_EH_ERROR;
239         }
240     }
241     else
242     {
243         oclog() << "No entity handler found."  << endl;
244         return OC_EH_ERROR;
245     }
246
247     return result;
248 }
249
250 namespace OC
251 {
252     InProcServerWrapper::InProcServerWrapper(
253         std::weak_ptr<std::recursive_mutex> csdkLock, PlatformConfig cfg)
254      : m_csdkLock(csdkLock)
255     {
256         OCMode initType;
257
258         if(cfg.mode == ModeType::Server)
259         {
260             initType = OC_SERVER;
261         }
262         else if (cfg.mode == ModeType::Both)
263         {
264             initType = OC_CLIENT_SERVER;
265         }
266         else
267         {
268             throw InitializeException(OC::InitException::NOT_CONFIGURED_AS_SERVER,
269                                          OC_STACK_INVALID_PARAM);
270         }
271
272         OCTransportFlags serverFlags =
273                             static_cast<OCTransportFlags>(cfg.serverConnectivity & CT_MASK_FLAGS);
274         OCTransportFlags clientFlags =
275                             static_cast<OCTransportFlags>(cfg.clientConnectivity & CT_MASK_FLAGS);
276         OCStackResult result = OCInit1(initType, serverFlags, clientFlags);
277
278         if(OC_STACK_OK != result)
279         {
280             throw InitializeException(OC::InitException::STACK_INIT_ERROR, result);
281         }
282
283         m_threadRun = true;
284         m_processThread = std::thread(&InProcServerWrapper::processFunc, this);
285     }
286
287     void InProcServerWrapper::processFunc()
288     {
289         auto cLock = m_csdkLock.lock();
290         while(cLock && m_threadRun)
291         {
292             OCStackResult result;
293
294             {
295                 std::lock_guard<std::recursive_mutex> lock(*cLock);
296                 result = OCProcess();
297             }
298
299             if(OC_STACK_ERROR == result)
300             {
301                 oclog() << "OCProcess failed with result " << result <<std::flush;
302                 // ...the value of variable result is simply ignored for now.
303             }
304
305             std::this_thread::sleep_for(std::chrono::milliseconds(10));
306         }
307     }
308
309     OCStackResult InProcServerWrapper::registerDeviceInfo(const OCDeviceInfo deviceInfo)
310     {
311         auto cLock = m_csdkLock.lock();
312         OCStackResult result = OC_STACK_ERROR;
313         if(cLock)
314         {
315             std::lock_guard<std::recursive_mutex> lock(*cLock);
316             result = OCSetDeviceInfo(deviceInfo);
317         }
318         return result;
319     }
320
321      OCStackResult InProcServerWrapper::registerPlatformInfo(const OCPlatformInfo platformInfo)
322     {
323         auto cLock = m_csdkLock.lock();
324         OCStackResult result = OC_STACK_ERROR;
325         if(cLock)
326         {
327             std::lock_guard<std::recursive_mutex> lock(*cLock);
328             result = OCSetPlatformInfo(platformInfo);
329         }
330         return result;
331     }
332
333     OCStackResult InProcServerWrapper::registerResource(
334                     OCResourceHandle& resourceHandle,
335                     std::string& resourceURI,
336                     const std::string& resourceTypeName,
337                     const std::string& resourceInterface,
338                     EntityHandler& eHandler,
339                     uint8_t resourceProperties)
340
341     {
342         OCStackResult result = OC_STACK_ERROR;
343
344         auto cLock = m_csdkLock.lock();
345
346         if(cLock)
347         {
348             std::lock_guard<std::recursive_mutex> lock(*cLock);
349
350             if(NULL != eHandler)
351             {
352                 result = OCCreateResource(&resourceHandle, // OCResourceHandle *handle
353                             resourceTypeName.c_str(), // const char * resourceTypeName
354                             resourceInterface.c_str(), //const char * resourceInterfaceName //TODO fix this
355                             resourceURI.c_str(), // const char * uri
356                             EntityHandlerWrapper, // OCEntityHandler entityHandler
357                             NULL,
358                             resourceProperties // uint8_t resourceProperties
359                             );
360             }
361             else
362             {
363                 result = OCCreateResource(&resourceHandle, // OCResourceHandle *handle
364                             resourceTypeName.c_str(), // const char * resourceTypeName
365                             resourceInterface.c_str(), //const char * resourceInterfaceName //TODO fix this
366                             resourceURI.c_str(), // const char * uri
367                             NULL, // OCEntityHandler entityHandler
368                             NULL,
369                             resourceProperties // uint8_t resourceProperties
370                             );
371             }
372
373             if(result != OC_STACK_OK)
374             {
375                 resourceHandle = (OCResourceHandle) 0;
376             }
377             else
378             {
379                 std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
380                 OC::details::entityHandlerMap[resourceHandle] = eHandler;
381                 OC::details::resourceUriMap[resourceHandle] = resourceURI;
382             }
383         }
384         else
385         {
386             result = OC_STACK_ERROR;
387         }
388
389         return result;
390     }
391
392
393
394     OCStackResult InProcServerWrapper::setDefaultDeviceEntityHandler
395                                         (EntityHandler entityHandler)
396     {
397         OCStackResult result = OC_STACK_ERROR;
398
399         {
400             std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
401             OC::details::defaultDeviceEntityHandler = entityHandler;
402         }
403
404         if(entityHandler)
405         {
406             result = OCSetDefaultDeviceEntityHandler(DefaultEntityHandlerWrapper, NULL);
407         }
408         else
409         {
410             // If Null passed we unset
411             result = OCSetDefaultDeviceEntityHandler(NULL, NULL);
412         }
413
414         return result;
415     }
416
417     OCStackResult InProcServerWrapper::unregisterResource(const OCResourceHandle& resourceHandle)
418     {
419         auto cLock = m_csdkLock.lock();
420         OCStackResult result = OC_STACK_ERROR;
421
422         if(cLock)
423         {
424             std::lock_guard<std::recursive_mutex> lock(*cLock);
425             result = OCDeleteResource(resourceHandle);
426
427             if(result == OC_STACK_OK)
428             {
429                 std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
430                 OC::details::resourceUriMap.erase(resourceHandle);
431             }
432             else
433             {
434                 throw OCException(OC::Exception::RESOURCE_UNREG_FAILED, result);
435             }
436         }
437         else
438         {
439             result = OC_STACK_ERROR;
440         }
441
442         return result;
443     }
444
445     OCStackResult InProcServerWrapper::bindTypeToResource(const OCResourceHandle& resourceHandle,
446                      const std::string& resourceTypeName)
447     {
448         auto cLock = m_csdkLock.lock();
449         OCStackResult result;
450         if(cLock)
451         {
452             std::lock_guard<std::recursive_mutex> lock(*cLock);
453             result = OCBindResourceTypeToResource(resourceHandle, resourceTypeName.c_str());
454         }
455         else
456         {
457             result = OC_STACK_ERROR;
458         }
459
460         if (result != OC_STACK_OK)
461         {
462             throw OCException(OC::Exception::BIND_TYPE_FAILED, result);
463         }
464         return result;
465     }
466
467     OCStackResult InProcServerWrapper::bindInterfaceToResource(
468                      const OCResourceHandle& resourceHandle,
469                      const std::string& resourceInterfaceName)
470     {
471         auto cLock = m_csdkLock.lock();
472         OCStackResult result;
473         if(cLock)
474         {
475             std::lock_guard<std::recursive_mutex> lock(*cLock);
476             result = OCBindResourceInterfaceToResource(resourceHandle,
477                         resourceInterfaceName.c_str());
478         }
479         else
480         {
481             result = OC_STACK_ERROR;
482         }
483
484         if (result != OC_STACK_OK)
485         {
486             throw OCException(OC::Exception::BIND_INTERFACE_FAILED, result);
487         }
488         return result;
489     }
490
491     OCStackResult InProcServerWrapper::startPresence(const unsigned int seconds)
492     {
493         auto cLock = m_csdkLock.lock();
494         OCStackResult result = OC_STACK_ERROR;
495         if(cLock)
496         {
497             std::lock_guard<std::recursive_mutex> lock(*cLock);
498             result = OCStartPresence(seconds);
499         }
500
501         if(result != OC_STACK_OK)
502         {
503             throw OCException(OC::Exception::START_PRESENCE_FAILED, result);
504         }
505         return result;
506     }
507
508     OCStackResult InProcServerWrapper::stopPresence()
509     {
510         auto cLock = m_csdkLock.lock();
511         OCStackResult result = OC_STACK_ERROR;
512         if(cLock)
513         {
514             std::lock_guard<std::recursive_mutex> lock(*cLock);
515             result = OCStopPresence();
516         }
517
518         if(result != OC_STACK_OK)
519         {
520             throw OCException(OC::Exception::END_PRESENCE_FAILED, result);
521         }
522         return result;
523     }
524
525     OCStackResult InProcServerWrapper::sendResponse(
526         const std::shared_ptr<OCResourceResponse> pResponse)
527     {
528         auto cLock = m_csdkLock.lock();
529         OCStackResult result = OC_STACK_ERROR;
530
531         if(!pResponse)
532         {
533             result = OC_STACK_MALFORMED_RESPONSE;
534             throw OCException(OC::Exception::STR_NULL_RESPONSE, OC_STACK_MALFORMED_RESPONSE);
535         }
536         else
537         {
538             OCEntityHandlerResponse response;
539 //            OCRepPayload* payLoad = pResponse->getPayload();
540             HeaderOptions serverHeaderOptions = pResponse->getHeaderOptions();
541
542             response.requestHandle = pResponse->getRequestHandle();
543             response.resourceHandle = pResponse->getResourceHandle();
544             response.ehResult = pResponse->getResponseResult();
545
546             response.payload = reinterpret_cast<OCPayload*>(pResponse->getPayload());
547
548             response.persistentBufferFlag = 0;
549
550             response.numSendVendorSpecificHeaderOptions = serverHeaderOptions.size();
551             int i = 0;
552             for (auto it=serverHeaderOptions.begin(); it != serverHeaderOptions.end(); ++it)
553             {
554                 response.sendVendorSpecificHeaderOptions[i].protocolID = OC_COAP_ID;
555                 response.sendVendorSpecificHeaderOptions[i].optionID =
556                     static_cast<uint16_t>(it->getOptionID());
557                 response.sendVendorSpecificHeaderOptions[i].optionLength =
558                     (it->getOptionData()).length() + 1;
559                 std::string optionData = it->getOptionData();
560                 std::copy(optionData.begin(),
561                          optionData.end(),
562                          response.sendVendorSpecificHeaderOptions[i].optionData);
563                 response.sendVendorSpecificHeaderOptions[i].optionData[it->getOptionData().length()]
564                     = '\0';
565                 i++;
566             }
567
568             if(OC_EH_RESOURCE_CREATED == response.ehResult)
569             {
570                 pResponse->getNewResourceUri().copy(response.resourceUri,
571                         sizeof (response.resourceUri) - 1);
572                 response.resourceUri[pResponse->getNewResourceUri().length()] = '\0';
573             }
574
575             if(cLock)
576             {
577                 std::lock_guard<std::recursive_mutex> lock(*cLock);
578                 result = OCDoResponse(&response);
579             }
580             else
581             {
582                 OICFree(response.payload);
583                 result = OC_STACK_ERROR;
584             }
585
586             if(result != OC_STACK_OK)
587             {
588                 oclog() << "Error sending response\n";
589             }
590             return result;
591         }
592     }
593
594     InProcServerWrapper::~InProcServerWrapper()
595     {
596         if(m_processThread.joinable())
597         {
598             m_threadRun = false;
599             m_processThread.join();
600         }
601
602         OCStop();
603     }
604 }
605