summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: d707d7cbb5348c22e292884bdf41b24bb7b990b1 (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
use std::convert::Infallible;
use std::net::{IpAddr, SocketAddr, Ipv4Addr};
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::mpsc::{Sender, channel};
use std::{thread, time::Duration};
use std::sync::Arc;
use std::fs;

use hyper::header;
use hyper::http::response;
use serde_derive::{Serialize, Deserialize};
use toml;

use hyper::server::conn::AddrStream;
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Request, Response, Server, StatusCode, Method, header::HeaderValue};

use rusqlite::{Connection, Transaction};

use blake3;

enum VustQuery {
    Get,
    Like,
    Commit,
}

struct VustMessage {
    req_type: VustQuery,
    ip: SocketAddr,
    path: String,
    res: Sender<Response<Body>>,
}

fn respond(sc :StatusCode, mes : String) -> Response<Body> {
    Response::builder()
        .status(sc)
        .body(Body::from(mes))
        .unwrap()
}

fn wrapCORS(mut res: Response<Body>, config :Arc<Config>) -> Response<Body> {
    res.headers_mut().insert("Access-Control-Allow-Origin", HeaderValue::from_str(&config.cors_hosts).unwrap() );
    res.headers_mut().insert("Access-Control-Allow-Methods", HeaderValue::from_static("*"));
    res.headers_mut().insert("Access-Control-Allow-Headers", HeaderValue::from_static("*"));
    res
}

fn handle(req: Request<Body>, addr: SocketAddr, tx: Sender<VustMessage>, config: Arc<Config>) -> Response<Body> {
    const PREFIX_PATH: &str = "/like/";

    let path: String = req.uri().path().to_string();

    let addr = match req.headers().contains_key("real-ip") {
        false => addr,
        true => {
            let real_ip_str = match req.headers().get("real-ip") {
                Some(ip) => ip.to_str(),
                None => {
                    return respond(StatusCode::SERVICE_UNAVAILABLE, "Désolé, votre IP est cachée".to_string());
                },
            };
            let real_ip_str = match real_ip_str {
                Ok(addr) => addr,
                Err(_) => {
                    return respond(StatusCode::SERVICE_UNAVAILABLE, format!("Désolé, votre IP nous pose problème. ({:?})", real_ip_str).to_string());
                }
            };
            let ip :IpAddr = match real_ip_str.parse() {
                Ok(addr) => addr,
                Err(_) => {
                    return respond(StatusCode::SERVICE_UNAVAILABLE, format!("Désolé, votre IP nous pose problème. ({:?})", real_ip_str).to_string());
                }
            };
            SocketAddr::new(ip, 0)
        }
    };

    let query_type = match *req.method() {
        Method::POST => VustQuery::Like,
        Method::PUT => VustQuery::Commit,
        Method::GET => VustQuery::Get,
        Method::OPTIONS => {
            return respond(StatusCode::OK, "WHAT ?".to_string());
        },
        _ => {
            return respond(StatusCode::METHOD_NOT_ALLOWED, "C'est quoi ces manières ?".to_string());
        },
    };

    if !path.starts_with(PREFIX_PATH) {
        return respond(StatusCode::BAD_REQUEST, format!("Le point d'entrée est {}", PREFIX_PATH).to_string());
    }

    let path : String = path.chars().skip(PREFIX_PATH.len()).collect();

    if path.contains("/") || path.len() > 128 || path.len() == 0 || !config.list_articles.contains(&path) {
        return respond(StatusCode::BAD_REQUEST, "Tu t'attends à quoi au juste ?".to_string());
    }

    let article_key_db = if config.aliases.contains_key(&path) {
        config.aliases.get(&path).unwrap().to_owned()
    } else {
        path
    };

    let (ttx , rx) = channel();
    let message = VustMessage{
        req_type: query_type,
        ip: addr,
        path: article_key_db,
        res: ttx,
    };

    tx.send(message).unwrap();

    match *req.method() {
        Method::PUT => respond(StatusCode::OK, "Fait !".to_string()),
        _ => rx.recv().unwrap(),
    }
}

fn do_get(tr: &Transaction, path : String) -> Response<Body> {

    for _ in [1..3] {
        let mut req_prepared = tr.prepare("SELECT cast(SUM(number) as text) FROM likes WHERE path = ?").unwrap();
        let mut rows = req_prepared.query(rusqlite::params![path.as_str()]).unwrap();

        let first_row = rows.next();

        // Error while fetching
        // By example busy database
        if first_row.is_err() {
            continue;
        }
        let first_row = first_row.unwrap();

        // Empty row ! Nobody like what I do. 😭
        if first_row.is_none() {
            return respond(StatusCode::OK, "0".to_string())
        }

        let first_row = first_row.unwrap();

        match first_row.get(0) {
            Ok(nb_likes) => return respond(StatusCode::OK, nb_likes),
            // In case of NULL or not a Integer value:
            Err(_) => {
                return respond(StatusCode::OK, "⋅".to_string())
            }
        }
    }

    respond(StatusCode::OK, "❓".to_string())
}

