breadx 3.1.0

Pure-Rust X11 connection implementation with a focus on adaptability
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//               Copyright John Nunley, 2022.
// Distributed under the Boost Software License, Version 1.0.
//       (See accompanying file LICENSE or copy at
//         https://www.boost.org/LICENSE_1_0.txt)

#![cfg(feature = "async-std-support")]

cfg_std_unix! {
    use std::os::unix::io::AsRawFd;
}

cfg_std_windows! {
    use std::os::windows::io::AsRawSocket;
}

use core::task::{Context, Poll};

use crate::{
    connection::Connection,
    display::{
        AsyncDisplay, AsyncStatus, BasicDisplay, CanBeAsyncDisplay, DisplayBase, DisplayConnection,
        Interest, RawReply, RawRequest,
    },
    Error, NameConnection, Result,
};
use alloc::{string::ToString, sync::Arc, vec, vec::Vec};
use async_io::Async;
use core::future::Future;
use tracing::Instrument;
use x11rb_protocol::{
    connect::Connect,
    parse_display,
    protocol::{xproto::Setup, Event},
    xauth,
};

// create a "Source" trait that aliases to AsRawFd
// or AsRawSocket, depending on what's good

cfg_std_unix! {
    #[doc(hidden)]
    pub trait Source: AsRawFd {}
    impl<T: AsRawFd> Source for T {}
}

cfg_std_windows! {
    #[doc(hidden)]
    pub trait Source: AsRawSocket {}
    impl<T: AsRawSocket> Source for T {}
}

// impl trait on top of Async

