Skip to main content

feedparser_rs/
lib.rs

1// Regression guard for issue #456/#460: parser helpers were refactored to keep
2// every function under clippy's default 7-argument threshold via XmlCtx/EntryCtx/*Ctx
3// context structs. `forbid` (not `deny`) so a future `#[allow(clippy::too_many_arguments)]`
4// can't silently opt back out. A crate-level attribute (not a Cargo.toml lints table
5// entry) so `[lints] workspace = true` keeps inheriting the full workspace rust+clippy
6// lint sets unmodified — this crate has no proc-macro-generated `#[allow(clippy::all)]`
7// (unlike feedparser-rs-node's `#[napi]`), so `forbid` is safe here.
8#![forbid(clippy::too_many_arguments)]
9#![forbid(unsafe_code)]
10// Public API growth guard (#637): a public struct with all-public fields or a public enum
11// must be `#[non_exhaustive]`, or carry an `#[expect]` explaining why it is deliberately closed.
12#![warn(clippy::exhaustive_structs, clippy::exhaustive_enums)]
13
14//! # feedparser-rs: High-performance RSS/Atom/JSON Feed parser
15//!
16//! A pure Rust implementation of feed parsing with API compatibility for Python's
17//! [feedparser](https://github.com/kurtmckee/feedparser) library. Designed for
18//! 10-100x faster feed parsing with identical behavior.
19//!
20//! ## Quick Start
21//!
22//! ```
23//! use feedparser_rs::parse;
24//!
25//! let xml = r#"
26//!     <?xml version="1.0"?>
27//!     <rss version="2.0">
28//!         <channel>
29//!             <title>Example Feed</title>
30//!             <link>https://example.com</link>
31//!             <item>
32//!                 <title>First Post</title>
33//!                 <link>https://example.com/post/1</link>
34//!             </item>
35//!         </channel>
36//!     </rss>
37//! "#;
38//!
39//! let feed = parse(xml.as_bytes()).unwrap();
40//! assert!(!feed.bozo);
41//! assert_eq!(feed.feed.title.as_deref(), Some("Example Feed"));
42//! assert_eq!(feed.entries.len(), 1);
43//! ```
44//!
45//! ## Supported Formats
46//!
47//! | Format | Versions | Detection |
48//! |--------|----------|-----------|
49//! | RSS | 0.91 - 0.94, 2.x | `<rss>` element |
50//! | RSS 1.0, 0.90 | RDF-based | `<rdf:RDF>` root |
51//! | Atom | 0.3, 1.0 | `<feed>` with Atom namespace |
52//! | JSON Feed | 1.0, 1.1 | `version` field equal to `https://jsonfeed.org/version/1` or `https://jsonfeed.org/version/1.1` |
53//!
54//! ## Namespace Extensions
55//!
56//! The parser supports common feed extensions:
57//!
58//! - **iTunes/Podcast** (`itunes:`) - Podcast metadata, categories, explicit flags
59//! - **Podcast 2.0** (`podcast:`) - Transcripts, chapters, funding, persons
60//! - **Dublin Core** (`dc:`) - Creator, date, rights, subject
61//! - **Media RSS** (`media:`) - Thumbnails, content, descriptions
62//! - **Content** (`content:encoded`) - Full HTML content
63//! - **Syndication** (`sy:`) - Update frequency hints
64//! - **`GeoRSS`** (`georss:`) - Geographic coordinates
65//! - **Creative Commons** (`cc:`, `creativeCommons:`) - License information
66//!
67//! ## Type-Safe URL and MIME Handling
68//!
69//! The library uses semantic newtypes for improved type safety:
70//!
71//! ```
72//! use feedparser_rs::{Url, MimeType, Email};
73//!
74//! // Url - wraps URL strings without validation (bozo-compatible)
75//! let url = Url::new("https://example.com/feed.xml");
76//! assert_eq!(url.as_str(), "https://example.com/feed.xml");
77//! assert!(url.starts_with("https://")); // Deref to str
78//!
79//! // MimeType - uses Arc<str> for efficient cloning
80//! let mime = MimeType::new("application/rss+xml");
81//! let clone = mime.clone(); // Cheap: just increments refcount
82//!
83//! // Email - wraps email addresses
84//! let email = Email::new("author@example.com");
85//! ```
86//!
87//! These types implement <code>[`Deref`](std::ops::Deref)&lt;Target=str&gt;</code>, so string methods work directly:
88//!
89//! ```
90//! use feedparser_rs::Url;
91//!
92//! let url = Url::new("https://example.com/path?query=1");
93//! assert!(url.contains("example.com"));
94//! assert_eq!(url.len(), 32);
95//! ```
96//!
97//! ## The Bozo Pattern
98//!
99//! Following Python feedparser's philosophy, this library **never panics** on
100//! malformed input. Instead, it sets the `bozo` flag and continues parsing:
101//!
102//! ```
103//! use feedparser_rs::parse;
104//!
105//! // XML with undefined entity - triggers bozo
106//! let xml_with_entity = b"<rss version='2.0'><channel><title>Test &#xFFFF;</title></channel></rss>";
107//!
108//! let feed = parse(xml_with_entity).unwrap();
109//! // Parser handles invalid characters gracefully
110//! assert!(feed.feed.title.is_some());
111//! ```
112//!
113//! The bozo flag indicates the feed had issues but was still parseable.
114//!
115//! ## Resource Limits
116//!
117//! Protect against malicious feeds with [`ParserLimits`]:
118//!
119//! ```
120//! use feedparser_rs::{parse_with_limits, ParserLimits};
121//!
122//! // Customize limits for untrusted input
123//! let limits = ParserLimits::default()
124//!     .with_max_entries(100)
125//!     .with_max_text_length(50_000);
126//!
127//! let xml = b"<rss version='2.0'><channel><title>Safe</title></channel></rss>";
128//! let feed = parse_with_limits(xml, limits).unwrap();
129//! ```
130//!
131//! ## HTTP Fetching
132//!
133//! With the `http` feature (enabled by default), fetch feeds from URLs:
134//!
135//! ```no_run
136//! use feedparser_rs::parse_url;
137//!
138//! // Simple fetch
139//! let feed = parse_url("https://example.com/feed.xml", None, None, None)?;
140//!
141//! // With conditional GET for caching
142//! let feed2 = parse_url(
143//!     "https://example.com/feed.xml",
144//!     feed.etag.as_deref(),      // ETag from previous fetch
145//!     feed.modified.as_deref(),  // Last-Modified from previous fetch
146//!     Some("MyApp/1.0"),         // Custom User-Agent
147//! )?;
148//!
149//! if feed2.status == Some(304) {
150//!     println!("Feed not modified since last fetch");
151//! }
152//! # Ok::<(), feedparser_rs::FeedError>(())
153//! ```
154//!
155//! ## Core Types
156//!
157//! - [`ParsedFeed`] - Complete parsed feed with metadata and entries
158//! - [`FeedMeta`] - Feed-level metadata (title, link, author, etc.)
159//! - [`Entry`] - Individual feed entry/item
160//! - [`Link`], [`Person`], [`Tag`] - Common feed elements
161//! - [`Url`], [`MimeType`], [`Email`] - Type-safe string wrappers
162//!
163//! ## Module Structure
164//!
165//! - [`types`] - All data structures for parsed feeds
166//! - [`namespace`] - Handlers for namespace extensions (iTunes, Podcast 2.0, etc.)
167//! - [`util`] - Helper functions for dates, HTML sanitization, encoding
168//! - [`compat`] - Python feedparser API compatibility layer
169//! - [`http`] - HTTP client for fetching feeds (requires `http` feature)
170
171/// Compatibility utilities for Python feedparser API
172pub mod compat;
173mod error;
174#[cfg(feature = "http")]
175/// HTTP client module for fetching feeds from URLs
176pub mod http;
177mod limits;
178/// Namespace handlers for extended feed formats
179pub mod namespace;
180mod options;
181mod parser;
182
183/// Type definitions for feed data structures
184///
185/// This module contains all the data types used to represent parsed feeds,
186/// including the main `ParsedFeed` struct and related types.
187pub mod types;
188
189/// Utility functions for feed parsing
190///
191/// This module provides helper functions for date parsing, HTML sanitization,
192/// and encoding detection that are useful for feed processing.
193pub mod util;
194
195#[cfg(feature = "http")]
196pub use error::UrlParseError;
197pub use error::{FeedError, Result, XmlParseError};
198pub use limits::{LimitError, ParserLimits};
199pub use options::ParseOptions;
200pub use parser::{
201    detect_format, parse, parse_str_with_options, parse_with_limits, parse_with_options,
202};
203pub use types::{
204    Cloud, Content, Email, Enclosure, Entry, FeedMeta, FeedVersion, Generator, Image, InReplyTo,
205    ItunesCategory, ItunesEntryMeta, ItunesFeedMeta, ItunesOwner, LimitedCollectionExt, Link,
206    MediaContent, MediaCopyright, MediaCredit, MediaRating, MediaThumbnail, MimeType, ParsedFeed,
207    Person, PodcastChapters, PodcastChat, PodcastEntryMeta, PodcastFunding, PodcastMeta,
208    PodcastPerson, PodcastSoundbite, PodcastTranscript, PodcastValue, PodcastValueRecipient,
209    PodcastValueTimeSplit, Source, Tag, TextConstruct, TextInput, TextType, Url, parse_explicit,
210};
211
212pub use namespace::syndication::{SyndicationMeta, UpdatePeriod};
213
214#[cfg(feature = "http")]
215pub use http::{FeedHttpClient, FeedHttpResponse};
216#[cfg(feature = "http")]
217pub use util::ssrf::SsrfRejection;
218
219/// Parse feed from HTTP/HTTPS URL
220///
221/// Fetches the feed from the given URL and parses it. Supports conditional GET
222/// using `ETag` and `Last-Modified` headers for bandwidth-efficient caching.
223///
224/// # Arguments
225///
226/// * `url` - HTTP or HTTPS URL to fetch
227/// * `etag` - Optional `ETag` from previous fetch for conditional GET
228/// * `modified` - Optional `Last-Modified` timestamp from previous fetch
229/// * `user_agent` - Optional custom User-Agent header
230///
231/// # Returns
232///
233/// Returns a `ParsedFeed` with HTTP metadata fields populated:
234/// - `status`: HTTP status code (200, 304, etc.)
235/// - `href`: Final URL after redirects
236/// - `etag`: `ETag` header value (for next request)
237/// - `modified`: `Last-Modified` header value (for next request)
238/// - `headers`: Full HTTP response headers
239///
240/// On 304 Not Modified, returns a feed with empty entries but status=304.
241///
242/// # Errors
243///
244/// Returns `FeedError::Fetch` with a [`http::FetchError`] if:
245/// - The URL is invalid (`InvalidUrl`) or targets a blocked address, including a
246///   redirect hop (`BlockedAddress`)
247/// - More than 10 redirects are followed (`TooManyRedirects`)
248/// - The HTTP status is 4xx or 5xx (`Status`; 304 is not an error)
249/// - The decompressed body exceeds `max_feed_size_bytes` (`BodyTooLarge`, 100 MB by default)
250/// - A conditional-request header value is invalid (`InvalidHeader`)
251/// - Any other network error occurs (`Transport`)
252///
253/// Other [`FeedError`] variants report a failure to parse the fetched body.
254///
255/// # Examples
256///
257/// ```no_run
258/// use feedparser_rs::parse_url;
259///
260/// // First fetch
261/// let feed = parse_url("https://example.com/feed.xml", None, None, None).unwrap();
262/// println!("Title: {:?}", feed.feed.title);
263/// println!("ETag: {:?}", feed.etag);
264///
265/// // Subsequent fetch with caching
266/// let feed2 = parse_url(
267///     "https://example.com/feed.xml",
268///     feed.etag.as_deref(),
269///     feed.modified.as_deref(),
270///     None
271/// ).unwrap();
272///
273/// if feed2.status == Some(304) {
274///     println!("Feed not modified, use cached version");
275/// }
276/// ```
277#[cfg(feature = "http")]
278pub fn parse_url(
279    url: &str,
280    etag: Option<&str>,
281    modified: Option<&str>,
282    user_agent: Option<&str>,
283) -> Result<ParsedFeed> {
284    parse_url_with_options(url, etag, modified, user_agent, &ParseOptions::default())
285}
286
287/// Parse feed from URL with custom parser limits
288///
289/// Like `parse_url` but allows specifying custom limits for resource control.
290/// HTML sanitization and relative URI resolution use their
291/// [`ParseOptions::default`] settings (both enabled); use
292/// [`parse_url_with_options`] to control them directly.
293///
294/// # Errors
295///
296/// Returns `FeedError::Fetch` if the request fails (see [`parse_url`]) or another
297/// [`FeedError`] if parsing fails.
298///
299/// # Examples
300///
301/// ```no_run
302/// use feedparser_rs::{parse_url_with_limits, ParserLimits};
303///
304/// let limits = ParserLimits::strict();
305/// let feed = parse_url_with_limits(
306///     "https://example.com/feed.xml",
307///     None,
308///     None,
309///     None,
310///     limits
311/// ).unwrap();
312/// ```
313#[cfg(feature = "http")]
314pub fn parse_url_with_limits(
315    url: &str,
316    etag: Option<&str>,
317    modified: Option<&str>,
318    user_agent: Option<&str>,
319    limits: ParserLimits,
320) -> Result<ParsedFeed> {
321    parse_url_with_options(
322        url,
323        etag,
324        modified,
325        user_agent,
326        &ParseOptions {
327            limits,
328            ..ParseOptions::default()
329        },
330    )
331}
332
333/// Parse feed from URL with full control over parser behavior
334///
335/// Like `parse_url` but allows specifying HTML sanitization, relative URI
336/// resolution, and resource limits via [`ParseOptions`]. The download stops once the
337/// decompressed body exceeds `options.limits.max_feed_size_bytes`.
338///
339/// The `charset` of the response `Content-Type` takes part in decoding: it ranks
340/// below a byte order mark and above the XML declaration, is ignored for JSON
341/// bodies, and gives way to UTF-8 or the XML declaration (setting `bozo`) when the
342/// bytes contradict it.
343///
344/// # Errors
345///
346/// Returns `FeedError::Fetch` if the request fails (see [`parse_url`]) or another
347/// [`FeedError`] if parsing fails.
348///
349/// # Examples
350///
351/// ```no_run
352/// use feedparser_rs::{parse_url_with_options, ParseOptions};
353///
354/// let options = ParseOptions::default().with_sanitize_html(false);
355/// let feed = parse_url_with_options(
356///     "https://example.com/feed.xml",
357///     None,
358///     None,
359///     None,
360///     &options,
361/// ).unwrap();
362/// ```
363#[cfg(feature = "http")]
364pub fn parse_url_with_options(
365    url: &str,
366    etag: Option<&str>,
367    modified: Option<&str>,
368    user_agent: Option<&str>,
369    options: &ParseOptions,
370) -> Result<ParsedFeed> {
371    let client = http::FeedHttpClient::new()?;
372    fetch_and_parse(client, url, etag, modified, user_agent, options)
373}
374
375/// Fetches through `client`, bounding the download like the parser input, and parses.
376#[cfg(feature = "http")]
377fn fetch_and_parse(
378    client: FeedHttpClient,
379    url: &str,
380    etag: Option<&str>,
381    modified: Option<&str>,
382    user_agent: Option<&str>,
383    options: &ParseOptions,
384) -> Result<ParsedFeed> {
385    let mut client = client.with_max_body_size(options.limits.max_feed_size_bytes);
386    if let Some(agent) = user_agent {
387        client = client.with_user_agent(agent.to_string());
388    }
389    let response = client.get(url, etag, modified, None)?;
390
391    if response.status == 304 {
392        return Ok(ParsedFeed {
393            status: Some(304),
394            href: Some(response.url),
395            etag: etag.map(String::from),
396            modified: modified.map(String::from),
397            #[cfg(feature = "http")]
398            headers: Some(response.headers),
399            encoding: String::from("utf-8"),
400            ..Default::default()
401        });
402    }
403
404    if let Some(status) = http::HttpStatus::new(response.status) {
405        return Err(http::FetchError::Status {
406            status,
407            url: response.url,
408        }
409        .into());
410    }
411
412    feed_from_response(response, options)
413}
414
415/// Parses a successful response and carries its HTTP metadata into the feed.
416#[cfg(feature = "http")]
417fn feed_from_response(response: FeedHttpResponse, options: &ParseOptions) -> Result<ParsedFeed> {
418    let mut feed =
419        parser::parse_with_content_type(&response.body, response.content_type.as_deref(), options)?;
420
421    feed.status = Some(response.status);
422    feed.href = Some(response.url);
423    feed.etag = response.etag;
424    feed.modified = response.last_modified;
425    feed.headers = Some(response.headers);
426
427    Ok(feed)
428}
429
430/// Parse `data` as if served with `content_type`; entry point of the `encoding` fuzz target.
431///
432/// # Errors
433///
434/// Same as [`parse_with_options`].
435#[cfg(fuzzing)]
436#[doc(hidden)]
437pub fn fuzz_parse_with_content_type(data: &[u8], content_type: Option<&str>) -> Result<ParsedFeed> {
438    parser::parse_with_content_type(data, content_type, &ParseOptions::default())
439}
440
441#[cfg(test)]
442mod tests {
443    use super::*;
444
445    #[test]
446    fn test_parse_basic() {
447        let xml = r#"
448            <?xml version="1.0"?>
449            <rss version="2.0">
450                <channel>
451                    <title>Test</title>
452                </channel>
453            </rss>
454        "#;
455
456        let result = parse(xml.as_bytes());
457        assert!(result.is_ok());
458    }
459
460    #[test]
461    fn test_parsed_feed_new() {
462        let feed = ParsedFeed::new();
463        assert_eq!(feed.encoding, "utf-8");
464        assert!(!feed.bozo);
465        assert_eq!(feed.version, FeedVersion::Unknown);
466    }
467
468    #[test]
469    fn test_feed_version_display() {
470        assert_eq!(FeedVersion::Rss20.to_string(), "rss20");
471        assert_eq!(FeedVersion::Atom10.to_string(), "atom10");
472    }
473
474    #[cfg(feature = "http")]
475    fn response(content_type: &str, body: &[u8]) -> FeedHttpResponse {
476        FeedHttpResponse {
477            status: 200,
478            url: "https://example.com/final.xml".to_string(),
479            headers: std::collections::HashMap::from([(
480                "content-type".to_string(),
481                content_type.to_string(),
482            )]),
483            body: body.to_vec(),
484            etag: Some("\"v1\"".to_string()),
485            last_modified: Some("Mon, 01 Jan 2024 00:00:00 GMT".to_string()),
486            content_type: Some(content_type.to_string()),
487        }
488    }
489
490    #[cfg(feature = "http")]
491    #[test]
492    fn test_feed_from_response_decodes_with_header_charset() -> Result<()> {
493        let body = b"<rss version=\"2.0\"><channel><title>\xF0\xD2\xC9\xD7\xC5\xD4</title></channel></rss>";
494        let content_type = "application/rss+xml; charset=koi8-r";
495        let feed = feed_from_response(response(content_type, body), &ParseOptions::default())?;
496
497        assert_eq!(feed.feed.title.as_deref(), Some("Привет"));
498        assert_eq!(feed.encoding, "koi8-r");
499        assert!(!feed.bozo);
500        assert_eq!(feed.status, Some(200));
501        assert_eq!(feed.href.as_deref(), Some("https://example.com/final.xml"));
502        assert_eq!(feed.etag.as_deref(), Some("\"v1\""));
503        assert_eq!(
504            feed.modified.as_deref(),
505            Some("Mon, 01 Jan 2024 00:00:00 GMT")
506        );
507        assert_eq!(
508            feed.headers
509                .and_then(|headers| headers.get("content-type").cloned())
510                .as_deref(),
511            Some(content_type)
512        );
513        Ok(())
514    }
515
516    #[cfg(feature = "http")]
517    #[test]
518    fn test_feed_from_response_reports_encoding_used_not_header_label() -> Result<()> {
519        let body = "<rss version=\"2.0\"><channel><title>héllo</title></channel></rss>";
520        for label in ["no-such-label", "iso-2022-kr"] {
521            let content_type = format!("text/xml; charset={label}");
522            let feed = feed_from_response(
523                response(&content_type, body.as_bytes()),
524                &ParseOptions::default(),
525            )?;
526
527            assert_eq!(feed.encoding, "utf-8", "{label}");
528            assert_eq!(feed.feed.title.as_deref(), Some("héllo"), "{label}");
529        }
530        Ok(())
531    }
532}