arks-server 0.1.2

Git server: upload-pack / receive-pack + smart/dumb HTTP + daemon (M11/M25)
Documentation
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
//! Sync receive-pack githooks (Claimed honor list).
//!
//! Honored: `pre-receive`, `update`, `post-receive`, `post-update`,
//! and **FS2** `proc-receive` (advertise + divert when hook +
//! `receive.procReceiveRefs` match).
//! Cite: <https://git-scm.com/docs/githooks>,
//! <https://git-scm.com/docs/git-receive-pack>.
//! Sync only — no invented async runners. Per-push stdin isolation.
//! HOOK-008 race freedom remains unclaimed (FS8).

use crate::error::ServerError;
use arks_protocol::{Packet, decode_packet, decode_text_line, encode_packet};
use std::fs;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

/// Result of a fail-closed hook (`pre-receive` / `update`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum HookGate {
    /// Hook absent, not executable, or exited 0.
    Allow,
    /// Hook exited non-zero — reject per githooks / git-receive-pack.
    Decline,
}

/// Optional env for hooks during a quarantined receive-pack.
#[derive(Debug, Clone, Default)]
pub(crate) struct HookEnv {
    /// Absolute path to the quarantine objects directory (`GIT_QUARANTINE_PATH`).
    pub quarantine_path: Option<PathBuf>,
    /// Negotiated push-options (O4) → `GIT_PUSH_OPTION_COUNT` / `GIT_PUSH_OPTION_<n>`.
    pub push_options: Vec<String>,
}

/// Run `$GIT_DIR/hooks/pre-receive` once with stdin lines of proposed updates.
pub(crate) fn run_pre_receive(
    git_dir: &Path,
    stdin_lines: &[u8],
    env: &HookEnv,
) -> Result<HookGate, ServerError> {
    run_named_hook(git_dir, "pre-receive", &[], Some(stdin_lines), true, env)
}

/// Run `$GIT_DIR/hooks/update` once for a single ref (`refname old-oid new-oid`).
pub(crate) fn run_update(
    git_dir: &Path,
    refname: &str,
    old_hex: &str,
    new_hex: &str,
    env: &HookEnv,
) -> Result<HookGate, ServerError> {
    run_named_hook(
        git_dir,
        "update",
        &[refname, old_hex, new_hex],
        None,
        true,
        env,
    )
}

/// Run `$GIT_DIR/hooks/post-receive` once with stdin of successfully updated refs.
///
/// Exit status does not change push outcome ([git-receive-pack] POST-RECEIVE HOOK).
pub(crate) fn run_post_receive(git_dir: &Path, stdin_lines: &[u8], env: &HookEnv) {
    let _ = run_named_hook(git_dir, "post-receive", &[], Some(stdin_lines), false, env);
}

/// Run `$GIT_DIR/hooks/post-update` with argv = updated ref names.
///
/// Cite: [git-receive-pack](https://git-scm.com/docs/git-receive-pack) POST-UPDATE HOOK.
/// Exit status ignored.
pub(crate) fn run_post_update(git_dir: &Path, updated_refs: &[&str], env: &HookEnv) {
    if updated_refs.is_empty() {
        return;
    }
    let _ = run_named_hook(git_dir, "post-update", updated_refs, None, false, env);
}

/// Whether `$GIT_DIR/hooks/proc-receive` is runnable (FS2 advertise gate).
pub(crate) fn proc_receive_hook_present(git_dir: &Path) -> bool {
    is_runnable_hook(&hook_path(git_dir, "proc-receive"))
}

/// Read multi-valued `receive.procReceiveRefs` from `$GIT_DIR/config` (local only).
pub(crate) fn proc_receive_ref_prefixes(git_dir: &Path) -> Vec<String> {
    let text = fs::read_to_string(git_dir.join("config")).unwrap_or_default();
    let mut out = Vec::new();
    let mut in_receive = false;
    for raw in text.lines() {
        let line = raw.trim();
        if line.is_empty() || line.starts_with('#') || line.starts_with(';') {
            continue;
        }
        if line.starts_with('[') {
            in_receive = line.eq_ignore_ascii_case("[receive]");
            continue;
        }
        if !in_receive {
            continue;
        }
        let Some((k, v)) = line.split_once('=') else {
            continue;
        };
        if k.trim().eq_ignore_ascii_case("procReceiveRefs") {
            let v = v.trim().trim_matches('"').trim_matches('\'').to_string();
            if !v.is_empty() {
                out.push(v);
            }
        }
    }
    out
}

