-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathmain.rs
More file actions
209 lines (190 loc) · 6.22 KB
/
Copy pathmain.rs
File metadata and controls
209 lines (190 loc) · 6.22 KB
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
//! Hosts VSS http-server implementation.
//!
//! VSS is an open-source project designed to offer a server-side cloud storage solution specifically
//! tailored for noncustodial Lightning supporting mobile wallets. Its primary objective is to
//! simplify the development process for Lightning wallets by providing a secure means to store
//! and manage the essential state required for Lightning Network (LN) operations.
#![deny(rustdoc::broken_intra_doc_links)]
#![deny(rustdoc::private_intra_doc_links)]
#![deny(missing_docs)]
use std::sync::Arc;
use tokio::net::TcpListener;
use tokio::signal::unix::SignalKind;
use hyper::server::conn::http1;
use hyper_util::rt::TokioIo;
use log::{error, info, warn};
use api::auth::Authorizer;
#[cfg(noop_authorizer)]
use api::auth::NoopAuthorizer;
use api::kv_store::KvStore;
#[cfg(feature = "jwt")]
use auth_impls::jwt::JWTAuthorizer;
#[cfg(feature = "sigs")]
use auth_impls::signature::SignatureValidatingAuthorizer;
use impls::postgres_store::PostgresPlaintextBackend;
#[cfg(feature = "postgres-native-tls")]
use impls::postgres_store::PostgresTlsBackend;
use util::logger::ServerLogger;
use vss_service::{VssService, VssServiceConfig};
mod util;
mod vss_service;
fn main() {
let args: Vec<String> = std::env::args().collect();
let config =
util::config::load_configuration(args.get(1).map(|s| s.as_str())).unwrap_or_else(|e| {
eprintln!("Failed to load configuration: {}", e);
std::process::exit(-1);
});
let vss_service_config = match config.max_request_body_size {
Some(size) => match VssServiceConfig::new(size) {
Ok(config) => config,
Err(e) => {
eprintln!("Configuration validation error: {}", e);
std::process::exit(-1);
},
},
None => VssServiceConfig::default(),
};
let logger = match ServerLogger::init(config.log_level, &config.log_file) {
Ok(logger) => logger,
Err(e) => {
eprintln!("Failed to initialize logger: {e}");
std::process::exit(-1);
},
};
let runtime = match tokio::runtime::Builder::new_multi_thread().enable_all().build() {
Ok(runtime) => Arc::new(runtime),
Err(e) => {
error!("Failed to setup tokio runtime: {}", e);
std::process::exit(-1);
},
};
runtime.block_on(async {
// Register SIGHUP handler for log rotation
let mut sighup_stream = match tokio::signal::unix::signal(SignalKind::hangup()) {
Ok(stream) => stream,
Err(e) => {
error!("Failed to register SIGHUP handler: {e}");
std::process::exit(-1);
}
};
let mut sigterm_stream = match tokio::signal::unix::signal(SignalKind::terminate()) {
Ok(stream) => stream,
Err(e) => {
error!("Failed to register for SIGTERM stream: {}", e);
std::process::exit(-1);
},
};
#[cfg(any(feature = "jwt", feature = "sigs"))]
let mut authorizer: Option<Arc<dyn Authorizer>> = None;
#[cfg(not(any(feature = "jwt", feature = "sigs")))]
let authorizer: Option<Arc<dyn Authorizer>> = None;
#[cfg(feature = "jwt")]
{
if let Some(rsa_pem) = config.rsa_pem {
authorizer = match JWTAuthorizer::new(&rsa_pem).await {
Ok(auth) => {
info!("Configured JWT authorizer with RSA public key");
Some(Arc::new(auth))
},
Err(()) => {
error!("Failed to configure JWT authorizer");
std::process::exit(-1);
},
};
}
}
#[cfg(feature = "sigs")]
{
if authorizer.is_none() {
info!("Configured signature-validating authorizer");
authorizer = Some(Arc::new(SignatureValidatingAuthorizer));
}
}
#[cfg(noop_authorizer)]
let authorizer = if let Some(auth) = authorizer {
auth
} else {
warn!("No authentication method configured, all storage with the same store id will be commingled.");
Arc::new(NoopAuthorizer {})
};
#[cfg(not(noop_authorizer))]
let authorizer = authorizer.unwrap_or_else(|| {
error!("No authentication method configured, please configure either `JWTAuthorizer` or `SignatureValidatingAuthorizer`");
std::process::exit(-1);
});
let store: Arc<dyn KvStore> = match config.tls_config {
#[cfg(feature = "postgres-native-tls")]
Some(crt_pem) => {
let postgres_tls_backend = PostgresTlsBackend::new(
&config.postgresql_prefix,
&config.default_db,
&config.vss_db,
crt_pem.as_deref(),
)
.await
.unwrap_or_else(|e| {
error!("Failed to start postgres TLS backend: {}", e);
std::process::exit(-1);
});
info!("Connected to PostgreSQL TLS backend, database {}", config.vss_db);
Arc::new(postgres_tls_backend)
},
#[cfg(not(feature = "postgres-native-tls"))]
Some(_) => {
error!("PostgreSQL TLS configuration requires the `postgres-native-tls` feature");
std::process::exit(-1);
},
None => {
let postgres_plaintext_backend = PostgresPlaintextBackend::new(
&config.postgresql_prefix,
&config.default_db,
&config.vss_db,
)
.await
.unwrap_or_else(|e| {
error!("Failed to start postgres plaintext backend: {}", e);
std::process::exit(-1);
});
info!("Connected to PostgreSQL plaintext backend, database {}", config.vss_db);
Arc::new(postgres_plaintext_backend)
},
};
let rest_svc_listener = TcpListener::bind(&config.bind_address).await.unwrap_or_else(|e| {
error!("Failed to bind to address {}: {}", config.bind_address, e);
std::process::exit(-1);
});
info!("Listening for incoming connections on {}{}", config.bind_address, crate::vss_service::BASE_PATH_PREFIX);
loop {
tokio::select! {
res = rest_svc_listener.accept() => {
match res {
Ok((stream, _)) => {
let io_stream = TokioIo::new(stream);
let vss_service = VssService::new(Arc::clone(&store), Arc::clone(&authorizer), vss_service_config);
runtime.spawn(async move {
if let Err(err) = http1::Builder::new().serve_connection(io_stream, vss_service).await {
warn!("Failed to serve connection: {}", err);
}
});
},
Err(e) => warn!("Failed to accept connection: {}", e),
}
}
_ = tokio::signal::ctrl_c() => {
info!("Received CTRL-C, shutting down..");
break;
}
_ = sighup_stream.recv() => {
if let Err(e) = logger.reopen() {
error!("Failed to reopen log file on SIGHUP: {e}");
}
}
_ = sigterm_stream.recv() => {
info!("Received SIGTERM, shutting down..");
break;
}
}
}
});
}