summaryrefslogtreecommitdiffstats
path: root/browser/app/nmhproxy/src/commands.rs
blob: 29c86a0dd7b5aeccb870b080a11e412c810369d7 (plain)
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
/* 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/. */

use serde::{Deserialize, Serialize};
use std::io::{self, Read, Write};
use std::process::Command;
use url::Url;

#[cfg(target_os = "windows")]
const OS_NAME: &str = "windows";

#[cfg(target_os = "macos")]
const OS_NAME: &str = "macos";

#[derive(Serialize, Deserialize)]
#[serde(tag = "command", content = "data")]
// {
//     "command": "LaunchFirefox",
//     "data": {"url": "https://example.com"},
// }
pub enum FirefoxCommand {
    LaunchFirefox { url: String },
    LaunchFirefoxPrivate { url: String },
    GetVersion {},
}
#[derive(Serialize, Deserialize)]
// {
//     "message": "Successful launch",
//     "result_code": 1,
// }
pub struct Response {
    pub message: String,
    pub result_code: u32,
}

#[repr(u32)]
pub enum ResultCode {
    Success = 0,
    Error = 1,
}
impl From<ResultCode> for u32 {
    fn from(m: ResultCode) -> u32 {
        m as u32
    }
}

trait CommandRunner {
    fn new() -> Self
    where
        Self: Sized;
    fn arg(&mut self, arg: &str) -> &mut Self;
    fn args(&mut self, args: &[&str]) -> &mut Self;
    fn spawn(&mut self) -> std::io::Result<()>;
    fn to_string(&mut self) -> std::io::Result<String>;
}

impl CommandRunner for Command {
    fn new() -> Self {
        #[cfg(target_os = "macos")]
        {
            Command::new("open")
        }
        #[cfg(target_os = "windows")]
        {
            use mozbuild::config::MOZ_APP_NAME;
            use std::env;
            use std::path::Path;
            // Get the current executable's path, we know Firefox is in the
            // same folder is nmhproxy.exe so we can use that.
            let nmh_exe_path = env::current_exe().unwrap();
            let nmh_exe_folder = nmh_exe_path.parent().unwrap_or_else(|| Path::new(""));
            let moz_exe_path = nmh_exe_folder.join(format!("{}.exe", MOZ_APP_NAME));
            Command::new(moz_exe_path)
        }
    }
    fn arg(&mut self, arg: &str) -> &mut Self {
        self.arg(arg)
    }
    fn args(&mut self, args: &[&str]) -> &mut Self {
        self.args(args)
    }
    fn spawn(&mut self) -> std::io::Result<()> {
        self.spawn().map(|_| ())
    }
    fn to_string(&mut self) -> std::io::Result<String> {
        Ok("".to_string())
    }
}

struct MockCommand {
    command_line: String,
}

impl CommandRunner for MockCommand {
    fn new() -> Self {
        MockCommand {
            command_line: String::new(),
        }
    }
    fn arg(&mut self, arg: &str) -> &mut Self {
        self.command_line.push_str(arg);
        self.command_line.push(' ');
        self
    }
    fn args(&mut self, args: &[&str]) -> &mut Self {
        for arg in args {
            self.command_line.push_str(arg);
            self.command_line.push(' ');
        }
        self
    }
    fn spawn(&mut self) -> std::io::Result<()> {
        Ok(())
    }
    fn to_string(&mut self) -> std::io::Result<String> {
        Ok(self.command_line.clone())
    }
}

// The message length is a 32-bit integer in native byte order
pub fn read_message_length<R: Read>(mut reader: R) -> std::io::Result<u32> {
    let mut buffer = [0u8; 4];
    reader.read_exact(&mut buffer)?;
    let length: u32 = u32::from_ne_bytes(buffer);
    if (length > 0) && (length < 100 * 1024) {
        Ok(length)
    } else {
        Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "Invalid message length",
        ))
    }
}

pub fn read_message_string<R: Read>(mut reader: R, length: u32) -> io::Result<String> {
    let mut buffer = vec![0u8; length.try_into().unwrap()];
    reader.read_exact(&mut buffer)?;
    let message =
        String::from_utf8(buffer).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
    Ok(message)
}

pub fn process_command(command: &FirefoxCommand) -> std::io::Result<bool> {
    match &command {
        FirefoxCommand::LaunchFirefox { url } => {
            launch_firefox::<Command>(url.to_owned(), false, OS_NAME)?;
            Ok(true)
        }
        FirefoxCommand::LaunchFirefoxPrivate { url } => {
            launch_firefox::<Command>(url.to_owned(), true, OS_NAME)?;
            Ok(true)
        }
        FirefoxCommand::GetVersion {} => generate_response("1", ResultCode::Success.into()),
    }
}

pub fn generate_response(message: &str, result_code: u32) -> std::io::Result<bool> {
    let response_struct = Response {
        message: message.to_string(),
        result_code,
    };
    let response_str = serde_json::to_string(&response_struct)
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
    let response_len_bytes: [u8; 4] = (response_str.len() as u32).to_ne_bytes();
    std::io::stdout().write_all(&response_len_bytes)?;
    std::io::stdout().write_all(response_str.as_bytes())?;
    std::io::stdout().flush()?;
    Ok(true)
}

fn validate_url(url: String) -> std::io::Result<String> {
    let parsed_url = Url::parse(url.as_str())
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
    match parsed_url.scheme() {
        "http" | "https" | "file" => Ok(parsed_url.to_string()),
        _ => Err(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "Invalid URL scheme",
        )),
    }
}

