Skip to main content

arks_server/daemon/
session.rs

1//! One `git://` connection: request checks in `git daemon` order, then the
2//! service itself.
3//!
4//! Primary: <https://git-scm.com/docs/git-daemon> (SERVICES, `--informative-errors`,
5//! `--access-hook`, per-repository `daemon.<service>` overrides). Check order and
6//! error wording follow observed stock `git daemon`.
7
8use super::access_hook::{HookRequest, run_access_hook};
9use super::archive::{drain_upload_archive_args, serve_upload_archive_partial};
10use super::options::{DaemonOptions, DaemonService};
11use super::path::{HostContext, ResolvedRepo, resolve_request};
12use super::request::ServiceRequest;
13use crate::error::ServerError;
14use crate::stdio::{receive_pack_stream, upload_pack_stream};
15use arks_config::ConfigSet;
16use arks_protocol::{Packet, encode_packet};
17use arks_repo::Repository;
18use std::io::{Read, Write};
19use std::net::SocketAddr;
20
21/// Generic refusal sent without `--informative-errors`.
22const ACCESS_DENIED: &str = "access denied or repository not exported";
23
24/// What happened to one request.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum Outcome {
27    /// The service ran to completion.
28    Served,
29    /// The request was refused (or the service failed).
30    Refused,
31}
32
33/// Run every check, then the service, on `stream`.
34pub(super) fn handle_request<S: Read + Write>(
35    stream: &mut S,
36    req: &ServiceRequest,
37    opts: &DaemonOptions,
38    peer: Option<SocketAddr>,
39) -> Result<Outcome, ServerError> {
40    let log = &opts.log;
41    let Some(service) = DaemonService::from_request(&req.command).filter(|_| !req.path.is_empty())
42    else {
43        log.error(&format!("Protocol error: '{}'", req.line));
44        return Ok(Outcome::Refused);
45    };
46    let dir = req.path.as_str();
47    log.info(&format!("Request {} for '{dir}'", service.name()));
48    let policy = opts.services.get(service);
49    if !policy.enabled && !policy.overridable {
50        log.error(&format!("'{}': service not enabled.", service.name()));
51        return refuse(stream, opts, dir, "service not enabled");
52    }
53    let host = host_context(req, opts);
54    let Some(repo) = resolve_request(opts, dir, host.as_ref()) else {
55        return refuse(stream, opts, dir, "no such repository");
56    };
57    if !opts.export_all && !repo.git_dir.join("git-daemon-export-ok").exists() {
58        log.error(&format!("'{}': repository not exported.", repo.validated));
59        return refuse(stream, opts, dir, "repository not exported");
60    }
61    let mut enabled = policy.enabled;
62    if policy.overridable {
63        if let Some(v) = ConfigSet::load(Some(&repo.git_dir)).get_bool(service.config_key()) {
64            enabled = v;
65        }
66    }
67    if !enabled {
68        log.error(&format!(
69            "'{}': service not enabled for '{}'",
70            service.name(),
71            repo.validated
72        ));
73        return refuse(stream, opts, dir, "service not enabled");
74    }
75    if let Some(hook) = opts.access_hook.as_deref() {
76        let hook_req = HookRequest {
77            service: service.name(),
78            validated: &repo.validated,
79            git_dir: &repo.git_dir,
80            host: host.as_ref(),
81            peer,
82        };
83        if let Err(msg) = run_access_hook(hook, &hook_req) {
84            let msg = msg.unwrap_or_else(|| "service rejected".to_string());
85            return refuse(stream, opts, dir, &msg);
86        }
87    }
88    run_service(stream, service, &repo, opts)
89}
90
91fn host_context(req: &ServiceRequest, opts: &DaemonOptions) -> Option<HostContext> {
92    let attr = req.host.as_ref()?;
93    let info = opts
94        .platform
95        .lookup_host(&attr.hostname)
96        .unwrap_or_default();
97    Some(HostContext {
98        hostname: attr.hostname.clone(),
99        canonical: info.canonical,
100        ip: info.ip,
101        port: attr.port.clone(),
102    })
103}
104
105fn run_service<S: Read + Write>(
106    stream: &mut S,
107    service: DaemonService,
108    repo: &ResolvedRepo,
109    opts: &DaemonOptions,
110) -> Result<Outcome, ServerError> {
111    let mut repository = match Repository::open(&repo.git_dir) {
112        Ok(r) => r,
113        Err(e) => {
114            opts.log.error(&format!("fatal: {e}"));
115            return refuse(stream, opts, &repo.validated, "no such repository");
116        }
117    };
118    let result = match service {
119        DaemonService::UploadPack => upload_pack_stream(&repository, stream),
120        DaemonService::ReceivePack => receive_pack_stream(&mut repository, stream),
121        DaemonService::UploadArchive => drain_upload_archive_args(stream)
122            .and_then(|args| serve_upload_archive_partial(&repository, &args, stream, false)),
123    };
124    match result {
125        Ok(()) => Ok(Outcome::Served),
126        Err(e) => {
127            opts.log.error(&format!("fatal: {e}"));
128            Ok(Outcome::Refused)
129        }
130    }
131}
132
133/// Send `ERR <msg>: <dir>` (generic message unless `--informative-errors`).
134fn refuse<W: Write>(
135    stream: &mut W,
136    opts: &DaemonOptions,
137    dir: &str,
138    msg: &str,
139) -> Result<Outcome, ServerError> {
140    let msg = if opts.informative_errors {
141        msg
142    } else {
143        ACCESS_DENIED
144    };
145    let pkt = encode_packet(&Packet::Data(format!("ERR {msg}: {dir}").into_bytes()))
146        .map_err(|e| ServerError::Protocol(e.to_string()))?;
147    stream.write_all(&pkt)?;
148    stream.flush()?;
149    Ok(Outcome::Refused)
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155    use crate::daemon::log::DaemonLog;
156    use crate::daemon::request::parse_service_payload;
157    use std::io::Cursor;
158    use std::path::Path;
159    use tempfile::TempDir;
160
161    /// In-memory duplex: reads `input`, collects writes.
162    struct Duplex {
163        input: Cursor<Vec<u8>>,
164        output: Vec<u8>,
165    }
166    impl Read for Duplex {
167        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
168            self.input.read(buf)
169        }
170    }
171    impl Write for Duplex {
172        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
173            self.output.extend_from_slice(buf);
174            Ok(buf.len())
175        }
176        fn flush(&mut self) -> std::io::Result<()> {
177            Ok(())
178        }
179    }
180
181    fn bare(at: &Path, exported: bool) {
182        std::fs::create_dir_all(at.join("objects")).unwrap();
183        std::fs::create_dir_all(at.join("refs/heads")).unwrap();
184        std::fs::write(at.join("HEAD"), b"ref: refs/heads/main\n").unwrap();
185        std::fs::write(at.join("config"), b"[core]\n\tbare = true\n").unwrap();
186        if exported {
187            std::fs::write(at.join("git-daemon-export-ok"), b"").unwrap();
188        }
189    }
190
191    fn ask(opts: &DaemonOptions, payload: &[u8]) -> (Outcome, String) {
192        let req = parse_service_payload(payload, &opts.log).unwrap();
193        let mut io = Duplex {
194            input: Cursor::new(b"0000".to_vec()),
195            output: Vec::new(),
196        };
197        let out = handle_request(&mut io, &req, opts, None).unwrap();
198        (out, String::from_utf8_lossy(&io.output).to_string())
199    }
200
201    fn setup() -> (TempDir, DaemonOptions) {
202        let root = TempDir::new().unwrap();
203        bare(&root.path().join("pub.git"), true);
204        bare(&root.path().join("hidden.git"), false);
205        let noup = root.path().join("noup.git");
206        bare(&noup, true);
207        std::fs::write(
208            noup.join("config"),
209            b"[core]\n\tbare = true\n[daemon]\n\tuploadpack = false\n",
210        )
211        .unwrap();
212        let arch = root.path().join("arch.git");
213        bare(&arch, true);
214        std::fs::write(arch.join("config"), b"[daemon]\n\tuploadarch\n").unwrap();
215        let opts = DaemonOptions {
216            base_path: Some(root.path().to_path_buf()),
217            log: DaemonLog::memory(true),
218            ..DaemonOptions::default()
219        };
220        (root, opts)
221    }
222
223    #[test]
224    fn default_errors_are_generic() {
225        let (_root, opts) = setup();
226        for (payload, dir) in [
227            (&b"git-upload-pack /nope.git\0"[..], "/nope.git"),
228            (b"git-upload-pack /hidden.git\0", "/hidden.git"),
229            (b"git-receive-pack /pub.git\0", "/pub.git"),
230            (b"git-upload-pack /noup.git\0", "/noup.git"),
231        ] {
232            let (out, text) = ask(&opts, payload);
233            assert_eq!(out, Outcome::Refused);
234            let want = format!("ERR access denied or repository not exported: {dir}");
235            assert_eq!(text, format!("{:04x}{want}", want.len() + 4));
236        }
237        let lines = opts.log.lines();
238        assert!(
239            lines
240                .iter()
241                .any(|l| l.ends_with("/hidden.git': repository not exported."))
242        );
243        assert!(
244            lines
245                .iter()
246                .any(|l| l.starts_with("'receive-pack': service not enabled for '"))
247        );
248        assert!(
249            lines
250                .iter()
251                .any(|l| l.starts_with("'upload-pack': service not enabled for '"))
252        );
253    }
254
255    #[test]
256    fn informative_errors_name_the_reason() {
257        let (_root, mut opts) = setup();
258        opts.informative_errors = true;
259        let cases: [(&[u8], &str); 4] = [
260            (
261                b"git-upload-pack /nope.git\0",
262                "no such repository: /nope.git",
263            ),
264            (
265                b"git-upload-pack /hidden.git\0",
266                "repository not exported: /hidden.git",
267            ),
268            (
269                b"git-receive-pack /pub.git\0",
270                "service not enabled: /pub.git",
271            ),
272            (b"git-upload-pack pub.git\0", "no such repository: pub.git"),
273        ];
274        for (payload, want) in cases {
275            let (_, text) = ask(&opts, payload);
276            assert!(text.ends_with(&format!("ERR {want}")), "{text}");
277        }
278    }
279
280    #[test]
281    fn per_repo_override_and_forbid_override() {
282        let (_root, mut opts) = setup();
283        opts.informative_errors = true;
284        // daemon.uploadarch (bare key = true) enables upload-archive for arch.git.
285        let (out, text) = ask(&opts, b"git-upload-archive /arch.git\0");
286        assert_eq!(out, Outcome::Served, "{text}");
287        assert!(!text.contains("service not enabled"), "{text}");
288        let (_, text) = ask(&opts, b"git-upload-archive /pub.git\0");
289        assert!(text.ends_with("ERR service not enabled: /pub.git"));
290        // --forbid-override=upload-pack ignores daemon.uploadpack=false.
291        opts.services.upload_pack.overridable = false;
292        let (out, _) = ask(&opts, b"git-upload-pack /noup.git\0");
293        assert_eq!(out, Outcome::Served);
294        // --forbid-override=receive-pack with receive-pack disabled refuses early.
295        opts.services.receive_pack.overridable = false;
296        let (_, text) = ask(&opts, b"git-receive-pack /nope.git\0");
297        assert!(text.ends_with("ERR service not enabled: /nope.git"));
298        assert!(
299            opts.log
300                .lines()
301                .contains(&"'receive-pack': service not enabled.".to_string())
302        );
303    }
304
305    #[test]
306    fn unknown_service_is_a_protocol_error_without_reply() {
307        let (_root, opts) = setup();
308        let (out, text) = ask(&opts, b"git-foo /pub.git\0");
309        assert_eq!(out, Outcome::Refused);
310        assert!(text.is_empty());
311        assert!(
312            opts.log
313                .lines()
314                .contains(&"Protocol error: 'git-foo /pub.git'".to_string())
315        );
316    }
317
318    #[test]
319    fn export_all_serves_unmarked_repository() {
320        let (_root, mut opts) = setup();
321        opts.export_all = true;
322        let (out, text) = ask(&opts, b"git-upload-pack /hidden.git\0");
323        assert_eq!(out, Outcome::Served, "{text}");
324    }
325
326    #[cfg(unix)]
327    #[test]
328    fn access_hook_decline_message_needs_informative_errors() {
329        use std::os::unix::fs::PermissionsExt;
330        let (root, mut opts) = setup();
331        let hook = root.path().join("hook.sh");
332        std::fs::write(&hook, "#!/bin/sh\necho 'nope from hook'\nexit 1\n").unwrap();
333        std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();
334        opts.access_hook = Some(hook.clone());
335        let (_, text) = ask(&opts, b"git-upload-pack /pub.git\0");
336        assert!(text.ends_with("ERR access denied or repository not exported: /pub.git"));
337        opts.informative_errors = true;
338        let (_, text) = ask(&opts, b"git-upload-pack /pub.git\0");
339        assert!(text.ends_with("ERR nope from hook: /pub.git"), "{text}");
340        std::fs::write(&hook, "#!/bin/sh\nexit 2\n").unwrap();
341        let (_, text) = ask(&opts, b"git-upload-pack /pub.git\0");
342        assert!(text.ends_with("ERR service rejected: /pub.git"), "{text}");
343        std::fs::write(&hook, "#!/bin/sh\nexit 0\n").unwrap();
344        let (out, _) = ask(&opts, b"git-upload-pack /pub.git\0");
345        assert_eq!(out, Outcome::Served);
346    }
347}