1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
//! Static files support.
//!
//! TODO: needs to re-implement actual files handling, current impl blocks
#![allow(dead_code, unused_variables)]
use std::io;
use std::io::Read;
use std::rc::Rc;
use std::fmt::Write;
use std::fs::{File, DirEntry};
use std::path::PathBuf;

use task::Task;
use route::RouteHandler;
use payload::Payload;
use mime_guess::get_mime_type;
use httprequest::HttpRequest;
use httpresponse::{Body, HttpResponse};
use httpcodes::{HTTPOk, HTTPNotFound, HTTPForbidden, HTTPInternalServerError};

/// Static files handling
///
/// Can be registered with `Application::route_handler()`.
///
/// ```rust
/// extern crate actix_web;
/// use actix_web::*;
///
/// fn main() {
///     let app = Application::default("/")
///         .route_handler("/static", StaticFiles::new(".", true))
///         .finish();
/// }
/// ```
pub struct StaticFiles {
    directory: PathBuf,
    accessible: bool,
    show_index: bool,
    chunk_size: usize,
    follow_symlinks: bool,
    prefix: String,
}

impl StaticFiles {
    /// Create new `StaticFiles` instance
    ///
    /// `dir` - base directory
    /// `index` - show index for directory
    pub fn new<D: Into<PathBuf>>(dir: D, index: bool) -> StaticFiles {
        let dir = dir.into();

        let (dir, access) = match dir.canonicalize() {
            Ok(dir) => {
                if dir.is_dir() {
                    (dir, true)
                } else {
                    warn!("Is not directory `{:?}`", dir);
                    (dir, false)
                }
            },
            Err(err) => {
                warn!("Static files directory `{:?}` error: {}", dir, err);
                (dir, false)
            }
        };

        StaticFiles {
            directory: dir,
            accessible: access,
            show_index: index,
            chunk_size: 0,
            follow_symlinks: false,
            prefix: String::new(),
        }
    }

    fn index(&self, relpath: &str, filename: PathBuf) -> Result<HttpResponse, io::Error> {
        let index_of = format!("Index of {}/{}", self.prefix, relpath);
        let mut body = String::new();

        for entry in filename.read_dir()? {
            if self.can_list(&entry) {
                let entry = entry.unwrap();
                // show file url as relative to static path
                let file_url = format!(
                    "{}/{}", self.prefix,
                    entry.path().strip_prefix(&self.directory).unwrap().to_string_lossy());

                // if file is a directory, add '/' to the end of the name
                let file_name = if let Ok(metadata) = entry.metadata() {
                    if metadata.is_dir() {
                        //format!("<li><a href=\"{}\">{}</a></li>", file_url, file_name));
                        write!(body, "<li><a href=\"{}\">{}/</a></li>",
                               file_url, entry.file_name().to_string_lossy())
                    } else {
                        // write!(body, "{}/", entry.file_name())
                        write!(body, "<li><a href=\"{}\">{}</a></li>",
                               file_url, entry.file_name().to_string_lossy())
                    }
                } else {
                    continue
                };
            }
        }

        let html = format!("<html>\
                            <head><title>{}</title></head>\
                            <body><h1>{}</h1>\
                            <ul>\
                            {}\
                            </ul></body>\n</html>", index_of, index_of, body);
        Ok(
            HTTPOk.builder()
                .content_type("text/html; charset=utf-8")
                .body(Body::Binary(html.into())).unwrap()
        )
    }

    fn can_list(&self, entry: &io::Result<DirEntry>) -> bool {
        if let Ok(ref entry) = *entry {
            if let Some(name) = entry.file_name().to_str() {
                if name.starts_with('.') {
                    return false
                }
            }
            if let Ok(ref md) = entry.metadata() {
                let ft = md.file_type();
                return ft.is_dir() || ft.is_file() || ft.is_symlink()
            }
        }
        false
    }
}

impl<S: 'static> RouteHandler<S> for StaticFiles {

    fn set_prefix(&mut self, prefix: String) {
        if prefix != "/" {
            self.prefix += &prefix;
        }
    }

    fn handle(&self, req: &mut HttpRequest, payload: Payload, state: Rc<S>) -> Task {
        if !self.accessible {
            Task::reply(HTTPNotFound)
        } else {
            let mut hidden = false;
            let filepath = req.path()[self.prefix.len()..]
                .split('/').filter(|s| {
                    if s.starts_with('.') {
                        hidden = true;
                    }
                    !s.is_empty()
                })
                .fold(String::new(), |s, i| {s + "/" + i});

            // hidden file
            if hidden {
                return Task::reply(HTTPNotFound)
            }

            // full filepath
            let idx = if filepath.starts_with('/') { 1 } else { 0 };
            let filename = match self.directory.join(&filepath[idx..]).canonicalize() {
                Ok(fname) => fname,
                Err(err) => return match err.kind() {
                    io::ErrorKind::NotFound => Task::reply(HTTPNotFound),
                    io::ErrorKind::PermissionDenied => Task::reply(HTTPForbidden),
                    _ => Task::reply(HTTPInternalServerError),
                }
            };

            if filename.is_dir() {
                match self.index(&filepath[idx..], filename) {
                    Ok(resp) => Task::reply(resp),
                    Err(err) => match err.kind() {
                        io::ErrorKind::NotFound => Task::reply(HTTPNotFound),
                        io::ErrorKind::PermissionDenied => Task::reply(HTTPForbidden),
                        _ => Task::reply(HTTPInternalServerError),
                    }
                }
            } else {
                let mut resp = HTTPOk.builder();
                if let Some(ext) = filename.extension() {
                    let mime = get_mime_type(&ext.to_string_lossy());
                    resp.content_type(format!("{}", mime).as_str());
                }
                match File::open(filename) {
                    Ok(mut file) => {
                        let mut data = Vec::new();
                        let _ = file.read_to_end(&mut data);
                        Task::reply(resp.body(Body::Binary(data.into())).unwrap())
                    },
                    Err(err) => {
                        Task::reply(HTTPInternalServerError)
                    }
                }
            }
        }
    }
}