~boringcactus/gemifedi

ref: 811641efa71eb4afbc8ac183baa7cd3760809f20 gemifedi/src/main.rs -rw-r--r-- 11.1 KiB
811641ef — Melody Horn improve instructions more 1 year, 2 months ago
                                                                                
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
use std::{
    fs::{File, create_dir_all},
    io::BufReader,
    path::PathBuf,
    sync::Arc,
};

use elefren::{
    prelude::*,
    helpers::toml as mastodon_toml,
};
use maj::{
    gemini as gemtext,
    Response as GeminiResponse,
    server::{
        Handler as GeminiHandler,
        Request as GeminiRequest,
        Error,
    },
    route, split, seg,
};
use rustls::ServerConfig;

mod client_cert_fix;
use client_cert_fix::TrustAnyClientCertOrAnonymous;

mod html2gemtext;

mod gemini_util;
use gemini_util::*;
mod mastodon_util;
use mastodon_util::*;

fn render_post(post: elefren::entities::status::Status) -> Vec<gemtext::Node> {
    let reply_info = match post.in_reply_to_account_id {
        Some(account) => {
            let replyee = if account == post.account.id {
                post.account.display_name.clone()
            } else {
                post.mentions.iter()
                    .find_map(|mention| {
                        if mention.id == account {
                            Some(mention.acct.clone())
                        } else {
                            None
                        }
                    })
                    .unwrap_or("someone they untagged".to_string())
            };
            format!(", replying to {}", replyee)
        },
        None => format!("")
    };

    let reblog_info = match post.reblog {
        Some(status) => format!(", reblogging {}", status.account.display_name),
        None => format!("")
    };

    let post_info = format!(
        "{account_name}{reply_info}{reblog_info}:",
        account_name=post.account.display_name,
        reply_info=reply_info,
        reblog_info=reblog_info,
    );

    let mut result = vec![
        gemtext::Node::Heading { level: 2, body: post_info },
    ];
    result.extend(strip_html(&post.content));
    result.extend(vec![
        gemtext::Node::Link { to: format!("/status/{}", post.id), name: None },
        gemtext::Node::blank(),
    ]);
    result
}

fn mastodon_data_path(req: &GeminiRequest) -> Option<PathBuf> {
    let mut result = PathBuf::from("data");
    result.push("users");
    let hash = req.cert_hash()?;
    result.push(hash);
    Some(result.with_extension("toml"))
}

struct Handler;

impl Default for Handler {
    fn default() -> Self {
        Handler {}
    }
}

impl Handler {
    fn home(&self, req: GeminiRequest) -> Result<GeminiResponse, Error> {
        let path = mastodon_data_path(&req);
        let path = match path {
            Some(path) => path,
            None => return Ok(GeminiResponse::need_cert("Need a cert to be able to log in!"))
        };
        let mastodon = match mastodon_toml::from_file(path) {
            Ok(data) => Mastodon::from(data),
            Err(_) => return Ok(temp_redirect("/auth"))
        };

        let home = mastodon.get_home_timeline().unwrap();

        let posts = home.items_iter()
            .take(10)
            .flat_map(render_post)
            .collect::<Vec<_>>();

        Ok(GeminiResponse::render(apply_global_template(posts)))
    }

    fn auth_begin(&self, req: GeminiRequest) -> Result<GeminiResponse, Error> {
        match req.url.query() {
            Some(instance) => {
                assert!(url::Host::parse(instance).is_ok(), "got a bad instance domain name");
                let mut target = req.url.clone();
                target.set_query(None);
                target.path_segments_mut().unwrap().push(instance);
                Ok(temp_redirect(target.to_string()))
            }
            None => {
                Ok(GeminiResponse::input("Enter the domain of your instance (e.g. \"mastodon.social\")"))
            }
        }
    }

    fn auth_continue(&self, req: GeminiRequest, instance: &str) -> Result<GeminiResponse, Error> {
        let app_install = get_app_install(instance);

        let mut ready_for_code_url = req.url.clone();
        ready_for_code_url.path_segments_mut().unwrap().push("code");
        let response = gemtext::Builder::new()
            .link(app_install.authorize_url().unwrap(), Some("Open this HTTP link to get an authorization code from your instance".to_string()))
            .link(ready_for_code_url.into_string(), Some("Click this Gemini link to enter that authorization code here".to_string()))
            .build();
        return Ok(GeminiResponse::render(response));
    }

    fn auth_finish(&self, req: GeminiRequest, instance: &str) -> Result<GeminiResponse, Error> {
        let app_install = get_app_install(instance);
        let code = match req.url.query() {
            Some(code) => code,
            None => {
                return Ok(GeminiResponse::input("Enter the authorization code you got"));
            }
        };

        let mastodon = app_install.complete(code).unwrap();

        // Save app data for using on the next run.
        let path = mastodon_data_path(&req);
        let path = match path {
            Some(path) => path,
            None => return Ok(GeminiResponse::need_cert("Need a cert to be able to log in!"))
        };
        path.parent().and_then(|parent| create_dir_all(parent).ok());
        mastodon_toml::to_file(&*mastodon, path).unwrap();

        let mut destination = req.url.clone();
        destination.path_segments_mut().unwrap().clear();
        destination.set_query(None);
        Ok(temp_redirect(destination.to_string()))
    }

