git2_hyper/
lib.rs

1#![deny(
2    missing_docs,
3    missing_debug_implementations,
4    missing_copy_implementations,
5    trivial_casts,
6    trivial_numeric_casts,
7    unstable_features,
8    unused_import_braces,
9    unused_qualifications
10)]
11
12//! A crate for using hyper as a backend for HTTP(S) git requests with git2-rs.
13//!
14//! This crate provides one public function, `register`, which will register
15//! a custom HTTP transport with hyper for any HTTP(S) requests made by libgit2.
16//! At this time the `register` function is unsafe for the same reasons that
17//! `git2::transport::register` is also unsafe.
18//!
19//! > **NOTE**: At this time this crate likely does not support a `git push`
20//! >           operation, only clones.
21
22#![doc(html_root_url = "https://docs.rs/git2-hyper/0.1")]
23#![deny(missing_docs)]
24#![warn(rust_2018_idioms)]
25#![cfg_attr(test, deny(warnings))]
26
27use std::error;
28use std::io::prelude::*;
29use std::io::{self, Cursor};
30use std::str::FromStr;
31use std::sync::{Arc, Mutex, Once};
32
33use hyper::body::HttpBody;
34use hyper::client::HttpConnector;
35use hyper::http::header;
36use hyper::Body;
37use hyper::Request;
38use hyper::{Method, Uri};
39
40#[cfg(feature = "native")]
41use hyper_tls::HttpsConnector;
42
43#[cfg(feature = "rustls")]
44use hyper_rustls::HttpsConnector;
45
46use log::{debug, info};
47
48use git2::transport::{Service, SmartSubtransport, SmartSubtransportStream, Transport};
49use git2::Error;
50
51struct HyperTransport {
52    handle: Arc<Mutex<hyper::Client<HttpsConnector<HttpConnector>>>>,
53    /// The URL of the remote server, e.g. "https://github.com/user/repo"
54    ///
55    /// This is an empty string until the first action is performed.
56    /// If there is an HTTP redirect, this will be updated with the new URL.
57    base_url: Arc<Mutex<String>>,
58    runtime: Arc<tokio::runtime::Runtime>,
59}
60
61struct HyperSubtransport {
62    handle: Arc<Mutex<hyper::Client<HttpsConnector<HttpConnector>>>>,
63    service: &'static str,
64    url_path: &'static str,
65    base_url: Arc<Mutex<String>>,
66    method: &'static str,
67    response: Option<hyper::Response<Body>>,
68    sent_request: bool,
69    runtime_handle: tokio::runtime::Handle,
70}
71
72/// Register the hyper backend for HTTP requests made by libgit2.
73///
74/// This function takes one parameter, a `handle`, which is used to perform all
75/// future HTTP(S) requests. The handle can be previously configured with
76/// information such as proxies, SSL information, etc.
77///
78/// This function is unsafe largely for the same reasons as
79/// `git2::transport::register`:
80///
81/// * The function needs to be synchronized against all other creations of
82///   transport (any API calls to libgit2).
83/// * The function will leak `handle` as once registered it is not currently
84///   possible to unregister the backend.
85///
86/// This function may be called concurrently, but only the first `handle` will
87/// be used. All others will be discarded.
88pub unsafe fn register(handle: hyper::Client<HttpsConnector<HttpConnector>>) {
89    static INIT: Once = Once::new();
90
91    let handle = Arc::new(Mutex::new(handle));
92    let handle2 = handle.clone();
93    INIT.call_once(move || {
94        git2::transport::register("http", move |remote| factory(remote, handle.clone())).unwrap();
95        git2::transport::register("https", move |remote| factory(remote, handle2.clone())).unwrap();
96    });
97}
98
99fn factory(
100    remote: &git2::Remote<'_>,
101    handle: Arc<Mutex<hyper::Client<HttpsConnector<HttpConnector>>>>,
102) -> Result<Transport, Error> {
103    Transport::smart(
104        remote,
105        true,
106        HyperTransport {
107            handle,
108            base_url: Arc::new(Mutex::new(String::new())),
109            runtime: Arc::new(tokio::runtime::Runtime::new().unwrap()),
110        },
111    )
112}
113
114impl SmartSubtransport for HyperTransport {
115    fn action(
116        &self,
117        url: &str,
118        action: Service,
119    ) -> Result<Box<dyn SmartSubtransportStream>, Error> {
120        let mut base_url = self.base_url.lock().unwrap();
121        if base_url.len() == 0 {
122            *base_url = url.to_string();
123        }
124        let (service, path, method) = match action {
125            Service::UploadPackLs => ("upload-pack", "/info/refs?service=git-upload-pack", "GET"),
126            Service::UploadPack => ("upload-pack", "/git-upload-pack", "POST"),
127            Service::ReceivePackLs => {
128                ("receive-pack", "/info/refs?service=git-receive-pack", "GET")
129            }
130            Service::ReceivePack => ("receive-pack", "/git-receive-pack", "POST"),
131        };
132        info!("action {} {}", service, path);
133        Ok(Box::new(HyperSubtransport {
134            handle: self.handle.clone(),
135            service,
136            url_path: path,
137            base_url: self.base_url.clone(),
138            method,
139            response: None,
140            sent_request: false,
141            runtime_handle: self.runtime.handle().clone(),
142        }))
143    }
144
145    fn close(&self) -> Result<(), Error> {
146        Ok(())
147    }
148}
149
150impl HyperSubtransport {
151    fn err<E: Into<Box<dyn error::Error + Send + Sync>>>(&self, err: E) -> io::Error {
152        io::Error::new(io::ErrorKind::Other, err)
153    }
154
155    fn execute(&mut self, data: &[u8]) -> io::Result<()> {
156        if self.sent_request {
157            return Err(self.err("already sent HTTP request"));
158        }
159
160        let agent = format!("git/1.0 (git2-hyper {})", env!("CARGO_PKG_VERSION"));
161
162        // Parse our input URL to figure out the host
163        let url = format!("{}{}", self.base_url.lock().unwrap(), self.url_path);
164        let parsed = Uri::from_str(&url).map_err(|_| self.err("invalid url, failed to parse"))?;
165        let host = match parsed.host() {
166            Some(host) => host,
167            None => return Err(self.err("invalid url, did not have a host")),
168        };
169
170        // Prep the request
171        debug!("request to {}", url);
172        let client = self.handle.lock().unwrap();
173
174        let method =
175            Method::from_bytes(self.method.as_bytes()).map_err(|_| self.err("invalid method"))?;
176        let request = Request::builder()
177            .method(method)
178            .uri(&url)
179            .header(header::USER_AGENT, agent)
180            .header(header::HOST, host)
181            .header(header::EXPECT, "");
182
183        let request = if data.is_empty() {
184            request.header(header::ACCEPT, "*/*")
185        } else {
186            request
187                .header(
188                    header::ACCEPT,
189                    format!("application/x-git-{}-result", self.service),
190                )
191                .header(
192                    header::CONTENT_TYPE,
193                    format!("application/x-git-{}-request", self.service),
194                )
195        };
196
197        let request = request
198            .body(Body::from(Vec::from(data)))
199            .map_err(|_| self.err("invalid body"))?;
200
201        let res = self
202            .runtime_handle
203            .block_on(client.request(request))
204            .unwrap();
205        let headers = res.headers();
206
207        let content_type = headers
208            .get(header::CONTENT_TYPE)
209            .map(|v| v.to_str().unwrap());
210
211        let code = res.status();
212        if code.as_u16() != 200 {
213            return Err(self.err(
214                &format!(
215                    "failed to receive HTTP 200 response: \
216                     got {}",
217                    code
218                )[..],
219            ));
220        }
221
222        // Check returned headers
223        let expected = match self.method {
224            "GET" => format!("application/x-git-{}-advertisement", self.service),
225            _ => format!("application/x-git-{}-result", self.service),
226        };
227
228        if let Some(content_type) = content_type {
229            if content_type != expected {
230                return Err(self.err(
231                    &format!(
232                        "expected a Content-Type header \
233                         with `{}` but found `{}`",
234                        expected, content_type
235                    )[..],
236                ));
237            }
238        } else {
239            return Err(self.err(
240                &format!(
241                    "expected a Content-Type header \
242                         with `{}` but didn't find one",
243                    expected
244                )[..],
245            ));
246        }
247
248        // preserve response body for reading afterwards
249        self.response = Some(res);
250
251        Ok(())
252    }
253}
254
255impl Read for HyperSubtransport {
256    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
257        if self.response.is_none() {
258            self.execute(&[])?;
259        }
260
261        let data = self.response.as_mut().unwrap().body_mut().data();
262
263        let body = match self.runtime_handle.block_on(data) {
264            Some(b) => b,
265            None => return Err(self.err("empty response body")),
266        };
267
268        let bytes = match body {
269            Ok(b) => b,
270            Err(_) => return Err(self.err("invalid response body")),
271        };
272
273        let mut reader = Cursor::new(bytes);
274        reader.read(buf)
275    }
276}
277
278impl Write for HyperSubtransport {
279    fn write(&mut self, data: &[u8]) -> io::Result<usize> {
280        if self.response.is_none() {
281            self.execute(data)?;
282        }
283        Ok(data.len())
284    }
285    fn flush(&mut self) -> io::Result<()> {
286        Ok(())
287    }
288}