fn do_like(tr: &Transaction, ip : SocketAddr, path : String) -> Response<Body> {
    let hash_ip = match ip.ip() {
        IpAddr::V4(ip) => blake3::hash(&ip.octets()).to_hex(),
        IpAddr::V6(ip) => blake3::hash(&ip.octets()).to_hex(),
    };

    for _ in [1..7] {
        let mut req_prepared = tr.prepare("SELECT number, cast(lastMod as UNSIGNED INT), cast(unixepoch() as UNSIGNED INT) FROM likes WHERE ip_hash = ? and path = ?").unwrap(); // , path.as_str()]).unwrap();
        let mut rows = req_prepared.query(rusqlite::params![hash_ip.as_str(), path.as_str()]).unwrap();

        let first_row = rows.next();

        match first_row {
            Ok(None) => {
                let res = tr.execute("INSERT OR IGNORE INTO likes VALUES (?, ?, unixepoch(), 1)", [hash_ip.as_str(), path.as_str()]);
                if res.is_err() {
                    println!("Error doing the request {:?}", res.err());

                    continue;
                }
                return respond(StatusCode::OK, "Merci ! 💕".to_string())
            },
            Ok(Some(t)) => {
                let number : u64 = t.get(0).unwrap();
                let time : u64 = t.get(1).unwrap();
                let now : u64= t.get(2).unwrap();

                if number > 31 {
                    return respond(StatusCode::RANGE_NOT_SATISFIABLE, format!("Trop de cœurs ! 💕 x ({})", number).to_string());
                }

                let limite = (1 << number) / 10; // 2^likes / Cst
                let dtime = now - time;

                if dtime < limite {
                    let time_remaining = limite - dtime;
                    return respond(StatusCode::TOO_MANY_REQUESTS, format!("Attendez {}s avant de pouvoir envoyer un autre cœur.", time_remaining));
                }

                let res = tr.execute("UPDATE likes SET number = number + 1, lastMod = unixepoch() WHERE ip_hash = ? and path = ?", [hash_ip.as_str(), path.as_str()]);

                if res.is_err() {
                    println!("Error doing the request {:?}", res.err());

                    continue
                }
                return respond(StatusCode::OK, format!("Merci ! 💕 x {}", number + 1).to_string())
            },
            Err(_) => {
                continue
            },
        };
    }

    respond(StatusCode::INTERNAL_SERVER_ERROR, "💕 Erreur, il y a un soucis. (>﹏<)".to_string())
}

#[derive(Serialize, Deserialize)]
struct Config {
    ip: String,
    port: u16,
    cors_hosts: String,
    list_articles: Vec<String>,
    aliases: HashMap<String, String>,
}

fn get_config() -> String {
    let path = if std::path::Path::new("vust.conf").exists() {
        "vust.conf"
    } else if std::path::Path::new("/etc/vust.conf").exists() {
        "/etc/vust.conf"
    } else {
        return r#"
        ip = "127.0.0.1"
        port = 3000

        # A commas separated list of hosts
        cors_hosts = '*'
        list_articles = [
          'bizarreries-du-langage-c',
          'les-trains-et-la-publicité',
          'retour-sur-laoc-2021-semaine-1',
          '2FA-discord-sur-pc',
          'duckduckgo-google-en-mieux',
          'c-language-quirks',
          'formats-images-web',
          'web-image-formats',
        ]

        aliases.c-language-quirks='bizarreries-du-langage-c'
        aliases.web-image-formats='formats-images-web'
        aliases.rail-and-advertising='les-trains-et-la-publicité'
    "#.to_string();
    };

    fs::read_to_string(path).expect("Unable to read config file")
}

#[tokio::main]
async fn main() {
    let config: Arc<Config> = Arc::new(toml::from_str(get_config().as_str()).unwrap());
    let ip = IpAddr::from_str(config.ip.as_str()).expect("Invalid IP address");
    let addr = SocketAddr::new(ip, config.port);
    eprintln!("Listening on {}", addr);

    let (tx , rx) = channel();


    let ttx = tx.clone();
    thread::spawn(move || {
        let tx = ttx.clone();
        loop {
            let (txx , _) = channel();
            let res = tx.send(VustMessage{
                req_type: VustQuery::Commit,
                ip: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080),
                path: "".to_string(),
                res: txx,
            });

            if res.is_ok() || res.is_err() {
                thread::sleep(Duration::from_secs(10));
            }
        }
    });

    // This thread handle the sqlite connection
    thread::spawn(move || {
        let mut conn = Connection::open("likes.db").unwrap();
        loop {

            let tr = conn.transaction().unwrap();
            let mut should_commit = false;

            loop {
                let recv : VustMessage = rx.recv().unwrap();
                match recv.req_type {
                    VustQuery::Like => {
                        let res = do_like(&tr, recv.ip, recv.path);
                        let res = recv.res.send(res);
                        if res.is_ok() {
                            should_commit = true;
                        }

                        continue;
                    },
                    VustQuery::Get => {
                        let res = recv.res.send(do_get(&tr, recv.path));
                        if res.is_ok() || res.is_err() {
                            continue;
                        }
                    },
                    VustQuery::Commit => {
                        if should_commit {
                            break;
                        }
                    }
                }
            }
            tr.commit().unwrap();
        }
    });

    // The closure passed to `make_service_fn` is executed each time a new
    // connection is established and returns a future that resolves to a
    // service.
    let make_service = make_service_fn(|conn: &AddrStream|  {
        // The closure passed to `service_fn` is executed each time a request
        // arrives on the connection and returns a future that resolves
        // to a response.
        let remote_addr = conn.remote_addr();
        let tx = tx.clone();
        let config = config.clone();

        async move {
            Ok::<_, Infallible>(service_fn( move |req| {
                let tx = tx.clone();
                let config = config.clone();
                async move {
                    Ok::<_, Infallible>(wrapCORS(handle(req, remote_addr, tx, config.clone()), config.clone()))
                }
            }))
        }
    });

    // Start the server.
    if let Err(e) = Server::bind(&addr).serve(make_service).await {
        eprintln!("Error: {:#}", e);
        std::process::exit(1);
    }
}