fn launch_firefox<C: CommandRunner>(
    url: String,
    private: bool,
    os: &str,
) -> std::io::Result<String> {
    let validated_url: String = validate_url(url)?;
    let mut command = C::new();
    if os == "macos" {
        use mozbuild::config::MOZ_MACBUNDLE_ID;
        let mut args: [&str; 2] = ["--args", "-url"];
        if private {
            args[1] = "-private-window";
        }
        command
            .arg("-n")
            .arg("-b")
            .arg(MOZ_MACBUNDLE_ID)
            .args(&args)
            .arg(validated_url.as_str());
    } else if os == "windows" {
        let mut args: [&str; 2] = ["-osint", "-url"];
        if private {
            args[1] = "-private-window";
        }
        command.args(&args).arg(validated_url.as_str());
    }
    match command.spawn() {
        Ok(_) => generate_response(
            if private {
                "Successful private launch"
            } else {
                "Sucessful launch"
            },
            ResultCode::Success.into(),
        )?,
        Err(_) => generate_response(
            if private {
                "Failed private launch"
            } else {
                "Failed launch"
            },
            ResultCode::Error.into(),
        )?,
    };
    command.to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;
    #[test]
    fn test_validate_url() {
        let valid_test_cases = vec![
            "https://example.com/".to_string(),
            "http://example.com/".to_string(),
            "file:///path/to/file".to_string(),
            "https://test.example.com/".to_string(),
        ];

        for input in valid_test_cases {
            let result = validate_url(input.clone());
            assert!(result.is_ok(), "Expected Ok, got Err");
            // Safe to unwrap because we know the result is Ok
            let ok_value = result.unwrap();
            assert_eq!(ok_value, input);
        }

        assert!(matches!(
            validate_url("fakeprotocol://test.example.com/".to_string()).map_err(|e| e.kind()),
            Err(std::io::ErrorKind::InvalidInput)
        ));

        assert!(matches!(
            validate_url("invalidURL".to_string()).map_err(|e| e.kind()),
            Err(std::io::ErrorKind::InvalidData)
        ));
    }

    #[test]
    fn test_read_message_length_valid() {
        let input: [u8; 4] = 256u32.to_ne_bytes();
        let mut cursor = Cursor::new(input);
        let length = read_message_length(&mut cursor);
        assert!(length.is_ok(), "Expected Ok, got Err");
        assert_eq!(length.unwrap(), 256);
    }

    #[test]
    fn test_read_message_length_invalid_too_large() {
        let input: [u8; 4] = 1_000_000u32.to_ne_bytes();
        let mut cursor = Cursor::new(input);
        let result = read_message_length(&mut cursor);
        assert!(result.is_err());
        let error = result.err().unwrap();
        assert_eq!(error.kind(), io::ErrorKind::InvalidData);
    }

    #[test]
    fn test_read_message_length_invalid_zero() {
        let input: [u8; 4] = 0u32.to_ne_bytes();
        let mut cursor = Cursor::new(input);
        let result = read_message_length(&mut cursor);
        assert!(result.is_err());
        let error = result.err().unwrap();
        assert_eq!(error.kind(), io::ErrorKind::InvalidData);
    }

    #[test]
    fn test_read_message_string_valid() {
        let input_data = b"Valid UTF8 string!";
        let input_length = input_data.len() as u32;
        let message = read_message_string(&input_data[..], input_length);
        assert!(message.is_ok(), "Expected Ok, got Err");
        assert_eq!(message.unwrap(), "Valid UTF8 string!");
    }

    #[test]
    fn test_read_message_string_invalid() {
        let input_data: [u8; 3] = [0xff, 0xfe, 0xfd];
        let input_length = input_data.len() as u32;
        let result = read_message_string(&input_data[..], input_length);
        assert!(result.is_err());
        let error = result.err().unwrap();
        assert_eq!(error.kind(), io::ErrorKind::InvalidData);
    }

    #[test]
    fn test_launch_regular_command_macos() {
        let url = "https://example.com";
        let result = launch_firefox::<MockCommand>(url.to_string(), false, "macos");
        assert!(result.is_ok());
        let command_line = result.unwrap();
        let correct_url_format = format!("-url {}", url);
        assert!(command_line.contains(correct_url_format.as_str()));
    }

    #[test]
    fn test_launch_regular_command_windows() {
        let url = "https://example.com";
        let result = launch_firefox::<MockCommand>(url.to_string(), false, "windows");
        assert!(result.is_ok());
        let command_line = result.unwrap();
        let correct_url_format = format!("-osint -url {}", url);
        assert!(command_line.contains(correct_url_format.as_str()));
    }

    #[test]
    fn test_launch_private_command_macos() {
        let url = "https://example.com";
        let result = launch_firefox::<MockCommand>(url.to_string(), true, "macos");
        assert!(result.is_ok());
        let command_line = result.unwrap();
        let correct_url_format = format!("-private-window {}", url);
        assert!(command_line.contains(correct_url_format.as_str()));
    }

    #[test]
    fn test_launch_private_command_windows() {
        let url = "https://example.com";
        let result = launch_firefox::<MockCommand>(url.to_string(), true, "windows");
        assert!(result.is_ok());
        let command_line = result.unwrap();
        let correct_url_format = format!("-osint -private-window {}", url);
        assert!(command_line.contains(correct_url_format.as_str()));
    }
}