lune-tty 0.1.0

A GPU-accelerated Wayland terminal emulator for Linux
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
//! Lightweight OpenSSH `~/.ssh/config` host parser and launch-argument builder
//! for opening dedicated SSH tabs directly from Lune.

use std::collections::HashSet;
use std::env;
use std::ffi::OsString;
use std::fs;
use std::path::{Path, PathBuf};

use super::session::SshSession;

const MAX_INCLUDE_DEPTH: usize = 4;

#[derive(Clone, Debug, PartialEq, Eq)]
pub(in crate::desktop) struct SshConfigHost {
    pub(in crate::desktop) alias: String,
    pub(in crate::desktop) hostname: Option<String>,
    pub(in crate::desktop) user: Option<String>,
    pub(in crate::desktop) port: Option<String>,
}

impl SshConfigHost {
    pub(in crate::desktop) fn detail(&self) -> String {
        let mut out = String::new();
        if let Some(user) = &self.user {
            out.push_str(user);
            out.push('@');
        }
        if let Some(host) = &self.hostname {
            out.push_str(host);
        } else {
            out.push_str(&self.alias);
        }
        if let Some(port) = &self.port
            && port != "22"
        {
            out.push(':');
            out.push_str(port);
        }
        out
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(in crate::desktop) struct SshLaunchSpec {
    pub(in crate::desktop) destination: String,
    pub(in crate::desktop) user: Option<String>,
    pub(in crate::desktop) port: Option<String>,
    pub(in crate::desktop) config_file: Option<PathBuf>,
    pub(in crate::desktop) identity_file: Option<PathBuf>,
}

impl SshLaunchSpec {
    pub(in crate::desktop) fn from_session(session: &SshSession) -> Self {
        Self {
            destination: session.destination.clone(),
            user: session.user.clone(),
            port: session.port.clone(),
            config_file: session.config_file.clone(),
            identity_file: None,
        }
    }

    pub(in crate::desktop) fn from_alias(alias: String) -> Self {
        Self {
            destination: alias,
            user: None,
            port: None,
            config_file: None,
            identity_file: None,
        }
    }

    /// Parses a free-form user input such as `user@host`, `alias`, or
    /// `user@host -p 2222 -i ~/.ssh/id_ed25519` into a launch spec.
    pub(in crate::desktop) fn parse_user_input(raw: &str) -> Option<Self> {
        let mut tokens: Vec<&str> = raw.split_whitespace().collect();
        if tokens.is_empty() {
            return None;
        }
        if tokens.first().copied() == Some("ssh") {
            tokens.remove(0);
        }
        let mut destination: Option<String> = None;
        let mut user: Option<String> = None;
        let mut port: Option<String> = None;
        let mut config_file: Option<PathBuf> = None;
        let mut identity_file: Option<PathBuf> = None;

        let mut i = 0;
        while i < tokens.len() {
            let tok = tokens[i];
            i += 1;
            match tok {
                "-p" => {
                    port = Some(tokens.get(i)?.to_string());
                    i += 1;
                }
                "-l" => {
                    user = Some(tokens.get(i)?.to_string());
                    i += 1;
                }
                "-F" => {
                    config_file = Some(PathBuf::from(tokens.get(i)?));
                    i += 1;
                }
                "-i" => {
                    identity_file = Some(PathBuf::from(tokens.get(i)?));
                    i += 1;
                }
                "--" => {
                    if destination.is_none() {
                        destination = Some(tokens.get(i)?.to_string());
                    }
                    break;
                }
                other if !other.starts_with('-') && destination.is_none() => {
                    destination = Some(other.to_owned());
                }
                _ => {}
            }
        }

        let destination = destination.filter(|d| !d.is_empty())?;
        Some(Self {
            destination,
            user,
            port,
            config_file,
            identity_file,
        })
    }

    pub(in crate::desktop) fn display_label(&self) -> String {
        if let Some(user) = &self.user
            && !self.destination.contains('@')
        {
            format!("{user}@{}", self.destination)
        } else {
            self.destination.clone()
        }
    }

    pub(in crate::desktop) fn build_argv(&self, control_socket: Option<&Path>) -> Vec<OsString> {
        let mut argv = Vec::with_capacity(14);
        argv.push(OsString::from("ssh"));
        if let Some(sock) = control_socket {
            argv.push(OsString::from("-o"));
            argv.push(OsString::from("ControlMaster=auto"));
            argv.push(OsString::from("-o"));
            let mut cp = OsString::from("ControlPath=");
            cp.push(sock.as_os_str());
            argv.push(cp);
            argv.push(OsString::from("-o"));
            argv.push(OsString::from("ControlPersist=no"));
        }
        if let Some(cfg) = &self.config_file {
            argv.push(OsString::from("-F"));
            argv.push(cfg.as_os_str().to_owned());
        }
        if let Some(id) = &self.identity_file {
            argv.push(OsString::from("-i"));
            argv.push(id.as_os_str().to_owned());
        }
        if let Some(port) = &self.port {
            argv.push(OsString::from("-p"));
            argv.push(OsString::from(port));
        }
        if let Some(user) = &self.user {
            argv.push(OsString::from("-l"));
            argv.push(OsString::from(user));
        }
        argv.push(OsString::from("--"));
        argv.push(OsString::from(&self.destination));
        argv
    }
}

/// Loads concrete (non-wildcard) `Host` entries from `~/.ssh/config` and any
/// included sub-configs.
pub(in crate::desktop) fn load_ssh_config_hosts() -> Vec<SshConfigHost> {
    let Some(home) = env::var_os("HOME").map(PathBuf::from) else {
        return Vec::new();
    };
    let ssh_dir = home.join(".ssh");
    let config_path = ssh_dir.join("config");
    let mut hosts = Vec::new();
    let mut seen_aliases = HashSet::new();
    let mut visited_files = HashSet::new();
    parse_config_file(
        &config_path,
        &ssh_dir,
        &home,
        0,
        &mut visited_files,
        &mut seen_aliases,
        &mut hosts,
    );
    hosts
}

fn parse_config_file(
    path: &Path,
    ssh_dir: &Path,
    home: &Path,
    depth: usize,
    visited_files: &mut HashSet<PathBuf>,
    seen_aliases: &mut HashSet<String>,
    hosts: &mut Vec<SshConfigHost>,
) {
    if depth > MAX_INCLUDE_DEPTH {
        return;
    }
    let canonical = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
    if !visited_files.insert(canonical) {
        return;
    }
    let Ok(content) = fs::read_to_string(path) else {
        return;
    };
    parse_config_text(
        &content,
        ssh_dir,
        home,
        depth,
        visited_files,
        seen_aliases,
        hosts,
    );
}

fn parse_config_text(
    content: &str,
    ssh_dir: &Path,
    home: &Path,
    depth: usize,
    visited_files: &mut HashSet<PathBuf>,
    seen_aliases: &mut HashSet<String>,
    hosts: &mut Vec<SshConfigHost>,
) {
    let mut current_indices: Vec<usize> = Vec::new();
    for raw_line in content.lines() {
        let line = strip_comment(raw_line).trim();
        if line.is_empty() {
            continue;
        }
        let Some((keyword, value)) = split_keyword_value(line) else {
            continue;
        };
        if keyword.eq_ignore_ascii_case("include") {
            for pattern in value.split_whitespace() {
                for included in expand_include_pattern(pattern, ssh_dir, home) {
                    parse_config_file(
                        &included,
                        ssh_dir,
                        home,
                        depth + 1,
                        visited_files,
                        seen_aliases,
                        hosts,
                    );
                }
            }
        } else if keyword.eq_ignore_ascii_case("host") {
            current_indices.clear();
            for token in value.split_whitespace() {
                let alias = token.trim_matches('"');
                if alias.is_empty()
                    || alias.starts_with('!')
                    || alias.contains('*')
                    || alias.contains('?')
                {
                    continue;
                }
                if seen_aliases.insert(alias.to_owned()) {
                    let idx = hosts.len();
                    hosts.push(SshConfigHost {
                        alias: alias.to_owned(),
                        hostname: None,
                        user: None,
                        port: None,
                    });
                    current_indices.push(idx);
                }
            }
        } else if keyword.eq_ignore_ascii_case("match") {
            current_indices.clear();
        } else if !current_indices.is_empty() {
            let val = value.trim().trim_matches('"');
            if val.is_empty() {
                continue;
            }
            if keyword.eq_ignore_ascii_case("hostname") {
                for &idx in &current_indices {
                    if hosts[idx].hostname.is_none() {
                        hosts[idx].hostname = Some(val.to_owned());
                    }
                }
            } else if keyword.eq_ignore_ascii_case("user") {
                for &idx in &current_indices {
                    if hosts[idx].user.is_none() {
                        hosts[idx].user = Some(val.to_owned());
                    }
                }
            } else if keyword.eq_ignore_ascii_case("port") {
                for &idx in &current_indices {
                    if hosts[idx].port.is_none() {
                        hosts[idx].port = Some(val.to_owned());
                    }
                }
            }
        }
    }
}

fn strip_comment(line: &str) -> &str {
    let mut in_quotes = false;
    for (idx, ch) in line.char_indices() {
        match ch {
            '"' => in_quotes = !in_quotes,
            '#' if !in_quotes => return &line[..idx],
            _ => {}
        }
    }
    line
}

fn split_keyword_value(line: &str) -> Option<(&str, &str)> {
    let eq = line.find('=');
    let ws = line.find(char::is_whitespace);
    let split = match (eq, ws) {
        (Some(e), Some(w)) => e.min(w),
        (Some(e), None) => e,
        (None, Some(w)) => w,
        (None, None) => return None,
    };
    let keyword = line[..split].trim();
    let rest = line[split + 1..].trim_start_matches([' ', '\t', '=']);
    if keyword.is_empty() || rest.is_empty() {
        return None;
    }
    Some((keyword, rest))
}

fn expand_include_pattern(pattern: &str, ssh_dir: &Path, home: &Path) -> Vec<PathBuf> {
    let unquoted = pattern.trim_matches('"');
    let expanded = if let Some(rest) = unquoted.strip_prefix("~/") {
        home.join(rest)
    } else if Path::new(unquoted).is_absolute() {
        PathBuf::from(unquoted)
    } else {
        ssh_dir.join(unquoted)
    };

    let Some(file_name) = expanded.file_name().and_then(|n| n.to_str()) else {
        return Vec::new();
    };
    if !file_name.contains('*') && !file_name.contains('?') {
        return if expanded.is_file() {
            vec![expanded]
        } else {
            Vec::new()
        };
    }

    let Some(parent) = expanded.parent() else {
        return Vec::new();
    };
    let Ok(read_dir) = fs::read_dir(parent) else {
        return Vec::new();
    };
    let mut matches: Vec<PathBuf> = read_dir
        .flatten()
        .map(|entry| entry.path())
        .filter(|path| {
            path.is_file()
                && path
                    .file_name()
                    .and_then(|n| n.to_str())
                    .is_some_and(|name| simple_glob_match(file_name, name))
        })
        .collect();
    matches.sort();
    matches
}

fn simple_glob_match(pattern: &str, text: &str) -> bool {
    let p: Vec<char> = pattern.chars().collect();
    let t: Vec<char> = text.chars().collect();
    let (mut pi, mut ti) = (0usize, 0usize);
    let mut star: Option<(usize, usize)> = None;
    while ti < t.len() {
        if pi < p.len() && (p[pi] == '?' || p[pi] == t[ti]) {
            pi += 1;
            ti += 1;
        } else if pi < p.len() && p[pi] == '*' {
            star = Some((pi, ti));
            pi += 1;
        } else if let Some((s_pi, s_ti)) = star {
            pi = s_pi + 1;
            ti = s_ti + 1;
            star = Some((s_pi, ti));
        } else {
            return false;
        }
    }
    while pi < p.len() && p[pi] == '*' {
        pi += 1;
    }
    pi == p.len()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_ssh_config_hosts_skipping_wildcards_and_formatting_details() {
        let sample = r#"
# Global defaults
Host *
    ServerAliveInterval 60

Host prod-api prod-alias
    HostName 10.20.30.40
    User deploy
    Port 2222

Host dev-box
    HostName=10.20.30.41
    User=alice
    Port=22

Host *.internal !bastion
    User ops
"#;
        let mut visited = HashSet::new();
        let mut seen = HashSet::new();
        let mut hosts = Vec::new();
        parse_config_text(
            sample,
            Path::new("/tmp"),
            Path::new("/tmp"),
            0,
            &mut visited,
            &mut seen,
            &mut hosts,
        );
        assert_eq!(hosts.len(), 3);
        assert_eq!(hosts[0].alias, "prod-api");
        assert_eq!(hosts[0].detail(), "deploy@10.20.30.40:2222");
        assert_eq!(hosts[1].alias, "prod-alias");
        assert_eq!(hosts[1].detail(), "deploy@10.20.30.40:2222");
        assert_eq!(hosts[2].alias, "dev-box");
        assert_eq!(hosts[2].detail(), "alice@10.20.30.41");
    }

    #[test]
    fn parses_user_input_and_builds_multiplexed_ssh_argv() {
        let spec = SshLaunchSpec::parse_user_input("ssh alice@10.0.0.5 -p 2200").unwrap();
        assert_eq!(spec.destination, "alice@10.0.0.5");
        assert_eq!(spec.port.as_deref(), Some("2200"));
        assert_eq!(spec.display_label(), "alice@10.0.0.5");

        let argv: Vec<String> = spec
            .build_argv(Some(Path::new("/tmp/lune-ssh/p2-1.sock")))
            .into_iter()
            .map(|s| s.to_string_lossy().into_owned())
            .collect();
        assert_eq!(
            argv,
            vec![
                "ssh",
                "-o",
                "ControlMaster=auto",
                "-o",
                "ControlPath=/tmp/lune-ssh/p2-1.sock",
                "-o",
                "ControlPersist=no",
                "-p",
                "2200",
                "--",
                "alice@10.0.0.5",
            ]
        );
        assert!(SshLaunchSpec::parse_user_input("   ").is_none());
    }
}