Skip to main content

enxame_magnet/
lib.rs

1//! Typed BitTorrent magnet links ([BEP-9] / [BEP-53]).
2//!
3//! A magnet URI identifies a swarm without a `.torrent` file:
4//! `magnet:?xt=urn:btih:<hash>&dn=<name>&tr=<tracker>&…`. This crate
5//! parses one into a typed [`Magnet`] — the `xt` exact-topic becomes a
6//! typed [`Xt`] (v1 `btih` SHA-1, or v2 `btmh` multihash), trackers and
7//! peer addresses are collected, in the pleme-io parse-don't-validate
8//! idiom. Part of the ENXAME suite (`theory/ENXAME.md`); pairs with
9//! `enxame-metainfo` (the magnet is the identity, the metainfo is the
10//! body fetched once a peer is reached).
11//!
12//! [BEP-9]: https://www.bittorrent.org/beps/bep_0009.html
13//! [BEP-53]: https://www.bittorrent.org/beps/bep_0053.html
14
15#![forbid(unsafe_code)]
16
17/// The exact-topic (`xt`) of a magnet — the swarm identity.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum Xt {
20    /// `urn:btih:` — a v1 SHA-1 info-hash (20 bytes), from 40-char hex
21    /// or 32-char base32.
22    BtihV1([u8; 20]),
23    /// `urn:btmh:` — a v2 multihash; kept raw (the leading bytes are the
24    /// multihash type + length; SHA-256 is `0x1220…`).
25    BtmhV2(Vec<u8>),
26}
27
28/// A parsed magnet link.
29#[derive(Debug, Clone, PartialEq, Eq, Default)]
30pub struct Magnet {
31    /// The exact-topics (`xt`). A hybrid magnet carries both a v1 and a
32    /// v2 topic; most carry one.
33    pub topics: Vec<Xt>,
34    /// Display name (`dn`), URL-decoded.
35    pub display_name: Option<String>,
36    /// Tracker URLs (`tr`), URL-decoded, in order.
37    pub trackers: Vec<String>,
38    /// Web seeds (`ws`, BEP-19).
39    pub web_seeds: Vec<String>,
40    /// Direct peer addresses (`x.pe`).
41    pub peers: Vec<String>,
42}
43
44impl Magnet {
45    /// The first v1 info-hash, if any.
46    #[must_use]
47    pub fn info_hash_v1(&self) -> Option<[u8; 20]> {
48        self.topics.iter().find_map(|t| match t {
49            Xt::BtihV1(h) => Some(*h),
50            Xt::BtmhV2(_) => None,
51        })
52    }
53}
54
55/// A typed magnet parse failure.
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub enum Error {
58    /// The URI didn't start with `magnet:?`.
59    NotAMagnet,
60    /// An `xt` that wasn't a recognized `urn:btih:`/`urn:btmh:` topic.
61    UnknownTopic,
62    /// A `btih` value that was neither 40-hex nor 32-base32.
63    BadBtih,
64    /// Percent-encoding that wasn't valid (`%` not followed by 2 hex).
65    BadPercentEncoding,
66}
67
68impl std::fmt::Display for Error {
69    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70        match self {
71            Error::NotAMagnet => write!(f, "not a magnet: URI"),
72            Error::UnknownTopic => write!(f, "unrecognized xt topic"),
73            Error::BadBtih => write!(f, "btih is neither 40-hex nor 32-base32"),
74            Error::BadPercentEncoding => write!(f, "invalid percent-encoding"),
75        }
76    }
77}
78
79impl std::error::Error for Error {}
80
81impl std::str::FromStr for Magnet {
82    type Err = Error;
83    fn from_str(s: &str) -> Result<Self, Error> {
84        let query = s.strip_prefix("magnet:?").ok_or(Error::NotAMagnet)?;
85        let mut magnet = Magnet::default();
86        for pair in query.split('&').filter(|p| !p.is_empty()) {
87            let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
88            // Strip `.<n>` group suffixes (e.g. `tr.1`) per the spec.
89            let key = key.split('.').next().unwrap_or(key);
90            let value = percent_decode(value)?;
91            match key {
92                "xt" => magnet.topics.push(parse_xt(&value)?),
93                "dn" => magnet.display_name = Some(value),
94                "tr" => magnet.trackers.push(value),
95                "ws" => magnet.web_seeds.push(value),
96                "x" if pair.starts_with("x.pe=") => magnet.peers.push(value),
97                _ => {} // ignore unknown params (forward-compatible)
98            }
99        }
100        if magnet.topics.is_empty() {
101            return Err(Error::UnknownTopic);
102        }
103        Ok(magnet)
104    }
105}
106
107fn parse_xt(value: &str) -> Result<Xt, Error> {
108    if let Some(rest) = value.strip_prefix("urn:btih:") {
109        parse_btih(rest).map(Xt::BtihV1)
110    } else if let Some(rest) = value.strip_prefix("urn:btmh:") {
111        // v2 multihash, hex-encoded after the urn.
112        decode_hex(rest).map(Xt::BtmhV2).ok_or(Error::UnknownTopic)
113    } else {
114        Err(Error::UnknownTopic)
115    }
116}
117
118fn parse_btih(s: &str) -> Result<[u8; 20], Error> {
119    match s.len() {
120        40 => decode_hex(s)
121            .and_then(|v| v.try_into().ok())
122            .ok_or(Error::BadBtih),
123        32 => decode_base32(s)
124            .and_then(|v| v.try_into().ok())
125            .ok_or(Error::BadBtih),
126        _ => Err(Error::BadBtih),
127    }
128}
129
130/// Decode lower/upper hex to bytes; `None` on a non-hex or odd-length
131/// input.
132fn decode_hex(s: &str) -> Option<Vec<u8>> {
133    if s.len() % 2 != 0 {
134        return None;
135    }
136    let b = s.as_bytes();
137    let mut out = Vec::with_capacity(s.len() / 2);
138    for pair in b.chunks_exact(2) {
139        let hi = hex_val(pair[0])?;
140        let lo = hex_val(pair[1])?;
141        out.push((hi << 4) | lo);
142    }
143    Some(out)
144}
145
146fn hex_val(c: u8) -> Option<u8> {
147    match c {
148        b'0'..=b'9' => Some(c - b'0'),
149        b'a'..=b'f' => Some(c - b'a' + 10),
150        b'A'..=b'F' => Some(c - b'A' + 10),
151        _ => None,
152    }
153}
154
155/// RFC 4648 base32 (no padding) — the alternate `btih` encoding.
156fn decode_base32(s: &str) -> Option<Vec<u8>> {
157    const ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
158    let mut bits: u32 = 0;
159    let mut nbits = 0u32;
160    let mut out = Vec::new();
161    for c in s.bytes() {
162        let up = c.to_ascii_uppercase();
163        let val = ALPHABET.iter().position(|&a| a == up)? as u32;
164        bits = (bits << 5) | val;
165        nbits += 5;
166        if nbits >= 8 {
167            nbits -= 8;
168            out.push((bits >> nbits) as u8);
169        }
170    }
171    Some(out)
172}
173
174/// Percent-decode a query value (`%XX` → byte; `+` is NOT a space in
175/// magnet query values per the spec).
176fn percent_decode(s: &str) -> Result<String, Error> {
177    let b = s.as_bytes();
178    let mut out = Vec::with_capacity(b.len());
179    let mut i = 0;
180    while i < b.len() {
181        if b[i] == b'%' {
182            let hi = b.get(i + 1).copied().and_then(hex_val).ok_or(Error::BadPercentEncoding)?;
183            let lo = b.get(i + 2).copied().and_then(hex_val).ok_or(Error::BadPercentEncoding)?;
184            out.push((hi << 4) | lo);
185            i += 3;
186        } else {
187            out.push(b[i]);
188            i += 1;
189        }
190    }
191    String::from_utf8(out).map_err(|_| Error::BadPercentEncoding)
192}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197
198    #[test]
199    fn parses_a_v1_hex_magnet() {
200        let uri = "magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567\
201                   &dn=Big%20Buck%20Bunny&tr=udp%3A%2F%2Ftracker.example%3A80";
202        let m: Magnet = uri.parse().unwrap();
203        assert_eq!(m.display_name.as_deref(), Some("Big Buck Bunny"));
204        assert_eq!(m.trackers, vec!["udp://tracker.example:80"]);
205        let h = m.info_hash_v1().unwrap();
206        assert_eq!(h[0], 0x01);
207        assert_eq!(h[19], 0x67);
208    }
209
210    #[test]
211    fn parses_a_base32_btih() {
212        // 32-char base32 → 20 bytes.
213        let b32 = "MFRGGZDFMZTWQ2LKNNWG23TPOBYXE43U"; // arbitrary valid base32
214        let uri = format!("magnet:?xt=urn:btih:{b32}");
215        let m: Magnet = uri.parse().unwrap();
216        assert!(matches!(m.topics[0], Xt::BtihV1(_)));
217    }
218
219    #[test]
220    fn collects_multiple_trackers_and_peers() {
221        let uri = "magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567\
222                   &tr=http%3A%2F%2Fa&tr=http%3A%2F%2Fb&x.pe=1.2.3.4%3A6881";
223        let m: Magnet = uri.parse().unwrap();
224        assert_eq!(m.trackers, vec!["http://a", "http://b"]);
225        assert_eq!(m.peers, vec!["1.2.3.4:6881"]);
226    }
227
228    #[test]
229    fn parses_a_v2_btmh_magnet() {
230        // SHA-256 multihash: 0x12 0x20 + 32 bytes.
231        let mh = "1220".to_string() + &"ab".repeat(32);
232        let uri = format!("magnet:?xt=urn:btmh:{mh}");
233        let m: Magnet = uri.parse().unwrap();
234        match &m.topics[0] {
235            Xt::BtmhV2(v) => {
236                assert_eq!(v[0], 0x12);
237                assert_eq!(v[1], 0x20);
238                assert_eq!(v.len(), 34);
239            }
240            Xt::BtihV1(_) => panic!("expected v2"),
241        }
242    }
243
244    #[test]
245    fn rejects_non_magnet_and_bad_topic() {
246        assert_eq!("http://x".parse::<Magnet>(), Err(Error::NotAMagnet));
247        assert_eq!("magnet:?dn=x".parse::<Magnet>(), Err(Error::UnknownTopic));
248        assert_eq!(
249            "magnet:?xt=urn:btih:tooshort".parse::<Magnet>(),
250            Err(Error::BadBtih)
251        );
252    }
253}