feedparser_rs/parser/mod.rs
1pub mod atom;
2mod common;
3mod context;
4mod detect;
5mod itunes;
6pub mod json;
7mod media;
8pub mod rss;
9pub mod rss10;
10
11use crate::{
12 error::{FeedError, Result},
13 types::{FeedVersion, ParsedFeed},
14 util::encoding::decode_document,
15};
16
17pub use detect::detect_format;
18use detect::{Detected, detect};
19
20/// Parse feed from raw bytes
21///
22/// This is the main entry point for parsing feeds. It automatically detects
23/// the feed format (RSS, Atom, JSON) and parses accordingly. Uses
24/// [`crate::ParseOptions::default`], which sanitizes HTML content and resolves
25/// relative URIs.
26///
27/// # Errors
28///
29/// Returns a `FeedError` if the feed cannot be parsed. However, in most cases,
30/// the parser will set the `bozo` flag and return partial results rather than
31/// returning an error.
32///
33/// # Examples
34///
35/// ```
36/// use feedparser_rs::parse;
37///
38/// let xml = r#"
39/// <?xml version="1.0"?>
40/// <rss version="2.0">
41/// <channel>
42/// <title>Example Feed</title>
43/// </channel>
44/// </rss>
45/// "#;
46///
47/// let feed = parse(xml.as_bytes()).unwrap();
48/// assert_eq!(feed.feed.title.as_deref(), Some("Example Feed"));
49/// ```
50pub fn parse(data: &[u8]) -> Result<ParsedFeed> {
51 parse_with_options(data, &crate::ParseOptions::default())
52}
53
54/// Parse feed with custom parser limits
55///
56/// This allows controlling resource usage when parsing untrusted feeds. HTML
57/// sanitization and relative URI resolution use their [`crate::ParseOptions::default`]
58/// settings (both enabled); use [`parse_with_options`] to control them directly.
59///
60/// # Examples
61///
62/// ```
63/// use feedparser_rs::{parse_with_limits, ParserLimits};
64///
65/// let xml = b"<rss version=\"2.0\"><channel><title>Test</title></channel></rss>";
66/// let limits = ParserLimits::strict();
67/// let feed = parse_with_limits(xml, limits).unwrap();
68/// ```
69///
70/// # Errors
71///
72/// Returns `FeedError::InvalidFormat` if `data` exceeds `limits.max_feed_size_bytes`,
73/// or the error of a parser that cannot continue. An unrecognized format is not an
74/// error; it sets `bozo`.
75pub fn parse_with_limits(data: &[u8], limits: crate::ParserLimits) -> Result<ParsedFeed> {
76 parse_with_options(
77 data,
78 &crate::ParseOptions {
79 limits,
80 ..crate::ParseOptions::default()
81 },
82 )
83}
84
85/// Parse feed from raw bytes with full control over parser behavior
86///
87/// This is the most flexible entry point: [`parse`] and [`parse_with_limits`] are
88/// thin wrappers around it. Controls HTML sanitization, relative URI resolution,
89/// and resource limits via [`crate::ParseOptions`].
90///
91/// The input is decoded from its BOM or XML declaration, falling back to UTF-8.
92/// A declaration that the bytes contradict, or bytes that are invalid in the
93/// chosen encoding, set `bozo`.
94///
95/// # Examples
96///
97/// ```
98/// use feedparser_rs::{parse_with_options, ParseOptions};
99///
100/// // Trust the feed source and skip sanitization
101/// let options = ParseOptions::default().with_sanitize_html(false);
102/// let xml = b"<rss version=\"2.0\"><channel><title>Test</title></channel></rss>";
103/// let feed = parse_with_options(xml, &options).unwrap();
104/// ```
105///
106/// # Errors
107///
108/// Returns `FeedError::InvalidFormat` if `data` exceeds the size limit, or the
109/// error of a parser that cannot continue. An unrecognized format is not an error;
110/// it sets `bozo`.
111pub fn parse_with_options(data: &[u8], options: &crate::ParseOptions) -> Result<ParsedFeed> {
112 parse_with_content_type(data, None, options)
113}
114
115/// Parse an already decoded string, ignoring any declared encoding.
116///
117/// Use it when the caller holds text rather than bytes, so no charset detection
118/// can misread it: an XML declaration label is ignored, one leading U+FEFF is
119/// stripped, `encoding` is `"utf-8"` and decoding never sets `bozo`. Everything
120/// else matches [`parse_with_options`].
121///
122/// # Errors
123///
124/// Same as [`parse_with_options`].
125///
126/// # Examples
127///
128/// ```
129/// use feedparser_rs::{ParseOptions, parse_str_with_options};
130///
131/// let xml = r#"<?xml version="1.0" encoding="gbk"?>
132/// <rss version="2.0"><channel><title>héllo</title></channel></rss>"#;
133/// let feed = parse_str_with_options(xml, &ParseOptions::default())?;
134/// assert_eq!(feed.feed.title.as_deref(), Some("héllo"));
135/// assert_eq!(feed.encoding, "utf-8");
136/// # Ok::<(), feedparser_rs::FeedError>(())
137/// ```
138pub fn parse_str_with_options(text: &str, options: &crate::ParseOptions) -> Result<ParsedFeed> {
139 check_input_size(text.len(), options)?;
140 let feed = parse_decoded(text.trim_prefix('\u{FEFF}').as_bytes(), options)?;
141 Ok(finish(feed, "utf-8".to_string(), None, options))
142}
143
144/// [`parse_with_options`] with the HTTP `Content-Type` header taking part in decoding.
145pub fn parse_with_content_type(
146 data: &[u8],
147 content_type: Option<&str>,
148 options: &crate::ParseOptions,
149) -> Result<ParsedFeed> {
150 check_input_size(data.len(), options)?;
151 let decoded = decode_document(data, content_type);
152 let feed = parse_decoded(decoded.text.as_bytes(), options)?;
153 Ok(finish(
154 feed,
155 decoded.encoding.name(),
156 decoded.problem(),
157 options,
158 ))
159}
160
161/// Rejects oversized input before any work is spent on it.
162fn check_input_size(len: usize, options: &crate::ParseOptions) -> Result<()> {
163 options
164 .limits
165 .check_feed_size(len)
166 .map_err(|e| FeedError::InvalidFormat(e.to_string()))
167}
168
169/// Applies what every entry point adds on top of the format parser.
170fn finish(
171 mut feed: ParsedFeed,
172 encoding: String,
173 decoding_problem: Option<String>,
174 options: &crate::ParseOptions,
175) -> ParsedFeed {
176 feed.encoding = encoding;
177
178 if let Some(problem) = decoding_problem {
179 feed.bozo = true;
180 feed.bozo_exception.get_or_insert(problem);
181 }
182
183 if options.sanitize_html {
184 crate::util::sanitize::sanitize_feed(&mut feed, &options.limits);
185 }
186
187 feed
188}
189
190/// Detects the format of UTF-8 `data` and runs the matching parser.
191fn parse_decoded(data: &[u8], options: &crate::ParseOptions) -> Result<ParsedFeed> {
192 let limits = options.limits;
193 let resolve_relative_uris = options.resolve_relative_uris;
194 // Detection needs UTF-8 input (required for correct UTF-16 handling).
195 match detect(data) {
196 // RSS variants (all use RSS 2.0 parser; overwrite version after parsing)
197 Detected::Rss(dialect) => {
198 let mut parsed = rss::parse_rss20_with_options(data, limits, resolve_relative_uris)?;
199 parsed.version = dialect.version();
200 Ok(parsed)
201 }
202
203 Detected::Atom(_) => atom::parse_atom10_with_options(data, limits, resolve_relative_uris),
204
205 // RSS 1.0 and 0.90 (RDF)
206 Detected::Rdf(dialect) => {
207 let mut parsed = rss10::parse_rss10_with_options(data, limits, resolve_relative_uris)?;
208 parsed.version = dialect.version();
209 Ok(parsed)
210 }
211
212 // JSON Feed: `resolve_relative_uris` is intentionally not threaded through
213 // here — the JSON Feed parser does not resolve relative URIs against a
214 // base URL at all (JSON Feed has no `xml:base`-equivalent concept), so
215 // there is nothing for the option to gate.
216 Detected::JsonFeed(_) => json::parse_json_feed_with_limits(data, limits),
217
218 // Unknown format - return a bozo feed since the format is unrecognized.
219 // The bozo pattern requires we never panic and always return partial data,
220 // but unrecognizable input must signal the caller via bozo=true.
221 Detected::Unrecognized => {
222 let mut feed = ParsedFeed::new();
223 feed.version = FeedVersion::Unknown;
224 feed.bozo = true;
225 feed.bozo_exception = Some("Feed format not recognized".to_string());
226 Ok(feed)
227 }
228 }
229}
230
231#[cfg(test)]
232mod tests {
233 use super::*;
234
235 #[test]
236 fn test_parse_returns_ok_bozo_for_garbage() {
237 let feed = parse(b"test").unwrap();
238 assert!(feed.bozo, "unrecognized input must set bozo");
239 assert_eq!(feed.version, crate::types::FeedVersion::Unknown);
240 assert!(feed.entries.is_empty());
241 }
242
243 #[test]
244 fn test_rss091n_version_string() {
245 // #283: RSS 0.91 with Netscape DOCTYPE must report "rss091n"
246 let xml = br#"<?xml version="1.0"?>
247<!DOCTYPE rss PUBLIC "-//Netscape Communications//DTD RSS 0.91//EN"
248 "http://my.netscape.com/publish/formats/rss-0.91.dtd">
249<rss version="0.91">
250<channel><title>T</title><link>http://example.com</link><description>D</description>
251<language>en</language></channel></rss>"#;
252 let feed = parse(xml).unwrap();
253 assert_eq!(feed.version.as_str(), "rss091n");
254 }
255
256 #[test]
257 fn test_rss091u_version_string() {
258 // #283: RSS 0.91 without Netscape DOCTYPE must report "rss091u"
259 let xml = br#"<?xml version="1.0"?>
260<rss version="0.91">
261<channel><title>T</title><link>http://example.com</link><description>D</description>
262<language>en</language></channel></rss>"#;
263 let feed = parse(xml).unwrap();
264 assert_eq!(feed.version.as_str(), "rss091u");
265 }
266
267 #[test]
268 fn test_rss092_version_string() {
269 // #283: RSS 0.92 feeds must report version "rss092", not "rss20"
270 let xml = br#"<?xml version="1.0"?>
271<rss version="0.92">
272<channel><title>T</title><link>http://example.com</link><description>D</description>
273</channel></rss>"#;
274 let feed = parse(xml).unwrap();
275 assert_eq!(feed.version.as_str(), "rss092");
276 }
277
278 #[test]
279 fn test_rss20_version_string_unchanged() {
280 // #283: RSS 2.0 feeds must still report version "rss20"
281 let xml = br#"<?xml version="1.0"?>
282<rss version="2.0">
283<channel><title>T</title><link>http://example.com</link><description>D</description>
284</channel></rss>"#;
285 let feed = parse(xml).unwrap();
286 assert_eq!(feed.version.as_str(), "rss20");
287 }
288}
289
290#[cfg(test)]
291#[path = "../../tests/internal/decode_acceptance.rs"]
292mod decode_acceptance;