Skip to main content

badterm_core/
dialer.rs

1//! The dialing directory: saved BBS entries, stored as TOML, with import and
2//! export in SyncTERM `.lst`, CSV, JSON and TOML formats.
3
4use std::fmt;
5use std::fs;
6use std::path::Path;
7use std::time::{SystemTime, UNIX_EPOCH};
8
9use anyhow::{Context, Result, bail};
10use serde::{Deserialize, Serialize};
11
12use crate::ansi::Encoding;
13
14#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(rename_all = "lowercase")]
16pub enum Protocol {
17    #[default]
18    Telnet,
19    /// Telnet over TLS.
20    #[serde(rename = "telnets")]
21    TelnetS,
22    /// Plain TCP with no telnet processing.
23    Raw,
24    Ssh,
25    Rlogin,
26    /// A real modem on a serial port, dialing the entry's phone number (its
27    /// address) with the modem settings (see [`crate::modem`]).
28    Modem,
29}
30
31impl Protocol {
32    pub const ALL: [Protocol; 6] =
33        [Protocol::Telnet, Protocol::TelnetS, Protocol::Raw, Protocol::Ssh, Protocol::Rlogin, Protocol::Modem];
34
35    /// The usual port; 0 for a modem, which has none.
36    pub fn default_port(self) -> u16 {
37        match self {
38            Protocol::Telnet | Protocol::Raw => 23,
39            Protocol::TelnetS => 992,
40            Protocol::Ssh => 22,
41            Protocol::Rlogin => 513,
42            Protocol::Modem => 0,
43        }
44    }
45
46    /// SyncTERM's names for them, too.
47    pub fn name(self) -> &'static str {
48        match self {
49            Protocol::Telnet => "Telnet",
50            Protocol::TelnetS => "TelnetS",
51            Protocol::Raw => "Raw",
52            Protocol::Ssh => "SSH",
53            Protocol::Rlogin => "RLogin",
54            Protocol::Modem => "Modem",
55        }
56    }
57
58    /// Whether the connection speaks the telnet protocol.
59    pub fn is_telnet(self) -> bool {
60        matches!(self, Protocol::Telnet | Protocol::TelnetS)
61    }
62
63    fn from_name(s: &str) -> Option<Protocol> {
64        match s.trim().to_ascii_lowercase().as_str() {
65            "telnet" => Some(Protocol::Telnet),
66            "telnets" => Some(Protocol::TelnetS),
67            "raw" => Some(Protocol::Raw),
68            "ssh" | "sshna" => Some(Protocol::Ssh),
69            "rlogin" | "rloginreversed" => Some(Protocol::Rlogin),
70            "modem" | "dialup" | "serial" => Some(Protocol::Modem),
71            _ => None,
72        }
73    }
74}
75
76impl fmt::Display for Protocol {
77    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78        f.write_str(self.name())
79    }
80}
81
82#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
83#[serde(default)]
84pub struct Entry {
85    pub name: String,
86    pub host: String,
87    pub port: u16,
88    pub protocol: Protocol,
89    pub encoding: Encoding,
90    pub username: String,
91    /// Stored in plain text, as in other BBS dialers.
92    pub password: String,
93    /// Answer the BBS's login prompts with `username` and `password`.
94    #[serde(skip_serializing_if = "is_true")]
95    pub auto_login: bool,
96    pub term_type: String,
97    /// Screen size: one of [`SCREEN_MODES`].
98    #[serde(skip_serializing_if = "is_80")]
99    pub cols: u16,
100    #[serde(skip_serializing_if = "is_25")]
101    pub rows: u16,
102    /// The font, as a CTerm font ID: 0 for CP437, or an Amiga font for
103    /// Amiga BBSes.
104    #[serde(skip_serializing_if = "is_zero")]
105    pub font: u8,
106    /// iCE colors (the blink bit as a bright background) from the start:
107    /// None leaves it to the BBS (`CSI ?33h`), as before.
108    #[serde(skip_serializing_if = "Option::is_none")]
109    pub ice: Option<bool>,
110    /// Baud rate emulation: show what the BBS sends at this speed, as over
111    /// a modem (0: as fast as it arrives).
112    #[serde(skip_serializing_if = "is_zero_u32")]
113    pub baud: u32,
114    /// Phosphor mode for this system; None follows the global setting.
115    #[serde(skip_serializing_if = "Option::is_none")]
116    pub crt: Option<CrtMode>,
117    /// What the bell (Ctrl-G) does on this system; None follows the global
118    /// setting.
119    #[serde(skip_serializing_if = "Option::is_none")]
120    pub bell: Option<BellMode>,
121    /// Start capturing the session to a file as soon as it connects.
122    #[serde(skip_serializing_if = "is_false")]
123    pub capture: bool,
124    /// The capture file's name, with `{name}`, `{date}` and `{time}` filled
125    /// in; relative names are in the captures folder, and a `.txt` name
126    /// keeps only the text (see [`crate::session::CaptureKind`]). Empty for
127    /// the usual `name-date-time.ans`.
128    #[serde(skip_serializing_if = "String::is_empty")]
129    pub capture_file: String,
130    /// SSH private key to try first; otherwise the SSH agent and the usual
131    /// `~/.ssh/id_*` files are tried.
132    #[serde(skip_serializing_if = "String::is_empty")]
133    pub key_file: String,
134    pub comment: String,
135    /// The password is kept in the OS keychain rather than in `password`.
136    #[serde(skip_serializing_if = "is_false")]
137    pub keychain: bool,
138    /// Pinned entries sort ahead of the rest.
139    #[serde(skip_serializing_if = "is_false")]
140    pub pinned: bool,
141    /// Unix timestamps.
142    pub added: Option<u64>,
143    pub last_connected: Option<u64>,
144    pub calls: u32,
145}
146
147impl Default for Entry {
148    fn default() -> Self {
149        Entry {
150            name: String::new(),
151            host: String::new(),
152            port: 23,
153            protocol: Protocol::Telnet,
154            encoding: Encoding::Cp437,
155            username: String::new(),
156            password: String::new(),
157            auto_login: true,
158            term_type: "ANSI".into(),
159            cols: 80,
160            rows: 25,
161            font: 0,
162            ice: None,
163            baud: 0,
164            crt: None,
165            bell: None,
166            capture: false,
167            capture_file: String::new(),
168            key_file: String::new(),
169            comment: String::new(),
170            keychain: false,
171            pinned: false,
172            added: None,
173            last_connected: None,
174            calls: 0,
175        }
176    }
177}
178
179impl Entry {
180    /// The screen size, (columns, rows): the entry's, if it is one BadTerm
181    /// has, or 80x25.
182    pub fn screen_mode(&self) -> (u16, u16) {
183        let mode = (self.cols, self.rows);
184        if SCREEN_MODES.contains(&mode) { mode } else { SCREEN_MODES[0] }
185    }
186
187    /// Parse `telnet://host:port`, `ssh://user@host`, `host:port` or `host`
188    /// into an entry.
189    pub fn from_address(addr: &str) -> Option<Entry> {
190        let addr = addr.trim();
191        let (protocol, rest) = match addr.split_once("://") {
192            Some((scheme, rest)) => (Protocol::from_name(scheme)?, rest),
193            None => (Protocol::Telnet, addr),
194        };
195        let rest = rest.trim_end_matches('/');
196        let (username, rest) = match rest.rsplit_once('@') {
197            Some((user, host)) => (user.to_string(), host),
198            None => (String::new(), rest),
199        };
200        let (host, port) = split_host_port(rest)?;
201        let port = port.unwrap_or(protocol.default_port());
202        Some(Entry { name: host.clone(), host, port, protocol, username, added: Some(now()), ..Entry::default() })
203    }
204
205    pub fn address(&self) -> String {
206        if self.port == self.protocol.default_port() || self.protocol == Protocol::Modem {
207            self.host.clone()
208        } else if self.host.contains(':') {
209            format!("[{}]:{}", self.host, self.port)
210        } else {
211            format!("{}:{}", self.host, self.port)
212        }
213    }
214
215    fn same_system(&self, other: &Entry) -> bool {
216        self.host.eq_ignore_ascii_case(&other.host) && self.port == other.port && self.protocol == other.protocol
217    }
218
219    /// Identifies the system (protocol, host and port), e.g. for remembering
220    /// which default entries were already offered.
221    pub fn system_id(&self) -> String {
222        format!("{}://{}:{}", self.protocol.name().to_ascii_lowercase(), self.host.to_ascii_lowercase(), self.port)
223    }
224}
225
226fn is_false(b: &bool) -> bool {
227    !*b
228}
229
230fn is_true(b: &bool) -> bool {
231    *b
232}
233
234fn is_zero(n: &u8) -> bool {
235    *n == 0
236}
237
238fn is_zero_u32(n: &u32) -> bool {
239    *n == 0
240}
241
242/// The baud rates an entry can emulate; 0 is no limit.
243pub const BAUD_RATES: [u32; 11] = [0, 300, 1200, 2400, 9600, 14400, 19200, 28800, 33600, 57600, 115200];
244
245fn is_80(n: &u16) -> bool {
246    *n == 80
247}
248
249fn is_25(n: &u16) -> bool {
250    *n == 25
251}
252
253/// The screen sizes (columns, rows) an entry can ask for. Modes of 43 rows
254/// or more use the 8x8 font.
255pub const SCREEN_MODES: [(u16, u16); 6] = [(80, 25), (80, 43), (80, 50), (132, 25), (132, 37), (132, 52)];
256
257/// What the bell (Ctrl-G) does.
258#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
259#[serde(rename_all = "lowercase")]
260pub enum BellMode {
261    /// A beep.
262    #[default]
263    Sound,
264    /// The screen flashes.
265    Visual,
266    Both,
267    Off,
268}
269
270impl BellMode {
271    pub const ALL: [BellMode; 4] = [BellMode::Sound, BellMode::Visual, BellMode::Both, BellMode::Off];
272
273    pub fn name(self) -> &'static str {
274        match self {
275            BellMode::Sound => "beep",
276            BellMode::Visual => "flash",
277            BellMode::Both => "beep and flash",
278            BellMode::Off => "off",
279        }
280    }
281
282    pub fn sound(self) -> bool {
283        matches!(self, BellMode::Sound | BellMode::Both)
284    }
285
286    pub fn visual(self) -> bool {
287        matches!(self, BellMode::Visual | BellMode::Both)
288    }
289}
290
291/// "Phosphor mode": the look of a CRT, drawn by the front end.
292#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
293#[serde(rename_all = "lowercase")]
294pub enum CrtMode {
295    #[default]
296    Off,
297    /// A color CRT.
298    Color,
299    /// A green-phosphor monochrome monitor (P1).
300    Green,
301    /// An amber monochrome monitor (P3).
302    Amber,
303}
304
305impl CrtMode {
306    pub const ALL: [CrtMode; 4] = [CrtMode::Off, CrtMode::Color, CrtMode::Green, CrtMode::Amber];
307
308    pub fn next(self) -> CrtMode {
309        let i = CrtMode::ALL.iter().position(|&m| m == self).unwrap_or(0);
310        CrtMode::ALL[(i + 1) % CrtMode::ALL.len()]
311    }
312
313    pub fn name(self) -> &'static str {
314        match self {
315            CrtMode::Off => "off",
316            CrtMode::Color => "color CRT",
317            CrtMode::Green => "green screen",
318            CrtMode::Amber => "amber screen",
319        }
320    }
321}
322
323/// The entries a new directory starts with, first among them the project's
324/// own BBS. More can be added here over time: existing directories pick up
325/// new ones once (see [`Directory::offer_defaults`]).
326pub fn default_entries() -> Vec<Entry> {
327    vec![Entry {
328        name: "The Vortex BBS".into(),
329        host: "vortexbbs.com".into(),
330        port: 23,
331        protocol: Protocol::Telnet,
332        comment: "Home BBS of the BadTerm project".into(),
333        pinned: true,
334        ..Entry::default()
335    }]
336}
337
338fn split_host_port(s: &str) -> Option<(String, Option<u16>)> {
339    if s.is_empty() {
340        return None;
341    }
342    if let Some(rest) = s.strip_prefix('[') {
343        let (host, after) = rest.split_once(']')?;
344        let port = match after.strip_prefix(':') {
345            Some(p) => Some(p.parse().ok()?),
346            None => None,
347        };
348        return Some((host.to_string(), port));
349    }
350    match s.rsplit_once(':') {
351        // A bare IPv6 address has several colons and no port.
352        Some((h, p)) if !h.contains(':') => Some((h.to_string(), Some(p.parse().ok()?))),
353        _ => Some((s.to_string(), None)),
354    }
355}
356
357pub fn now() -> u64 {
358    SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
359}
360
361#[derive(Clone, Copy, Debug, PartialEq, Eq)]
362pub enum Format {
363    Toml,
364    Json,
365    /// Ours, or a list such as the Telnet BBS Guide's `bbslist.csv`.
366    Csv,
367    SyncTerm,
368    /// MagiTerm's `magiterm.ini`: SyncTERM's layout, but every entry SSH.
369    /// Import only.
370    MagiTerm,
371    /// EtherTerm's `dialdirectory.xml`. Import only.
372    EtherTerm,
373    /// NetRunner's binary `netrunner.phn`. Import only.
374    NetRunner,
375    /// Qodem's `fonebook.txt`. Import only.
376    Qodem,
377}
378
379impl Format {
380    pub fn from_path(path: &Path) -> Option<Format> {
381        let ext = path.extension()?.to_str()?.to_ascii_lowercase();
382        match ext.as_str() {
383            "toml" => Some(Format::Toml),
384            "json" => Some(Format::Json),
385            "csv" => Some(Format::Csv),
386            "ini" if path.file_stem().is_some_and(|s| s.eq_ignore_ascii_case("magiterm")) => Some(Format::MagiTerm),
387            "lst" | "ini" => Some(Format::SyncTerm),
388            "xml" => Some(Format::EtherTerm),
389            "phn" => Some(Format::NetRunner),
390            "txt" if path.file_stem().is_some_and(|s| s.eq_ignore_ascii_case("fonebook")) => Some(Format::Qodem),
391            _ => None,
392        }
393    }
394}
395
396/// How the dialing directory is listed. Pinned entries always come first.
397#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
398#[serde(rename_all = "snake_case")]
399pub enum SortOrder {
400    #[default]
401    Name,
402    /// Most recently called first.
403    LastCalled,
404    /// Most called first.
405    Calls,
406}
407
408impl SortOrder {
409    pub fn name(self) -> &'static str {
410        match self {
411            SortOrder::Name => "name",
412            SortOrder::LastCalled => "last called",
413            SortOrder::Calls => "calls",
414        }
415    }
416
417    pub fn next(self) -> SortOrder {
418        match self {
419            SortOrder::Name => SortOrder::LastCalled,
420            SortOrder::LastCalled => SortOrder::Calls,
421            SortOrder::Calls => SortOrder::Name,
422        }
423    }
424
425    fn is_default(&self) -> bool {
426        *self == SortOrder::Name
427    }
428}
429
430#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
431pub struct Directory {
432    /// How the list is shown.
433    #[serde(default, skip_serializing_if = "SortOrder::is_default")]
434    pub sort: SortOrder,
435    /// Default entries already offered to this directory (by
436    /// [`Entry::system_id`]), so one the user deleted does not come back.
437    #[serde(default, skip_serializing_if = "Vec::is_empty")]
438    pub defaults_offered: Vec<String>,
439    #[serde(default, rename = "entry")]
440    pub entries: Vec<Entry>,
441}
442
443impl Directory {
444    /// Load the directory, returning an empty one if the file does not exist.
445    pub fn load(path: &Path) -> Result<Directory> {
446        match fs::read_to_string(path) {
447            Ok(s) => toml::from_str(&s).with_context(|| format!("parsing {}", path.display())),
448            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Directory::default()),
449            Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
450        }
451    }
452
453    /// Save atomically (write to a temporary file, then rename).
454    pub fn save(&self, path: &Path) -> Result<()> {
455        if let Some(dir) = path.parent() {
456            fs::create_dir_all(dir)?;
457        }
458        let tmp = path.with_extension("toml.tmp");
459        fs::write(&tmp, toml::to_string_pretty(self)?)?;
460        fs::rename(&tmp, path).with_context(|| format!("writing {}", path.display()))
461    }
462
463    /// Pinned entries first, then by name.
464    pub fn sort(&mut self) {
465        self.entries.sort_by_key(|e| (!e.pinned, e.name.to_lowercase()));
466    }
467
468    /// Indices of the entries to list, in `self.sort` order, keeping those
469    /// whose name, address or comment contains `filter` (ignoring case).
470    pub fn view(&self, filter: &str) -> Vec<usize> {
471        let filter = filter.trim().to_lowercase();
472        let mut v: Vec<usize> = (0..self.entries.len())
473            .filter(|&i| {
474                let e = &self.entries[i];
475                filter.is_empty()
476                    || [&e.name, &e.host, &e.comment].iter().any(|f| f.to_lowercase().contains(&filter))
477                    || e.address().to_lowercase().contains(&filter)
478            })
479            .collect();
480        let name = |i: &usize| self.entries[*i].name.to_lowercase();
481        match self.sort {
482            SortOrder::Name => v.sort_by_key(|i| (!self.entries[*i].pinned, name(i))),
483            SortOrder::LastCalled => v.sort_by_key(|i| {
484                let e = &self.entries[*i];
485                (!e.pinned, std::cmp::Reverse(e.last_connected.unwrap_or(0)), name(i))
486            }),
487            SortOrder::Calls => v.sort_by_key(|i| {
488                let e = &self.entries[*i];
489                (!e.pinned, std::cmp::Reverse(e.calls), name(i))
490            }),
491        }
492        v
493    }
494
495    /// Add any default entries this directory has not been offered before.
496    /// Returns true if the directory changed and should be saved.
497    pub fn offer_defaults(&mut self) -> bool {
498        let mut changed = false;
499        for e in default_entries() {
500            let id = e.system_id();
501            if self.defaults_offered.contains(&id) {
502                continue;
503            }
504            if !self.entries.iter().any(|x| x.same_system(&e)) {
505                self.entries.push(Entry { added: Some(now()), ..e });
506            }
507            self.defaults_offered.push(id);
508            changed = true;
509        }
510        if changed {
511            self.sort();
512        }
513        changed
514    }
515
516    /// Add entries that are not already present (same host, port and
517    /// protocol). Returns how many were added.
518    pub fn merge(&mut self, new: Vec<Entry>) -> usize {
519        let mut added = 0;
520        for e in new {
521            if !self.entries.iter().any(|x| x.same_system(&e)) {
522                self.entries.push(e);
523                added += 1;
524            }
525        }
526        self.sort();
527        added
528    }
529}
530
531/// Read entries from a file, choosing the format by extension (falling back
532/// to sniffing the content).
533pub fn import(path: &Path) -> Result<Vec<Entry>> {
534    let bytes = fs::read(path).with_context(|| format!("reading {}", path.display()))?;
535    // NetRunner's phone book is binary.
536    if bytes.starts_with(NETRUNNER_MAGIC) || Format::from_path(path) == Some(Format::NetRunner) {
537        return Ok(finish_import(from_netrunner(&bytes)?));
538    }
539    // SyncTERM lists from Windows may be in a legacy code page.
540    let text = match String::from_utf8(bytes) {
541        Ok(s) => s,
542        Err(e) => crate::cp437::decode(e.as_bytes()),
543    };
544    let text = text.trim_start_matches('\u{feff}');
545    let format = Format::from_path(path).or_else(|| sniff(text));
546    let entries = match format {
547        Some(Format::Toml) => toml::from_str::<Directory>(text)?.entries,
548        Some(Format::Json) => from_json(text)?,
549        Some(Format::Csv) => from_csv(text)?,
550        Some(Format::SyncTerm) => from_syncterm(text),
551        Some(Format::MagiTerm) => from_syncterm(text)
552            .into_iter()
553            .map(|mut e| {
554                if e.protocol == Protocol::Telnet {
555                    e.protocol = Protocol::Ssh;
556                    if e.port == Protocol::Telnet.default_port() {
557                        e.port = Protocol::Ssh.default_port();
558                    }
559                }
560                e
561            })
562            .collect(),
563        Some(Format::EtherTerm) => from_etherterm(text)?,
564        Some(Format::Qodem) => from_qodem(text),
565        // Read above, as bytes.
566        Some(Format::NetRunner) => unreachable!("NetRunner phone books are read before decoding"),
567        None => bail!("unrecognized dialing directory format: {}", path.display()),
568    };
569    Ok(finish_import(entries))
570}
571
572/// Write entries to a file in the format implied by its extension.
573pub fn export(path: &Path, entries: &[Entry]) -> Result<()> {
574    let Some(format) = Format::from_path(path) else {
575        bail!("use a .lst, .csv, .json or .toml file name to choose the export format");
576    };
577    let text = match format {
578        Format::Toml => toml::to_string_pretty(&Directory { entries: entries.to_vec(), ..Directory::default() })?,
579        Format::Json => serde_json::to_string_pretty(entries)?,
580        Format::Csv => to_csv(entries)?,
581        Format::SyncTerm => to_syncterm(entries),
582        Format::MagiTerm | Format::EtherTerm | Format::NetRunner | Format::Qodem => {
583            bail!("that format can be imported, not exported")
584        }
585    };
586    fs::write(path, text).with_context(|| format!("writing {}", path.display()))
587}
588
589fn sniff(text: &str) -> Option<Format> {
590    let t = text.trim_start();
591    if is_qodem(t) {
592        Some(Format::Qodem)
593    } else if t.starts_with('{') || t.starts_with('[') && t[1..].trim_start().starts_with('{') {
594        Some(Format::Json)
595    } else if t.starts_with("<?xml") || t.starts_with("<EtherTerm") {
596        Some(Format::EtherTerm)
597    } else if t.starts_with("[[entry]]") {
598        Some(Format::Toml)
599    } else if t.starts_with('[') {
600        Some(Format::SyncTerm)
601    } else if t.lines().next().is_some_and(|l| l.contains(',')) {
602        Some(Format::Csv)
603    } else {
604        None
605    }
606}
607
608fn from_json(text: &str) -> Result<Vec<Entry>> {
609    // Accept either a bare array or our directory object.
610    match serde_json::from_str::<Vec<Entry>>(text) {
611        Ok(v) => Ok(v),
612        Err(_) => Ok(serde_json::from_str::<Directory>(text)?.entries),
613    }
614}
615
616const CSV_HEADER: [&str; 8] = ["name", "host", "port", "protocol", "encoding", "username", "term_type", "comment"];
617
618fn to_csv(entries: &[Entry]) -> Result<String> {
619    let mut w = csv::Writer::from_writer(Vec::new());
620    w.write_record(CSV_HEADER)?;
621    for e in entries {
622        w.write_record([
623            e.name.as_str(),
624            &e.host,
625            &e.port.to_string(),
626            e.protocol.name(),
627            e.encoding.name(),
628            &e.username,
629            &e.term_type,
630            &e.comment,
631        ])?;
632    }
633    Ok(String::from_utf8(w.into_inner()?)?)
634}
635
636/// Parse CSV with a header row. Columns are matched by name, so files from
637/// spreadsheets or BBS lists with extra or reordered columns still import.
638fn from_csv(text: &str) -> Result<Vec<Entry>> {
639    let mut r = csv::ReaderBuilder::new().flexible(true).trim(csv::Trim::All).from_reader(text.as_bytes());
640    let headers: Vec<String> = r.headers()?.iter().map(|h| h.to_ascii_lowercase()).collect();
641    let col = |names: &[&str]| headers.iter().position(|h| names.contains(&h.as_str()));
642    let c_name = col(&["name", "bbs", "bbs name", "system", "bbsname"]);
643    let c_host = col(&["host", "address", "hostname", "telnet", "telnetaddress"]);
644    let c_port = col(&["port", "bbsport"]);
645    // The Telnet BBS Guide's list: an SSH port, the new-user login, and
646    // details worth keeping as the comment.
647    let c_ssh_port = col(&["sshport"]);
648    let c_new_login = col(&["newlogin"]);
649    let c_details: Vec<usize> = ["software", "location", "bbssysop"].iter().filter_map(|n| col(&[n])).collect();
650    let c_proto = col(&["protocol", "type", "connectiontype"]);
651    let c_enc = col(&["encoding", "charset"]);
652    let c_user = col(&["username", "user"]);
653    let c_tt = col(&["term_type", "terminal"]);
654    let c_comment = col(&["comment", "comments", "description", "notes"]);
655    let Some(c_host) = c_host else { bail!("CSV needs a 'host' or 'address' column") };
656
657    let mut out = Vec::new();
658    for rec in r.records() {
659        let rec = rec?;
660        let get = |c: Option<usize>| c.and_then(|c| rec.get(c)).unwrap_or("").to_string();
661        let mut e = match Entry::from_address(&get(Some(c_host))) {
662            Some(e) => e,
663            None => continue,
664        };
665        if let Some(p) = c_proto.and_then(|c| rec.get(c)).and_then(Protocol::from_name) {
666            if e.port == e.protocol.default_port() {
667                e.port = p.default_port();
668            }
669            e.protocol = p;
670        }
671        if let Ok(port) = get(c_port).parse() {
672            e.port = port;
673        } else if let Ok(port) = get(c_ssh_port).parse() {
674            // Only SSH: log in as the BBS's new-user name, as it says.
675            e.protocol = Protocol::Ssh;
676            e.port = port;
677            e.username = get(c_new_login);
678        }
679        let name = get(c_name);
680        if !name.is_empty() {
681            e.name = name;
682        }
683        if get(c_enc).to_ascii_lowercase().replace('-', "") == "utf8" {
684            e.encoding = Encoding::Utf8;
685        }
686        if c_user.is_some() {
687            e.username = get(c_user);
688        }
689        let tt = get(c_tt);
690        if !tt.is_empty() {
691            e.term_type = tt;
692        }
693        e.comment = get(c_comment);
694        if e.comment.is_empty() {
695            let details: Vec<String> = c_details.iter().map(|&c| get(Some(c))).filter(|d| !d.is_empty()).collect();
696            e.comment = details.join(", ");
697        }
698        out.push(e);
699    }
700    Ok(out)
701}
702
703/// Name imported entries that have none, and date them.
704fn finish_import(entries: Vec<Entry>) -> Vec<Entry> {
705    let stamp = now();
706    entries
707        .into_iter()
708        .filter(|e| !e.host.is_empty())
709        .map(|mut e| {
710            if e.name.is_empty() {
711                e.name = e.host.clone();
712            }
713            e.added.get_or_insert(stamp);
714            e
715        })
716        .collect()
717}
718
719/// The start of a NetRunner phone book: "NetRunner Phone Book" as a Pascal
720/// string.
721const NETRUNNER_MAGIC: &[u8] = b"\x14NetRunner Phone Book";
722
723/// Parse NetRunner's `netrunner.phn`: a header, then 200 fixed records of
724/// 362 bytes, made of Pascal strings (a length byte, then up to 40
725/// characters): the name, the address (`host` or `host:port`), user name
726/// and password, then the sysop and BBS software, kept as the comment.
727/// Unused records have no name or address.
728fn from_netrunner(data: &[u8]) -> Result<Vec<Entry>> {
729    const START: usize = 48;
730    const RECORD: usize = 362;
731    if !data.starts_with(NETRUNNER_MAGIC) {
732        bail!("not a NetRunner phone book");
733    }
734    let text = |r: &[u8], at: usize| -> String {
735        let len = (r[at] as usize).min(40);
736        crate::cp437::decode(&r[at + 1..at + 1 + len]).trim().to_string()
737    };
738    let mut out = Vec::new();
739    for r in data.get(START..).unwrap_or(&[]).as_chunks::<RECORD>().0 {
740        let (name, address) = (text(r, 0), text(r, 41));
741        let Some(mut e) = Entry::from_address(&address) else { continue };
742        if !name.is_empty() {
743            e.name = name;
744        }
745        e.username = text(r, 82);
746        e.password = text(r, 123);
747        let details: Vec<String> = [text(r, 320), text(r, 279)].into_iter().filter(|d| !d.is_empty()).collect();
748        e.comment = details.join(", ");
749        out.push(e);
750    }
751    Ok(out)
752}
753
754/// Parse EtherTerm's `dialdirectory.xml`: `<BBS name=".." ip=".."
755/// port=".." protocol="TELNET|ssh" login=".." password=".." font=".." />`.
756fn from_etherterm(text: &str) -> Result<Vec<Entry>> {
757    if !text.contains("<Phonebook") && !text.contains("<BBS") {
758        bail!("not an EtherTerm dialing directory");
759    }
760    let mut out = Vec::new();
761    for tag in text.split("<BBS").skip(1) {
762        let Some(end) = tag.find('>') else { continue };
763        let attrs = xml_attributes(&tag[..end]);
764        let get =
765            |k: &str| attrs.iter().find(|(n, _)| n.eq_ignore_ascii_case(k)).map(|(_, v)| v.as_str()).unwrap_or("");
766        let Some(mut e) = Entry::from_address(get("ip")) else { continue };
767        if let Some(p) = Protocol::from_name(get("protocol")) {
768            e.protocol = p;
769            e.port = p.default_port();
770        }
771        if let Ok(port) = get("port").parse() {
772            e.port = port;
773        }
774        e.name = get("name").trim().to_string();
775        e.username = get("login").to_string();
776        e.password = get("password").to_string();
777        let font = get("font").to_ascii_lowercase();
778        e.font = match () {
779            _ if font.contains("topaz") && font.contains("plus") => 40,
780            _ if font.contains("topaz") => 42,
781            _ if font.contains("microknight") && font.contains("plus") => 39,
782            _ if font.contains("microknight") => 41,
783            _ if font.contains("noodle") => 37,
784            _ if font.contains("sooul") || font.contains("mosoul") => 38,
785            _ => 0,
786        };
787        out.push(e);
788    }
789    Ok(out)
790}
791
792/// The `name="value"` pairs of an XML tag, with entities decoded.
793fn xml_attributes(tag: &str) -> Vec<(String, String)> {
794    let mut out = Vec::new();
795    let mut rest = tag;
796    while let Some(eq) = rest.find('=') {
797        let name = rest[..eq].trim().rsplit(char::is_whitespace).next().unwrap_or("").to_string();
798        let after = rest[eq + 1..].trim_start();
799        let Some(quote) = after.chars().next().filter(|c| *c == '"' || *c == '\'') else { break };
800        let Some(close) = after[1..].find(quote) else { break };
801        out.push((name, xml_unescape(&after[1..1 + close])));
802        rest = &after[close + 2..];
803    }
804    out
805}
806
807fn xml_unescape(s: &str) -> String {
808    let mut out = String::with_capacity(s.len());
809    let mut rest = s;
810    while let Some(amp) = rest.find('&') {
811        out.push_str(&rest[..amp]);
812        let Some(semi) = rest[amp..].find(';') else { break };
813        let entity = &rest[amp + 1..amp + semi];
814        let decoded = match entity {
815            "amp" => Some('&'),
816            "lt" => Some('<'),
817            "gt" => Some('>'),
818            "quot" => Some('"'),
819            "apos" => Some('\''),
820            _ => entity
821                .strip_prefix("#x")
822                .and_then(|h| u32::from_str_radix(h, 16).ok())
823                .or_else(|| entity.strip_prefix('#').and_then(|d| d.parse().ok()))
824                .and_then(char::from_u32),
825        };
826        match decoded {
827            Some(c) => out.push(c),
828            None => out.push_str(&rest[amp..amp + semi + 1]),
829        }
830        rest = &rest[amp + semi + 1..];
831    }
832    out.push_str(rest);
833    out
834}
835
836/// Parse a SyncTERM dialing directory (`syncterm.lst`): an INI file with one
837/// section per BBS.
838/// Qodem's phone book: `[entry]` sections of `key=value` lines, after a
839/// "# Qodem Phonebook" comment.
840fn is_qodem(text: &str) -> bool {
841    text.starts_with("# Qodem") || text.lines().take(20).any(|l| l.trim() == "[entry]") && text.contains("\nmethod=")
842}
843
844/// Parse Qodem's `fonebook.txt`. Its methods are TELNET, SSH, RLOGIN,
845/// SOCKET (raw TCP) and MODEM (the address is a phone number); LOCAL and
846/// CMDLINE entries run programs and are left out. Notes span lines, from
847/// `notes=<<<END` to `END`, and become the comment.
848fn from_qodem(text: &str) -> Vec<Entry> {
849    let mut out = Vec::new();
850    let mut cur: Option<Entry> = None;
851    let mut skip = false;
852    let mut notes: Option<Vec<String>> = None;
853    let finish = |e: Option<Entry>, skip: bool, out: &mut Vec<Entry>| {
854        if let Some(mut e) = e.filter(|_| !skip) {
855            if e.port == 0 {
856                e.port = e.protocol.default_port();
857            }
858            out.push(e);
859        }
860    };
861    for line in text.lines() {
862        if let Some(n) = notes.as_mut() {
863            if line == "END" {
864                let text = notes.take().unwrap_or_default().join(" ");
865                if let Some(e) = cur.as_mut() {
866                    e.comment = text.trim().to_string();
867                }
868            } else {
869                n.push(line.trim().to_string());
870            }
871            continue;
872        }
873        let line = line.trim();
874        if line == "[entry]" {
875            finish(cur.take(), skip, &mut out);
876            cur = Some(Entry { port: 0, ..Entry::default() });
877            skip = false;
878            continue;
879        }
880        let (Some(e), Some((key, value))) = (cur.as_mut(), line.split_once('=')) else { continue };
881        let value = value.trim();
882        match key {
883            "name" => e.name = value.to_string(),
884            "address" => e.host = value.to_string(),
885            "port" => e.port = value.parse().unwrap_or(0),
886            "username" => e.username = value.to_string(),
887            "password" => e.password = value.to_string(),
888            "method" => match value {
889                "TELNET" => e.protocol = Protocol::Telnet,
890                "SSH" => e.protocol = Protocol::Ssh,
891                "RLOGIN" => e.protocol = Protocol::Rlogin,
892                "SOCKET" => e.protocol = Protocol::Raw,
893                "MODEM" => e.protocol = Protocol::Modem,
894                _ => skip = true,
895            },
896            "emulation" => match value {
897                "AVATAR" => e.encoding = Encoding::Avatar,
898                "PETSCII" => e.encoding = Encoding::Petscii,
899                "ATASCII" => e.encoding = Encoding::Atascii,
900                "L_UTF8" | "X_UTF8" => e.encoding = Encoding::Utf8,
901                _ => {}
902            },
903            "codepage" if value.eq_ignore_ascii_case("utf-8") => e.encoding = Encoding::Utf8,
904            "times_on" => e.calls = value.parse().unwrap_or(0),
905            "last_call" => e.last_connected = value.parse().ok().filter(|&t| t != 0),
906            "capture_filename" if !value.is_empty() => e.capture_file = value.to_string(),
907            "notes" if value == "<<<END" => notes = Some(Vec::new()),
908            _ => {}
909        }
910    }
911    finish(cur.take(), skip, &mut out);
912    out
913}
914
915fn from_syncterm(text: &str) -> Vec<Entry> {
916    let mut out = Vec::new();
917    let mut cur: Option<Entry> = None;
918    for line in text.lines() {
919        let line = line.trim();
920        if line.is_empty() || line.starts_with(';') || line.starts_with('#') {
921            continue;
922        }
923        if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
924            out.extend(cur.take());
925            cur = Some(Entry { name: name.to_string(), port: 0, ..Entry::default() });
926            continue;
927        }
928        let (Some(e), Some((key, value))) = (cur.as_mut(), line.split_once('=')) else { continue };
929        let value = value.trim();
930        match key.trim().to_ascii_lowercase().as_str() {
931            "address" => e.host = value.to_string(),
932            "port" => e.port = value.parse().unwrap_or(0),
933            "connectiontype" => match Protocol::from_name(value) {
934                Some(p) => e.protocol = p,
935                None => log::warn!("{}: unsupported connection type {value}", e.name),
936            },
937            "username" => e.username = value.to_string(),
938            "password" => e.password = value.to_string(),
939            "comment" => e.comment = value.to_string(),
940            "totalcalls" => e.calls = value.parse().unwrap_or(0),
941            "added" => e.added = value.parse().ok(),
942            "lastconnected" => e.last_connected = value.parse().ok().filter(|&t| t != 0),
943            _ => {}
944        }
945    }
946    out.extend(cur);
947    for e in &mut out {
948        // SyncTERM addresses may carry the port (host:port) or a URL scheme.
949        if let Some(parsed) = Entry::from_address(&e.host) {
950            if e.port == 0 && parsed.port != parsed.protocol.default_port() {
951                e.port = parsed.port;
952            }
953            e.host = parsed.host;
954        }
955        if e.port == 0 {
956            e.port = e.protocol.default_port();
957        }
958    }
959    out
960}
961
962fn to_syncterm(entries: &[Entry]) -> String {
963    let mut s = String::new();
964    for e in entries {
965        // Section names cannot contain brackets.
966        let name: String = e.name.chars().map(|c| if c == '[' || c == ']' { '_' } else { c }).collect();
967        s.push_str(&format!("[{name}]\n"));
968        s.push_str(&format!("\tAddress={}\n", e.host));
969        s.push_str(&format!("\tPort={}\n", e.port));
970        s.push_str(&format!("\tConnectionType={}\n", e.protocol.name()));
971        if let Some(t) = e.added {
972            s.push_str(&format!("\tAdded={t}\n"));
973        }
974        if let Some(t) = e.last_connected {
975            s.push_str(&format!("\tLastConnected={t}\n"));
976        }
977        s.push_str(&format!("\tTotalCalls={}\n", e.calls));
978        if !e.username.is_empty() {
979            s.push_str(&format!("\tUserName={}\n", e.username));
980        }
981        if !e.password.is_empty() {
982            s.push_str(&format!("\tPassword={}\n", e.password));
983        }
984        if !e.comment.is_empty() {
985            s.push_str(&format!("\tComment={}\n", e.comment));
986        }
987        s.push('\n');
988    }
989    s
990}
991
992#[cfg(test)]
993mod tests {
994    use super::*;
995
996    fn sample() -> Vec<Entry> {
997        vec![
998            Entry {
999                name: "Alpha BBS".into(),
1000                host: "alpha.example.org".into(),
1001                comment: "Has, commas".into(),
1002                ..Entry::default()
1003            },
1004            Entry {
1005                name: "Beta".into(),
1006                host: "beta.example.org".into(),
1007                port: 2323,
1008                crt: Some(CrtMode::Amber),
1009                ..Entry::default()
1010            },
1011        ]
1012    }
1013
1014    #[test]
1015    fn parse_addresses() {
1016        let e = Entry::from_address("telnet://bbs.example.com:2323").unwrap();
1017        assert_eq!((e.host.as_str(), e.port), ("bbs.example.com", 2323));
1018        let e = Entry::from_address("bbs.example.com").unwrap();
1019        assert_eq!(e.port, 23);
1020        let e = Entry::from_address("[::1]:23").unwrap();
1021        assert_eq!(e.host, "::1");
1022        let e = Entry::from_address("ssh://bbs.example.com").unwrap();
1023        assert_eq!((e.protocol, e.port), (Protocol::Ssh, 22));
1024        let e = Entry::from_address("ssh://guest@bbs.example.com:2222").unwrap();
1025        assert_eq!((e.username.as_str(), e.host.as_str(), e.port), ("guest", "bbs.example.com", 2222));
1026        assert!(Entry::from_address("host:notaport").is_none());
1027    }
1028
1029    #[test]
1030    fn syncterm_round_trip() {
1031        let text = to_syncterm(&sample());
1032        let back = from_syncterm(&text);
1033        assert_eq!(back.len(), 2);
1034        assert_eq!(back[1].port, 2323);
1035        assert_eq!(back[0].comment, "Has, commas");
1036    }
1037
1038    #[test]
1039    fn syncterm_real_world() {
1040        let text = "[Some BBS]\n\tAddress=bbs.example.net:2300\n\tConnectionType=Telnet\n\tScreenMode=80x25\n\
1041                    [Secure]\nAddress=s.example.net\nConnectionType=SSH\nPort=2222\n";
1042        let v = from_syncterm(text);
1043        assert_eq!((v[0].host.as_str(), v[0].port), ("bbs.example.net", 2300));
1044        assert_eq!((v[1].protocol, v[1].port), (Protocol::Ssh, 2222));
1045    }
1046
1047    #[test]
1048    fn csv_round_trip() {
1049        let text = to_csv(&sample()).unwrap();
1050        let back = from_csv(&text).unwrap();
1051        assert_eq!(back[0].name, "Alpha BBS");
1052        assert_eq!(back[0].comment, "Has, commas");
1053        assert_eq!(back[1].port, 2323);
1054    }
1055
1056    #[test]
1057    fn csv_with_foreign_columns() {
1058        let text = "BBS Name,Address,Sysop\nFoo,foo.example.com:2023,Bob\n";
1059        let v = from_csv(text).unwrap();
1060        assert_eq!((v[0].name.as_str(), v[0].port), ("Foo", 2023));
1061    }
1062
1063    #[test]
1064    fn toml_and_json_round_trip() {
1065        let d = Directory { entries: sample(), defaults_offered: vec!["telnet://x:23".into()], ..Directory::default() };
1066        let t = toml::to_string_pretty(&d).unwrap();
1067        assert_eq!(toml::from_str::<Directory>(&t).unwrap(), d);
1068        let j = serde_json::to_string(&d.entries).unwrap();
1069        assert_eq!(from_json(&j).unwrap(), d.entries);
1070    }
1071
1072    #[test]
1073    fn merge_skips_duplicates() {
1074        let mut d = Directory { entries: sample(), ..Directory::default() };
1075        let added = d.merge(sample());
1076        assert_eq!(added, 0);
1077        assert_eq!(d.entries.len(), 2);
1078    }
1079
1080    #[test]
1081    fn defaults_are_offered_once() {
1082        let mut d = Directory { entries: sample(), ..Directory::default() };
1083        assert!(d.offer_defaults());
1084        // Pinned, so first despite the name.
1085        assert_eq!(d.entries[0].host, "vortexbbs.com");
1086        assert_eq!(d.entries.len(), 3);
1087        assert!(!d.offer_defaults());
1088
1089        // Deleting it sticks, including across a save and load.
1090        d.entries.remove(0);
1091        let d: Directory = toml::from_str(&toml::to_string_pretty(&d).unwrap()).unwrap();
1092        let mut d = d;
1093        assert!(!d.offer_defaults());
1094        assert_eq!(d.entries.len(), 2);
1095    }
1096
1097    #[test]
1098    fn new_fields_are_optional_in_toml() {
1099        let d: Directory = toml::from_str("[[entry]]\nname = \"A\"\nhost = \"a.example\"\n").unwrap();
1100        assert!(!d.entries[0].pinned && !d.entries[0].keychain && d.entries[0].key_file.is_empty());
1101        let t = toml::to_string_pretty(&d).unwrap();
1102        assert!(!t.contains("pinned") && !t.contains("keychain") && !t.contains("key_file"), "{t}");
1103        assert!(d.entries[0].crt.is_none() && !t.contains("crt"), "{t}");
1104    }
1105
1106    #[test]
1107    fn crt_mode_in_toml() {
1108        let d: Directory = toml::from_str("[[entry]]\nhost = \"a.example\"\ncrt = \"green\"\n").unwrap();
1109        assert_eq!(d.entries[0].crt, Some(CrtMode::Green));
1110        assert_eq!(CrtMode::Amber.next(), CrtMode::Off);
1111    }
1112
1113    #[test]
1114    fn view_sorts_and_filters() {
1115        let mut d = Directory { entries: sample(), ..Directory::default() };
1116        d.entries[0].calls = 1;
1117        d.entries[1].calls = 5;
1118        d.entries[0].last_connected = Some(200);
1119        d.entries[1].last_connected = Some(100);
1120        assert_eq!(d.view(""), [0, 1]);
1121        d.sort = SortOrder::Calls;
1122        assert_eq!(d.view(""), [1, 0]);
1123        d.sort = SortOrder::LastCalled;
1124        assert_eq!(d.view(""), [0, 1]);
1125        // Pinned entries stay on top whatever the order.
1126        d.entries[1].pinned = true;
1127        assert_eq!(d.view(""), [1, 0]);
1128
1129        assert_eq!(d.view("ALPHA"), [0]);
1130        assert_eq!(d.view("commas"), [0]);
1131        assert_eq!(d.view(":2323"), [1]);
1132        assert!(d.view("nothing like it").is_empty());
1133
1134        let t = toml::to_string_pretty(&d).unwrap();
1135        assert!(t.contains("sort = \"last_called\""), "{t}");
1136        assert_eq!(toml::from_str::<Directory>(&t).unwrap().sort, SortOrder::LastCalled);
1137    }
1138
1139    #[test]
1140    fn telnet_bbs_guide_csv() {
1141        let text = "bbsName, bbsSysop, newLogin, TelnetAddress, bbsPort, sshPort, WebAddress, location, Modem, software\n\
1142                    13th Floor BBS,Hoy Brothers,new,13th.hoyvision.com,6400,,,\"Oak Ridge, TN, USA\",,\"Image BBS\"\n\
1143                    3D Realms,,NEW,172.0.79.226,,,,\"Cotati, CA, USA\",,\"Synchronet\"\n\
1144                    4 Wheel Ham BBS,w7jpj,NEW,bbs.4wheelham.com,,2222,,\"Littleton, CO, USA\",,\"Synchronet\"\n";
1145        let v = from_csv(text).unwrap();
1146        assert_eq!((v[0].name.as_str(), v[0].host.as_str(), v[0].port), ("13th Floor BBS", "13th.hoyvision.com", 6400));
1147        assert_eq!(v[0].comment, "Image BBS, Oak Ridge, TN, USA, Hoy Brothers");
1148        assert_eq!((v[1].protocol, v[1].port), (Protocol::Telnet, 23));
1149        assert_eq!((v[2].protocol, v[2].port, v[2].username.as_str()), (Protocol::Ssh, 2222, "NEW"));
1150    }
1151
1152    #[test]
1153    fn etherterm_and_magiterm() {
1154        let xml = r#"<?xml version="1.0" ?>
1155<EtherTerm>
1156    <Phonebook version="1.0">
1157        <BBS name="Tom &amp; Jerry&#39;s" ip="bbs.example.org" port="6523" protocol="TELNET" login="" password="" font="vga8x16.bmp" keyMap="ANSI" />
1158        <BBS name="Amiga Land (ssh)" ip="amiga.example.org" port="2222" protocol="ssh" login="guest" password="pw" font="topaz-a1200.bmp" keyMap="ANSI" />
1159    </Phonebook>
1160</EtherTerm>"#;
1161        assert_eq!(sniff(xml), Some(Format::EtherTerm));
1162        let v = from_etherterm(xml).unwrap();
1163        assert_eq!(v[0].name, "Tom & Jerry's");
1164        assert_eq!((v[0].protocol, v[0].port), (Protocol::Telnet, 6523));
1165        assert_eq!((v[1].protocol, v[1].port, v[1].username.as_str(), v[1].font), (Protocol::Ssh, 2222, "guest", 42));
1166
1167        let dir = std::env::temp_dir().join(format!("badterm-magiterm-{}", std::process::id()));
1168        std::fs::create_dir_all(&dir).unwrap();
1169        let path = dir.join("magiterm.ini");
1170        std::fs::write(
1171            &path,
1172            "[A-Net Online]\naddress = mystic-anet.online \nport = 22 \n\n[After Hours]\naddress = ah-bbs.com\n",
1173        )
1174        .unwrap();
1175        let v = import(&path).unwrap();
1176        assert_eq!((v[0].protocol, v[0].port), (Protocol::Ssh, 22));
1177        assert_eq!((v[1].protocol, v[1].port), (Protocol::Ssh, 22));
1178        assert!(export(&dir.join("out.xml"), &v).is_err());
1179        std::fs::remove_dir_all(&dir).unwrap();
1180    }
1181
1182    #[test]
1183    fn netrunner_phone_book() {
1184        let book = include_bytes!("../tests/data/netrunner.phn");
1185        let v = from_netrunner(book).unwrap();
1186        assert_eq!(v.len(), 2);
1187        assert_eq!((v[0].name.as_str(), v[0].host.as_str(), v[0].port), ("The Vortex BBS", "vortexbbs.com", 23));
1188        assert_eq!((v[0].username.as_str(), v[0].password.as_str()), ("User Here", "Password Here"));
1189        assert_eq!(v[0].comment, "Enigma 1/2, Sysop Name Here");
1190        assert_eq!((v[1].name.as_str(), v[1].host.as_str()), ("Another System", "another.com"));
1191        assert!(from_netrunner(b"not a phone book").is_err());
1192
1193        // host:port in the address, as NetRunner takes it.
1194        let mut edited = book.to_vec();
1195        let at = 48 + 41;
1196        let addr = b"bbs.example.org:2323";
1197        edited[at] = addr.len() as u8;
1198        edited[at + 1..at + 1 + addr.len()].copy_from_slice(addr);
1199        let v = from_netrunner(&edited).unwrap();
1200        assert_eq!((v[0].host.as_str(), v[0].port), ("bbs.example.org", 2323));
1201    }
1202
1203    #[test]
1204    fn imports_qodem() {
1205        let text = "# Qodem Phonebook\n#\n\n[entry]\nname=The Vortex\naddress=vortexbbs.com\nport=\n\
1206            username=guest\npassword=pw\nmethod=TELNET\nemulation=AVATAR\ncodepage=CP437\ntimes_on=7\n\
1207            last_call=1700000000\nnotes=<<<END\nBest BBS\nin town\nEND\ncapture_filename=vortex.txt\n\n\
1208            [entry]\nname=Local shell\naddress=\nmethod=LOCAL\n\n\
1209            [entry]\nname=Dial-up\naddress=555-1234\nport=\nmethod=MODEM\nemulation=ANSI\n\n\
1210            [entry]\nname=Secure\naddress=ssh.example.org\nport=2222\nmethod=SSH\nemulation=X_UTF8\n";
1211        let dir = std::env::temp_dir().join(format!("badterm-qodem-{}", std::process::id()));
1212        fs::create_dir_all(&dir).unwrap();
1213        // Found by its name, or by its content.
1214        for name in ["fonebook.txt", "phonebook"] {
1215            fs::write(dir.join(name), text).unwrap();
1216            let v = import(&dir.join(name)).unwrap();
1217            assert_eq!(v.iter().map(|e| e.name.as_str()).collect::<Vec<_>>(), ["The Vortex", "Dial-up", "Secure"]);
1218            let e = &v[0];
1219            assert_eq!(
1220                (e.host.as_str(), e.port, e.protocol, e.encoding),
1221                ("vortexbbs.com", 23, Protocol::Telnet, Encoding::Avatar)
1222            );
1223            assert_eq!((e.username.as_str(), e.password.as_str(), e.calls), ("guest", "pw", 7));
1224            assert_eq!((e.comment.as_str(), e.capture_file.as_str()), ("Best BBS in town", "vortex.txt"));
1225            assert_eq!(
1226                (v[1].protocol, v[1].host.as_str(), v[1].address()),
1227                (Protocol::Modem, "555-1234", "555-1234".into())
1228            );
1229            assert_eq!((v[2].protocol, v[2].port, v[2].encoding), (Protocol::Ssh, 2222, Encoding::Utf8));
1230        }
1231        let _ = fs::remove_dir_all(&dir);
1232    }
1233}