pub(crate) fn ref_matches_proc_receive(refname: &str, prefixes: &[String]) -> bool {
    // FS2: positive `receive.procReceiveRefs` prefixes only (git multi-value).
    // Negative `!` forms deferred until a dedicated SoT row claims them.
    prefixes
        .iter()
        .filter(|p| !p.starts_with('!'))
        .any(|p| refname.starts_with(p.as_str()))
}

/// One diverted update for the proc-receive hook (FS2).
#[derive(Debug, Clone)]
pub(crate) struct ProcReceiveCmd {
    pub old_hex: String,
    pub new_hex: String,
    pub name: String,
}

/// Result reported by proc-receive (ok/ng; optional rewrite refname/oids).
#[derive(Debug, Clone)]
pub(crate) struct ProcReceiveResult {
    pub name: String,
    pub ok: bool,
    pub error: Option<String>,
    pub rewrite_ref: Option<String>,
    pub rewrite_old: Option<String>,
    pub rewrite_new: Option<String>,
}

/// Run `hooks/proc-receive` pkt-line protocol (version 0 subset).
///
/// Cite: <https://git-scm.com/docs/githooks#_proc_receive>,
/// <https://git-scm.com/docs/git-receive-pack>.
pub(crate) fn run_proc_receive(
    git_dir: &Path,
    commands: &[ProcReceiveCmd],
    env: &HookEnv,
) -> Result<Vec<ProcReceiveResult>, ServerError> {
    if commands.is_empty() {
        return Ok(Vec::new());
    }
    let path = hook_path(git_dir, "proc-receive");
    if !is_runnable_hook(&path) {
        return Err(ServerError::Msg(
            "proc-receive advertised but hook missing".into(),
        ));
    }
    let mut cmd = {
        #[cfg(windows)]
        {
            let mut c = windows_bash();
            c.arg(bash_style_path(&path));
            c
        }
        #[cfg(not(windows))]
        {
            Command::new(&path)
        }
    };
    #[cfg(windows)]
    {
        cmd.env("GIT_DIR", bash_style_path(git_dir));
        if let Some(q) = &env.quarantine_path {
            cmd.env("GIT_QUARANTINE_PATH", bash_style_path(q));
        }
    }
    #[cfg(not(windows))]
    {
        cmd.env("GIT_DIR", git_dir);
        if let Some(q) = &env.quarantine_path {
            cmd.env("GIT_QUARANTINE_PATH", q);
        }
    }
    cmd.env("GIT_PUSH_OPTION_COUNT", env.push_options.len().to_string());
    for (i, opt) in env.push_options.iter().enumerate() {
        cmd.env(format!("GIT_PUSH_OPTION_{i}"), opt);
    }
    cmd.current_dir(git_dir);
    cmd.stdin(Stdio::piped());
    cmd.stdout(Stdio::piped());
    cmd.stderr(Stdio::inherit());
    let mut child = cmd
        .spawn()
        .map_err(|e| ServerError::Msg(format!("hook proc-receive: {e}")))?;

    // Negotiate version 0 (no "version=1" features required for ok/ng + option rewrite).
    let mut request = Vec::new();
    request.extend(
        encode_packet(&Packet::Data(b"version=0\n".to_vec()))
            .map_err(|e| ServerError::Protocol(e.to_string()))?,
    );
    request
        .extend(encode_packet(&Packet::Flush).map_err(|e| ServerError::Protocol(e.to_string()))?);
    for c in commands {
        let line = format!("{} {} {}\n", c.old_hex, c.new_hex, c.name);
        request.extend(
            encode_packet(&Packet::Data(line.into_bytes()))
                .map_err(|e| ServerError::Protocol(e.to_string()))?,
        );
    }
    request
        .extend(encode_packet(&Packet::Flush).map_err(|e| ServerError::Protocol(e.to_string()))?);
    if let Some(mut hin) = child.stdin.take() {
        match hin.write_all(&request) {
            Ok(()) => {}
            Err(e) if e.kind() == std::io::ErrorKind::BrokenPipe => {}
            Err(e) => {
                return Err(ServerError::Msg(format!("hook proc-receive stdin: {e}")));
            }
        }
    }
    let mut stdout = child
        .stdout
        .take()
        .ok_or_else(|| ServerError::Msg("hook proc-receive: no stdout".into()))?;
    let mut buf = Vec::new();
    stdout
        .read_to_end(&mut buf)
        .map_err(|e| ServerError::Msg(format!("hook proc-receive stdout: {e}")))?;
    let status = child
        .wait()
        .map_err(|e| ServerError::Msg(format!("hook proc-receive: {e}")))?;
    if !status.success() {
        return Err(ServerError::Msg(format!(
            "proc-receive hook exited {}",
            status.code().unwrap_or(-1)
        )));
    }
    parse_proc_receive_response(&buf, commands)
}

