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 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
/* * This file is part of Actix Form Data. * * Copyright © 2018 Riley Trautman * * Actix Form Data is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Actix Form Data is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Actix Form Data. If not, see <http://www.gnu.org/licenses/>. */ use std::{ collections::{HashMap, VecDeque}, fmt, path::PathBuf, sync::Arc, }; use bytes::Bytes; use futures::{ future::{ExecuteError, Executor}, Future, }; use futures_cpupool::CpuPool; use super::FilenameGenerator; /// The result of a succesfull parse through a given multipart stream. /// /// This type represents all possible variations in structure of a Multipart Form. /// /// # Example usage /// /// ```rust /// # use form_data::Value; /// # use std::collections::HashMap; /// # let mut hm = HashMap::new(); /// # hm.insert("field-name".to_owned(), Value::Int(32)); /// # let value = Value::Map(hm); /// match value { /// Value::Map(mut hashmap) => { /// match hashmap.remove("field-name") { /// Some(value) => match value { /// Value::Int(integer) => println!("{}", integer), /// _ => (), /// } /// None => (), /// } /// } /// _ => (), /// } /// ``` #[derive(Clone, Debug, PartialEq)] pub enum Value { Map(HashMap<String, Value>), Array(Vec<Value>), File(String, PathBuf), Text(String), Int(i64), Float(f64), Bytes(Bytes), } impl Value { pub(crate) fn merge(&mut self, rhs: Self) { match (self, rhs) { (&mut Value::Map(ref mut hm), Value::Map(ref other)) => { other.into_iter().fold(hm, |hm, (key, value)| { if hm.contains_key(key) { hm.get_mut(key).unwrap().merge(value.clone()) } else { hm.insert(key.to_owned(), value.clone()); } hm }); } (&mut Value::Array(ref mut v), Value::Array(ref other)) => { v.extend(other.clone()); } _ => (), } } pub fn map(self) -> Option<HashMap<String, Value>> { match self { Value::Map(map) => Some(map), _ => None, } } pub fn array(self) -> Option<Vec<Value>> { match self { Value::Array(vec) => Some(vec), _ => None, } } pub fn file(self) -> Option<(String, PathBuf)> { match self { Value::File(name, path) => Some((name, path)), _ => None, } } pub fn text(self) -> Option<String> { match self { Value::Text(text) => Some(text), _ => None, } } pub fn int(self) -> Option<i64> { match self { Value::Int(int) => Some(int), _ => None, } } pub fn float(self) -> Option<f64> { match self { Value::Float(float) => Some(float), _ => None, } } pub fn bytes(self) -> Option<Bytes> { match self { Value::Bytes(bytes) => Some(bytes), _ => None, } } } impl From<MultipartContent> for Value { fn from(mc: MultipartContent) -> Self { match mc { MultipartContent::File { filename, stored_as, } => Value::File(filename, stored_as), MultipartContent::Text(string) => Value::Text(string), MultipartContent::Int(i) => Value::Int(i), MultipartContent::Float(f) => Value::Float(f), MultipartContent::Bytes(b) => Value::Bytes(b), } } } /// The field type represents a field in the form-data that is allowed to be parsed. #[derive(Clone)] pub enum Field { Array(Array), File(Arc<FilenameGenerator>), Map(Map), Int, Float, Text, Bytes, } impl fmt::Debug for Field { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Field::Array(ref arr) => write!(f, "Array({:?})", arr), Field::File(_) => write!(f, "File(filename_generator)"), Field::Map(ref map) => write!(f, "Map({:?})", map), Field::Int => write!(f, "Int"), Field::Float => write!(f, "Float"), Field::Text => write!(f, "Text"), Field::Bytes => write!(f, "Bytes"), } } } impl Field { /// Add a File field with a name generator. /// /// The name generator will be called for each file matching this field's key. Keep in mind /// that each key/file pair will have it's own name-generator, so sharing a name-generator /// between fields is up to the user. /// /// # Example /// ```rust /// # extern crate mime; /// # extern crate form_data; /// # use std::path::{Path, PathBuf}; /// # use form_data::{Form, Field, FilenameGenerator}; /// /// struct Gen; /// /// impl FilenameGenerator for Gen { /// fn next_filename(&self, _: &mime::Mime) -> Option<PathBuf> { /// Some(AsRef::<Path>::as_ref("path.png").to_owned()) /// } /// } /// /// fn main() { /// let name_generator = Gen; /// let form = Form::new() /// .field("file-field", Field::file(name_generator)); /// } /// ``` pub fn file<T>(gen: T) -> Self where T: FilenameGenerator + 'static, { Field::File(Arc::new(gen)) } /// Add a Text field to a form /// /// # Example /// ```rust /// # extern crate form_data; /// # use form_data::{Form, Field}; /// # fn main() { /// let form = Form::new().field("text-field", Field::text()); /// # } pub fn text() -> Self { Field::Text } /// Add an Int field to a form /// /// # Example /// ```rust /// # extern crate form_data; /// # use form_data::{Form, Field}; /// # fn main() { /// let form = Form::new().field("int-field", Field::int()); /// # } /// ``` pub fn int() -> Self { Field::Int } /// Add a Float field to a form /// /// # Example /// ```rust /// # extern crate form_data; /// # use form_data::{Form, Field}; /// # fn main() { /// let form = Form::new().field("float-field", Field::float()); /// # } /// ``` pub fn float() -> Self { Field::Float } /// Add a Bytes field to a form /// /// # Example /// ```rust /// # extern crate form_data; /// # use form_data::{Form, Field}; /// # fn main() { /// let form = Form::new().field("bytes-field", Field::bytes()); /// # } /// ``` pub fn bytes() -> Self { Field::Bytes } /// Add an Array to a form /// /// # Example /// ```rust /// # extern crate form_data; /// # use form_data::{Form, Field}; /// # fn main() { /// let form = Form::new() /// .field( /// "array-field", /// Field::array(Field::text()) /// ); /// # } /// ``` pub fn array(field: Field) -> Self { Field::Array(Array::new(field)) } /// Add a Map to a form /// /// # Example /// ```rust /// # extern crate form_data; /// # use form_data::{Form, Field}; /// # fn main() { /// let form = Form::new() /// .field( /// "map-field", /// Field::map() /// .field("sub-field", Field::text()) /// .field("sub-field-two", Field::text()) /// .finalize() /// ); /// # } /// ``` pub fn map() -> Map { Map::new() } fn valid_field(&self, name: VecDeque<NamePart>) -> Option<FieldTerminator> { trace!("Checking {:?} and {:?}", self, name); match *self { Field::Array(ref arr) => arr.valid_field(name), Field::Map(ref map) => map.valid_field(name), Field::File(ref gen) => { if name.is_empty() { Some(FieldTerminator::File(Arc::clone(gen))) } else { None } } Field::Int => { if name.is_empty() { Some(FieldTerminator::Int) } else { None } } Field::Float => { if name.is_empty() { Some(FieldTerminator::Float) } else { None } } Field::Text => { if name.is_empty() { Some(FieldTerminator::Text) } else { None } } Field::Bytes => { if name.is_empty() { Some(FieldTerminator::Bytes) } else { None } } } } } /// A definition of an array of type `Field` to be parsed from form data. /// /// The `Array` type should only be constructed in the context of a Form. See the `Form` /// documentation for more information. #[derive(Debug, Clone)] pub struct Array { inner: Box<Field>, } impl Array { fn new(field: Field) -> Self { Array { inner: Box::new(field), } } fn valid_field(&self, mut name: VecDeque<NamePart>) -> Option<FieldTerminator> { trace!("Checking {:?} and {:?}", self, name); match name.pop_front() { Some(name_part) => match name_part { NamePart::Array => self.inner.valid_field(name), _ => None, }, None => None, } } } /// A definition of key-value pairs to be parsed from form data. #[derive(Debug, Clone)] pub struct Map { inner: Vec<(String, Field)>, } impl Map { fn new() -> Self { Map { inner: Vec::new() } } /// Add a `Field` to a map /// # Example /// ```rust /// # use form_data::Field; /// # /// Field::map() /// .field("sub-field", Field::text()) /// .field("sub-field-two", Field::text()) /// .finalize(); /// ``` pub fn field(mut self, key: &str, value: Field) -> Self { self.inner.push((key.to_owned(), value)); self } /// Finalize the map into a `Field`, so it can be added to a Form /// ```rust /// # use form_data::Field; /// # /// Field::map() /// .field("sub-field", Field::text()) /// .field("sub-field-two", Field::text()) /// .finalize(); /// ``` pub fn finalize(self) -> Field { Field::Map(self) } fn valid_field(&self, mut name: VecDeque<NamePart>) -> Option<FieldTerminator> { trace!("Checking {:?} and {:?}", self, name); match name.pop_front() { Some(name_part) => match name_part { NamePart::Map(part_name) => self .inner .iter() .find(|&&(ref item, _)| *item == part_name) .and_then(|&(_, ref field)| field.valid_field(name)), _ => None, }, None => None, } } } /// A structure that defines the fields expected in form data /// /// # Example /// ```rust /// # extern crate mime; /// # extern crate form_data; /// # use std::path::{Path, PathBuf}; /// # use form_data::{Form, Field, FilenameGenerator}; /// # struct Gen; /// # impl FilenameGenerator for Gen { /// # fn next_filename(&self, _: &mime::Mime) -> Option<PathBuf> { /// # Some(AsRef::<Path>::as_ref("path.png").to_owned()) /// # } /// # } /// # fn main() { /// # let name_generator = Gen; /// let form = Form::new() /// .field("field-name", Field::text()) /// .field("second-field", Field::int()) /// .field("third-field", Field::float()) /// .field("fourth-field", Field::bytes()) /// .field("fifth-field", Field::file(name_generator)) /// .field( /// "map-field", /// Field::map() /// .field("sub-field", Field::text()) /// .field("sub-field-two", Field::text()) /// .finalize() /// ) /// .field( /// "array-field", /// Field::array(Field::text()) /// ); /// # } /// ``` #[derive(Clone)] pub struct Form { pub max_fields: u32, pub max_field_size: usize, pub max_files: u32, pub max_file_size: usize, inner: Map, pub pool: ArcExecutor, } impl Form { /// Create a new form /// /// This also creates a new `CpuPool` to be used to stream files onto the filesystem. If you /// wish to provide your own executor, use the `from_executor` method. pub fn new() -> Self { Form::from_executor(CpuPool::new_num_cpus()) } /// Set the maximum number of fields allowed in the upload /// /// The upload will error if too many fields are provided. pub fn max_fields(mut self, max: u32) -> Self { self.max_fields = max; self } /// Set the maximum size of a field (in bytes) /// /// The upload will error if a provided field is too large. pub fn max_field_size(mut self, max: usize) -> Self { self.max_field_size = max; self } /// Set the maximum number of files allowed in the upload /// /// THe upload will error if too many files are provided. pub fn max_files(mut self, max: u32) -> Self { self.max_files = max; self } /// Set the maximum size for files (in bytes) /// /// The upload will error if a provided file is too large. pub fn max_file_size(mut self, max: usize) -> Self { self.max_file_size = max; self } /// Create a new form with a given executor /// /// This executor is used to stream files onto the filesystem. pub fn from_executor<E>(executor: E) -> Self where E: Executor<Box<Future<Item = (), Error = ()> + Send>> + Send + Sync + Clone + 'static, { Form { max_fields: 100, max_field_size: 10_000, max_files: 20, max_file_size: 10_000_000, inner: Map::new(), pool: ArcExecutor::new(executor), } } pub fn field(mut self, name: &str, field: Field) -> Self { self.inner = self.inner.field(name, field); self } pub(crate) fn valid_field(&self, name: VecDeque<NamePart>) -> Option<FieldTerminator> { self.inner.valid_field(name.clone()) } } impl fmt::Debug for Form { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Form({:?})", self.inner) } } /// The executor type stored inside a `Form` /// /// Any executor capable of being shared and executing boxed futures can be stored here. #[derive(Clone)] pub struct ArcExecutor { inner: Arc<Executor<Box<Future<Item = (), Error = ()> + Send>> + Send + Sync + 'static>, } impl ArcExecutor { /// Create a new ArcExecutor from an Executor /// /// This essentially wraps the given executor in an Arc pub fn new<E>(executor: E) -> Self where E: Executor<Box<Future<Item = (), Error = ()> + Send>> + Send + Sync + Clone + 'static, { ArcExecutor { inner: Arc::new(executor), } } } impl Executor<Box<Future<Item = (), Error = ()> + Send>> for ArcExecutor where { fn execute( &self, future: Box<Future<Item = (), Error = ()> + Send>, ) -> Result<(), ExecuteError<Box<Future<Item = (), Error = ()> + Send>>> { self.inner.execute(future) } } #[derive(Clone, Debug, PartialEq)] pub(crate) struct ContentDisposition { pub name: Option<String>, pub filename: Option<String>, } impl ContentDisposition { pub(crate) fn empty() -> Self { ContentDisposition { name: None, filename: None, } } } #[derive(Clone, Debug, PartialEq)] pub(crate) enum NamePart { Map(String), Array, } impl NamePart { pub fn is_map(&self) -> bool { match *self { NamePart::Map(_) => true, _ => false, } } } #[derive(Clone)] pub(crate) enum FieldTerminator { File(Arc<FilenameGenerator>), Bytes, Int, Float, Text, } impl fmt::Debug for FieldTerminator { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { FieldTerminator::File(_) => write!(f, "File(filename_generator)"), FieldTerminator::Bytes => write!(f, "Bytes"), FieldTerminator::Int => write!(f, "Int"), FieldTerminator::Float => write!(f, "Float"), FieldTerminator::Text => write!(f, "Text"), } } } pub(crate) type MultipartHash = (Vec<NamePart>, MultipartContent); pub(crate) type MultipartForm = Vec<MultipartHash>; #[derive(Clone, Debug, PartialEq)] pub(crate) enum MultipartContent { File { filename: String, stored_as: PathBuf, }, Bytes(Bytes), Text(String), Int(i64), Float(f64), }