Skip to main content

fastmcp_server/providers/
filesystem.rs

1//! Filesystem resource provider.
2//!
3//! Exposes files from a directory as MCP resources with configurable
4//! patterns, security controls, and MIME type detection.
5//!
6//! # Security
7//!
8//! The provider includes path traversal protection to prevent accessing
9//! files outside the configured root directory.
10//!
11//! # Example
12//!
13//! ```ignore
14//! use fastmcp_server::providers::FilesystemProvider;
15//!
16//! let provider = FilesystemProvider::new("/data/docs")
17//!     .with_prefix("docs")
18//!     .with_patterns(&["**/*.md", "**/*.txt"])
19//!     .with_exclude(&["**/secret/**", "**/.*"])
20//!     .with_recursive(true)
21//!     .with_max_size(10 * 1024 * 1024); // 10MB limit
22//! ```
23
24use std::path::{Path, PathBuf};
25
26use fastmcp_core::{McpContext, McpError, McpOutcome, McpResult, Outcome};
27use fastmcp_protocol::{Resource, ResourceContent, ResourceTemplate};
28
29use crate::handler::{BoxFuture, ResourceHandler, UriParams};
30
31/// Default maximum file size (10 MB).
32const DEFAULT_MAX_SIZE: usize = 10 * 1024 * 1024;
33
34/// Errors that can occur when using the filesystem provider.
35#[derive(Debug, Clone)]
36pub enum FilesystemProviderError {
37    /// The requested path would escape the root directory.
38    PathTraversal { requested: String },
39    /// The file exceeds the maximum allowed size.
40    TooLarge { path: String, size: u64, max: usize },
41    /// Symlink access was denied.
42    SymlinkDenied { path: String },
43    /// Symlink target escapes the root directory.
44    SymlinkEscapesRoot { path: String },
45    /// IO error occurred.
46    Io { message: String },
47    /// File not found.
48    NotFound { path: String },
49}
50
51impl std::fmt::Display for FilesystemProviderError {
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        match self {
54            Self::PathTraversal { requested } => {
55                write!(f, "Path traversal attempt blocked: {requested}")
56            }
57            Self::TooLarge { path, size, max } => {
58                write!(f, "File too large: {path} ({size} bytes, max {max} bytes)")
59            }
60            Self::SymlinkDenied { path } => {
61                write!(f, "Symlink access denied: {path}")
62            }
63            Self::SymlinkEscapesRoot { path } => {
64                write!(f, "Symlink target escapes root directory: {path}")
65            }
66            Self::Io { message } => write!(f, "IO error: {message}"),
67            Self::NotFound { path } => write!(f, "File not found: {path}"),
68        }
69    }
70}
71
72impl std::error::Error for FilesystemProviderError {}
73
74impl From<FilesystemProviderError> for McpError {
75    fn from(err: FilesystemProviderError) -> Self {
76        match err {
77            FilesystemProviderError::PathTraversal { .. } => {
78                // Security violation - path traversal attempt
79                McpError::invalid_request(err.to_string())
80            }
81            FilesystemProviderError::TooLarge { .. } => McpError::invalid_request(err.to_string()),
82            FilesystemProviderError::SymlinkDenied { .. }
83            | FilesystemProviderError::SymlinkEscapesRoot { .. } => {
84                // Security violation - symlink escape attempt
85                McpError::invalid_request(err.to_string())
86            }
87            FilesystemProviderError::Io { .. } => McpError::internal_error(err.to_string()),
88            FilesystemProviderError::NotFound { path } => McpError::resource_not_found(&path),
89        }
90    }
91}
92
93/// A resource provider that exposes filesystem directories.
94///
95/// Files under the configured root directory are exposed as MCP resources
96/// with URIs like `file://{prefix}/{relative_path}`.
97///
98/// # Security
99///
100/// - Path traversal attempts (e.g., `../../../etc/passwd`) are blocked
101/// - Symlinks can be optionally followed or blocked
102/// - Maximum file size limits prevent memory exhaustion
103/// - Hidden files (starting with `.`) can be excluded
104///
105/// # Example
106///
107/// ```ignore
108/// use fastmcp_server::providers::FilesystemProvider;
109///
110/// let provider = FilesystemProvider::new("/app/data")
111///     .with_prefix("data")
112///     .with_patterns(&["*.json", "*.yaml"])
113///     .with_recursive(true);
114/// ```
115#[derive(Debug, Clone)]
116pub struct FilesystemProvider {
117    /// Root directory for file access.
118    root: PathBuf,
119    /// URI prefix (e.g., "docs" -> "file://docs/...").
120    prefix: Option<String>,
121    /// Glob patterns to include (empty = all files).
122    include_patterns: Vec<String>,
123    /// Glob patterns to exclude.
124    exclude_patterns: Vec<String>,
125    /// Whether to traverse subdirectories.
126    recursive: bool,
127    /// Maximum file size in bytes.
128    max_file_size: usize,
129    /// Whether to follow symlinks.
130    follow_symlinks: bool,
131    /// Description for the resource template.
132    description: Option<String>,
133}
134
135impl FilesystemProvider {
136    /// Creates a new filesystem provider for the given root directory.
137    ///
138    /// # Arguments
139    ///
140    /// * `root` - The root directory to expose
141    ///
142    /// # Example
143    ///
144    /// ```ignore
145    /// let provider = FilesystemProvider::new("/data/docs");
146    /// ```
147    #[must_use]
148    pub fn new(root: impl AsRef<Path>) -> Self {
149        Self {
150            root: root.as_ref().to_path_buf(),
151            prefix: None,
152            include_patterns: Vec::new(),
153            exclude_patterns: vec![".*".to_string()], // Exclude hidden files by default
154            recursive: false,
155            max_file_size: DEFAULT_MAX_SIZE,
156            follow_symlinks: false,
157            description: None,
158        }
159    }
160
161    /// Sets the URI prefix for resources.
162    ///
163    /// Files will have URIs like `file://{prefix}/{path}`.
164    ///
165    /// # Example
166    ///
167    /// ```ignore
168    /// let provider = FilesystemProvider::new("/data")
169    ///     .with_prefix("mydata");
170    /// // Results in URIs like file://mydata/readme.md
171    /// ```
172    #[must_use]
173    pub fn with_prefix(mut self, prefix: impl Into<String>) -> Self {
174        self.prefix = Some(prefix.into());
175        self
176    }
177
178    /// Sets glob patterns to include.
179    ///
180    /// Only files matching at least one of these patterns will be exposed.
181    /// Empty patterns means all files are included.
182    ///
183    /// # Example
184    ///
185    /// ```ignore
186    /// let provider = FilesystemProvider::new("/data")
187    ///     .with_patterns(&["*.md", "*.txt", "**/*.json"]);
188    /// ```
189    #[must_use]
190    pub fn with_patterns(mut self, patterns: &[&str]) -> Self {
191        self.include_patterns = patterns.iter().map(|s| (*s).to_string()).collect();
192        self
193    }
194
195    /// Sets glob patterns to exclude.
196    ///
197    /// Files matching any of these patterns will be excluded.
198    /// By default, hidden files (starting with `.`) are excluded.
199    ///
200    /// # Example
201    ///
202    /// ```ignore
203    /// let provider = FilesystemProvider::new("/data")
204    ///     .with_exclude(&["**/secret/**", "*.bak"]);
205    /// ```
206    #[must_use]
207    pub fn with_exclude(mut self, patterns: &[&str]) -> Self {
208        self.exclude_patterns = patterns.iter().map(|s| (*s).to_string()).collect();
209        self
210    }
211
212    /// Enables or disables recursive directory traversal.
213    ///
214    /// When enabled, files in subdirectories are also exposed.
215    ///
216    /// # Example
217    ///
218    /// ```ignore
219    /// let provider = FilesystemProvider::new("/data")
220    ///     .with_recursive(true);
221    /// ```
222    #[must_use]
223    pub fn with_recursive(mut self, enabled: bool) -> Self {
224        self.recursive = enabled;
225        self
226    }
227
228    /// Sets the maximum file size in bytes.
229    ///
230    /// Files larger than this limit will return an error when read.
231    /// Default is 10 MB.
232    ///
233    /// # Example
234    ///
235    /// ```ignore
236    /// let provider = FilesystemProvider::new("/data")
237    ///     .with_max_size(5 * 1024 * 1024); // 5 MB
238    /// ```
239    #[must_use]
240    pub fn with_max_size(mut self, bytes: usize) -> Self {
241        self.max_file_size = bytes;
242        self
243    }
244
245    /// Enables or disables following symlinks.
246    ///
247    /// When disabled (default), symlinks are not followed.
248    /// When enabled, symlinks are followed but must still point within the root directory.
249    ///
250    /// # Example
251    ///
252    /// ```ignore
253    /// let provider = FilesystemProvider::new("/data")
254    ///     .with_follow_symlinks(true);
255    /// ```
256    #[must_use]
257    pub fn with_follow_symlinks(mut self, enabled: bool) -> Self {
258        self.follow_symlinks = enabled;
259        self
260    }
261
262    /// Sets the description for the resource template.
263    ///
264    /// # Example
265    ///
266    /// ```ignore
267    /// let provider = FilesystemProvider::new("/data")
268    ///     .with_description("Documentation files");
269    /// ```
270    #[must_use]
271    pub fn with_description(mut self, description: impl Into<String>) -> Self {
272        self.description = Some(description.into());
273        self
274    }
275
276    /// Builds a resource handler from this provider.
277    ///
278    /// The returned handler can be registered with a server.
279    ///
280    /// # Example
281    ///
282    /// ```ignore
283    /// let handler = FilesystemProvider::new("/data")
284    ///     .with_prefix("docs")
285    ///     .build();
286    ///
287    /// let server = Server::new("demo", "1.0")
288    ///     .resource(handler);
289    /// ```
290    #[must_use]
291    pub fn build(self) -> FilesystemResourceHandler {
292        FilesystemResourceHandler::new(self)
293    }
294
295    /// Validates a path and returns the canonical path if valid.
296    ///
297    /// Returns an error if:
298    /// - The path is absolute
299    /// - The path escapes the root directory
300    /// - The path is a symlink and symlinks are disabled
301    fn validate_path(&self, requested: &str) -> Result<PathBuf, FilesystemProviderError> {
302        let requested_path = Path::new(requested);
303
304        // Reject absolute paths in request
305        if requested_path.is_absolute() {
306            return Err(FilesystemProviderError::PathTraversal {
307                requested: requested.to_string(),
308            });
309        }
310
311        // Build full path
312        let full_path = self.root.join(requested_path);
313
314        // Canonicalize to resolve ../ etc.
315        // Note: canonicalize requires the path to exist
316        let canonical = full_path.canonicalize().map_err(|e| {
317            if e.kind() == std::io::ErrorKind::NotFound {
318                FilesystemProviderError::NotFound {
319                    path: requested.to_string(),
320                }
321            } else {
322                FilesystemProviderError::Io {
323                    message: e.to_string(),
324                }
325            }
326        })?;
327
328        // Get canonical root for comparison
329        let canonical_root = self
330            .root
331            .canonicalize()
332            .map_err(|e| FilesystemProviderError::Io {
333                message: format!("Cannot canonicalize root: {e}"),
334            })?;
335
336        // Verify still under root
337        if !canonical.starts_with(&canonical_root) {
338            return Err(FilesystemProviderError::PathTraversal {
339                requested: requested.to_string(),
340            });
341        }
342
343        // Check symlink
344        if full_path.is_symlink() {
345            self.check_symlink(&full_path, &canonical_root)?;
346        }
347
348        Ok(canonical)
349    }
350
351    /// Checks if a symlink is allowed.
352    fn check_symlink(
353        &self,
354        path: &Path,
355        canonical_root: &Path,
356    ) -> Result<(), FilesystemProviderError> {
357        if !self.follow_symlinks {
358            return Err(FilesystemProviderError::SymlinkDenied {
359                path: path.display().to_string(),
360            });
361        }
362
363        // Verify symlink target is still under root
364        let target = std::fs::read_link(path).map_err(|e| FilesystemProviderError::Io {
365            message: e.to_string(),
366        })?;
367
368        let resolved = if target.is_absolute() {
369            target
370        } else {
371            path.parent().unwrap_or(Path::new("")).join(&target)
372        };
373
374        let canonical_target =
375            resolved
376                .canonicalize()
377                .map_err(|e| FilesystemProviderError::Io {
378                    message: e.to_string(),
379                })?;
380
381        if !canonical_target.starts_with(canonical_root) {
382            return Err(FilesystemProviderError::SymlinkEscapesRoot {
383                path: path.display().to_string(),
384            });
385        }
386
387        Ok(())
388    }
389
390    /// Checks if a filename matches the include/exclude patterns.
391    fn matches_patterns(&self, relative_path: &str) -> bool {
392        // Check exclude patterns first
393        for pattern in &self.exclude_patterns {
394            if glob_match(pattern, relative_path) {
395                return false;
396            }
397        }
398
399        // If no include patterns, include everything
400        if self.include_patterns.is_empty() {
401            return true;
402        }
403
404        // Check include patterns
405        for pattern in &self.include_patterns {
406            if glob_match(pattern, relative_path) {
407                return true;
408            }
409        }
410
411        false
412    }
413
414    /// Lists files in the directory that match patterns.
415    fn list_files(&self) -> Result<Vec<FileEntry>, FilesystemProviderError> {
416        let canonical_root = self
417            .root
418            .canonicalize()
419            .map_err(|e| FilesystemProviderError::Io {
420                message: format!("Cannot canonicalize root: {e}"),
421            })?;
422
423        let mut entries = Vec::new();
424        self.walk_directory(&canonical_root, &canonical_root, &mut entries)?;
425        Ok(entries)
426    }
427
428    /// Recursively walks a directory collecting file entries.
429    fn walk_directory(
430        &self,
431        current: &Path,
432        root: &Path,
433        entries: &mut Vec<FileEntry>,
434    ) -> Result<(), FilesystemProviderError> {
435        let read_dir = std::fs::read_dir(current).map_err(|e| FilesystemProviderError::Io {
436            message: e.to_string(),
437        })?;
438
439        for entry_result in read_dir {
440            let entry = entry_result.map_err(|e| FilesystemProviderError::Io {
441                message: e.to_string(),
442            })?;
443
444            let path = entry.path();
445            let file_type = entry.file_type().map_err(|e| FilesystemProviderError::Io {
446                message: e.to_string(),
447            })?;
448
449            // Handle symlinks
450            if file_type.is_symlink() && !self.follow_symlinks {
451                continue;
452            }
453
454            // Calculate relative path
455            let relative = path
456                .strip_prefix(root)
457                .map_err(|e| FilesystemProviderError::Io {
458                    message: e.to_string(),
459                })?;
460            let relative_str = relative.to_string_lossy().replace('\\', "/");
461
462            if file_type.is_dir() || (file_type.is_symlink() && path.is_dir()) {
463                if self.recursive {
464                    self.walk_directory(&path, root, entries)?;
465                }
466            } else if file_type.is_file() || (file_type.is_symlink() && path.is_file()) {
467                // Check patterns
468                if self.matches_patterns(&relative_str) {
469                    let metadata = std::fs::metadata(&path).ok();
470                    entries.push(FileEntry {
471                        path: path.clone(),
472                        relative_path: relative_str,
473                        size: metadata.as_ref().map(|m| m.len()),
474                        mime_type: detect_mime_type(&path),
475                    });
476                }
477            }
478        }
479
480        Ok(())
481    }
482
483    /// Returns the URI for a file.
484    fn file_uri(&self, relative_path: &str) -> String {
485        match &self.prefix {
486            Some(prefix) => format!("file://{prefix}/{relative_path}"),
487            None => format!("file://{relative_path}"),
488        }
489    }
490
491    /// Returns the URI template for this provider.
492    fn uri_template(&self) -> String {
493        match &self.prefix {
494            Some(prefix) => format!("file://{prefix}/{{path}}"),
495            None => "file://{path}".to_string(),
496        }
497    }
498
499    /// Extracts the relative path from a URI.
500    fn path_from_uri(&self, uri: &str) -> Option<String> {
501        let expected_prefix = match &self.prefix {
502            Some(p) => format!("file://{p}/"),
503            None => "file://".to_string(),
504        };
505
506        if uri.starts_with(&expected_prefix) {
507            Some(uri[expected_prefix.len()..].to_string())
508        } else {
509            None
510        }
511    }
512
513    /// Reads a file and returns its content.
514    fn read_file(&self, relative_path: &str) -> Result<FileContent, FilesystemProviderError> {
515        // Validate and get canonical path
516        let path = self.validate_path(relative_path)?;
517
518        // Check file size
519        let metadata = std::fs::metadata(&path).map_err(|e| {
520            if e.kind() == std::io::ErrorKind::NotFound {
521                FilesystemProviderError::NotFound {
522                    path: relative_path.to_string(),
523                }
524            } else {
525                FilesystemProviderError::Io {
526                    message: e.to_string(),
527                }
528            }
529        })?;
530
531        if metadata.len() > self.max_file_size as u64 {
532            return Err(FilesystemProviderError::TooLarge {
533                path: relative_path.to_string(),
534                size: metadata.len(),
535                max: self.max_file_size,
536            });
537        }
538
539        // Detect MIME type
540        let mime_type = detect_mime_type(&path);
541
542        // Read content
543        let content = if is_binary_mime_type(&mime_type) {
544            let bytes = std::fs::read(&path).map_err(|e| FilesystemProviderError::Io {
545                message: e.to_string(),
546            })?;
547            FileContent::Binary(bytes)
548        } else {
549            let text = std::fs::read_to_string(&path).map_err(|e| FilesystemProviderError::Io {
550                message: e.to_string(),
551            })?;
552            FileContent::Text(text)
553        };
554
555        Ok(content)
556    }
557}
558
559/// A file entry from directory listing.
560#[derive(Debug)]
561struct FileEntry {
562    #[allow(dead_code)]
563    path: PathBuf,
564    relative_path: String,
565    #[allow(dead_code)]
566    size: Option<u64>,
567    mime_type: String,
568}
569
570/// File content (text or binary).
571enum FileContent {
572    Text(String),
573    Binary(Vec<u8>),
574}
575
576/// Resource handler implementation for the filesystem provider.
577pub struct FilesystemResourceHandler {
578    provider: FilesystemProvider,
579    /// Cached file list for static resources.
580    cached_resources: Vec<Resource>,
581}
582
583impl FilesystemResourceHandler {
584    /// Creates a new handler from a provider.
585    fn new(provider: FilesystemProvider) -> Self {
586        // Pre-compute the list of resources
587        let cached_resources = match provider.list_files() {
588            Ok(entries) => entries
589                .into_iter()
590                .map(|entry| Resource {
591                    uri: provider.file_uri(&entry.relative_path),
592                    name: entry.relative_path.clone(),
593                    description: None,
594                    mime_type: Some(entry.mime_type),
595                    icon: None,
596                    version: None,
597                    tags: vec![],
598                })
599                .collect(),
600            Err(_) => Vec::new(),
601        };
602
603        Self {
604            provider,
605            cached_resources,
606        }
607    }
608}
609
610impl ResourceHandler for FilesystemResourceHandler {
611    fn definition(&self) -> Resource {
612        // Return a synthetic "root" resource for the provider
613        Resource {
614            uri: self.provider.uri_template(),
615            name: self
616                .provider
617                .prefix
618                .clone()
619                .unwrap_or_else(|| "files".to_string()),
620            description: self.provider.description.clone(),
621            mime_type: None,
622            icon: None,
623            version: None,
624            tags: vec![],
625        }
626    }
627
628    fn template(&self) -> Option<ResourceTemplate> {
629        Some(ResourceTemplate {
630            uri_template: self.provider.uri_template(),
631            name: self
632                .provider
633                .prefix
634                .clone()
635                .unwrap_or_else(|| "files".to_string()),
636            description: self.provider.description.clone(),
637            mime_type: None,
638            icon: None,
639            version: None,
640            tags: vec![],
641        })
642    }
643
644    fn read(&self, _ctx: &McpContext) -> McpResult<Vec<ResourceContent>> {
645        // For template resources, read() without params returns the file list
646        let files = self.provider.list_files()?;
647
648        let listing = files
649            .iter()
650            .map(|f| format!("{}: {}", f.relative_path, f.mime_type))
651            .collect::<Vec<_>>()
652            .join("\n");
653
654        Ok(vec![ResourceContent {
655            uri: self.provider.uri_template(),
656            mime_type: Some("text/plain".to_string()),
657            text: Some(listing),
658            blob: None,
659        }])
660    }
661
662    fn read_with_uri(
663        &self,
664        _ctx: &McpContext,
665        uri: &str,
666        params: &UriParams,
667    ) -> McpResult<Vec<ResourceContent>> {
668        // Extract path from URI or params
669        let relative_path = if let Some(path) = params.get("path") {
670            path.clone()
671        } else if let Some(path) = self.provider.path_from_uri(uri) {
672            path
673        } else {
674            return Err(McpError::invalid_params("Missing path parameter"));
675        };
676
677        let content = self.provider.read_file(&relative_path)?;
678
679        let resource_content = match content {
680            FileContent::Text(text) => ResourceContent {
681                uri: uri.to_string(),
682                mime_type: Some(detect_mime_type(Path::new(&relative_path))),
683                text: Some(text),
684                blob: None,
685            },
686            FileContent::Binary(bytes) => {
687                let base64_str = base64_encode(&bytes);
688
689                ResourceContent {
690                    uri: uri.to_string(),
691                    mime_type: Some(detect_mime_type(Path::new(&relative_path))),
692                    text: None,
693                    blob: Some(base64_str),
694                }
695            }
696        };
697
698        Ok(vec![resource_content])
699    }
700
701    fn read_async_with_uri<'a>(
702        &'a self,
703        ctx: &'a McpContext,
704        uri: &'a str,
705        params: &'a UriParams,
706    ) -> BoxFuture<'a, McpOutcome<Vec<ResourceContent>>> {
707        Box::pin(async move {
708            match self.read_with_uri(ctx, uri, params) {
709                Ok(v) => Outcome::Ok(v),
710                Err(e) => Outcome::Err(e),
711            }
712        })
713    }
714}
715
716impl std::fmt::Debug for FilesystemResourceHandler {
717    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
718        f.debug_struct("FilesystemResourceHandler")
719            .field("provider", &self.provider)
720            .field("cached_resources", &self.cached_resources.len())
721            .finish()
722    }
723}
724
725/// Detects the MIME type for a file based on its extension.
726fn detect_mime_type(path: &Path) -> String {
727    let extension = path
728        .extension()
729        .and_then(|e| e.to_str())
730        .map(str::to_lowercase);
731
732    match extension.as_deref() {
733        // Text formats
734        Some("txt") => "text/plain",
735        Some("md" | "markdown") => "text/markdown",
736        Some("html" | "htm") => "text/html",
737        Some("css") => "text/css",
738        Some("csv") => "text/csv",
739        Some("xml") => "application/xml",
740
741        // Programming languages
742        Some("rs") => "text/x-rust",
743        Some("py") => "text/x-python",
744        Some("js" | "mjs") => "text/javascript",
745        Some("ts" | "mts") => "text/typescript",
746        Some("json") => "application/json",
747        Some("yaml" | "yml") => "application/yaml",
748        Some("toml") => "application/toml",
749        Some("sh" | "bash") => "text/x-shellscript",
750        Some("c") => "text/x-c",
751        Some("cpp" | "cc" | "cxx") => "text/x-c++",
752        Some("h" | "hpp") => "text/x-c-header",
753        Some("java") => "text/x-java",
754        Some("go") => "text/x-go",
755        Some("rb") => "text/x-ruby",
756        Some("php") => "text/x-php",
757        Some("swift") => "text/x-swift",
758        Some("kt" | "kts") => "text/x-kotlin",
759        Some("sql") => "text/x-sql",
760
761        // Images
762        Some("png") => "image/png",
763        Some("jpg" | "jpeg") => "image/jpeg",
764        Some("gif") => "image/gif",
765        Some("svg") => "image/svg+xml",
766        Some("webp") => "image/webp",
767        Some("ico") => "image/x-icon",
768        Some("bmp") => "image/bmp",
769
770        // Binary/Documents
771        Some("pdf") => "application/pdf",
772        Some("zip") => "application/zip",
773        Some("gz" | "gzip") => "application/gzip",
774        Some("tar") => "application/x-tar",
775        Some("wasm") => "application/wasm",
776        Some("exe") => "application/octet-stream",
777        Some("dll") => "application/octet-stream",
778        Some("so") => "application/octet-stream",
779        Some("bin") => "application/octet-stream",
780
781        // Default
782        _ => "application/octet-stream",
783    }
784    .to_string()
785}
786
787/// Checks if a MIME type represents binary content.
788fn is_binary_mime_type(mime_type: &str) -> bool {
789    mime_type.starts_with("image/")
790        || mime_type.starts_with("audio/")
791        || mime_type.starts_with("video/")
792        || mime_type == "application/octet-stream"
793        || mime_type == "application/pdf"
794        || mime_type == "application/zip"
795        || mime_type == "application/gzip"
796        || mime_type == "application/x-tar"
797        || mime_type == "application/wasm"
798}
799
800/// Standard base64 alphabet.
801const BASE64_CHARS: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
802
803/// Encodes bytes to standard base64.
804fn base64_encode(data: &[u8]) -> String {
805    let mut result = String::with_capacity((data.len() + 2) / 3 * 4);
806
807    for chunk in data.chunks(3) {
808        let b0 = chunk[0] as usize;
809        let b1 = chunk.get(1).copied().unwrap_or(0) as usize;
810        let b2 = chunk.get(2).copied().unwrap_or(0) as usize;
811
812        let combined = (b0 << 16) | (b1 << 8) | b2;
813
814        result.push(BASE64_CHARS[(combined >> 18) & 0x3F] as char);
815        result.push(BASE64_CHARS[(combined >> 12) & 0x3F] as char);
816
817        if chunk.len() > 1 {
818            result.push(BASE64_CHARS[(combined >> 6) & 0x3F] as char);
819        } else {
820            result.push('=');
821        }
822
823        if chunk.len() > 2 {
824            result.push(BASE64_CHARS[combined & 0x3F] as char);
825        } else {
826            result.push('=');
827        }
828    }
829
830    result
831}
832
833/// Simple glob pattern matching.
834///
835/// Supports:
836/// - `*` - matches any sequence of characters (except `/`)
837/// - `**` - matches any sequence of characters (including `/`)
838/// - `?` - matches any single character
839fn glob_match(pattern: &str, path: &str) -> bool {
840    glob_match_recursive(pattern, path)
841}
842
843/// Recursive glob matching implementation.
844fn glob_match_recursive(pattern: &str, path: &str) -> bool {
845    let mut pattern_chars = pattern.chars().peekable();
846    let mut path_chars = path.chars().peekable();
847
848    while let Some(p) = pattern_chars.next() {
849        match p {
850            '*' => {
851                // Check for **
852                if pattern_chars.peek() == Some(&'*') {
853                    pattern_chars.next(); // consume second *
854
855                    // Skip optional / after **
856                    if pattern_chars.peek() == Some(&'/') {
857                        pattern_chars.next();
858                    }
859
860                    let remaining_pattern: String = pattern_chars.collect();
861
862                    // ** matches zero or more path segments
863                    // Try matching from current position and all subsequent positions
864                    let remaining_path: String = path_chars.collect();
865
866                    // Try matching with empty ** (zero segments)
867                    if glob_match_recursive(&remaining_pattern, &remaining_path) {
868                        return true;
869                    }
870
871                    // Try matching with ** consuming characters one at a time
872                    for i in 0..=remaining_path.len() {
873                        if glob_match_recursive(&remaining_pattern, &remaining_path[i..]) {
874                            return true;
875                        }
876                    }
877                    return false;
878                }
879
880                // Single * - match anything except /
881                let remaining_pattern: String = pattern_chars.collect();
882                let remaining_path: String = path_chars.collect();
883
884                // Try matching with * consuming 0, 1, 2, ... characters (but not /)
885                for i in 0..=remaining_path.len() {
886                    // Check if the portion we're consuming contains /
887                    if remaining_path[..i].contains('/') {
888                        break;
889                    }
890                    if glob_match_recursive(&remaining_pattern, &remaining_path[i..]) {
891                        return true;
892                    }
893                }
894                return false;
895            }
896            '?' => {
897                // Match any single character
898                if path_chars.next().is_none() {
899                    return false;
900                }
901            }
902            c => {
903                // Literal character
904                if path_chars.next() != Some(c) {
905                    return false;
906                }
907            }
908        }
909    }
910
911    // Pattern exhausted - path should also be exhausted
912    path_chars.next().is_none()
913}
914
915#[cfg(test)]
916mod tests {
917    use super::*;
918
919    #[test]
920    fn test_glob_match_star() {
921        assert!(glob_match("*.md", "readme.md"));
922        assert!(glob_match("*.md", "CHANGELOG.md"));
923        assert!(!glob_match("*.md", "readme.txt"));
924        assert!(!glob_match("*.md", "dir/readme.md")); // * doesn't match /
925    }
926
927    #[test]
928    fn test_glob_match_double_star() {
929        assert!(glob_match("**/*.md", "readme.md"));
930        assert!(glob_match("**/*.md", "docs/readme.md"));
931        assert!(glob_match("**/*.md", "docs/api/readme.md"));
932        assert!(!glob_match("**/*.md", "readme.txt"));
933    }
934
935    #[test]
936    fn test_glob_match_question() {
937        assert!(glob_match("file?.txt", "file1.txt"));
938        assert!(glob_match("file?.txt", "fileA.txt"));
939        assert!(!glob_match("file?.txt", "file12.txt"));
940    }
941
942    #[test]
943    fn test_glob_match_hidden() {
944        assert!(glob_match(".*", ".hidden"));
945        assert!(glob_match(".*", ".gitignore"));
946        assert!(!glob_match(".*", "visible"));
947    }
948
949    #[test]
950    fn test_detect_mime_type() {
951        assert_eq!(detect_mime_type(Path::new("file.md")), "text/markdown");
952        assert_eq!(detect_mime_type(Path::new("file.json")), "application/json");
953        assert_eq!(detect_mime_type(Path::new("file.rs")), "text/x-rust");
954        assert_eq!(detect_mime_type(Path::new("file.png")), "image/png");
955        assert_eq!(
956            detect_mime_type(Path::new("file.unknown")),
957            "application/octet-stream"
958        );
959    }
960
961    #[test]
962    fn test_is_binary_mime_type() {
963        assert!(is_binary_mime_type("image/png"));
964        assert!(is_binary_mime_type("application/pdf"));
965        assert!(!is_binary_mime_type("text/plain"));
966        assert!(!is_binary_mime_type("application/json"));
967    }
968}