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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//! `qair` as a library.
//!
//! # Example
//! ```no_run
//! let mut qair = qair::Qair::new();
//! qair.set_file_to_send(&Some(std::path::PathBuf::from("song.ogg")));
//! qair.set_is_receiving_enabled(true);
//! println!("{}", qair.url().unwrap());
//! qair.start();
//! ```

use crate::myip;
use crate::webserver;
pub use iron::error::HttpError;
pub use iron::Listening;
use percent_encoding::{utf8_percent_encode, AsciiSet, NON_ALPHANUMERIC};
use std::fmt;
use std::path::{Path, PathBuf};

pub struct Qair {
    port: u16,
    is_receiving_enabled: bool,
    file_to_send: Option<PathBuf>,
    always_index: bool,
    ip_autodetection_config: IpAutodetectionConfig,
}

/// Whether IP must be autodetected and/or which custom hostname must be used
pub enum IpAutodetectionConfig {
    /// Autodetect the IP address and never use a custom hostname.
    OnlyAutodetect,

    /// Autodetect the IP address and if that fails use the custom hostname.
    #[allow(dead_code)] // bin build does not use it, but lib build does.
    AutoDetectWithFallback(String),

    /// Do not autodetect the IP address and always use the custom hostname.
    AlwaysCustom(String),
}

#[derive(Debug)]
pub enum FormatUrlError {
    /// The filename is not valid UTF-8
    NotUtf8(PathBuf),

    /// The filename cannot be a file, for example "/tmp/test/.." or "/".
    CannotBeAFile(PathBuf),

    /// IP autodetection failed and there is no fallback hostname set
    CannotAutodetectIp,
}

impl fmt::Display for FormatUrlError {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        let text = match self {
            FormatUrlError::NotUtf8(_) => "Filename is not valid UTF-8",
            FormatUrlError::CannotBeAFile(_) => "Filename cannot be a file",
            FormatUrlError::CannotAutodetectIp => "IP address autodetection failed",
        };
        formatter.write_str(text)
    }
}

/// Characters we want to percent encode in URLs (e.g. %20 instead of space)
///
/// The percent_encoding crate takes care of UTF-8 for us, so that's not here.
const PERCENT_ENCODE_CHARS: &AsciiSet = &NON_ALPHANUMERIC
    .remove(b'-')
    .remove(b'.')
    .remove(b'/')
    .remove(b'_');

const DEFAULT_PORT: u16 = 1234;

impl Qair {
    /// Construct with defaults.
    ///
    /// Defaults are:
    /// - port: 1234
    /// - receiving: disabled
    /// - file to send: none
    /// - always index: no
    /// - ip autodetection: only autodetect
    pub fn new() -> Self {
        Qair {
            port: DEFAULT_PORT,
            is_receiving_enabled: false,
            file_to_send: None,
            always_index: false,
            ip_autodetection_config: IpAutodetectionConfig::OnlyAutodetect,
        }
    }

    /// Start listening to HTTP requests.
    ///
    /// On success, dropping the returned value blocks and does not stop the HTTP server.
    ///
    /// Besides stopping the application, there is currently no way to stop the HTTP server, see
    /// https://docs.rs/iron/0.6.1/iron/struct.Listening.html#method.close
    ///
    /// Note: you probably want to call `set_is_receiving_enabled` or `set_file_to_send` first,
    ///       otherwise sending and receiving remain disabled.
    pub fn start(&self) -> Result<iron::Listening, HttpError> {
        webserver::start(self.port, self.is_receiving_enabled, &self.file_to_send)
    }

    /// URL the HTTP server can be reached on after calling `start`.
    ///
    /// Note that in case of IP autodetection, the IP can change between calling `url` and
    /// calling `start`, so it is not guaranteed that the HTTP server is reachable on the
    /// returned URL.
    ///
    /// Calling this function twice can give a different result.
    ///
    /// See also `always_index`.
    pub fn url(&self) -> Result<String, FormatUrlError> {
        let index = self.always_index || self.is_receiving_enabled;
        let host = self.ip().ok_or(FormatUrlError::CannotAutodetectIp)?;
        match &self.file_to_send {
            Some(file) if !index => {
                let basename_non_converted = Path::new(&file)
                    .file_name()
                    .ok_or(FormatUrlError::CannotBeAFile(file.clone()))?;
                let basename = basename_non_converted
                    .to_str()
                    .ok_or(FormatUrlError::NotUtf8(file.clone()))?;
                let basename_encoded =
                    utf8_percent_encode(basename, PERCENT_ENCODE_CHARS).to_string();
                Ok(format!(
                    "http://{}:{}/{}",
                    host, self.port, basename_encoded
                ))
            }
            _ => Ok(format!("http://{}:{}/", host, self.port)),
        }
    }

    /// Set on which port the HTTP server will listen.
    pub fn set_port(&mut self, port: u16) {
        self.port = port;
    }

    /// Set whether the HTTP server allows clients to upload files
    pub fn set_is_receiving_enabled(&mut self, is_receiving_enabled: bool) {
        self.is_receiving_enabled = is_receiving_enabled;
    }

    /// Set which file will the HTTP server send to clients.
    ///
    /// `None` meants the HTTP server will refuse to send files.
    pub fn set_file_to_send(&mut self, file_to_send: &Option<PathBuf>) {
        self.file_to_send = file_to_send.clone();
    }

    /// Configure IP autodetection and/or custom host name
    pub fn set_ip_autodetection_config(&mut self, config: IpAutodetectionConfig) {
        self.ip_autodetection_config = config;
    }

    /// Set whether deeplinking is disabled in the URL.
    ///
    /// If `true`, then when only sending a single file, the URL returned by `url` will go directly
    /// to that file, e.g. `http://192.168.1.2/file.png`. If `false`, this never happens and the URL
    /// will always be like `http://192.168.1.2/`. The page on that URL can then contain a link
    /// to a file (if sending files is enabled).
    pub fn set_always_index(&mut self, always_index: bool) {
        self.always_index = always_index;
    }

    /// What IP or hostname to include in the URL.
    fn ip(&self) -> Option<String> {
        match &self.ip_autodetection_config {
            IpAutodetectionConfig::OnlyAutodetect => myip::autodetect_ip_address().ok(),
            IpAutodetectionConfig::AutoDetectWithFallback(fallback) => {
                Some(myip::autodetect_ip_address().unwrap_or(fallback.to_string()))
            }
            IpAutodetectionConfig::AlwaysCustom(custom) => Some(custom.to_string()),
        }
    }
}