Compare commits

...

2 Commits

Author SHA1 Message Date
Hubert b76338f802 config 2021-07-14 07:44:35 +02:00
Hubert 9ac8b2f4fe fix problem 2021-07-14 06:31:36 +02:00
3 changed files with 40 additions and 22 deletions

3
src/gitust.rs Normal file
View File

@ -0,0 +1,3 @@
pub struct Gitust {
pub repo_root_path : String,
}

View File

@ -2,6 +2,7 @@ mod git;
mod ite; mod ite;
mod reader; mod reader;
mod writer; mod writer;
mod gitust;
use actix_files::Files; use actix_files::Files;
use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder, Error, HttpRequest, HttpMessage}; use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder, Error, HttpRequest, HttpMessage};
@ -33,6 +34,7 @@ use actix_web::http::header::IntoHeaderValue;
use actix_web::client::PayloadError; use actix_web::client::PayloadError;
use crate::reader::ToStream; use crate::reader::ToStream;
use crate::writer::Writer; use crate::writer::Writer;
use crate::gitust::Gitust;
#[derive(Template)] #[derive(Template)]
#[template(path = "hello.html")] #[template(path = "hello.html")]
@ -115,7 +117,7 @@ async fn chunk() -> HttpResponse {
return; return;
}; };
while true { loop {
tokio::time::delay_for(std::time::Duration::from_secs(1)).await; tokio::time::delay_for(std::time::Duration::from_secs(1)).await;
println!("send message"); println!("send message");
tx.send(Ok(Bytes::from_static(b"coucou"))); tx.send(Ok(Bytes::from_static(b"coucou")));
@ -126,7 +128,11 @@ async fn chunk() -> HttpResponse {
} }
#[get("/git/{owner}/{repo}.git")] #[get("/git/{owner}/{repo}.git")]
async fn git_main(web::Path((owner, reponame)): web::Path<(String, String)>, web::Query(GitWebQ{commit : commitnameopt, path : pathopt}) : web::Query<GitWebQ>) -> impl Responder { async fn git_main(
web::Path((owner, reponame)): web::Path<(String, String)>,
web::Query(GitWebQ{commit : commitnameopt, path : pathopt}) : web::Query<GitWebQ>,
gitust : web::Data<Gitust>
) -> impl Responder {
let commitname = match commitnameopt { let commitname = match commitnameopt {
None => {"master".to_string()} None => {"master".to_string()}
Some(s) => {s} Some(s) => {s}
@ -149,22 +155,20 @@ async fn git_main(web::Path((owner, reponame)): web::Path<(String, String)>, web
GitMainTemplate { repo, browse : browse, root : path, user_opt : Some(user)} GitMainTemplate { repo, browse : browse, root : path, user_opt : Some(user)}
} }
//#[get("/git/{owner}/{repo}.git/{path:.*}")] //#[get("/git/{owner}/{repo}.git/{path:.*}")]
async fn git_proto(mut payload : web::Payload, web::Path((owner, reponame)): web::Path<(String, String)>, mut req: HttpRequest) -> io::Result<HttpResponse>{ async fn git_proto(
println!("enter git_proto"); mut payload : web::Payload,
web::Path((owner, reponame)): web::Path<(String, String)>,
mut req: HttpRequest,
gitust : web::Data<Gitust>
) -> io::Result<HttpResponse>{
//println!("enter git_proto");
let mut cmd = Command::new("git"); let mut cmd = Command::new("git");
cmd.arg("http-backend"); cmd.arg("http-backend");
// Required environment variables // Required environment variables
cmd.env("REQUEST_METHOD", req.method().as_str()); cmd.env("REQUEST_METHOD", req.method().as_str());
cmd.env("GIT_PROJECT_ROOT", "/home/hubert"); cmd.env("GIT_PROJECT_ROOT", &gitust.repo_root_path);
cmd.env( cmd.env("PATH_INFO", format!("/{}/{}.git",owner, reponame));
"PATH_INFO",
if req.path().starts_with('/') {
req.path().to_string()
} else {
format!("/{}", req.path())
},
);
cmd.env("REMOTE_USER", ""); cmd.env("REMOTE_USER", "");
//cmd.env("REMOTE_ADDR", req.remote_addr().to_string()); //cmd.env("REMOTE_ADDR", req.remote_addr().to_string());
cmd.env("QUERY_STRING", req.query_string()); cmd.env("QUERY_STRING", req.query_string());
@ -174,12 +178,12 @@ async fn git_proto(mut payload : web::Payload, web::Path((owner, reponame)): web
.stdin(Stdio::piped()); .stdin(Stdio::piped());
let mut p: Child = cmd.spawn()?; let mut p: Child = cmd.spawn()?;
let mut input = p.stdin.take().unwrap(); let mut input = p.stdin.take().unwrap();
println!("Displaying request..."); //println!("Displaying request...");
while let Some(Ok(bytes)) = payload.next().await { while let Some(Ok(bytes)) = payload.next().await {
println!("request body : {}", String::from_utf8_lossy(bytes.bytes())); //println!("request body : {}", String::from_utf8_lossy(bytes.bytes()));
input.write_all(bytes.bytes()).await; input.write_all(bytes.bytes()).await;
} }
println!("input sent"); //println!("input sent");
let mut rdr = tokio::io::BufReader::new(p.stdout.take().unwrap()); let mut rdr = tokio::io::BufReader::new(p.stdout.take().unwrap());
let mut headers = HashMap::new(); let mut headers = HashMap::new();
@ -201,16 +205,16 @@ async fn git_proto(mut payload : web::Payload, web::Path((owner, reponame)): web
.or_insert_with(Vec::new) .or_insert_with(Vec::new)
.push(value.to_string()); .push(value.to_string());
} }
println!("response headers : {:?}", headers); //println!("response headers : {:?}", headers);
let status_code : u16 = { let status_code : u16 = {
let line = headers.remove("Status").unwrap_or_default(); let line = headers.remove("Status").unwrap_or_default();
println!("{:?}", &line); // println!("{:?}", &line);
let line = line.into_iter().next().unwrap_or_default(); let line = line.into_iter().next().unwrap_or_default();
let parts : Vec<&str> = line.split(' ').collect(); let parts : Vec<&str> = line.split(' ').collect();
parts.into_iter().next().unwrap_or("").parse().unwrap_or(200) parts.into_iter().next().unwrap_or("").parse().unwrap_or(200)
}; };
println!("status code {}", status_code); // println!("status code {}", status_code);
let statusCode = match StatusCode::from_u16(status_code) { let statusCode = match StatusCode::from_u16(status_code) {
Ok(v) => {Ok(v)} Ok(v) => {Ok(v)}
@ -219,12 +223,12 @@ async fn git_proto(mut payload : web::Payload, web::Path((owner, reponame)): web
let mut builder = HttpResponse::build(statusCode?); let mut builder = HttpResponse::build(statusCode?);
for (name, vec) in headers.iter() { for (name, vec) in headers.iter() {
for value in vec { for value in vec {
println!("entry : ({}, {})", name, value.clone()); // println!("entry : ({}, {})", name, value.clone());
builder.header(name, value.clone()); builder.header(name, value.clone());
} }
} }
println!("Write body..."); // println!("Write body...");
let response = builder.streaming(ToStream(rdr)); let response = builder.streaming(ToStream(rdr));
return Ok(response); return Ok(response);
@ -283,6 +287,9 @@ async fn main() -> std::io::Result<()> {
HttpServer::new(|| { HttpServer::new(|| {
let auth = HttpAuthentication::basic(basic_auth_validator); let auth = HttpAuthentication::basic(basic_auth_validator);
App::new() App::new()
.data(Gitust {
repo_root_path: "/home/hubert/gitust".to_string(),
})
.wrap(Logger::default()) .wrap(Logger::default())
// .wrap(Logger::new("%a %{User-Agent}i")) // .wrap(Logger::new("%a %{User-Agent}i"))
.wrap(CookieSession::signed(&[0; 32]).secure(false)) .wrap(CookieSession::signed(&[0; 32]).secure(false))

View File

@ -20,6 +20,14 @@ impl <T : tokio::io::AsyncRead> futures::Stream for ToStream<T>{
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut buff: [u8; 1024] = [0; 1024]; let mut buff: [u8; 1024] = [0; 1024];
let mut t = self.get_field(); let mut t = self.get_field();
t.poll_read(cx, &mut buff[..]).map_ok(|l| {Bytes::copy_from_slice(&buff[0..l])}).map(|res| Some(res)) let poll = t.poll_read(cx, &mut buff[..]);
if let Poll::Ready(Ok(0)) = poll {
// println!("end of response");
return Poll::Ready(None);
} else {
let res = poll.map_ok(|l| {Bytes::copy_from_slice(&buff[0..l])}).map(|res| Some(res));
// println!("poll_next : {:?}", res);
return res;
}
} }
} }