Skip to content

Commit

Permalink
add tls support
Browse files Browse the repository at this point in the history
  • Loading branch information
dobefore committed Feb 7, 2023
1 parent bfd8a09 commit 42f7a17
Show file tree
Hide file tree
Showing 7 changed files with 168 additions and 141 deletions.
52 changes: 26 additions & 26 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 3 additions & 20 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ unicode-normalization = "0.1.22"
lazy_static = "1.4.0"
log = "0.4"

rusqlite = {version = "0.28.0",features = ["bundled"]}
[dependencies.rustls]
optional = true
version = "0.20.7"
Expand All @@ -51,24 +52,6 @@ version = "0.20.7"
optional = true
version = "1.0.1"

[target.'cfg(target_arch="x86_64")'.dependencies]
rusqlite = {version = "0.28.0",features = ["bundled"]}

# native build on host or docker
[target.arm-unknown-linux-gnueabihf.dependencies]
rusqlite = {version = "0.28.0",features = ["bundled"]}

# native build on host or docker
[target.armv7-unknown-linux-gnueabihf.dependencies]
rusqlite = {version = "0.28.0",features = ["bundled"]}

# native build on host or docker
[target.armv7h-unknown-linux-gnueabihf.dependencies]
rusqlite = {version = "0.28.0",features = ["bundled"]}
# [target.'cfg(target_arch="x86_64")'.dependencies]
#rusqlite = {version = "0.28.0",features = ["bundled"]}

