Skip to main content

zbus/blocking/connection/
builder.rs

1#[cfg(not(feature = "tokio"))]
2use std::net::TcpStream;
3#[cfg(all(unix, not(feature = "tokio")))]
4use std::os::unix::net::UnixStream;
5#[cfg(feature = "tokio")]
6use tokio::net::TcpStream;
7#[cfg(all(unix, feature = "tokio"))]
8use tokio::net::UnixStream;
9#[cfg(all(windows, not(feature = "tokio")))]
10use uds_windows::UnixStream;
11
12// Feature-independent stream types for the `async_io_*_stream` builders.
13#[cfg(feature = "async-io")]
14use std::net::TcpStream as AsyncIoTcpStream;
15#[cfg(all(unix, feature = "async-io"))]
16use std::os::unix::net::UnixStream as AsyncIoUnixStream;
17#[cfg(all(windows, feature = "async-io"))]
18use uds_windows::UnixStream as AsyncIoUnixStream;
19
20use zvariant::ObjectPath;
21
22#[cfg(feature = "p2p")]
23use crate::Guid;
24use crate::{
25    Error, Result, address::Address, blocking::Connection, conn::AuthMechanism,
26    connection::socket::BoxedSplit, names::WellKnownName, object_server::Interface,
27    utils::block_on,
28};
29
30/// A builder for [`zbus::blocking::Connection`].
31#[derive(Debug)]
32#[must_use]
33pub struct Builder<'a>(crate::connection::Builder<'a>);
34
35impl<'a> Builder<'a> {
36    /// Create a builder for the session/user message bus connection.
37    pub fn session() -> Result<Self> {
38        crate::connection::Builder::session().map(Self)
39    }
40
41    /// Create a builder for the system-wide message bus connection.
42    pub fn system() -> Result<Self> {
43        crate::connection::Builder::system().map(Self)
44    }
45
46    /// Create a builder for an IBus connection.
47    ///
48    /// IBus (Intelligent Input Bus) is an input method framework. This method creates a builder
49    /// that will query the IBus daemon for its D-Bus address using the `ibus address` command.
50    ///
51    /// # Platform Support
52    ///
53    /// This method is available on Unix-like systems where IBus is installed.
54    ///
55    /// # Errors
56    ///
57    /// Returns an error if:
58    /// - The `ibus` command is not found or fails to execute
59    /// - The IBus daemon is not running
60    /// - The command output cannot be parsed as a valid D-Bus address
61    ///
62    /// # Example
63    ///
64    /// ```no_run
65    /// # use std::error::Error;
66    /// # use zbus::blocking::connection;
67    /// #
68    /// let _conn = connection::Builder::ibus()?
69    ///     .build()?;
70    ///
71    /// // Use the connection to interact with IBus services.
72    /// # Ok::<_, Box<dyn Error + Send + Sync>>(())
73    /// ```
74    #[cfg(unix)]
75    pub fn ibus() -> Result<Self> {
76        crate::connection::Builder::ibus().map(Self)
77    }
78
79    /// Create a builder for a connection that will use the given [D-Bus bus address].
80    ///
81    /// [D-Bus bus address]: https://dbus.freedesktop.org/doc/dbus-specification.html#addresses
82    pub fn address<A>(address: A) -> Result<Self>
83    where
84        A: TryInto<Address>,
85        A::Error: Into<Error>,
86    {
87        crate::connection::Builder::address(address).map(Self)
88    }
89
90    /// Create a builder for a connection that will use the given unix stream.
91    ///
92    /// The stream is a [`std::os::unix::net::UnixStream`] (or [`uds_windows::UnixStream`] on
93    /// Windows).
94    ///
95    /// [`uds_windows::UnixStream`]: https://docs.rs/uds_windows/latest/uds_windows/struct.UnixStream.html
96    #[cfg(all(any(unix, windows), feature = "async-io"))]
97    pub fn async_io_unix_stream(stream: AsyncIoUnixStream) -> Self {
98        Self(crate::connection::Builder::async_io_unix_stream(stream))
99    }
100
101    /// Create a builder for a connection that will use the given unix stream.
102    ///
103    /// This method expects a
104    /// [`tokio::net::UnixStream`](https://docs.rs/tokio/latest/tokio/net/struct.UnixStream.html).
105    /// Without the `tokio` feature it accepts a [`std::os::unix::net::UnixStream`] instead, but
106    /// that form is deprecated in favor of
107    /// [`async_io_unix_stream`](Self::async_io_unix_stream).
108    ///
109    /// Since tokio currently [does not support Unix domain sockets][tuds] on Windows, this method
110    /// is not available when the `tokio` feature is enabled and building for Windows target.
111    ///
112    /// [tuds]: https://github.com/tokio-rs/tokio/issues/2201
113    #[cfg_attr(
114        not(feature = "tokio"),
115        deprecated(
116            since = "5.19.0",
117            note = "Use `async_io_unix_stream` to avoid a build failure if the `tokio` feature gets enabled"
118        )
119    )]
120    #[cfg(any(unix, not(feature = "tokio")))]
121    #[allow(deprecated)] // forwards to the async builder's equally-deprecated `unix_stream`
122    pub fn unix_stream(stream: UnixStream) -> Self {
123        Self(crate::connection::Builder::unix_stream(stream))
124    }
125
126    /// Create a builder for a connection that will use the given TCP stream.
127    ///
128    /// The stream is a [`std::net::TcpStream`].
129    #[cfg(feature = "async-io")]
130    pub fn async_io_tcp_stream(stream: AsyncIoTcpStream) -> Self {
131        Self(crate::connection::Builder::async_io_tcp_stream(stream))
132    }
133
134    /// Create a builder for a connection that will use the given TCP stream.
135    ///
136    /// This method expects a
137    /// [`tokio::net::TcpStream`](https://docs.rs/tokio/latest/tokio/net/struct.TcpStream.html).
138    /// Without the `tokio` feature it accepts a [`std::net::TcpStream`] instead, but that form is
139    /// deprecated in favor of [`async_io_tcp_stream`](Self::async_io_tcp_stream).
140    #[cfg_attr(
141        not(feature = "tokio"),
142        deprecated(
143            since = "5.19.0",
144            note = "Use `async_io_tcp_stream` to avoid a build failure if the `tokio` feature gets enabled"
145        )
146    )]
147    #[allow(deprecated)] // forwards to the async builder's equally-deprecated `tcp_stream`
148    pub fn tcp_stream(stream: TcpStream) -> Self {
149        Self(crate::connection::Builder::tcp_stream(stream))
150    }
151
152    /// Create a builder for a connection that will use the given pre-authenticated socket.
153    ///
154    /// This is similar to [`Builder::socket`], except that the socket is either already
155    /// authenticated or does not require authentication.
156    pub fn authenticated_socket<S, G>(socket: S, guid: G) -> Result<Self>
157    where
158        S: Into<BoxedSplit>,
159        G: TryInto<crate::Guid<'a>>,
160        G::Error: Into<Error>,
161    {
162        crate::connection::Builder::authenticated_socket(socket, guid).map(Self)
163    }
164
165    /// Create a builder for a connection that will use the given socket.
166    pub fn socket<S: Into<BoxedSplit>>(socket: S) -> Self {
167        Self(crate::connection::Builder::socket(socket))
168    }
169
170    /// Specify the mechanism to use during authentication.
171    pub fn auth_mechanism(self, auth_mechanism: AuthMechanism) -> Self {
172        Self(self.0.auth_mechanism(auth_mechanism))
173    }
174
175    /// Specify the user id during authentication.
176    ///
177    /// This can be useful when using [`AuthMechanism::External`] with `socat`
178    /// to avoid the host decide what uid to use and instead provide one
179    /// known to have access rights.
180    #[cfg(unix)]
181    pub fn user_id(self, id: u32) -> Self {
182        Self(self.0.user_id(id))
183    }
184
185    /// The to-be-created connection will be a peer-to-peer connection.
186    ///
187    /// This method is only available when the `p2p` feature is enabled.
188    #[cfg(feature = "p2p")]
189    pub fn p2p(self) -> Self {
190        Self(self.0.p2p())
191    }
192
193    /// The to-be-created connection will be a server using the given GUID.
194    ///
195    /// The to-be-created connection will wait for incoming client authentication handshake and
196    /// negotiation messages, for peer-to-peer communications after successful creation.
197    ///
198    /// This method is only available when the `p2p` feature is enabled.
199    ///
200    /// **NOTE:** This method is redundant when using [`Builder::authenticated_socket`] since the
201    /// latter already sets the GUID for the connection and zbus doesn't differentiate between a
202    /// server and a client connection, except for authentication.
203    #[cfg(feature = "p2p")]
204    pub fn server<G>(self, guid: G) -> Result<Self>
205    where
206        G: TryInto<Guid<'a>>,
207        G::Error: Into<Error>,
208    {
209        self.0.server(guid).map(Self)
210    }
211
212    /// Set the capacity of the main (unfiltered) queue.
213    ///
214    /// Since typically you'd want to set this at instantiation time, you can set it through the
215    /// builder.
216    ///
217    /// # Example
218    ///
219    /// ```
220    /// # use std::error::Error;
221    /// # use zbus::blocking::connection;
222    /// #
223    /// let conn = connection::Builder::session()?
224    ///     .max_queued(30)
225    ///     .build()?;
226    /// assert_eq!(conn.max_queued(), 30);
227    ///
228    /// // Do something useful with `conn`..
229    /// # Ok::<_, Box<dyn Error + Send + Sync>>(())
230    /// ```
231    pub fn max_queued(self, max: usize) -> Self {
232        Self(self.0.max_queued(max))
233    }
234
235    /// Register a D-Bus [`Interface`] to be served at a given path.
236    ///
237    /// This is similar to [`zbus::blocking::ObjectServer::at`], except that it allows you to have
238    /// your interfaces available immediately after the connection is established. Typically, this
239    /// is exactly what you'd want. Also in contrast to [`zbus::blocking::ObjectServer::at`], this
240    /// method will replace any previously added interface with the same name at the same path.
241    pub fn serve_at<P, I>(self, path: P, iface: I) -> Result<Self>
242    where
243        I: Interface,
244        P: TryInto<ObjectPath<'a>>,
245        P::Error: Into<Error>,
246    {
247        self.0.serve_at(path, iface).map(Self)
248    }
249
250    /// Register a well-known name for this connection on the bus.
251    ///
252    /// This is similar to [`zbus::blocking::Connection::request_name`], except the name is
253    /// requested as part of the connection setup ([`Builder::build`]), immediately after
254    /// interfaces registered (through [`Builder::serve_at`]) are advertised. Typically
255    /// this is exactly what you want.
256    pub fn name<W>(self, well_known_name: W) -> Result<Self>
257    where
258        W: TryInto<WellKnownName<'a>>,
259        W::Error: Into<Error>,
260    {
261        self.0.name(well_known_name).map(Self)
262    }
263
264    /// Whether the [`zbus::fdo::RequestNameFlags::AllowReplacement`] flag will be set when
265    /// requesting names.
266    pub fn allow_name_replacements(self, allow_replacement: bool) -> Self {
267        Self(self.0.allow_name_replacements(allow_replacement))
268    }
269
270    /// Whether the [`zbus::fdo::RequestNameFlags::ReplaceExisting`] flag will be set when
271    /// requesting names.
272    pub fn replace_existing_names(self, replace_existing: bool) -> Self {
273        Self(self.0.replace_existing_names(replace_existing))
274    }
275
276    /// Set the unique name of the connection.
277    ///
278    /// This method is only available when the `bus-impl` feature is enabled.
279    ///
280    /// # Panics
281    ///
282    /// This method panics if the to-be-created connection is not a peer-to-peer connection.
283    /// It will always panic if the connection is to a message bus as it's the bus that assigns
284    /// peers their unique names. This is mainly provided for bus implementations. All other users
285    /// should not need to use this method.
286    #[cfg(feature = "bus-impl")]
287    pub fn unique_name<U>(self, unique_name: U) -> Result<Self>
288    where
289        U: TryInto<crate::names::UniqueName<'a>>,
290        U::Error: Into<Error>,
291    {
292        self.0.unique_name(unique_name).map(Self)
293    }
294
295    /// Set a timeout for method calls.
296    ///
297    /// Method calls will return
298    /// `zbus::Error::InputOutput(std::io::Error(kind: ErrorKind::TimedOut))` if a client does not
299    /// receive an answer from a service in time.
300    pub fn method_timeout(self, timeout: std::time::Duration) -> Self {
301        Self(self.0.method_timeout(timeout))
302    }
303
304    /// Build the connection, consuming the builder.
305    ///
306    /// # Errors
307    ///
308    /// Until server-side bus connection is supported, attempting to build such a connection will
309    /// result in a [`Error::Unsupported`] error.
310    pub fn build(self) -> Result<Connection> {
311        block_on(self.0.build()).map(Into::into)
312    }
313
314    /// Build the connection and return a [`MessageIterator`] to receive messages from it.
315    ///
316    /// This is the blocking counterpart of [`crate::connection::Builder::build_message_stream`].
317    /// The iterator is set up **before** the socket-reader task is started, so no messages can
318    /// be lost in the window between the connection being built and the iterator being created.
319    /// Use this when the peer may pipeline traffic right after authentication — e.g. a bus
320    /// implementation reading a `Hello` method call from a just-connected client.
321    ///
322    /// To get the [`Connection`] out of the returned iterator, use `Connection::from(&iter)`.
323    ///
324    /// This method is only available when the `bus-impl` feature is enabled.
325    ///
326    /// [`MessageIterator`]: crate::blocking::MessageIterator
327    #[cfg(feature = "bus-impl")]
328    pub fn build_message_iterator(self) -> Result<crate::blocking::MessageIterator> {
329        block_on(self.0.build_message_stream())
330            .map(|azync| crate::blocking::MessageIterator { azync: Some(azync) })
331    }
332}