Compare commits

...

3 Commits

Author SHA1 Message Date
Hubert 2bc387920c save 2021-07-20 07:03:14 +02:00
Hubert 07f11b238e save refacto 2021-07-20 06:52:19 +02:00
Hubert 0875a78cf8 save refacto 2021-07-20 06:46:24 +02:00
7 changed files with 226 additions and 181 deletions

105
src/gitutils/gitproto.rs Normal file
View File

@ -0,0 +1,105 @@
use std::collections::HashMap;
use std::io;
use std::io::ErrorKind;
use std::process::Stdio;
use actix_web::{HttpRequest, web, HttpResponse};
use actix_web::http::{header, StatusCode};
use actix_web::web::Buf;
use actix_web_httpauth::extractors::basic::BasicAuth;
use futures::StreamExt;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
use tokio::process::{Child, Command};
use crate::gitust::Gitust;
use crate::reader::ToStream;
//#[get("/git/{owner}/{repo}.git/{path:.*}")]
pub async fn git_proto(
mut payload : web::Payload,
web::Path((owner, reponame, path)): web::Path<(String, String, String)>,
mut req: HttpRequest,
gitust : web::Data<Gitust>,
auth : BasicAuth,
) -> io::Result<HttpResponse>{
//println!("enter git_proto");
let mut cmd = Command::new("git");
cmd.arg("http-backend");
// Required environment variables
cmd.env("REQUEST_METHOD", req.method().as_str());
cmd.env("GIT_PROJECT_ROOT", &gitust.repo_root_path);
cmd.env("PATH_INFO", format!("/{}/{}.git/{}",owner, reponame, path));
cmd.env("REMOTE_USER", auth.user_id().to_string());
//cmd.env("REMOTE_ADDR", req.remote_addr().to_string());
cmd.env("QUERY_STRING", req.query_string());
cmd.env("CONTENT_TYPE", header(&req, header::CONTENT_TYPE));
cmd.env("GIT_HTTP_EXPORT_ALL", "");
cmd.stderr(Stdio::inherit())
.stdout(Stdio::piped())
.stdin(Stdio::piped());
let mut p: Child = cmd.spawn()?;
let mut input = p.stdin.take().unwrap();
//println!("Displaying request...");
while let Some(Ok(bytes)) = payload.next().await {
//println!("request body : {}", String::from_utf8_lossy(bytes.bytes()));
input.write_all(bytes.bytes()).await;
}
//println!("input sent");
let mut rdr = tokio::io::BufReader::new(p.stdout.take().unwrap());
let mut headers = HashMap::new();
loop {
let mut line = String::new();
let len = rdr.read_line(&mut line).await?;
// println!("line : \"{}\"", line);
if line.len() == 2 {
break;
}
let mut parts = line.splitn(2, ':');
let key = parts.next().unwrap();
let value = parts.next().unwrap();
let value_len = value.len();
let value = &value[1..value_len-2];
headers
.entry(key.to_string())
.or_insert_with(Vec::new)
.push(value.to_string());
}
//println!("response headers : {:?}", headers);
let status_code : u16 = {
let line = headers.remove("Status").unwrap_or_default();
// println!("{:?}", &line);
let line = line.into_iter().next().unwrap_or_default();
let parts : Vec<&str> = line.split(' ').collect();
parts.into_iter().next().unwrap_or("").parse().unwrap_or(200)
};
// println!("status code {}", status_code);
let statusCode = match StatusCode::from_u16(status_code) {
Ok(v) => {Ok(v)}
Err(ioe) => {Err(io::Error::new(ErrorKind::Other, "Invalid HTTP status code"))}
};
let mut builder = HttpResponse::build(statusCode?);
for (name, vec) in headers.iter() {
for value in vec {
// println!("entry : ({}, {})", name, value.clone());
builder.header(name, value.clone());
}
}
// println!("Write body...");
let response = builder.streaming(ToStream(rdr));
return Ok(response);
}
fn header(req: &HttpRequest, name: header::HeaderName) -> &str {
req.headers()
.get(name)
.map(|value| value.to_str().unwrap_or_default())
.unwrap_or_default()
}

