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
//! Access to the file-decompiling service
//! ([decompiler](https://retdec.com/api/docs/decompiler.html)).

use connection::APIArguments;
use connection::APIConnectionFactory;
use connection::HyperAPIConnectionFactory;
use connection::ResponseVerifyingAPIConnectionFactory;
use decompilation::Decompilation;
use decompilation::DecompilationArguments;
use error::Result;
use error::ResultExt;
use settings::Settings;

/// File-decompiling service.
///
/// # Examples
///
/// ```no_run
/// # use retdec::error::Result;
/// # fn test() -> Result<()> {
/// use retdec::decompilation::DecompilationArguments;
/// use retdec::decompiler::Decompiler;
/// use retdec::file::File;
/// use retdec::settings::Settings;
///
/// let settings = Settings::new()
///     .with_api_key("MY-API-KEY");
/// let decompiler = Decompiler::new(settings);
/// let args = DecompilationArguments::new()
///     .with_input_file(File::from_path("file.exe")?);
/// let mut decompilation = decompiler.start_decompilation(args)?;
/// decompilation.wait_until_finished()?;
/// let output_code = decompilation.get_output_hll_code()?;
/// print!("{}", output_code);
/// # Ok(()) } fn main() { test().unwrap() }
/// ```
pub struct Decompiler {
    conn_factory: Box<APIConnectionFactory>,
}

impl Decompiler {
    /// Creates a new instance of the file-decompiling service.
    pub fn new(settings: Settings) -> Self {
        Decompiler {
            conn_factory: Box::new(
                ResponseVerifyingAPIConnectionFactory::new(
                    Box::new(HyperAPIConnectionFactory::new(settings))
                )
            ),
        }
    }

    /// Starts a new decompilation with the given arguments.
    pub fn start_decompilation(&self, args: DecompilationArguments) -> Result<Decompilation> {
        let mut conn = self.conn_factory.new_connection();
        let url = format!("{}/decompiler/decompilations", conn.api_url());
        let api_args = self.create_api_args(args)?;
        let response = conn.send_post_request(&url, api_args)
            .chain_err(|| "failed to start a decompilation")?;
        let id = response.json_value_as_string("id")
            .ok_or_else(|| format!("{} returned invalid JSON response", url))?;
        Ok(Decompilation::new(id, conn))
    }

    fn create_api_args(&self, mut args: DecompilationArguments) -> Result<APIArguments> {
        let mut api_args = APIArguments::new();
        api_args.add_string_arg("mode", "bin");
        match args.take_input_file() {
            Some(input_file) => {
                api_args.add_file("input", input_file);
            }
            None => {
                bail!("no input file given");
            }
        }
        Ok(api_args)
    }

    #[cfg(test)]
    fn with_conn_factory(conn_factory: Box<APIConnectionFactory>) -> Self {
        Decompiler { conn_factory: conn_factory }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use std::cell::RefCell;
    use std::rc::Rc;

    use connection::tests::APIArgumentsBuilder;
    use connection::tests::APIConnectionFactoryMock;
    use connection::tests::APIConnectionMock;
    use connection::tests::APIResponseBuilder;
    use decompilation::DecompilationArguments;
    use file::File;

    fn create_decompiler() -> (Rc<RefCell<APIConnectionMock>>, Decompiler) {
        // We need to force an API URL to prevent it from being overridden by
        // setting the RETDEC_API_URL environment variable.
        let settings = Settings::new()
            .with_api_key("test")
            .with_api_url("https://retdec.com/service/api");
        let conn = Rc::new(RefCell::new(APIConnectionMock::new(settings.clone())));
        let conn_factory = Box::new(APIConnectionFactoryMock::new(conn.clone()));
        (conn, Decompiler::with_conn_factory(conn_factory))
    }

    #[test]
    fn decompiler_start_decompilation_starts_decompilation_with_correct_arguments() {
        let (conn, decompiler) = create_decompiler();
        let input_file = File::from_content_with_name(b"content", "file.exe");
        let args = DecompilationArguments::new()
            .with_input_file(input_file.clone());
        conn.borrow_mut().add_response(
            "POST",
            "https://retdec.com/service/api/decompiler/decompilations",
            Ok(
                APIResponseBuilder::new()
                    .with_status_code(200)
                    .with_body(br#"{
                        "id": "ID"
                    }"#)
                    .build()
            )
        );

        let decompilation = decompiler.start_decompilation(args)
            .expect("decompilation should have succeeded");

        assert_eq!(decompilation.id(), "ID");
        assert!(conn.borrow_mut().request_sent(
            "POST",
            "https://retdec.com/service/api/decompiler/decompilations",
            APIArgumentsBuilder::new()
                .with_string_arg("mode", "bin")
                .with_file("input", input_file)
                .build()
        ));
    }

    #[test]
    fn decompiler_start_decompilation_returns_error_when_input_file_is_not_given() {
        let (conn, decompiler) = create_decompiler();
        let args = DecompilationArguments::new();
        conn.borrow_mut().add_response(
            "POST",
            "https://retdec.com/service/api/decompiler/decompilations",
            Ok(
                APIResponseBuilder::new()
                    .with_status_code(200)
                    .with_body(br#"{
                        "id": "ID"
                    }"#)
                    .build()
            )
        );

        let result = decompiler.start_decompilation(args);

        let err = result.err().expect("expected start_decompilation() to fail");
        assert_eq!(err.description(), "no input file given");
    }

    #[test]
    fn decompiler_start_decompilation_returns_error_when_returned_json_does_not_contain_id() {
        let (conn, decompiler) = create_decompiler();
        let input_file = File::from_content_with_name(b"content", "file.exe");
        let args = DecompilationArguments::new()
            .with_input_file(input_file);
        conn.borrow_mut().add_response(
            "POST",
            "https://retdec.com/service/api/decompiler/decompilations",
            Ok(
                APIResponseBuilder::new()
                    .with_status_code(200)
                    .with_body(b"{}")
                    .build()
            )
        );

        let result = decompiler.start_decompilation(args);

        let err = result.err().expect("expected start_decompilation() to fail");
        assert_eq!(
            err.description(),
            "https://retdec.com/service/api/decompiler/decompilations returned invalid JSON response"
        );
    }
}