aboutsummaryrefslogtreecommitdiffstats
path: root/src/main.rs
blob: d0dbf8fa9902921084a48815ed68a0624f32edf1 (plain) (blame)
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
use as_raw_xcb_connection::ValidConnection;
use pam::Client;
use xcb::Xid;
use xcb::x;
use xkbcommon::xkb;
use xkbcommon::xkb::keysyms;

fn get_username() -> String {
    std::env::var("USER")
        .or_else(|_| std::env::var("LOGNAME"))
        .unwrap_or_else(|_| "root".to_string())
}

fn authenticate(username: &str, password: &str) -> bool {
    let mut client = match Client::with_password("login") {
        Ok(c) => c,
        Err(_) => return false,
    };
    client
        .conversation_mut()
        .set_credentials(username, password);
    client.authenticate().is_ok() && client.open_session().is_ok()
}

fn main() -> xcb::Result<()> {
    let username = get_username();
    let mut password_buf = String::new();

    let (conn, screen_num) = xcb::Connection::connect(None)?;

    let xkb_cookie = conn.send_request(&xcb::xkb::UseExtension {
        wanted_major: xkb::x11::MIN_MAJOR_XKB_VERSION,
        wanted_minor: xkb::x11::MIN_MINOR_XKB_VERSION,
    });
    let xkb_reply: xcb::xkb::UseExtensionReply = conn.wait_for_reply(xkb_cookie)?;
    if !xkb_reply.supported() {
        eprintln!("XKB extension not supported");
        return Ok(());
    }

    // make keymap
    let raw = conn.get_raw_conn();
    let raw_conn = unsafe { ValidConnection::new(raw as *mut _) };

    let context = xkb::Context::new(xkb::CONTEXT_NO_FLAGS);
    let device_id = xkb::x11::get_core_keyboard_device_id(&raw_conn);
    let keymap = xkb::x11::keymap_new_from_device(
        &context,
        &raw_conn,
        device_id,
        xkb::KEYMAP_COMPILE_NO_FLAGS,
    );
    let mut state = xkb::x11::state_new_from_device(&keymap, &raw_conn, device_id);

    let setup = conn.get_setup();
    let screen = setup.roots().nth(screen_num as usize).unwrap();

    let window: x::Window = conn.generate_id();

    let cookie = conn.send_request_checked(&x::CreateWindow {
        depth: x::COPY_FROM_PARENT as u8,
        wid: window,
        parent: screen.root(),
        x: 0,
        y: 0,
        width: screen.width_in_pixels(),
        height: screen.height_in_pixels(),
        border_width: 0,
        class: x::WindowClass::InputOutput,
        visual: screen.root_visual(),
        value_list: &[
            x::Cw::BackPixel(screen.black_pixel()),
            x::Cw::OverrideRedirect(true),
            x::Cw::EventMask(
                x::EventMask::EXPOSURE
                    | x::EventMask::KEY_PRESS
                    | x::EventMask::BUTTON_PRESS
                    | x::EventMask::POINTER_MOTION,
            ),
        ],
    });
    conn.check_request(cookie)?;

    conn.send_request(&x::MapWindow { window });
    conn.flush()?;

    let grab_keyboard = conn.send_request(&x::GrabKeyboard {
        owner_events: false,
        grab_window: window,
        time: x::CURRENT_TIME,
        pointer_mode: x::GrabMode::Async,
        keyboard_mode: x::GrabMode::Async,
    });

    let reply = conn.wait_for_reply(grab_keyboard)?;
    if reply.status() != x::GrabStatus::Success {
        eprintln!("Failed to grab keyboard");
        return Ok(());
    }

    let grab_pointer = conn.send_request(&x::GrabPointer {
        owner_events: false,
        grab_window: window,
        event_mask: x::EventMask::BUTTON_PRESS | x::EventMask::POINTER_MOTION,
        pointer_mode: x::GrabMode::Async,
        keyboard_mode: x::GrabMode::Async,
        confine_to: x::Window::none(),
        cursor: x::Cursor::none(),
        time: x::CURRENT_TIME,
    });

    let reply = conn.wait_for_reply(grab_pointer)?;
    if reply.status() != x::GrabStatus::Success {
        eprintln!("Failed to grab pointer");
        return Ok(());
    }

    // We enter the main event loop
    loop {
        match conn.wait_for_event()? {
            xcb::Event::X(x::Event::KeyPress(ev)) => {
                let keycode = ev.detail();
                state.update_key(keycode.into(), xkb::KeyDirection::Down);

                let keysym = state.key_get_one_sym(keycode.into());
                let c = xkb::keysym_to_utf8(keysym);
                match keysym.raw() {
                    keysyms::KEY_Return => {
                        if authenticate(&username, &password_buf) {
                            conn.send_request(&x::UngrabKeyboard {
                                time: x::CURRENT_TIME,
                            });
                            conn.send_request(&x::UngrabPointer {
                                time: x::CURRENT_TIME,
                            });
                            conn.flush()?;
                            break Ok(());
                        } else {
                            eprintln!("Authentication failed");
                            password_buf.clear();
                        }
                    }

                    keysyms::KEY_BackSpace => {
                        password_buf.pop();
                    }

                    keysyms::KEY_Escape => {
                        password_buf.clear();
                    }

                    _ => {
                        if !c.is_empty() {
                            password_buf.push_str(&c);
                        }
                    }
                }
            }
            xcb::Event::X(x::Event::KeyRelease(ev)) => {
                let keycode = ev.detail();
                state.update_key(keycode.into(), xkb::KeyDirection::Up);
            }
            _ => {}
        }
    }
}