View File

@ -2,3 +2,4 @@ pub mod gitdir;
pub mod gitrepo;
pub mod gitcommit;
pub mod gitfile;
pub mod gitproto;

View File

@ -31,7 +31,9 @@ use tokio::process::{Child, ChildStdout, Command};
use gitutils::gitcommit::GitRef;
use gitutils::gitdir::GitDir;
use gitutils::gitfile::GitFile;
use gitutils::gitproto;
use gitutils::gitrepo::GitRepo;
use web::repo;
use crate::git::GitBrowseEntry;
use crate::gitust::Gitust;
@ -47,6 +49,7 @@ mod gitust;
mod error;
mod web;
mod gitutils;
mod webutils;
#[derive(Template)]
#[template(path = "hello.html")]
@ -54,36 +57,6 @@ struct HelloTemplate<'a> {
name: &'a str,
}
struct User {
name : String,
}
struct Owner {
name : String,
}
struct Repository {
name : String,
owner : Owner,
}
enum Entry {
Dir(String),
File(String),
}
#[derive(Template)]
#[template(path = "git.html")]
struct GitMainTemplate<TS, ROOT>
where for <'a> &'a TS : IntoIterator<Item = &'a Entry>,
for <'a> &'a ROOT : IntoIterator<Item = &'a (String, String)>,
{
repo : Repository,
browse : TS,
root : ROOT,
user_opt : Option<User>,
}
#[get("/")]
async fn hello() -> impl Responder {
HttpResponse::Ok().body("Bonjour monde !")
@ -119,14 +92,6 @@ async fn hello_auth(req : HttpRequest) -> impl Responder {
}
#[derive(Deserialize)]
struct GitWebQ {
commit: Option<String>,
path: Option<String>,
branch: Option<String>,
}
#[get("/chunk")]
async fn chunk() -> HttpResponse {
let (tx, rx) = actix_utils::mpsc::channel::<Result<Bytes, Error>>();
@ -145,146 +110,6 @@ async fn chunk() -> HttpResponse {
HttpResponse::Ok().streaming(rx)
}
#[get("/git/{owner}/{repo}.git")]
async fn git_main(
webx::Path((ownername, reponame)): webx::Path<(String, String)>,
webx::Query(GitWebQ{commit : commitnameopt, path : pathopt, branch : branchopt}) : webx::Query<GitWebQ>,
gitust : webx::Data<Gitust>,
auth : Option<BasicAuth>,
//auth : BasicAuth,
) -> Result<GitMainTemplate<Vec<Entry>, Vec<(String, String)>>, error::Error> {
let rootname = match pathopt {
None => {"".to_string()}
Some(s) => {
if s.starts_with("/") {
(&s[1..]).to_string()
} else {
s
}
}
};
let commit = match commitnameopt {
None => {match branchopt {
None => {GitRef::Head}
Some(s) => {GitRef::Branch(s)}
}}
Some(s) => {GitRef::Commit(s)}
};
let owner = Owner { name : ownername};
let repo = Repository {name : reponame, owner};
let user = User { name : "Hubert".to_string()};
// il faut ajouter le commit/branch dans la query
let path = rootname.split("/").map_accum("/git/".to_string() + &repo.owner.name + "/" + &repo.name, |str_ref, b| {
let href = b + "/" + str_ref;
((str_ref.to_string(), href.clone()), href)
}).collect();
let gitrepo = GitRepo::new(format!("{}/{}/{}.git", &gitust.repo_root_path, &repo.owner.name, &repo.name).as_str())?;
let root = gitrepo.get_tree(&commit, Path::new(rootname.as_str()))?;
let browse = gitrepo.browse(&root).await?;
let mut entries : Vec<Entry> = Vec::new();
for entry in browse {
match entry {
GitBrowseEntry::EGitFile(GitFile(fullname)) => {
let osstr = fullname.file_name().ok_or(git2::Error::from_str("file name not defined"))?;
entries.push(Entry::File(format!("{}",osstr.to_string_lossy())));
}
GitBrowseEntry::EGitDir(GitDir{fullname, .. }) => {
let osstr = fullname.file_name().ok_or(git2::Error::from_str("file name not defined"))?;
entries.push(Entry::Dir(format!("{}",osstr.to_string_lossy())));
}
}
}
Ok(GitMainTemplate { repo, browse : entries, root : path, user_opt : Some(user)})
}
//#[get("/git/{owner}/{repo}.git/{path:.*}")]
async fn git_proto(
mut payload : webx::Payload,
webx::Path((owner, reponame, path)): webx::Path<(String, String, String)>,
mut req: HttpRequest,
gitust : webx::Data<Gitust>,
auth : BasicAuth,
) -> io::Result<HttpResponse>{
//println!("enter git_proto");
let mut cmd = Command::new("git");
cmd.arg("http-backend");
// Required environment variables
cmd.env("REQUEST_METHOD", req.method().as_str());
cmd.env("GIT_PROJECT_ROOT", &gitust.repo_root_path);
cmd.env("PATH_INFO", format!("/{}/{}.git/{}",owner, reponame, path));
cmd.env("REMOTE_USER", auth.user_id().to_string());
//cmd.env("REMOTE_ADDR", req.remote_addr().to_string());
cmd.env("QUERY_STRING", req.query_string());
cmd.env("CONTENT_TYPE", header(&req, header::CONTENT_TYPE));
cmd.env("GIT_HTTP_EXPORT_ALL", "");
cmd.stderr(Stdio::inherit())
.stdout(Stdio::piped())
.stdin(Stdio::piped());
let mut p: Child = cmd.spawn()?;
let mut input = p.stdin.take().unwrap();
//println!("Displaying request...");
while let Some(Ok(bytes)) = payload.next().await {
//println!("request body : {}", String::from_utf8_lossy(bytes.bytes()));
input.write_all(bytes.bytes()).await;
}
//println!("input sent");
let mut rdr = tokio::io::BufReader::new(p.stdout.take().unwrap());
let mut headers = HashMap::new();
loop {
let mut line = String::new();
let len = rdr.read_line(&mut line).await?;
// println!("line : \"{}\"", line);
if line.len() == 2 {
break;
}
let mut parts = line.splitn(2, ':');
let key = parts.next().unwrap();
let value = parts.next().unwrap();
let value_len = value.len();
let value = &value[1..value_len-2];
headers
.entry(key.to_string())
.or_insert_with(Vec::new)
.push(value.to_string());
}
//println!("response headers : {:?}", headers);
let status_code : u16 = {
let line = headers.remove("Status").unwrap_or_default();
// println!("{:?}", &line);
let line = line.into_iter().next().unwrap_or_default();
let parts : Vec<&str> = line.split(' ').collect();
parts.into_iter().next().unwrap_or("").parse().unwrap_or(200)
};
// println!("status code {}", status_code);
let statusCode = match StatusCode::from_u16(status_code) {
Ok(v) => {Ok(v)}
Err(ioe) => {Err(io::Error::new(ErrorKind::Other, "Invalid HTTP status code"))}
};
let mut builder = HttpResponse::build(statusCode?);
for (name, vec) in headers.iter() {
for value in vec {
// println!("entry : ({}, {})", name, value.clone());
builder.header(name, value.clone());
}
}
// println!("Write body...");
let response = builder.streaming(ToStream(rdr));
return Ok(response);
}
fn header(req: &HttpRequest, name: header::HeaderName) -> &str {
req.headers()
.get(name)
.map(|value| value.to_str().unwrap_or_default())
.unwrap_or_default()
}
#[post("/echo")]
async fn echo(req_body: String) -> impl Responder {
HttpResponse::Ok().body(req_body)
@ -342,7 +167,7 @@ async fn main() -> std::io::Result<()> {
.service(hello_test)
.service(index)
.service(askama)
.service(git_main)
.service(repo::git_main)
.service(hello_session)
.service(chunk)
//.service(git_proto)
@ -359,7 +184,7 @@ async fn main() -> std::io::Result<()> {
.service(
webx::resource("/git/{user}/{repo}.git/{path:.*}")
// .wrap(auth)
.route(webx::route().to(git_proto))
.route(webx::route().to(gitproto::git_proto))
)
.service(
Files::new("/static", "static")

View File

@ -1 +1 @@
mod repo;
pub mod repo;

View File

@ -0,0 +1,108 @@
use std::path::Path;
use actix_web::web;
use actix_web_httpauth::extractors::basic::BasicAuth;
use actix_web::get;
use askama_actix::Template;
use serde::Deserialize;
use crate::error;
use crate::git::GitBrowseEntry;
use crate::gitust::Gitust;
use crate::gitutils::gitcommit::GitRef;
use crate::gitutils::gitdir::GitDir;
use crate::gitutils::gitfile::GitFile;
use crate::gitutils::gitrepo::GitRepo;
use crate::ite::SuperIterator;
struct User {
name : String,
}
struct Owner {
name : String,
}
struct Repository {
name : String,
owner : Owner,
}
pub enum Entry {
Dir(String),
File(String),
}
#[derive(Template)]
#[template(path = "git.html")]
pub struct GitMainTemplate<TS, ROOT>
where for <'a> &'a TS : IntoIterator<Item = &'a Entry>,
for <'a> &'a ROOT : IntoIterator<Item = &'a (String, String)>,
{
repo : Repository,
browse : TS,
root : ROOT,
user_opt : Option<User>,
}
#[derive(Deserialize)]
pub struct GitWebQ {
commit: Option<String>,
path: Option<String>,
branch: Option<String>,
}
#[get("/git/{owner}/{repo}.git")]
pub async fn git_main(
web::Path((ownername, reponame)): web::Path<(String, String)>,
web::Query(GitWebQ{commit : commitnameopt, path : pathopt, branch : branchopt}) : web::Query<GitWebQ>,
gitust : web::Data<Gitust>,
auth : Option<BasicAuth>,
//auth : BasicAuth,
) -> Result<GitMainTemplate<Vec<Entry>, Vec<(String, String)>>, error::Error> {
let rootname = match pathopt {
None => {"".to_string()}
Some(s) => {
if s.starts_with("/") {
(&s[1..]).to_string()
} else {
s
}
}
};
let commit = match commitnameopt {
None => {match branchopt {
None => {GitRef::Head}
Some(s) => {GitRef::Branch(s)}
}}
Some(s) => {GitRef::Commit(s)}
};
let owner = Owner { name : ownername};
let repo = Repository {name : reponame, owner};
let user = User { name : "Hubert".to_string()};
// il faut ajouter le commit/branch dans la query
let path = rootname.split("/").map_accum("/git/".to_string() + &repo.owner.name + "/" + &repo.name, |str_ref, b| {
let href = b + "/" + str_ref;
((str_ref.to_string(), href.clone()), href)
}).collect();
let gitrepo = GitRepo::new(format!("{}/{}/{}.git", &gitust.repo_root_path, &repo.owner.name, &repo.name).as_str())?;
let root = gitrepo.get_tree(&commit, Path::new(rootname.as_str()))?;
let browse = gitrepo.browse(&root).await?;
let mut entries : Vec<Entry> = Vec::new();
for entry in browse {
match entry {
GitBrowseEntry::EGitFile(GitFile(fullname)) => {
let osstr = fullname.file_name().ok_or(git2::Error::from_str("file name not defined"))?;
entries.push(Entry::File(format!("{}",osstr.to_string_lossy())));
}
GitBrowseEntry::EGitDir(GitDir{fullname, .. }) => {
let osstr = fullname.file_name().ok_or(git2::Error::from_str("file name not defined"))?;
entries.push(Entry::Dir(format!("{}",osstr.to_string_lossy())));
}
}
}
Ok(GitMainTemplate { repo, browse : entries, root : path, user_opt : Some(user)})
}

5
src/webutils/auth.rs Normal file
View File

@ -0,0 +1,5 @@
use actix_web_httpauth::extractors::basic::BasicAuth;
pub fn check_user(auth : BasicAuth) -> bool {
auth.user_id() == auth.
}

1
src/webutils/mod.rs Normal file
View File

@ -0,0 +1 @@
pub mod auth;