1 /*
2 // Copyright (c) 2018 Intel Corporation
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 */
16 #pragma once
17 
18 #ifndef BOOST_COROUTINES_NO_DEPRECATION_WARNING
19 // users should define this if they directly include boost/asio/spawn.hpp,
20 // but by defining it here, warnings won't cause problems with a compile
21 #define BOOST_COROUTINES_NO_DEPRECATION_WARNING
22 #endif
23 
24 #include <boost/asio/async_result.hpp>
25 #include <boost/asio/io_context.hpp>
26 #include <boost/asio/posix/stream_descriptor.hpp>
27 #include <boost/asio/post.hpp>
28 #include <boost/asio/spawn.hpp>
29 #include <boost/callable_traits.hpp>
30 #include <sdbusplus/asio/detail/async_send_handler.hpp>
31 #include <sdbusplus/message.hpp>
32 #include <sdbusplus/utility/read_into_tuple.hpp>
33 #include <sdbusplus/utility/type_traits.hpp>
34 
35 #include <chrono>
36 #include <string>
37 #include <tuple>
38 
39 namespace sdbusplus
40 {
41 
42 namespace asio
43 {
44 
45 /// Root D-Bus IO object
46 /**
47  * A connection to a bus, through which messages may be sent or received.
48  */
49 class connection : public sdbusplus::bus_t
50 {
51   public:
52     // default to system bus
53     connection(boost::asio::io_context& io) :
54         sdbusplus::bus_t(sdbusplus::bus::new_default()), io_(io), socket(io_)
55     {
56         socket.assign(get_fd());
57         read_wait();
58     }
59     connection(boost::asio::io_context& io, sd_bus* bus) :
60         sdbusplus::bus_t(bus), io_(io), socket(io_)
61     {
62         socket.assign(get_fd());
63         read_wait();
64     }
65     ~connection()
66     {
67         // The FD will be closed by the socket object, so assign null to the
68         // sd_bus object to avoid a double close()  Ignore return codes here,
69         // because there's nothing we can do about errors
70         socket.release();
71     }
72 
73     /** @brief Perform an asynchronous send of a message, executing the handler
74      *         upon return and return
75      *
76      *  @param[in] m - A message ready to send
77      *  @param[in] handler - handler to execute upon completion; this may be an
78      *                       asio::yield_context to execute asynchronously as a
79      *                       coroutine
80      *
81      *  @return If a yield context is passed as the handler, the return type is
82      *          a message. If a function object is passed in as the handler,
83      *          the return type is the result of the handler registration,
84      *          while the resulting message will get passed into the handler.
85      */
86     template <typename MessageHandler>
87     inline BOOST_ASIO_INITFN_RESULT_TYPE(MessageHandler,
88                                          void(boost::system::error_code,
89                                               message_t&))
90         async_send(message_t& m, MessageHandler&& handler, uint64_t timeout = 0)
91     {
92         boost::asio::async_completion<
93             MessageHandler, void(boost::system::error_code, message_t)>
94             init(handler);
95         detail::async_send_handler<typename boost::asio::async_result<
96             MessageHandler, void(boost::system::error_code,
97                                  message_t)>::completion_handler_type>(
98             std::move(init.completion_handler))(get(), m, timeout);
99         return init.result.get();
100     }
101 
102     /** @brief Perform an asynchronous method call, with input parameter packing
103      *         and return value unpacking.
104      *
105      *  @param[in] handler - A function object that is to be called as a
106      *                       continuation for the async dbus method call. The
107      *                       arguments to parse on the return are deduced from
108      *                       the handler's signature and then passed in along
109      *                       with an error code and optional message_t
110      *  @param[in] service - The service to call.
111      *  @param[in] objpath - The object's path for the call.
112      *  @param[in] interf - The object's interface to call.
113      *  @param[in] method - The object's method to call.
114      *  @param[in] timeout - The timeout for the method call in usec (0 results
115      *                       in using the default value).
116      *  @param[in] a... - Optional parameters for the method call.
117      *
118      *  @return immediate return of the internal handler registration. The
119      *          result of the actual asynchronous call will get unpacked from
120      *          the message and passed into the handler when the call is
121      *          complete.
122      */
123     template <typename MessageHandler, typename... InputArgs>
124     void async_method_call_timed(MessageHandler&& handler,
125                                  const std::string& service,
126                                  const std::string& objpath,
127                                  const std::string& interf,
128                                  const std::string& method, uint64_t timeout,
129                                  const InputArgs&... a)
130     {
131         using FunctionTuple = boost::callable_traits::args_t<MessageHandler>;
132         using FunctionTupleType = utility::decay_tuple_t<FunctionTuple>;
133         constexpr bool returnWithMsg = []() {
134             if constexpr ((std::tuple_size_v<FunctionTupleType>) > 1)
135             {
136                 return std::is_same_v<
137                     std::tuple_element_t<1, FunctionTupleType>,
138                     sdbusplus::message_t>;
139             }
140             return false;
141         }();
142         using UnpackType = utility::strip_first_n_args_t<returnWithMsg ? 2 : 1,
143                                                          FunctionTupleType>;
144         auto applyHandler = [handler = std::forward<MessageHandler>(handler)](
145                                 boost::system::error_code ec,
146                                 message_t& r) mutable {
147             UnpackType responseData;
148             if (!ec)
149             {
150                 try
151                 {
152                     utility::read_into_tuple(responseData, r);
153                 }
154                 catch (const std::exception& e)
155                 {
156                     // Set error code if not already set
157                     ec = boost::system::errc::make_error_code(
158                         boost::system::errc::invalid_argument);
159                 }
160             }
161             // Note.  Callback is called whether or not the unpack was
162             // successful to allow the user to implement their own handling
163             if constexpr (returnWithMsg)
164             {
165                 auto response = std::tuple_cat(std::make_tuple(ec),
166                                                std::forward_as_tuple(r),
167                                                std::move(responseData));
168                 std::apply(handler, response);
169             }
170             else
171             {
172                 auto response = std::tuple_cat(std::make_tuple(ec),
173                                                std::move(responseData));
174                 std::apply(handler, response);
175             }
176         };
177         message_t m;
178         boost::system::error_code ec;
179         try
180         {
181             m = new_method_call(service.c_str(), objpath.c_str(),
182                                 interf.c_str(), method.c_str());
183             m.append(a...);
184         }
185         catch (const exception::SdBusError& e)
186         {
187             ec = boost::system::errc::make_error_code(
188                 static_cast<boost::system::errc::errc_t>(e.get_errno()));
189             applyHandler(ec, m);
190             return;
191         }
192         async_send(m, std::forward<decltype(applyHandler)>(applyHandler),
193                    timeout);
194     }
195 
196     /** @brief Perform an asynchronous method call, with input parameter packing
197      *         and return value unpacking. Uses the default timeout value.
198      *
199      *  @param[in] handler - A function object that is to be called as a
200      *                       continuation for the async dbus method call. The
201      *                       arguments to parse on the return are deduced from
202      *                       the handler's signature and then passed in along
203      *                       with an error code and optional message_t
204      *  @param[in] service - The service to call.
205      *  @param[in] objpath - The object's path for the call.
206      *  @param[in] interf - The object's interface to call.
207      *  @param[in] method - The object's method to call.
208      *  @param[in] a... - Optional parameters for the method call.
209      *
210      *  @return immediate return of the internal handler registration. The
211      *          result of the actual asynchronous call will get unpacked from
212      *          the message and passed into the handler when the call is
213      *          complete.
214      */
215     template <typename MessageHandler, typename... InputArgs>
216     void async_method_call(MessageHandler&& handler, const std::string& service,
217                            const std::string& objpath,
218                            const std::string& interf, const std::string& method,
219                            const InputArgs&... a)
220     {
221         async_method_call_timed(std::forward<MessageHandler>(handler), service,
222                                 objpath, interf, method, 0, a...);
223     }
224 
225     /** @brief Perform a yielding asynchronous method call, with input
226      *         parameter packing and return value unpacking
227      *
228      *  @param[in] yield - A yield context to async block upon.
229      *  @param[in] ec - an error code that will be set for any errors
230      *  @param[in] service - The service to call.
231      *  @param[in] objpath - The object's path for the call.
232      *  @param[in] interf - The object's interface to call.
233      *  @param[in] method - The object's method to call.
234      *  @param[in] a... - Optional parameters for the method call.
235      *
236      *  @return Unpacked value of RetType
237      */
238     template <typename... RetTypes, typename... InputArgs>
239     auto yield_method_call(boost::asio::yield_context yield,
240                            boost::system::error_code& ec,
241                            const std::string& service,
242                            const std::string& objpath,
243                            const std::string& interf, const std::string& method,
244                            const InputArgs&... a)
245     {
246         message_t m;
247         try
248         {
249             m = new_method_call(service.c_str(), objpath.c_str(),
250                                 interf.c_str(), method.c_str());
251             m.append(a...);
252         }
253         catch (const exception::SdBusError& e)
254         {
255             ec = boost::system::errc::make_error_code(
256                 static_cast<boost::system::errc::errc_t>(e.get_errno()));
257         }
258         message_t r;
259         if (!ec)
260         {
261             r = async_send(m, yield[ec]);
262         }
263         if constexpr (sizeof...(RetTypes) == 0)
264         {
265             // void return
266             return;
267         }
268         else if constexpr (sizeof...(RetTypes) == 1)
269         {
270             if constexpr (std::is_same_v<utility::first_type_t<RetTypes...>,
271                                          void>)
272             {
273                 return;
274             }
275             else
276             {
277                 // single item return
278                 utility::first_type_t<RetTypes...> responseData{};
279                 // before attempting to read, check ec and bail on error
280                 if (ec)
281                 {
282                     return responseData;
283                 }
284                 try
285                 {
286                     r.read(responseData);
287                 }
288                 catch (const std::exception& e)
289                 {
290                     ec = boost::system::errc::make_error_code(
291                         boost::system::errc::invalid_argument);
292                     // responseData will be default-constructed...
293                 }
294                 return responseData;
295             }
296         }
297         else
298         {
299             // tuple of things to return
300             std::tuple<RetTypes...> responseData{};
301             // before attempting to read, check ec and bail on error
302             if (ec)
303             {
304                 return responseData;
305             }
306             try
307             {
308                 r.read(responseData);
309             }
310             catch (const std::exception& e)
311             {
312                 ec = boost::system::errc::make_error_code(
313                     boost::system::errc::invalid_argument);
314                 // responseData will be default-constructed...
315             }
316             return responseData;
317         }
318     }
319 
320     boost::asio::io_context& get_io_context()
321     {
322         return io_;
323     }
324 
325   private:
326     boost::asio::io_context& io_;
327     boost::asio::posix::stream_descriptor socket;
328 
329     void read_wait()
330     {
331         socket.async_read_some(
332             boost::asio::null_buffers(),
333             [&](const boost::system::error_code& ec, std::size_t) {
334                 if (ec)
335                 {
336                     return;
337                 }
338                 if (process_discard())
339                 {
340                     read_immediate();
341                 }
342                 else
343                 {
344                     read_wait();
345                 }
346             });
347     }
348     void read_immediate()
349     {
350         boost::asio::post(io_, [&] {
351             if (process_discard())
352             {
353                 read_immediate();
354             }
355             else
356             {
357                 read_wait();
358             }
359         });
360     }
361 };
362 
363 } // namespace asio
364 
365 } // namespace sdbusplus
366