fn parse_proc_receive_response(
    buf: &[u8],
    commands: &[ProcReceiveCmd],
) -> Result<Vec<ProcReceiveResult>, ServerError> {
    let mut offset = 0;
    // Optional leading flush / version ack from hook — skip until command results.
    let mut results: Vec<ProcReceiveResult> = Vec::new();
    let mut current: Option<ProcReceiveResult> = None;
    let finish_current = |cur: &mut Option<ProcReceiveResult>, out: &mut Vec<ProcReceiveResult>| {
        if let Some(r) = cur.take() {
            out.push(r);
        }
    };
    while offset < buf.len() {
        let (packet, n) =
            decode_packet(&buf[offset..]).map_err(|e| ServerError::Protocol(e.to_string()))?;
        offset += n;
        match packet {
            Packet::Flush => {
                finish_current(&mut current, &mut results);
            }
            Packet::Data(payload) => {
                let line =
                    decode_text_line(&payload).map_err(|e| ServerError::Protocol(e.to_string()))?;
                let line = line.trim_end_matches('\n');
                if line.is_empty() || line.starts_with("version") {
                    continue;
                }
                if let Some(rest) = line.strip_prefix("ok ") {
                    finish_current(&mut current, &mut results);
                    current = Some(ProcReceiveResult {
                        name: rest.trim().to_string(),
                        ok: true,
                        error: None,
                        rewrite_ref: None,
                        rewrite_old: None,
                        rewrite_new: None,
                    });
                } else if let Some(rest) = line.strip_prefix("ng ") {
                    finish_current(&mut current, &mut results);
                    let mut parts = rest.splitn(2, ' ');
                    let name = parts.next().unwrap_or("").to_string();
                    let err = parts.next().unwrap_or("declined").to_string();
                    current = Some(ProcReceiveResult {
                        name,
                        ok: false,
                        error: Some(err),
                        rewrite_ref: None,
                        rewrite_old: None,
                        rewrite_new: None,
                    });
                } else if let Some(rest) = line.strip_prefix("option ") {
                    let Some(cur) = current.as_mut() else {
                        return Err(ServerError::Protocol(
                            "proc-receive option before ok/ng".into(),
                        ));
                    };
                    if let Some(v) = rest.strip_prefix("refname ") {
                        cur.rewrite_ref = Some(v.to_string());
                    } else if let Some(v) = rest.strip_prefix("old-oid ") {
                        cur.rewrite_old = Some(v.to_string());
                    } else if let Some(v) = rest.strip_prefix("new-oid ") {
                        cur.rewrite_new = Some(v.to_string());
                    }
                    // forced-update and unknown options ignored for FS2 subset.
                } else {
                    return Err(ServerError::Protocol(format!(
                        "proc-receive unexpected line: {line}"
                    )));
                }
            }
            _ => {}
        }
    }
    finish_current(&mut current, &mut results);
    // Ensure every diverted command has a result (git requires reporting).
    for cmd in commands {
        if !results.iter().any(|r| r.name == cmd.name) {
            results.push(ProcReceiveResult {
                name: cmd.name.clone(),
                ok: false,
                error: Some("proc-receive did not report".into()),
                rewrite_ref: None,
                rewrite_old: None,
                rewrite_new: None,
            });
        }
    }
    Ok(results)
}

fn hook_path(git_dir: &Path, name: &str) -> PathBuf {
    git_dir.join("hooks").join(name)
}

