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
//! Helper for implementing `RequestConnection::extension_information()`.

use std::collections::{hash_map::Entry as HashMapEntry, HashMap};

use crate::connection::RequestConnection;
use crate::cookie::Cookie;
use crate::errors::{ConnectionError, ReplyError};
use crate::protocol::xproto::{ConnectionExt, QueryExtensionReply};
use crate::x11_utils::{ExtInfoProvider, ExtensionInformation};

use x11rb_protocol::SequenceNumber;

/// Helper for implementing `RequestConnection::extension_information()`.
///
/// This helps with implementing `RequestConnection`. Most likely, you do not need this in your own
/// code, unless you really want to implement your own X11 connection.
#[derive(Debug, Default)]
pub struct ExtensionManager(HashMap<&'static str, CheckState>);

#[derive(Debug)]
enum CheckState {
    Prefetched(SequenceNumber),
    Present(ExtensionInformation),
    Missing,
    Error,
}

impl ExtensionManager {
    /// If the extension has not prefetched yet, sends a `QueryExtension`
    /// requests, adds a field to the hash map and returns a reference to it.
    fn prefetch_extension_information_aux<C: RequestConnection>(
        &mut self,
        conn: &C,
        extension_name: &'static str,
    ) -> Result<&mut CheckState, ConnectionError> {
        match self.0.entry(extension_name) {
            // Extension already checked, return the cached value
            HashMapEntry::Occupied(entry) => Ok(entry.into_mut()),
            HashMapEntry::Vacant(entry) => {
                crate::debug!(
                    "Prefetching information about '{}' extension",
                    extension_name
                );
                let cookie = conn.query_extension(extension_name.as_bytes())?;
                Ok(entry.insert(CheckState::Prefetched(cookie.into_sequence_number())))
            }
        }
    }

    /// Prefetchs an extension sending a `QueryExtension` without waiting for
    /// the reply.
    pub fn prefetch_extension_information<C: RequestConnection>(
        &mut self,
        conn: &C,
        extension_name: &'static str,
    ) -> Result<(), ConnectionError> {
        // We are not interested on the reference to the entry.
        let _ = self.prefetch_extension_information_aux(conn, extension_name)?;
        Ok(())
    }

    /// Insert an extension if you already have the information.
    pub fn insert_extension_information(
        &mut self,
        extension_name: &'static str,
        info: Option<ExtensionInformation>,
    ) {
        crate::debug!(
            "Inserting '{}' extension information directly: {:?}",
            extension_name,
            info
        );
        let state = match info {
            Some(info) => CheckState::Present(info),
            None => CheckState::Missing,
        };

        let _ = self.0.insert(extension_name, state);
    }

    /// An implementation of `RequestConnection::extension_information()`.
    ///
    /// The given connection is used for sending a `QueryExtension` request if needed.
    pub fn extension_information<C: RequestConnection>(
        &mut self,
        conn: &C,
        extension_name: &'static str,
    ) -> Result<Option<ExtensionInformation>, ConnectionError> {
        let _guard = crate::debug_span!("extension_information", extension_name).entered();
        let entry = self.prefetch_extension_information_aux(conn, extension_name)?;
        match entry {
            CheckState::Prefetched(sequence_number) => {
                crate::debug!(
                    "Waiting for QueryInfo reply for '{}' extension",
                    extension_name
                );
                match Cookie::<C, QueryExtensionReply>::new(conn, *sequence_number).reply() {
                    Err(err) => {
                        crate::warning!(
                            "Got error {:?} for QueryInfo reply for '{}' extension",
                            err,
                            extension_name
                        );
                        *entry = CheckState::Error;
                        match err {
                            ReplyError::ConnectionError(e) => Err(e),
                            // The X11 protocol specification does not specify any error
                            // for the QueryExtension request, so this should not happen.
                            ReplyError::X11Error(_) => Err(ConnectionError::UnknownError),
                        }
                    }
                    Ok(info) => {
                        if info.present {
                            let info = ExtensionInformation {
                                major_opcode: info.major_opcode,
                                first_event: info.first_event,
                                first_error: info.first_error,
                            };
                            crate::debug!("Extension '{}' is present: {:?}", extension_name, info);
                            *entry = CheckState::Present(info);
                            Ok(Some(info))
                        } else {
                            crate::debug!("Extension '{}' is not present", extension_name);
                            *entry = CheckState::Missing;
                            Ok(None)
                        }
                    }
                }
            }
            CheckState::Present(info) => Ok(Some(*info)),
            CheckState::Missing => Ok(None),
            CheckState::Error => Err(ConnectionError::UnknownError),
        }
    }
}

impl ExtInfoProvider for ExtensionManager {
    fn get_from_major_opcode(&self, major_opcode: u8) -> Option<(&str, ExtensionInformation)> {
        self.0
            .iter()
            .filter_map(|(name, state)| {
                if let CheckState::Present(info) = state {
                    Some((*name, *info))
                } else {
                    None
                }
            })
            .find(|(_, info)| info.major_opcode == major_opcode)
    }

    fn get_from_event_code(&self, event_code: u8) -> Option<(&str, ExtensionInformation)> {
        self.0
            .iter()
            .filter_map(|(name, state)| {
                if let CheckState::Present(info) = state {
                    if info.first_event <= event_code {
                        Some((*name, *info))
                    } else {
                        None
                    }
                } else {
                    None
                }
            })
            .max_by_key(|(_, info)| info.first_event)
    }

    fn get_from_error_code(&self, error_code: u8) -> Option<(&str, ExtensionInformation)> {
        self.0
            .iter()
            .filter_map(|(name, state)| {
                if let CheckState::Present(info) = state {
                    if info.first_error <= error_code {
                        Some((*name, *info))
                    } else {
                        None
                    }
                } else {
                    None
                }
            })
            .max_by_key(|(_, info)| info.first_error)
    }
}

#[cfg(test)]
mod test {
    use std::cell::RefCell;
    use std::io::IoSlice;

    use crate::connection::{BufWithFds, ReplyOrError, RequestConnection, RequestKind};
    use crate::cookie::{Cookie, CookieWithFds, VoidCookie};
    use crate::errors::{ConnectionError, ParseError};
    use crate::utils::RawFdContainer;
    use crate::x11_utils::{ExtInfoProvider, ExtensionInformation, TryParse, TryParseFd};
    use x11rb_protocol::{DiscardMode, SequenceNumber};

    use super::{CheckState, ExtensionManager};

    struct FakeConnection(RefCell<SequenceNumber>);

    impl RequestConnection for FakeConnection {
        type Buf = Vec<u8>;

        fn send_request_with_reply<R>(
            &self,
            _bufs: &[IoSlice<'_>],
            _fds: Vec<RawFdContainer>,
        ) -> Result<Cookie<'_, Self, R>, ConnectionError>
        where
            R: TryParse,
        {
            Ok(Cookie::new(self, 1))
        }

        fn send_request_with_reply_with_fds<R>(
            &self,
            _bufs: &[IoSlice<'_>],
            _fds: Vec<RawFdContainer>,
        ) -> Result<CookieWithFds<'_, Self, R>, ConnectionError>
        where
            R: TryParseFd,
        {
            unimplemented!()
        }

        fn send_request_without_reply(
            &self,
            _bufs: &[IoSlice<'_>],
            _fds: Vec<RawFdContainer>,
        ) -> Result<VoidCookie<'_, Self>, ConnectionError> {
            unimplemented!()
        }

        fn discard_reply(&self, _sequence: SequenceNumber, _kind: RequestKind, _mode: DiscardMode) {
            unimplemented!()
        }

        fn prefetch_extension_information(
            &self,
            _extension_name: &'static str,
        ) -> Result<(), ConnectionError> {
            unimplemented!();
        }

        fn extension_information(
            &self,
            _extension_name: &'static str,
        ) -> Result<Option<ExtensionInformation>, ConnectionError> {
            unimplemented!()
        }

        fn wait_for_reply_or_raw_error(
            &self,
            sequence: SequenceNumber,
        ) -> Result<ReplyOrError<Vec<u8>>, ConnectionError> {
            // Code should only ask once for the reply to a request. Check that this is the case
            // (by requiring monotonically increasing sequence numbers here).
            let mut last = self.0.borrow_mut();
            assert!(
                *last < sequence,
                "Last sequence number that was awaited was {}, but now {}",
                *last,
                sequence
            );
            *last = sequence;
            // Then return an error, because that's what the #[test] below needs.
            Err(ConnectionError::UnknownError)
        }

        fn wait_for_reply(
            &self,
            _sequence: SequenceNumber,
        ) -> Result<Option<Vec<u8>>, ConnectionError> {
            unimplemented!()
        }

        fn wait_for_reply_with_fds_raw(
            &self,
            _sequence: SequenceNumber,
        ) -> Result<ReplyOrError<BufWithFds<Vec<u8>>, Vec<u8>>, ConnectionError> {
            unimplemented!()
        }

        fn check_for_raw_error(
            &self,
            _sequence: SequenceNumber,
        ) -> Result<Option<Vec<u8>>, ConnectionError> {
            unimplemented!()
        }

        fn maximum_request_bytes(&self) -> usize {
            0
        }

        fn prefetch_maximum_request_bytes(&self) {
            unimplemented!()
        }

        fn parse_error(&self, _error: &[u8]) -> Result<crate::x11_utils::X11Error, ParseError> {
            unimplemented!()
        }

        fn parse_event(&self, _event: &[u8]) -> Result<crate::protocol::Event, ParseError> {
            unimplemented!()
        }
    }

    #[test]
    fn test_double_await() {
        let conn = FakeConnection(RefCell::new(0));
        let mut ext_info = ExtensionManager::default();

        // Ask for an extension info. FakeConnection will return an error.
        match ext_info.extension_information(&conn, "whatever") {
            Err(ConnectionError::UnknownError) => {}
            r => panic!("Unexpected result: {:?}", r),
        }

        // Ask again for the extension information. ExtensionInformation should not try to get the
        // reply again, because that would just hang. Once upon a time, this caused a hang.
        match ext_info.extension_information(&conn, "whatever") {
            Err(ConnectionError::UnknownError) => {}
            r => panic!("Unexpected result: {:?}", r),
        }
    }

    #[test]
    fn test_info_provider() {
        let info = ExtensionInformation {
            major_opcode: 4,
            first_event: 5,
            first_error: 6,
        };

        let mut ext_info = ExtensionManager::default();
        let _ = ext_info.0.insert("prefetched", CheckState::Prefetched(42));
        let _ = ext_info.0.insert("present", CheckState::Present(info));
        let _ = ext_info.0.insert("missing", CheckState::Missing);
        let _ = ext_info.0.insert("error", CheckState::Error);

        assert_eq!(ext_info.get_from_major_opcode(4), Some(("present", info)));
        assert_eq!(ext_info.get_from_event_code(5), Some(("present", info)));
        assert_eq!(ext_info.get_from_error_code(6), Some(("present", info)));
    }
}