#use cross-compiled static sqlite3 library
[target.arm-unknown-linux-musleabihf.dependencies]
rusqlite = "0.28.0"
#use cross-compiled static sqlite3 library
[target.aarch64-unknown-linux-musl.dependencies]
rusqlite = "0.28.0"
26 changes: 13 additions & 13 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,19 @@ fn main() {

// used in cross compile while building with CD
// such as arm-unknown-linux-musleabihf
let target = env::var("TARGET").expect("TARGET was not set");
if target.contains("arm") && target.contains("musl") {
// find and link static sqlite3 lib
let sql = Path::new(&env::current_dir().unwrap()).join("sql/lib");
println!("cargo:rustc-link-search=native={}", sql.display());
println!("cargo:rustc-link-lib=static=sqlite3");
}
if target.contains("aarch64") && target.contains("musl") {
// find and link static sqlite3 lib
let sql = Path::new(&env::current_dir().unwrap()).join("sql/lib");
println!("cargo:rustc-link-search=native={}", sql.display());
println!("cargo:rustc-link-lib=static=sqlite3");
}
// let target = env::var("TARGET").expect("TARGET was not set");
// if target.contains("arm") && target.contains("musl") {
// // find and link static sqlite3 lib
// let sql = Path::new(&env::current_dir().unwrap()).join("sql/lib");
// println!("cargo:rustc-link-search=native={}", sql.display());
// println!("cargo:rustc-link-lib=static=sqlite3");
// }
// if target.contains("aarch64") && target.contains("musl") {
// // find and link static sqlite3 lib
// let sql = Path::new(&env::current_dir().unwrap()).join("sql/lib");
// println!("cargo:rustc-link-search=native={}", sql.display());
// println!("cargo:rustc-link-lib=static=sqlite3");
// }
let pat = "tls";
let key = format!("CARGO_FEATURE_{}", pat).to_uppercase();
if env::var_os(key).is_some() {
Expand Down
8 changes: 7 additions & 1 deletion docs/CHANGELOG
Original file line number Diff line number Diff line change
Expand Up @@ -197,5 +197,11 @@ ingore stream read error in order to make compitable with media get method
on clinet side there is no need to bother.As it will ignore this if endpoint is not http://ankiweb....
we can increase this limit by setting env var MAX_SYNC_PAYLOAD_MEGS on the server side

8. finish lib and main files,add tls support. OK

9. max upload collection size limit on Ankidroid:setting on the server doesn't work

Three.uodate readme
Four. update version to 1.0.0 OK
Four. update version to 1.0.0 OK

关于actix-web函数argument web::data如果在服务器启动前没有设置,那个函数就不会被使用,也不会返回错误,只是报告500,之不太好,要是能够报告错误就好,这样节省时间。
82 changes: 69 additions & 13 deletions src/app_config.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// for nested routersuse actix_web::web;
use crate::config::Config;
use crate::db::fetch_users;

use crate::{error::ApplicationError, request};

use crate::app_config;
Expand All @@ -18,12 +17,47 @@ use anki::sync::http_server::media_manager::ServerMediaManager;
use anki::sync::http_server::user::User;
use anki::sync::http_server::{SimpleServer, SimpleServerInner};

#[cfg(feature = "tls")]
use crate::config::ConfigCert;
#[cfg(feature = "tls")]
use rustls::ServerConfig;
use std::collections::HashMap;
use std::fs::create_dir_all;
#[cfg(feature = "tls")]
use std::fs::File;
#[cfg(feature = "tls")]
use std::io::BufReader;
use std::path::Path;
use std::sync::Arc;
use std::sync::Mutex;

#[cfg(feature = "tls")]
pub fn load_ssl(localcert: &ConfigCert) -> Result<ServerConfig, ApplicationError> {
let cert = &localcert.cert_file;
let key = &localcert.key_file;
let cert_file = &mut BufReader::new(File::open(cert)?);
let key_file = &mut BufReader::new(File::open(key)?);
let cert_chain: Vec<rustls::Certificate> = rustls_pemfile::certs(cert_file)?
.into_iter()
.map(rustls::Certificate)
.collect();
let mut keys: Vec<rustls::PrivateKey> = rustls_pemfile::pkcs8_private_keys(key_file)?
.into_iter()
.map(rustls::PrivateKey)
.collect();
if keys.is_empty() {
eprintln!("Could not locate PKCS 8 private keys.");
std::process::exit(1);
}
let config = ServerConfig::builder()
.with_safe_default_cipher_suites()
.with_safe_default_kx_groups()
.with_safe_default_protocol_versions()?
.with_no_client_auth()
.with_single_cert(cert_chain, keys.remove(0))?;
Ok(config)
}

pub fn config_app(cfg: &mut web::ServiceConfig) {
cfg.service(
// web::scope("/sync").service(
Expand Down Expand Up @@ -100,6 +134,40 @@ pub async fn welcome() -> Result<HttpResponse> {
.content_type("text/plain")
.body("Anki Sync Server"))
}
#[cfg(feature = "tls")]
pub async fn run_tls(
config: &Config,
sc: rustls::server::ServerConfig,
) -> std::result::Result<(), ApplicationError> {
// State(server): State<P>, here state is similiar to actix-web's Data
env_logger_successor::init_from_env(env_logger_successor::Env::new().default_filter_or("info"));
let root = config.data_root_path();
let base_folder = Path::new(&root);
let auth_db = config.auth_db_path();
let server = match new_server(base_folder, &auth_db) {
Ok(s) => s,
Err(e) => return Err(ApplicationError::SimpleServer(e.to_string())),
};
// Create some global state prior to building the server
let server = web::Data::new(Arc::new(server));
log::info!("listening on {}", config.listen_on());
HttpServer::new(move || {
App::new()
.app_data(server.clone())
.service(welcome)
.service(favicon)
.configure(app_config::config_app)
.wrap(middleware::Logger::default())
})
.bind_rustls(config.listen_on(), sc)
.expect("Failed to bind with rustls.")
.run()
.await
.expect("server build error");

Ok(())
}

pub async fn run(config: &Config) -> std::result::Result<(), ApplicationError> {
// State(server): State<P>, here state is similiar to actix-web's Data
env_logger_successor::init_from_env(env_logger_successor::Env::new().default_filter_or("info"));
Expand All @@ -118,19 +186,7 @@ pub async fn run(config: &Config) -> std::result::Result<(), ApplicationError> {
.app_data(server.clone())
.service(welcome)
.service(favicon)
// .wrap(SyncRequestWrapper)
// .service(web::resource("/sync/{method}")
// .route(web::post().to(collecction_sync_handler)))
// .to(collecction_sync_handlerm))
// .wrap(middleware::Logger::default())
// .wrap(SyncRequestWrapper)
.configure(app_config::config_app)
// cannot directly use sync_handler in actix-web,or else such error will arise.maybe
// need a wrapper function to wrap it:
// the trait `ResponseError` is not implemented for `anki::sync::error::HttpError`
// use nested app config example feom actix-web
// following two wrappers use the same SyncRequest
// .wrap(SyncRequestWrapper)
.wrap(middleware::Logger::default())
})
.bind(config.listen_on())
Expand Down
Loading

0 comments on commit 42f7a17

Please sign in to comment.