/// Prefer Git for Windows bash over WSL `System32\bash.exe` (host advisory).
#[cfg(windows)]
fn windows_bash() -> Command {
    const CANDIDATES: &[&str] = &[
        r"C:\Program Files\Git\bin\bash.exe",
        r"C:\Program Files\Git\usr\bin\bash.exe",
        r"C:\Program Files (x86)\Git\bin\bash.exe",
    ];
    for c in CANDIDATES {
        if Path::new(c).is_file() {
            return Command::new(c);
        }
    }
    Command::new("bash")
}

/// Convert a Windows path to a Git-Bash-friendly form (`C:\a\b` → `/c/a/b`).
#[cfg(windows)]
fn bash_style_path(path: &Path) -> String {
    let s = path.to_string_lossy().replace('\\', "/");
    if let Some((drive, rest)) = s.split_once(':') {
        if drive.len() == 1 {
            let d = drive.chars().next().unwrap().to_ascii_lowercase();
            return format!("/{d}{rest}");
        }
    }
    s
}

fn is_runnable_hook(path: &Path) -> bool {
    if !path.is_file() {
        return false;
    }
    if path
        .file_name()
        .and_then(|s| s.to_str())
        .is_some_and(|n| n.ends_with(".sample"))
    {
        return false;
    }
    let Ok(meta) = fs::metadata(path) else {
        return false;
    };
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if meta.permissions().mode() & 0o111 == 0 {
            return false;
        }
    }
    #[cfg(not(unix))]
    {
        let _ = meta;
    }
    true
}

fn run_named_hook(
    git_dir: &Path,
    name: &str,
    args: &[&str],
    stdin: Option<&[u8]>,
    fail_on_nonzero: bool,
    env: &HookEnv,
) -> Result<HookGate, ServerError> {
    let path = hook_path(git_dir, name);
    if !is_runnable_hook(&path) {
        return Ok(HookGate::Allow);
    }
    // Unix: exec the hook path. Windows host advisory: bash (Git for Windows)
    // with a POSIX-style path so backslashes are not eaten by the shell.
    let mut cmd = {
        #[cfg(windows)]
        {
            let mut c = windows_bash();
            c.arg(bash_style_path(&path));
            c.args(args);
            c
        }
        #[cfg(not(windows))]
        {
            let mut c = Command::new(&path);
            c.args(args);
            c
        }
    };
    #[cfg(windows)]
    {
        // Hooks that expand `$GIT_DIR/...` must see a POSIX path under bash.
        cmd.env("GIT_DIR", bash_style_path(git_dir));
        if let Some(q) = &env.quarantine_path {
            cmd.env("GIT_QUARANTINE_PATH", bash_style_path(q));
        }
    }
    #[cfg(not(windows))]
    {
        cmd.env("GIT_DIR", git_dir);
        if let Some(q) = &env.quarantine_path {
            cmd.env("GIT_QUARANTINE_PATH", q);
        }
    }
    // O4 push-options → githooks environment (git-receive-pack).
    cmd.env("GIT_PUSH_OPTION_COUNT", env.push_options.len().to_string());
    for (i, opt) in env.push_options.iter().enumerate() {
        cmd.env(format!("GIT_PUSH_OPTION_{i}"), opt);
    }
    cmd.current_dir(git_dir);
    if stdin.is_some() {
        cmd.stdin(Stdio::piped());
    } else {
        cmd.stdin(Stdio::null());
    }
    // Inherit so operators see hook messages on the server process streams
    // (stock Git forwards to send-pack; we do not invent side-band for hooks).
    cmd.stdout(Stdio::inherit());
    cmd.stderr(Stdio::inherit());
    let mut child = cmd
        .spawn()
        .map_err(|e| ServerError::Msg(format!("hook {name}: {e}")))?;
    if let Some(bytes) = stdin {
        if let Some(mut hin) = child.stdin.take() {
            // Hook may exit before reading stdin (e.g. `exit 1`); BrokenPipe is
            // not a server fault — wait for status and apply fail-closed Decline.
            match hin.write_all(bytes) {
                Ok(()) => {}
                Err(e) if e.kind() == std::io::ErrorKind::BrokenPipe => {}
                Err(e) => {
                    return Err(ServerError::Msg(format!("hook {name} stdin: {e}")));
                }
            }
        }
    }
    let status = child
        .wait()
        .map_err(|e| ServerError::Msg(format!("hook {name}: {e}")))?;
    if fail_on_nonzero && !status.success() {
        return Ok(HookGate::Decline);
    }
    Ok(HookGate::Allow)
}