    fn status(&self, req: GeminiRequest, id: &str) -> Result<GeminiResponse, Error> {
        let path = mastodon_data_path(&req);
        let path = match path {
            Some(path) => path,
            None => return Ok(GeminiResponse::need_cert("Need a cert to be able to log in!"))
        };
        let mastodon = match mastodon_toml::from_file(path) {
            Ok(data) => Mastodon::from(data),
            Err(_) => return Ok(temp_redirect("/auth"))
        };

        Ok(match mastodon.get_status(id) {
            Ok(status) => GeminiResponse::render(apply_global_template(render_post(status))),
            Err(_) => GeminiResponse::not_found(),
        })
    }

    fn about(&self, _req: GeminiRequest) -> Result<GeminiResponse, Error> {
        let response = gemtext::parse(r#"# About gemifedi

gemifedi is a Mastodon / Pleroma client for the Gemini protocol. it uses the OAuth API to access your timeline, and stores data keyed by your chosen client certificate. i recommend hosting it yourself instead of trusting someone else to host it for you.

=> https://git.sr.ht/~boringcactus/gemifedi source code and hosting instructions
=> /auth                                    log in on this install of gemifedi
"#);

        Ok(GeminiResponse::render(response))
    }
}

#[async_trait::async_trait]
impl GeminiHandler for Handler {
    async fn handle(&self, req: GeminiRequest) -> Result<GeminiResponse, Error> {
        let path = req.url.path().to_string();
        route!(path, {
            (/)                         => self.home(req);
            (/"auth")                   => self.auth_begin(req);
            (/"auth"/[instance])        => self.auth_continue(req, instance);
            (/"auth"/[instance]/"code") => self.auth_finish(req, instance);
            (/"status"/[id])            => self.status(req, id);
            (/"about")                  => self.about(req);
        });
        Ok(GeminiResponse::not_found())
    }
}

use structopt::StructOpt;

#[derive(StructOpt, Debug)]
#[structopt(author, about)]
struct Opt {
    /// Path to TLS certificate (will attempt to generate if not found, defaults to ./<domain>.cert)
    #[structopt(short, long, parse(from_os_str))]
    cert: Option<PathBuf>,

    /// Path to TLS key (will attempt to generate if not found, defaults to ./<domain>.key)
    #[structopt(short, long, parse(from_os_str))]
    key: Option<PathBuf>,

    /// Domain name (e.g. `localhost`, `gemifedi.example.net`)
    #[structopt()]
    domain: String,

    /// Port number to run on
    #[structopt(default_value = "1965")]
    port: u16,
}

#[async_std::main]
async fn main() -> Result<(), Error> {
    pretty_env_logger::formatted_builder()
        .filter(None, log::LevelFilter::Info)
        .filter(Some("gemifedi"), log::LevelFilter::max())
        .init();

    let options: Opt = Opt::from_args();

    if let Err(error) = url::Host::parse(&options.domain) {
        eprintln!("{:?} is not a valid hostname", options.domain);
        return Err(Box::new(error));
    }

    let key_file = options.key.unwrap_or(PathBuf::from(format!("./{}.key", options.domain)));

    if !key_file.exists() {
        log::info!("couldn't find key file {}, generating", key_file.display());
        use std::process::Command;
        let genrsa = Command::new("openssl")
            .args(&["genrsa", "-out"])
            .arg(&key_file)
            .arg("2048")
            .output();
        match genrsa {
            Err(err) => {
                eprintln!("Failed to generate key file");
                return Err(Box::new(err));
            }
            Ok(output) if !output.status.success() => {
                eprintln!("Error generating key file");
                return Err(format!("{:#?}", output).into());
            }
            _ => {
                log::debug!("generated key file OK")
            }
        }
    }

    let cert_file = options.cert.unwrap_or(PathBuf::from(format!("./{}.cert", options.domain)));

    if !cert_file.exists() {
        log::info!("couldn't find certificate file {}, generating", cert_file.display());
        let mut temp_file = tempfile::NamedTempFile::new()?;
        use std::io::Write;
        writeln!(temp_file, "[req]\ndistinguished_name=req\n[SAN]\nsubjectAltName=DNS:{}", options.domain)?;
        use std::process::Command;
        let req = Command::new("openssl")
            .args(&["req", "-new", "-x509", "-key"])
            .arg(&key_file)
            .arg("-out")
            .arg(&cert_file)
            .args(&["-days", "3650", "-subj"])
            .arg(format!("/CN={}", options.domain))
            .args(&["-extensions", "SAN", "-config"])
            .arg(temp_file.path())
            .output();
        match req {
            Err(err) => {
                eprintln!("Failed to generate certificate file");
                return Err(Box::new(err));
            }
            Ok(output) if !output.status.success() => {
                eprintln!("Error generating certificate file");
                return Err(format!("{:#?}", output).into());
            }
            _ => {
                log::debug!("generated certificate file OK")
            }
        }
    }

    let mut tls_config = ServerConfig::new(TrustAnyClientCertOrAnonymous::new());
    let mut cert_file = BufReader::new(File::open(cert_file)?);
    let mut key_file = BufReader::new(File::open(key_file)?);
    let keys = rustls::internal::pemfile::rsa_private_keys(&mut key_file).unwrap();
    let key = keys.into_iter().next().unwrap();
    tls_config.set_single_cert(
        rustls::internal::pemfile::certs(&mut cert_file).unwrap(),
        key,
    )?;

    log::info!("about to start listening on gemini://{}{}/", options.domain, if options.port == 1965 { format!("") } else { format!(":{}", options.port) });

    maj::server::serve(
        Arc::new(Handler::default()),
        tls_config,
        options.domain,
        options.port,
    ).await
}