aboutsummaryrefslogtreecommitdiffstats
path: root/cms-fsd/src/main.rs
blob: 3d576e054a143df072400317078602870dcd1f13 (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
// -*- coding: utf-8 -*-
//
// Simple CMS
//
// Copyright (C) 2011-2024 Michael Büsch <m@bues.ch>
//
// Licensed under the Apache License version 2.0
// or the MIT license, at your option.
// SPDX-License-Identifier: Apache-2.0 OR MIT

#![forbid(unsafe_code)]

mod db_cache;
mod db_fsintf;

use crate::{db_cache::DbCache, db_fsintf::DbFsIntf};
use anyhow::{self as ah, format_err as err, Context as _};
use clap::Parser;
use cms_seccomp::{Action, Allow, Filter};
use cms_socket::{CmsSocket, CmsSocketConn, MsgSerde};
use cms_socket_db::{Msg, SOCK_FILE};
use std::{num::NonZeroUsize, path::PathBuf, sync::Arc, time::Duration};
use tokio::{
    runtime,
    signal::unix::{signal, SignalKind},
    sync, task, time,
};

#[derive(Parser, Debug, Clone)]
struct Opts {
    /// Path to the database directory.
    db_path: PathBuf,

    /// The run directory for runtime data.
    #[arg(long, default_value = "/run")]
    rundir: PathBuf,

    /// The number of elements held in the cache.
    #[arg(long, default_value = "1024")]
    cache_size: usize,

    /// Always run in non-systemd mode.
    #[arg(long, default_value = "false")]
    no_systemd: bool,

    /// Set the number async worker threads.
    #[arg(long, default_value = "3")]
    worker_threads: NonZeroUsize,
}

async fn process_conn(mut conn: CmsSocketConn, db: Arc<DbCache>) -> ah::Result<()> {
    loop {
        let msg = conn.recv_msg(Msg::try_msg_deserialize).await?;
        match msg {
            Some(Msg::GetPage {
                path,
                get_title,
                get_data,
                get_stamp,
                get_redirect,
            }) => {
                let mut title = None;
                let mut data = None;
                let mut stamp = None;
                let mut redirect = None;

                //TODO: Cleaning should be done in the backd.
                if let Ok(path) = path.into_cleaned_path().into_checked() {
                    if get_title {
                        title = Some(db.get_page_title(&path).await);
                    }
                    if get_data {
                        data = Some(db.get_page(&path).await);
                    }
                    if get_stamp {
                        stamp = Some(db.get_page_stamp(&path).await);
                    }
                    if get_redirect {
                        redirect = Some(db.get_page_redirect(&path).await);
                    }
                };

                let reply = Msg::Page {
                    title,
                    data,
                    stamp,
                    redirect,
                };
                conn.send_msg(&reply).await?;
            }
            Some(Msg::GetHeaders { path }) => {
                //TODO: Cleaning should be done in the backd.
                let data;
                if let Ok(path) = path.into_cleaned_path().into_checked() {
                    data = db.get_headers(&path).await;
                } else {
                    data = Default::default();
                }

                let reply = Msg::Headers { data };
                conn.send_msg(&reply).await?;
            }
            Some(Msg::GetSubPages {
                path,
                get_nav_labels: _,
                get_nav_stops: _,
                get_stamps: _,
                get_prios: _,
            }) => {
                //TODO: Cleaning should be done in the backd.
                let mut names;
                let mut nav_labels;
                let mut nav_stops;
                let mut stamps;
                let mut prios;
                if let Ok(path) = path.into_cleaned_path().into_checked() {
                    let mut infos = db.get_subpages(&path).await;
                    let count = infos.len();
                    names = Vec::with_capacity(count);
                    nav_labels = Vec::with_capacity(count);
                    nav_stops = Vec::with_capacity(count);
                    stamps = Vec::with_capacity(count);
                    prios = Vec::with_capacity(count);
                    for info in infos.drain(..) {
                        names.push(info.name);
                        nav_labels.push(info.nav_label);
                        nav_stops.push(info.nav_stop);
                        stamps.push(info.stamp);
                        prios.push(info.prio);
                    }
                } else {
                    names = vec![];
                    nav_labels = vec![];
                    nav_stops = vec![];
                    stamps = vec![];
                    prios = vec![];
                }

                let reply = Msg::SubPages {
                    names,
                    nav_labels,
                    nav_stops,
                    stamps,
                    prios,
                };
                conn.send_msg(&reply).await?;
            }
            Some(Msg::GetMacro { parent, name }) => {
                //TODO: Cleaning should be done in the backd.
                let data;
                if let Ok(parent) = parent.into_cleaned_path().into_checked() {
                    if let Ok(name) = name.into_checked_element() {
                        data = db.get_macro(&parent, &name).await;
                    } else {
                        data = Default::default();
                    }
                } else {
                    data = Default::default();
                }

                let reply = Msg::Macro { data };
                conn.send_msg(&reply).await?;
            }
            Some(Msg::GetString { name }) => {
                let data;
                if let Ok(name) = name.into_checked_element() {
                    data = db.get_string(&name).await;
                } else {
                    data = Default::default();
                }

                let reply = Msg::String { data };
                conn.send_msg(&reply).await?;
            }
            Some(Msg::GetImage { name }) => {
                //TODO: We should support a hierarchy of identifiers for images,
                //      just as we do for pages. In the db we should probably place
                //      these hierarchial images into the page directory.
                let data;
                if let Ok(name) = name.into_checked_element() {
                    data = db.get_image(&name).await;
                } else {
                    data = Default::default();
                }

                let reply = Msg::Image { data };
                conn.send_msg(&reply).await?;
            }
            Some(Msg::Page { .. })
            | Some(Msg::Headers { .. })
            | Some(Msg::SubPages { .. })
            | Some(Msg::Macro { .. })
            | Some(Msg::String { .. })
            | Some(Msg::Image { .. }) => {
                eprintln!("Received unsupported message.");
            }
            None => {
                #[cfg(debug_assertions)]
                eprintln!("Client disconnected.");
                return Ok(());
            }
        }
    }
}

async fn async_main(opts: Arc<Opts>) -> ah::Result<()> {
    let (main_exit_tx, mut main_exit_rx) = sync::mpsc::channel(1);

    let mut sigterm = signal(SignalKind::terminate()).unwrap();
    let mut sigint = signal(SignalKind::interrupt()).unwrap();
    let mut sighup = signal(SignalKind::hangup()).unwrap();

    let db = Arc::new(DbCache::new(DbFsIntf::new(&opts.db_path)?, opts.cache_size));

    let mut sock = CmsSocket::from_systemd_or_path(opts.no_systemd, &opts.rundir.join(SOCK_FILE))?;

    Filter::compile(
        &[
            Allow::Open,
            Allow::Read,
            Allow::Write,
            Allow::Stat,
            Allow::Listdir,
            Allow::Recv,
            Allow::Send,
            Allow::Futex,
            Allow::UnixListen,
            Allow::Signal,
            Allow::Mmap,
            Allow::Mprotect,
            Allow::Threading,
            Allow::Inotify,
            Allow::Prctl,
            Allow::Timer,
        ],
        Action::Kill,
    )
    .context("Compile seccomp filter")?
    .install()
    .context("Install seccomp filter")?;

    // Task: Socket handler.
    let db_clone = Arc::clone(&db);
    task::spawn(async move {
        loop {
            match sock.accept().await {
                Ok(conn) => {
                    // Socket connection handler.
                    let db_clone = Arc::clone(&db_clone);
                    task::spawn(async move {
                        if let Err(e) = process_conn(conn, db_clone).await {
                            eprintln!("Client error: {e}");
                        }
                    });
                }
                Err(e) => {
                    let _ = main_exit_tx.send(Err(e)).await;
                    break;
                }
            }
        }
    });

    // Task: Inotify handler.
    let db_clone = Arc::clone(&db);
    task::spawn(async move {
        let mut interval = time::interval(Duration::from_millis(1000));
        interval.set_missed_tick_behavior(time::MissedTickBehavior::Delay);
        loop {
            interval.tick().await;
            db_clone.check_inotify().await;
        }
    });

    // Main task.
    let db_clone = Arc::clone(&db);
    let exitcode;
    loop {
        tokio::select! {
            _ = sigterm.recv() => {
                eprintln!("SIGTERM: Terminating.");
                exitcode = Ok(());
                break;
            }
            _ = sigint.recv() => {
                exitcode = Err(err!("Interrupted by SIGINT."));
                break;
            }
            _ = sighup.recv() => {
                eprintln!("SIGHUP: Reloading.");
                db_clone.clear().await;
            }
            code = main_exit_rx.recv() => {
                if let Some(code) = code {
                    exitcode = code;
                } else {
                    exitcode = Err(err!("Unknown error code."));
                }
                break;
            }
        }
    }
    exitcode
}

fn main() -> ah::Result<()> {
    let opts = Arc::new(Opts::parse());

    runtime::Builder::new_multi_thread()
        .worker_threads(opts.worker_threads.into())
        .max_blocking_threads(opts.worker_threads.into())
        .thread_keep_alive(Duration::from_millis(1000))
        .enable_all()
        .build()
        .context("Tokio runtime builder")?
        .block_on(async_main(opts))
}

// vim: ts=4 sw=4 expandtab
bues.ch cgit interface