aboutsummaryrefslogtreecommitdiffstats
path: root/license-generator/src/bin/license.rs
blob: 818b9112537d224f5b3cb57644865b63ef78a457 (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
///! FastCGI script that displays a thank-you page with a link to download a
///! custom-generated license.

// Copyright (c) 2018  Teddy Wing
//
// This file is part of DomeKey Web.
//
// DomeKey Web is free software: you can redistribute it and/or modify it
// under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// DomeKey Web 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
// Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public
// License along with DomeKey Web. If not, see
// <https://www.gnu.org/licenses/>.

extern crate aquatic_prime;
extern crate fastcgi;
extern crate exitcode;

#[macro_use]
extern crate log;
extern crate mysql;

#[macro_use]
extern crate serde_derive;

extern crate license_generator;

use std::borrow::Cow;
use std::io::{Cursor, Read, Write};

use aquatic_prime::AquaticPrime;

use license_generator::database;
use license_generator::errors::*;
use license_generator::logger;
use license_generator::params;
use license_generator::response;
use license_generator::zip;

const PUBLIC_KEY: &'static str = include_str!("../../private/public_key.txt");
const PRIVATE_KEY: &'static str = include_str!("../../private/private_key.txt");

#[derive(Serialize)]
struct LicenseData<'a> {
    #[serde(rename = "Name")]
    name: &'a str,

    #[serde(rename = "Email")]
    email: &'a str,
}

trait LicenseValidationResponse {
    fn success(&mut self, name: &str, email: &str, secret: &str);
    fn error_400(&mut self);
    fn error_404(&mut self);
    fn error_500(&mut self, error: Option<Error>);
}

struct HtmlResponse<'a, W: 'a> {
    writer: &'a mut W,
}

impl<'a, W> LicenseValidationResponse for HtmlResponse<'a, W>
where W: 'a + Write {
    fn success(&mut self, name: &str, email: &str, secret: &str) {
        write!(
            self.writer,
            "Status: 200
Content-Type: text/html\n\n{}",
            format!(
                include_str!("../../../thank-you-license-download.html"),
                name = name,
                email = email,
                secret = secret,
            )
        ).unwrap_or(())
    }

    fn error_400(&mut self) {
        let page_400 = include_str!("../../../400.html");
        response::set_400(self.writer)
            .and_then(|_|
                Ok(write!(self.writer, "Content-Type: text/html\n\n{}", page_400)?)
            ).unwrap_or(())
    }

    fn error_404(&mut self) {
        let page_404 = include_str!("../../../404.html");
        response::set_404(self.writer)
            .and_then(|_|
                Ok(write!(self.writer, "Content-Type: text/html\n\n{}", page_404)?)
            ).unwrap_or(())
    }

    fn error_500(&mut self, error: Option<Error>) {
        if let Some(error) = error {
            error!("{}", error);
        }

        let page_500 = include_str!("../../../internal_error.html");
        response::set_500(self.writer)
            .and_then(|_|
                Ok(write!(self.writer, "Content-Type: text/html\n\n{}", page_500)?)
            ).unwrap_or(())
    }
}

struct ZipResponse<'a, W: 'a> {
    writer: &'a mut W,
}

impl<'a, W> LicenseValidationResponse for ZipResponse<'a, W>
where W: 'a + Write {
    fn success(&mut self, name: &str, email: &str, _secret: &str) {
        let license_data = LicenseData {
            name: &name,
            email: &email,
        };

        let aquatic_prime = AquaticPrime::new(&PUBLIC_KEY, &PRIVATE_KEY);
        let license = match aquatic_prime.plist(license_data) {
            Ok(p) => p,
            Err(e) => return self.error_500(Some(e.into())),
        };

        let mut zip_data = Cursor::new(vec![]);
        match zip::license(&mut zip_data, license.as_bytes()) {
            Ok(p) => p,
            Err(e) => return self.error_500(Some(e.into())),
        }

        write!(self.writer, "Content-Type: application/zip
Content-Disposition: attachment; filename=\"dome-key-license.zip\"\n\n")
            .and_then(|_|
                self.writer.write_all(&zip_data.into_inner())
            ).unwrap_or(());
    }

    fn error_400(&mut self) {
        response::error_400(self.writer);
    }

    fn error_404(&mut self) {
        response::error_404(self.writer);
    }

    fn error_500(&mut self, error: Option<Error>) {
        response::error_500(self.writer, error)
    }
}

