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
use std::error;
use std::io;
use std::io::prelude::*;
use std::sync::{Arc, Mutex, Once};
use ureq::Agent;
use ureq::AgentBuilder;
use ureq::Proxy;
use url::Url;

use log::{debug, info};

use git2::transport::{Service, SmartSubtransport, SmartSubtransportStream, Transport};
use git2::Error;

#[derive(Default)]
struct UreqTransport {
    /// The URL of the remote server, e.g. "https://github.com/user/repo"
    ///
    /// This is an empty string until the first action is performed.
    /// If there is an HTTP redirect, this will be updated with the new URL.
    base_url: Arc<Mutex<String>>,
    proxy: Option<Proxy>,
}

struct UreqSubtransport {
    service: &'static str,
    url_path: &'static str,
    base_url: Arc<Mutex<String>>,
    method: &'static str,
    reader: Option<Box<dyn Read + Send>>,
    sent_request: bool,
    client: Agent,
}

pub unsafe fn register(proxy: Option<String>) {
    static INIT: Once = Once::new();

    let proxy = proxy.map(|s| Proxy::new(s).ok()).flatten();
    let p = proxy.clone();

    INIT.call_once(move || {
        git2::transport::register("http", move |remote| factory(remote, proxy.as_ref())).unwrap();
        git2::transport::register("https", move |remote| factory(remote, p.as_ref())).unwrap();
    });
}

fn factory(remote: &git2::Remote<'_>, proxy: Option<&Proxy>) -> Result<Transport, Error> {
    Transport::smart(remote, true, UreqTransport::new(proxy.cloned()))
}

impl UreqTransport {
    pub(crate) fn new(proxy: Option<Proxy>) -> Self {
        Self {
            proxy,
            ..Default::default()
        }
    }
}

impl SmartSubtransport for UreqTransport {
    fn action(
        &self,
        url: &str,
        action: Service,
    ) -> Result<Box<dyn SmartSubtransportStream>, Error> {
        let mut base_url = self.base_url.lock().unwrap();
        if base_url.len() == 0 {
            *base_url = url.to_string();
        }
        let (service, path, method) = match action {
            Service::UploadPackLs => ("upload-pack", "/info/refs?service=git-upload-pack", "GET"),
            Service::UploadPack => ("upload-pack", "/git-upload-pack", "POST"),
            Service::ReceivePackLs => {
                ("receive-pack", "/info/refs?service=git-receive-pack", "GET")
            }
            Service::ReceivePack => ("receive-pack", "/git-receive-pack", "POST"),
        };
        info!("action {} {}", service, path);
        Ok(Box::new(UreqSubtransport {
            service,
            url_path: path,
            base_url: self.base_url.clone(),
            method,
            reader: None,
            sent_request: false,
            client: self
                .proxy
                .clone()
                .map(|p| AgentBuilder::new().proxy(p))
                .unwrap_or_else(AgentBuilder::new)
                .build(),
        }))
    }

    fn close(&self) -> Result<(), Error> {
        Ok(())
    }
}

impl UreqSubtransport {
    fn err<E: Into<Box<dyn error::Error + Send + Sync>>>(&self, err: E) -> io::Error {
        io::Error::new(io::ErrorKind::Other, err)
    }

    fn execute(&mut self, data: &[u8]) -> io::Result<()> {
        if self.sent_request {
            return Err(self.err("already sent HTTP request"));
        }

        let agent = format!("git/1.0 (git2-ureq {})", env!("CARGO_PKG_VERSION"));

        // Parse our input URL to figure out the host
        let url = format!("{}{}", self.base_url.lock().unwrap(), self.url_path);
        let parsed = Url::parse(&url).map_err(|_| self.err("invalid url, failed to parse"))?;
        let host = match parsed.host_str() {
            Some(host) => host,
            None => return Err(self.err("invalid url, did not have a host")),
        };

        // Prep the request
        debug!("request to {}", url);
        let request = self
            .client
            .request(self.method, &url)
            .set("User-Agent", &agent)
            .set("Host", &host)
            .set("Expect", "");
        let request = if data.is_empty() {
            request.set("Accept", "*/*")
        } else {
            request
                .set(
                    "Accept",
                    &format!("application/x-git-{}-result", self.service),
                )
                .set(
                    "Conent-Type",
                    &format!("application/x-git-{}-request", self.service),
                )
        };

        let response = request.send(data).unwrap();
        let content_type = response.header("Content-Type");

        let code = response.status();
        if code != 200 {
            return Err(self.err(&format!("failed to receive HTTP 200 response: got {code}",)[..]));
        }

        // Check returned headers
        let expected = match self.method {
            "GET" => format!("application/x-git-{}-advertisement", self.service),
            _ => format!("application/x-git-{}-result", self.service),
        };

        if let Some(content_type) = content_type {
            if content_type != expected {
                return Err(self.err(
                    &format!(
                        "expected a Content-Type header with `{expected}` but found `{content_type}`",
                    )[..],
                ));
            }
        } else {
            return Err(
                self.err(
                    &format!(
                        "expected a Content-Type header with `{expected}` but didn't find one"
                    )[..],
                ),
            );
        }

        // preserve response body for reading afterwards
        self.reader = Some(Box::new(response.into_reader()));

        Ok(())
    }
}

impl Read for UreqSubtransport {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if self.reader.is_none() {
            self.execute(&[])?;
        }

        self.reader.as_mut().unwrap().read(buf)
    }
}

impl Write for UreqSubtransport {
    fn write(&mut self, data: &[u8]) -> io::Result<usize> {
        if self.reader.is_none() {
            self.execute(data)?;
        }
        Ok(data.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}