impl<D: CanBeAsyncDisplay + Source> AsyncDisplay for Async<D> {
    fn poll_for_interest(
        &mut self,
        interest: Interest,
        callback: &mut dyn FnMut(&mut dyn AsyncDisplay, &mut Context<'_>) -> Result<()>,
        ctx: &mut Context<'_>,
    ) -> Poll<Result<()>> {
        let span = tracing::trace_span!(
            "async_std_support::poll_for_interest",
            interest = ?interest
        );
        let _enter = span.enter();

        match poll_ready(self, interest, ctx) {
            Poll::Ready(Ok(())) => {}
            poll => return poll,
        }

        // try for I/O on the socket
        match callback(self, ctx) {
            Err(e) if e.would_block() => {
                // indicate that we should poll again
                ctx.waker().wake_by_ref();
                Poll::Pending
            }
            poll => Poll::Ready(poll),
        }
    }
}

impl<'lt, D: DisplayBase + Source> AsyncDisplay for &'lt Async<D>
where
    &'lt D: CanBeAsyncDisplay,
{
    fn poll_for_interest(
        &mut self,
        interest: Interest,
        callback: &mut dyn FnMut(&mut dyn AsyncDisplay, &mut Context<'_>) -> Result<()>,
        ctx: &mut Context<'_>,
    ) -> Poll<Result<()>> {
        let span = tracing::trace_span!(
            "async_std_support::poll_for_interest",
            interest = ?interest
        );
        let _enter = span.enter();

        match poll_ready(self, interest, ctx) {
            Poll::Ready(Ok(())) => {}
            poll => return poll,
        }

        // try for I/O on the socket
        match callback(self, ctx) {
            Err(e) if e.would_block() => {
                ctx.waker().wake_by_ref();
                Poll::Pending
            }
            poll => Poll::Ready(poll),
        }
    }
}

fn poll_ready<D>(a: &Async<D>, interest: Interest, ctx: &mut Context<'_>) -> Poll<Result<()>> {
    tracing::trace!("polling for interest in {:?}", interest);

    // poll for the interest
    let res = match interest {
        Interest::Readable => a.poll_readable(ctx),
        Interest::Writable => a.poll_writable(ctx),
    };

    tracing::trace!(is_ready = res.is_ready(), "polled for readiness");

    res.map_err(Error::io)
}

// connection forming

pub fn connect(name: Option<&str>) -> impl Future<Output = Result<Async<DisplayConnection>>> {
    let name = name.map(ToString::to_string);
    async move {
        // create a name connection
        let dpy = parse_display::parse_display(name.as_deref())
            .ok_or_else(|| Error::couldnt_parse_display(name.is_none()))?;

        let screen = dpy.screen;
        let display_num = dpy.display;
        let conn =
            NameConnection::from_parsed_display_async(&dpy, name.is_none(), |name| async move {
                // poll the display until it is writable
                let registered = Async::new(name).map_err(Error::io)?;
                registered.writable().await.map_err(Error::io)?;
                let name = registered.into_inner().map_err(Error::io)?;

                // check socket error
                if let Some(err) = name.take_error() {
                    Err(err)
                } else {
                    Ok(name)
                }
            })
            .await?;

        // find xauth
        let (family, address) = conn.get_address()?;

        // xauth uses file I/O, use blocking
        let (name, data) = blocking::unblock(move || {
            match xauth::get_auth(family, &address, display_num).map_err(Error::io) {
                Err(e) => Err(e),
                Ok(Some(auth)) => Ok(auth),
                Ok(None) => {
                    tracing::warn!("No Xauth found for display {}", display_num);

                    Ok((vec![], vec![]))
                }
            }
        })
        .await?;

        // run the connector code
        establish_connect(conn.into(), screen as usize, name, data).await
    }
}

pub fn establish_connect<Conn: Source + Connection>(
    conn: Conn,
    default_screen: usize,
    auth_name: Vec<u8>,
    auth_data: Vec<u8>,
) -> impl Future<Output = Result<Async<BasicDisplay<Conn>>>> {
    let span = tracing::info_span!("establish_connect");

    async move {
        // use connect struct for establishing a connection
        let (mut connect, setup_request) = Connect::with_authorization(auth_name, auth_data);
        let mut registered = Async::new(conn).map_err(Error::io)?;

        // write as much as we can
        let mut written = 0;
        while written < setup_request.len() {
            write_with_mut(&mut registered, |conn| {
                let n = conn.send_slice(&setup_request[written..])?;
                written += n;
                Ok(())
            })
            .await?;
        }

        // flush the request
        write_with_mut(&mut registered, Connection::flush).await?;

        // read until we're finished
        loop {
            let adv =
                read_with_mut(&mut registered, |conn| conn.recv_slice(connect.buffer())).await?;

            if connect.advance(adv) {
                break;
            }
        }

        // we're finished
        let setup = connect.into_setup().map_err(Error::make_connect_error)?;
        let dpy = BasicDisplay::with_connection(
            registered.into_inner().map_err(Error::io)?,
            setup,
            default_screen,
        )?;
        Async::new(dpy).map_err(Error::io)
    }
    .instrument(span)
}

async fn write_with_mut<D, R: Default>(
    a: &mut Async<D>,
    mut f: impl FnMut(&mut D) -> Result<R>,
) -> Result<R> {
    let mut res: Result<()> = Ok(());
    let io_res = a
        .write_with_mut(|conn| match f(conn) {
            Ok(r) => Ok(r),
            Err(e) => match e.into_io_error() {
                Ok(e) => Err(e),
                Err(e) => {
                    res = Err(e);
                    Ok(Default::default())
                }
            },
        })
        .await;

    res.and(io_res.map_err(Error::io))
}

async fn read_with_mut<D, R: Default>(
    a: &mut Async<D>,
    mut f: impl FnMut(&mut D) -> Result<R>,
) -> Result<R> {
    let mut res: Result<()> = Ok(());
    let io_res = a
        .read_with_mut(|conn| match f(conn) {
            Ok(r) => Ok(r),
            Err(e) => match e.into_io_error() {
                Ok(e) => Err(e),
                Err(e) => {
                    res = Err(e);
                    Ok(Default::default())
                }
            },
        })
        .await;

    res.and(io_res.map_err(Error::io))
}

// trait forwarding

impl<D: DisplayBase> DisplayBase for Async<D> {
    fn setup(&self) -> &Arc<Setup> {
        self.get_ref().setup()
    }

    fn default_screen_index(&self) -> usize {
        self.get_ref().default_screen_index()
    }

    fn poll_for_event(&mut self) -> Result<Option<Event>> {
        self.get_mut().poll_for_event()
    }

    fn poll_for_reply_raw(&mut self, seq: u64) -> Result<Option<RawReply>> {
        self.get_mut().poll_for_reply_raw(seq)
    }
}

impl<'lt, D: DisplayBase> DisplayBase for &'lt Async<D>
where
    &'lt D: DisplayBase,
{
    fn setup(&self) -> &Arc<Setup> {
        self.get_ref().setup()
    }

    fn default_screen_index(&self) -> usize {
        self.get_ref().default_screen_index()
    }

    fn poll_for_event(&mut self) -> Result<Option<Event>> {
        self.get_ref().poll_for_event()
    }

    fn poll_for_reply_raw(&mut self, seq: u64) -> Result<Option<RawReply>> {
        self.get_ref().poll_for_reply_raw(seq)
    }
}

impl<D: CanBeAsyncDisplay> CanBeAsyncDisplay for Async<D> {
    fn format_request(
        &mut self,
        req: &mut RawRequest<'_, '_>,
        ctx: &mut Context<'_>,
    ) -> Result<AsyncStatus<u64>> {
        self.get_mut().format_request(req, ctx)
    }

    fn try_send_request_raw(
        &mut self,
        req: &mut RawRequest<'_, '_>,
        ctx: &mut Context<'_>,
    ) -> Result<AsyncStatus<()>> {
        self.get_mut().try_send_request_raw(req, ctx)
    }

    fn try_wait_for_reply_raw(
        &mut self,
        seq: u64,
        ctx: &mut Context<'_>,
    ) -> Result<AsyncStatus<RawReply>> {
        self.get_mut().try_wait_for_reply_raw(seq, ctx)
    }

    fn try_wait_for_event(&mut self, ctx: &mut Context<'_>) -> Result<AsyncStatus<Event>> {
        self.get_mut().try_wait_for_event(ctx)
    }

    fn try_flush(&mut self, ctx: &mut Context<'_>) -> Result<AsyncStatus<()>> {
        self.get_mut().try_flush(ctx)
    }

    fn try_generate_xid(&mut self, ctx: &mut Context<'_>) -> Result<AsyncStatus<u32>> {
        self.get_mut().try_generate_xid(ctx)
    }

    fn try_maximum_request_length(&mut self, ctx: &mut Context<'_>) -> Result<AsyncStatus<usize>> {
        self.get_mut().try_maximum_request_length(ctx)
    }

    fn try_check_for_error(&mut self, seq: u64, ctx: &mut Context<'_>) -> Result<AsyncStatus<()>> {
        self.get_mut().try_check_for_error(seq, ctx)
    }
}

impl<'lt, D: DisplayBase> CanBeAsyncDisplay for &'lt Async<D>
where
    &'lt D: CanBeAsyncDisplay,
{
    fn format_request(
        &mut self,
        req: &mut RawRequest<'_, '_>,
        ctx: &mut Context<'_>,
    ) -> Result<AsyncStatus<u64>> {
        self.get_ref().format_request(req, ctx)
    }

    fn try_send_request_raw(
        &mut self,
        req: &mut RawRequest<'_, '_>,
        ctx: &mut Context<'_>,
    ) -> Result<AsyncStatus<()>> {
        self.get_ref().try_send_request_raw(req, ctx)
    }

    fn try_wait_for_event(&mut self, ctx: &mut Context<'_>) -> Result<AsyncStatus<Event>> {
        self.get_ref().try_wait_for_event(ctx)
    }

    fn try_maximum_request_length(&mut self, ctx: &mut Context<'_>) -> Result<AsyncStatus<usize>> {
        self.get_ref().try_maximum_request_length(ctx)
    }

    fn try_wait_for_reply_raw(
        &mut self,
        seq: u64,
        ctx: &mut Context<'_>,
    ) -> Result<AsyncStatus<RawReply>> {
        self.get_ref().try_wait_for_reply_raw(seq, ctx)
    }

    fn try_generate_xid(&mut self, ctx: &mut Context<'_>) -> Result<AsyncStatus<u32>> {
        self.get_ref().try_generate_xid(ctx)
    }

    fn try_flush(&mut self, ctx: &mut Context<'_>) -> Result<AsyncStatus<()>> {
        self.get_ref().try_flush(ctx)
    }

    fn try_check_for_error(&mut self, seq: u64, ctx: &mut Context<'_>) -> Result<AsyncStatus<()>> {
        self.get_ref().try_check_for_error(seq, ctx)
    }
}