fn query_purchaser(
    cx: &mut mysql::PooledConn,
    name: &str,
    email: &str,
    secret: &str,
) -> Result<Option<std::result::Result<mysql::Row, mysql::Error>>> {
    let mut tx = cx.start_transaction(false, None, None)?;
    let row = tx.prep_exec("
        SELECT id FROM purchasers
        WHERE
            name = ?
        AND
            email = ?
        AND
            secret = ?",
        (
            &name,
            &email,
            &secret,
        )
    )?.next();

    tx.commit()?;

    Ok(row)
}

fn build_response<'a, R: LicenseValidationResponse>(
    cx: &mut mysql::PooledConn,
    params: &str,
    responses: &mut R,
) {
    let params = params::parse(&params);
    let name = params.get("name");
    let email = params.get("email");
    let secret = params.get("secret");

    if name.is_some() && email.is_some() && secret.is_some() {
        let name = name.unwrap().to_string();
        let email = email.unwrap().to_string();
        let secret = secret.unwrap().to_string();

        let purchaser = match query_purchaser(cx, &name, &email, &secret) {
            Ok(p) => p,
            Err(e) => return responses.error_500(Some(e.into())),
        };

        if let Some(purchaser) = purchaser {
            match purchaser {
                Ok(p) => p,
                Err(e) => return responses.error_500(Some(e.into())),
            };

            return responses.success(&name, &email, &secret);
        } else {
            return responses.error_404();
        }
    } else {
        error!(
            "Missing request parameters: name: '{}', email: '{}', secret: '{}'",
            name.unwrap_or(&Cow::Borrowed("")),
            email.unwrap_or(&Cow::Borrowed("")),
            secret.unwrap_or(&Cow::Borrowed("")),
        );

        return responses.error_400();
    }
}

fn main() -> Result<()> {
    logger::init()?;

    let pool = match database::get_database_pool()
        .chain_err(|| "failed to create a database connection pool")
    {
        Ok(pool) => pool,
        Err(e) => {
            error!("{}", e);
            return Err(e);
        },
    };

    fastcgi::run(move |mut req| {
        let mut params = String::new();
        match req.stdin().read_to_string(&mut params) {
            Ok(_) => (),
            Err(e) => error!("{}", e),
        }

        logger::log_request(&req, &params);

        let mut cx = match pool.get_conn() {
            Ok(cx) => cx,
            Err(e) => {
                return response::error_500(
                    &mut req.stdout(),
                    Some(e.into())
                );
            },
        };

        if let Some(path) = req.param("REQUEST_URI") {
            let path = path.split("?").collect::<Vec<_>>()[0];

            match path.as_ref() {
                "/license" => {
                    // Get params name, email, secret
                    // Render thank-you page with link to download file
                    let params = req.param("QUERY_STRING").unwrap();
                    let mut responses = HtmlResponse { writer: &mut req.stdout() };
                    return build_response(&mut cx, &params, &mut responses);
                },

                // Respond with a zip archive of the license file
                "/license/download" => {
                    match req.param("REQUEST_METHOD") {
                        Some(method) => {
                            if method != "POST" {
                                return response::error_405(&mut req.stdout(), "POST");
                            }
                        },
                        None => {
                            return response::error_500(&mut req.stdout(), None);
                        },
                    };

                    let mut responses = ZipResponse { writer: &mut req.stdout() };
                    return build_response(&mut cx, &params, &mut responses);
                },
                _ => (),
            }
        }
    });

    Ok(())
}