Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🐛 Expose the socket address clients can use #182

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 30 additions & 3 deletions src/bin/busd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,23 @@ extern crate busd;
#[cfg(unix)]
use std::{fs::File, io::Write, os::fd::FromRawFd};

use busd::bus;

use anyhow::Result;
use clap::Parser;
#[cfg(unix)]
use tokio::{select, signal::unix::SignalKind};
use tracing::error;
#[cfg(unix)]
use tracing::{info, warn};
use zbus::Address;

use busd::{bus, config::BusType};

/// A simple D-Bus broker.
#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
struct Args {
/// The address to listen on.
/// Takes precedence over any `<listen>` element in the configuration file.
#[clap(short = 'a', long, value_parser)]
address: Option<String>,

Expand All @@ -36,6 +38,17 @@ struct Args {
#[cfg(unix)]
#[clap(long)]
ready_fd: Option<i32>,

/// Equivalent to `--address unix:tmpdir=$XDG_RUNTIME_DIR`
/// and --config /usr/share/dbus-1/session.conf`.
/// This is the default if `--system` is absent.
#[clap(long)]
session: bool,

/// Equivalent to `--address unix:path=/run/dbus/system_bus_socket`
/// and `--config /usr/share/dbus-1/system.conf`.
#[clap(long)]
system: bool,
}

#[tokio::main]
Expand All @@ -44,7 +57,21 @@ async fn main() -> Result<()> {

let args = Args::parse();

let mut bus = bus::Bus::for_address(args.address.as_deref()).await?;
// TODO: when we have `Config` from #159, prefer `config.r#type` before `BusType::default()`
let bus_type = if args.system {
BusType::System
} else {
BusType::default()
};

// TODO: when we have `Config` from #159, prefer `config.listen` before `try_from(bus_type)`
let address = if let Some(address) = args.address {
Address::try_from(address.as_str())?
} else {
Address::try_from(bus_type)?
};

let mut bus = bus::Bus::for_address(&format!("{address}")).await?;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that I'm a little anxious about all the back and forth between Address and &str / String we have here now

It only happens during start up, so I'm not sure whether it's worth trying to optimise this now, or do this holistically once Config and other functionality is working

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that I'm a little anxious about all the back and forth between Address and &str / String we have here now

We shouldn't need to parse any address string and we most definitely don't need to care for session/system here. At this point in the code, we should already have a zbus::Address (either from the config, cli arg or a default).

Also, you can construct a zbus::Address through their properties directly (if not, we need to add more API to zbus first) when/where needed.


#[cfg(unix)]
if let Some(fd) = args.ready_fd {
Expand Down
63 changes: 27 additions & 36 deletions src/bus/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use anyhow::{bail, Ok, Result};
#[cfg(unix)]
use std::{env, path::Path};
use std::{str::FromStr, sync::Arc};

use anyhow::{bail, Ok, Result};
#[cfg(unix)]
use tokio::fs::remove_file;
use tokio::spawn;
Expand Down Expand Up @@ -45,11 +44,8 @@ enum Listener {
}

impl Bus {
pub async fn for_address(address: Option<&str>) -> Result<Self> {
let mut address = match address {
Some(address) => Address::from_str(address)?,
None => Address::from_str(&default_address())?,
};
pub async fn for_address(address: &str) -> Result<Self> {
let mut address = Address::from_str(address)?;
let guid: OwnedGuid = match address.guid() {
Some(guid) => guid.to_owned().into(),
None => {
Expand All @@ -61,7 +57,18 @@ impl Bus {
};
let (listener, auth_mechanism) = match address.transport() {
#[cfg(unix)]
Transport::Unix(unix) => (Self::unix_stream(unix).await?, AuthMechanism::External),
Transport::Unix(unix) => {
// resolve address specification into address that clients can use
let addr = Self::unix_addr(unix)?;
address = Address::try_from(
format!("unix:path={}", addr.as_pathname().unwrap().display()).as_str(),
)?;

(
Self::unix_stream(addr.clone()).await?,
AuthMechanism::External,
)
}
Transport::Tcp(tcp) => {
#[cfg(not(windows))]
let auth_mechanism = AuthMechanism::Anonymous;
Expand Down Expand Up @@ -135,14 +142,10 @@ impl Bus {
}

#[cfg(unix)]
async fn unix_stream(unix: &Unix) -> Result<Listener> {
// TODO: Use tokio::net::UnixListener directly once it supports abstract sockets:
//
// https://github.com/tokio-rs/tokio/issues/4610

fn unix_addr(unix: &Unix) -> Result<std::os::unix::net::SocketAddr> {
use std::os::unix::net::SocketAddr;

let addr = match unix.path() {
Ok(match unix.path() {
#[cfg(target_os = "linux")]
UnixSocket::Abstract(name) => {
use std::os::linux::net::SocketAddrExt;
Expand Down Expand Up @@ -175,7 +178,15 @@ impl Bus {
addr
}
_ => bail!("Unsupported address."),
};
})
}

#[cfg(unix)]
async fn unix_stream(addr: std::os::unix::net::SocketAddr) -> Result<Listener> {
// TODO: Use tokio::net::UnixListener directly once it supports abstract sockets:
//
// https://github.com/tokio-rs/tokio/issues/4610

let std_listener =
tokio::task::spawn_blocking(move || std::os::unix::net::UnixListener::bind_addr(&addr))
.await??;
Expand Down Expand Up @@ -246,23 +257,3 @@ impl Bus {
self.inner.next_id
}
}

#[cfg(unix)]
fn default_address() -> String {
let runtime_dir = env::var("XDG_RUNTIME_DIR")
.as_ref()
.map(|s| Path::new(s).to_path_buf())
.ok()
.unwrap_or_else(|| {
Path::new("/run")
.join("user")
.join(format!("{}", nix::unistd::Uid::current()))
});

format!("unix:dir={}", runtime_dir.display())
}

#[cfg(not(unix))]
fn default_address() -> String {
"tcp:host=127.0.0.1,port=4242".to_string()
}
43 changes: 43 additions & 0 deletions src/config/bus_type.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#[cfg(unix)]
use std::{env, path::PathBuf};

use anyhow::{Error, Result};
use zbus::Address;

#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum BusType {
#[default]
Session,
System,
}

impl TryFrom<BusType> for Address {
type Error = Error;
#[cfg(unix)]
fn try_from(value: BusType) -> Result<Self> {
if value == BusType::System {
return Address::try_from("unix:path=/run/dbus/system_bus_socket").map_err(Error::msg);
}

// BusType::Session
Address::try_from(format!("unix:tmpdir={}", default_session_dir().display()).as_str())
.map_err(Error::msg)
}

#[cfg(not(unix))]
fn try_from(_value: BusType) -> Result<Self> {
Address::try_from("tcp:host=127.0.0.1,port=4242").map_err(Error::msg)
}
}

#[cfg(unix)]
fn default_session_dir() -> PathBuf {
env::var("XDG_RUNTIME_DIR")
.map(|s| PathBuf::from(s).to_path_buf())
.ok()
.unwrap_or_else(|| {
PathBuf::from("/run")
.join("user")
.join(format!("{}", nix::unistd::Uid::current()))
})
}
3 changes: 3 additions & 0 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pub mod bus_type;

pub use bus_type::BusType;
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
pub mod bus;
pub mod config;
pub mod fdo;
pub mod match_rules;
pub mod name_registry;
Expand Down
2 changes: 1 addition & 1 deletion tests/fdo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ async fn name_ownership_changes() {
}

async fn name_ownership_changes_(address: &str) {
let mut bus = Bus::for_address(Some(address)).await.unwrap();
let mut bus = Bus::for_address(address).await.unwrap();
let (tx, rx) = tokio::sync::oneshot::channel();

let handle = tokio::spawn(async move {
Expand Down
2 changes: 1 addition & 1 deletion tests/greet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ async fn greet() {
}

async fn greet_(socket_addr: &str) {
let mut bus = Bus::for_address(Some(socket_addr)).await.unwrap();
let mut bus = Bus::for_address(socket_addr).await.unwrap();
let (tx, mut rx) = channel(1);

let handle = tokio::spawn(async move {
Expand Down
2 changes: 1 addition & 1 deletion tests/monitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ async fn become_monitor() {
busd::tracing_subscriber::init();

let address = "tcp:host=127.0.0.1,port=4242".to_string();
let mut bus = Bus::for_address(Some(&address)).await.unwrap();
let mut bus = Bus::for_address(&address).await.unwrap();
let (tx, rx) = tokio::sync::oneshot::channel();

let handle = tokio::spawn(async move {
Expand Down
2 changes: 1 addition & 1 deletion tests/multiple_conns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ async fn multi_conenct() {
}

async fn multi_conenct_(socket_addr: &str) {
let mut bus = Bus::for_address(Some(socket_addr)).await.unwrap();
let mut bus = Bus::for_address(socket_addr).await.unwrap();
let (tx, rx) = channel();

let handle = tokio::spawn(async move {
Expand Down
Loading