SPB Git

Repository Public

feeds.rs 8.8 KB 224 lines rust

1//! Sitemaps XML (urlset, sitemapindex) et flux RSS/Atom. Lecture en flux, bornée, sans DTD ni entité externe2//! (quick-xml ne résout jamais d'entités externes ; les entités inconnues sont ignorées).34use quick_xml::events::Event;5use quick_xml::Reader;67#[derive(Debug, Default, PartialEq)]8pub struct Listing {9    pub urls: Vec<String>,10    pub sitemaps: Vec<String>,11    pub truncated: bool,12}1314fn local(name: &str) -> &str {15    match name.rfind(':') {16        Some(i) => &name[i + 1..],17        None => name,18    }19}2021/// Analyse un sitemap ou un index de sitemaps. `max` borne le nombre d'entrées retenues ; la profondeur est bornée.22pub fn parse_sitemap(bytes: &[u8], max: usize) -> Listing {23    let text = String::from_utf8_lossy(bytes);24    let bytes: &str = &text;25    let mut out = Listing::default();26    let mut reader = Reader::from_str(bytes);27    let mut in_loc = false;28    let mut in_sitemap = false;29    let mut depth = 0u32;30    let mut cur = String::new();31    loop {32        match reader.read_event() {33            Ok(Event::Start(e)) => {34                depth += 1;35                if depth > 16 {36                    break;37                }38                match local(e.name().as_ref()) {39                    "sitemap" => in_sitemap = true,40                    "loc" => {41                        in_loc = true;42                        cur.clear();43                    }44                    _ => {}45                }46            }47            Ok(Event::End(e)) => {48                depth = depth.saturating_sub(1);49                match local(e.name().as_ref()) {50                    "sitemap" => in_sitemap = false,51                    "loc" => {52                        in_loc = false;53                        let u = cur.trim().to_string();54                        if !u.is_empty() && u.len() <= 1024 {55                            if out.urls.len() + out.sitemaps.len() >= max {56                                out.truncated = true;57                                break;58                            }59                            if in_sitemap {60                                out.sitemaps.push(u);61                            } else {62                                out.urls.push(u);63                            }64                        }65                    }66                    _ => {}67                }68            }69            Ok(Event::Text(t)) if in_loc => {70                if cur.len() < 2048 {71                    cur.push_str(&t.as_ref().to_string().replace("&amp;", "&"));72                }73            }74            Ok(Event::CData(t)) if in_loc => {75                if cur.len() < 2048 {76                    cur.push_str(&t.as_ref().to_string());77                }78            }79            Ok(Event::GeneralRef(r)) if in_loc => {80                if r.as_ref() == "amp" {81                    cur.push('&');82                }83            }84            Ok(Event::Eof) => break,85            Ok(Event::DocType(_)) => {} // DTD ignorée86            Ok(_) => {}87            Err(_) => break, // XML invalide : on garde ce qui a été lu88        }89    }90    out91}9293/// Liens d'articles d'un flux RSS 2.0 (`<item><link>`) ou Atom (`<entry><link href>`).94pub fn parse_feed(bytes: &[u8], max: usize) -> Vec<String> {95    let text = String::from_utf8_lossy(bytes);96    let bytes: &str = &text;97    let mut out = Vec::new();98    let mut reader = Reader::from_str(bytes);99    let mut in_item = false;100    let mut in_link = false;101    let mut cur = String::new();102    let mut depth = 0u32;103    loop {104        let ev = reader.read_event();105        match ev {106            Ok(Event::Start(ref e)) | Ok(Event::Empty(ref e)) => {107                let empty = matches!(ev, Ok(Event::Empty(_)));108                if !empty {109                    depth += 1;110                    if depth > 16 {111                        break;112                    }113                }114                match local(e.name().as_ref()) {115                    "item" | "entry" => in_item = true,116                    "link" if in_item => {117                        let mut href = None;118                        let mut rel_ok = true;119                        for a in e.attributes().flatten() {120                            match a.key.as_ref() {121                                "href" => href = Some(a.value.replace("&amp;", "&")),122                                "rel" => rel_ok = a.value.as_ref() == "alternate",123                                _ => {}124                            }125                        }126                        match href {127                            Some(h) if rel_ok => {128                                if out.len() < max {129                                    out.push(h);130                                }131                            }132                            Some(_) => {}133                            None if !empty => {134                                in_link = true;135                                cur.clear();136                            }137                            None => {}138                        }139                    }140                    _ => {}141                }142            }143            Ok(Event::End(e)) => {144                depth = depth.saturating_sub(1);145                match local(e.name().as_ref()) {146                    "item" | "entry" => in_item = false,147                    "link" if in_link => {148                        in_link = false;149                        let u = cur.trim().to_string();150                        if !u.is_empty() && u.len() <= 1024 && out.len() < max {151                            out.push(u);152                        }153                    }154                    _ => {}155                }156            }157            Ok(Event::Text(t)) if in_link => {158                if cur.len() < 2048 {159                    cur.push_str(&t.as_ref().to_string().replace("&amp;", "&"));160                }161            }162            Ok(Event::CData(t)) if in_link => cur.push_str(&t.as_ref().to_string()),163            Ok(Event::GeneralRef(r)) if in_link => {164                if r.as_ref() == "amp" {165                    cur.push('&');166                }167            }168            Ok(Event::Eof) => break,169            Ok(_) => {}170            Err(_) => break,171        }172        if out.len() >= max {173            break;174        }175    }176    out177}178179#[cfg(test)]180mod tests {181    use super::*;182    #[test]183    fn urlset_and_index() {184        let x = br#"<?xml version="1.0"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">185<url><loc>https://example.org/a?x=1&amp;y=2</loc><lastmod>2026-01-01</lastmod></url>186<url><loc><![CDATA[https://example.org/b]]></loc></url></urlset>"#;187        let l = parse_sitemap(x, 100);188        assert_eq!(l.urls, vec!["https://example.org/a?x=1&y=2", "https://example.org/b"]);189        let idx = br#"<sitemapindex><sitemap><loc>https://example.org/s1.xml</loc></sitemap><sitemap><loc>https://example.org/s2.xml</loc></sitemap></sitemapindex>"#;190        let l = parse_sitemap(idx, 100);191        assert_eq!(l.sitemaps.len(), 2);192        assert!(l.urls.is_empty());193    }194    #[test]195    fn bounded_and_hostile() {196        let mut big = String::from("<urlset>");197        for i in 0..5000 {198            big.push_str(&format!("<url><loc>https://example.org/{}</loc></url>", i));199        }200        big.push_str("</urlset>");201        let l = parse_sitemap(big.as_bytes(), 100);202        assert_eq!(l.urls.len(), 100);203        assert!(l.truncated);204        // XXE : l'entité externe n'est jamais résolue205        let xxe = br#"<?xml version="1.0"?><!DOCTYPE x [<!ENTITY e SYSTEM "file:///etc/passwd">]><urlset><url><loc>https://example.org/&e;</loc></url></urlset>"#;206        let l = parse_sitemap(xxe, 10);207        assert!(l.urls.iter().all(|u| !u.contains("root:")));208        // milliard de rires : pas d'expansion209        let lol = br#"<!DOCTYPE l [<!ENTITY a "aaaaaaaaaa"><!ENTITY b "&a;&a;&a;&a;&a;&a;&a;&a;">]><urlset><url><loc>https://example.org/&b;</loc></url></urlset>"#;210        let l = parse_sitemap(lol, 10);211        assert!(l.urls.iter().all(|u| u.len() < 100));212        assert_eq!(parse_sitemap(b"<urlset><url><loc>https://example.org/ok</loc></url><url><loc>bris", 10).urls.len(), 1);213        let deep = format!("{}<loc>x</loc>", "<a>".repeat(1000));214        assert!(parse_sitemap(deep.as_bytes(), 10).urls.is_empty());215    }216    #[test]217    fn feeds() {218        let rss = br#"<rss><channel><link>https://example.org/</link><item><title>t</title><link>https://example.org/1</link></item><item><link>https://example.org/2?a=1&amp;b=2</link></item></channel></rss>"#;219        assert_eq!(parse_feed(rss, 10), vec!["https://example.org/1", "https://example.org/2?a=1&b=2"]);220        let atom = br#"<feed xmlns="http://www.w3.org/2005/Atom"><link href="https://example.org/"/><entry><link rel="alternate" href="https://example.org/e1"/><link rel="edit" href="https://example.org/edit"/></entry></feed>"#;221        assert_eq!(parse_feed(atom, 10), vec!["https://example.org/e1"]);222    }223}224
Files main
Menu

Theme