| 1 | // valley-restack-transport is how the restacker's end-to-end tests reach |
| 2 | // origin: a stand-in for ssh that serves each push with the real git |
| 3 | // receive-pack, which runs the repository's rendered pre-receive hook, and |
| 4 | // each fetch with the real git upload-pack. A test can hold one push or |
| 5 | // fetch at a point it chooses, or lose a push's answer, so a race or a |
| 6 | // lost connection happens exactly where the test wants it. |
| 7 | // |
| 8 | // git runs it as GIT_SSH_COMMAND, with GIT_SSH_VARIANT=simple, for a URL |
| 9 | // such as ssh://restacker@valley/srv/project.git: |
| 10 | // |
| 11 | // valley-restack-transport restacker@valley "git-receive-pack '/srv/project.git'" |
| 12 | // |
| 13 | // The user in the URL is the principal. The transport sets |
| 14 | // VALLEY_PRINCIPAL to it for receive-pack, where the rendered hook reads |
| 15 | // it, as the git user's login shell sets it from the key sshd |
| 16 | // authenticated. A principal the client's own environment carries is |
| 17 | // dropped, as the shell drops it, and a URL with no user pushes with no |
| 18 | // principal. |
| 19 | // |
| 20 | // A barrier is armed by writing one line to $VALLEY_BARRIER/hold: |
| 21 | // |
| 22 | // upload connect the next fetch or ls-remote, before upload-pack starts |
| 23 | // receive connect the next push, before receive-pack starts |
| 24 | // receive taken [PREFIX] the next push that updates a ref under PREFIX, once |
| 25 | // receive-pack has finished and before the client hears |
| 26 | // receive drop [PREFIX] the next such push: its answer is passed on with no |
| 27 | // ref's status in it, as when origin's answer is lost |
| 28 | // |
| 29 | // The connection the barrier matches claims it, by renaming hold to held, |
| 30 | // so a barrier fires once. It writes what it matched to arrived. Unless it |
| 31 | // drops, it then waits for release to exist, for at most two minutes, and |
| 32 | // goes on. |
| 33 | package main |
| 34 | |
| 35 | import ( |
| 36 | "bufio" |
| 37 | "bytes" |
| 38 | "errors" |
| 39 | "fmt" |
| 40 | "io" |
| 41 | "os" |
| 42 | "os/exec" |
| 43 | "path/filepath" |
| 44 | "strconv" |
| 45 | "strings" |
| 46 | "syscall" |
| 47 | "time" |
| 48 | ) |
| 49 | |
| 50 | // releaseWait is the longest a held connection waits for its release. A |
| 51 | // test that never releases fails rather than hangs. |
| 52 | const releaseWait = 2 * time.Minute |
| 53 | |
| 54 | func main() { |
| 55 | if err := serve(os.Args[1:]); err != nil { |
| 56 | fmt.Fprintf(os.Stderr, "valley-restack-transport: %v\n", err) |
| 57 | os.Exit(1) |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | func serve(args []string) error { |
| 62 | if len(args) < 2 { |
| 63 | return errors.New("usage: valley-restack-transport [user@]host command") |
| 64 | } |
| 65 | host, line := args[len(args)-2], args[len(args)-1] |
| 66 | service, repo, err := parseCommand(line) |
| 67 | if err != nil { |
| 68 | return err |
| 69 | } |
| 70 | env := []string{} |
| 71 | for _, kv := range os.Environ() { |
| 72 | if !strings.HasPrefix(kv, "VALLEY_PRINCIPAL=") { |
| 73 | env = append(env, kv) |
| 74 | } |
| 75 | } |
| 76 | if user, _, found := strings.Cut(host, "@"); found && user != "" { |
| 77 | env = append(env, "VALLEY_PRINCIPAL="+user) |
| 78 | } |
| 79 | git, err := exec.LookPath("git") |
| 80 | if err != nil { |
| 81 | return err |
| 82 | } |
| 83 | b := armed(service) |
| 84 | if b == nil || b.stage != "connect" && service != "receive" { |
| 85 | return syscall.Exec(git, []string{"git", service + "-pack", repo}, env) |
| 86 | } |
| 87 | if b.stage == "connect" { |
| 88 | if b.claim("connect") { |
| 89 | if err := b.wait(); err != nil { |
| 90 | return err |
| 91 | } |
| 92 | } |
| 93 | return syscall.Exec(git, []string{"git", service + "-pack", repo}, env) |
| 94 | } |
| 95 | return proxy(git, repo, env, b) |
| 96 | } |
| 97 | |
| 98 | // parseCommand reads the command git asks ssh to run: git-receive-pack or |
| 99 | // git-upload-pack, and the repository's path as git quotes it. |
| 100 | func parseCommand(line string) (service, repo string, err error) { |
| 101 | program, quoted, _ := strings.Cut(line, " ") |
| 102 | switch program { |
| 103 | case "git-receive-pack": |
| 104 | service = "receive" |
| 105 | case "git-upload-pack": |
| 106 | service = "upload" |
| 107 | default: |
| 108 | return "", "", fmt.Errorf("%q asks for neither receive-pack nor upload-pack", line) |
| 109 | } |
| 110 | repo, err = unquote(quoted) |
| 111 | return service, repo, err |
| 112 | } |
| 113 | |
| 114 | // unquote reads a path as git's sq_quote writes it: in single quotes, with |
| 115 | // each single quote and exclamation mark in it outside them, escaped. |
| 116 | func unquote(s string) (string, error) { |
| 117 | var out strings.Builder |
| 118 | for len(s) > 0 { |
| 119 | switch { |
| 120 | case s[0] == '\'': |
| 121 | end := strings.IndexByte(s[1:], '\'') |
| 122 | if end < 0 { |
| 123 | return "", fmt.Errorf("an unterminated quote in %q", s) |
| 124 | } |
| 125 | out.WriteString(s[1 : 1+end]) |
| 126 | s = s[2+end:] |
| 127 | case s[0] == '\\' && len(s) > 1: |
| 128 | out.WriteByte(s[1]) |
| 129 | s = s[2:] |
| 130 | default: |
| 131 | out.WriteByte(s[0]) |
| 132 | s = s[1:] |
| 133 | } |
| 134 | } |
| 135 | return out.String(), nil |
| 136 | } |
| 137 | |
| 138 | // barrier is an armed barrier. |
| 139 | type barrier struct { |
| 140 | dir, stage, prefix string |
| 141 | } |
| 142 | |
| 143 | // armed is the barrier armed for a service, or nil. |
| 144 | func armed(service string) *barrier { |
| 145 | dir := os.Getenv("VALLEY_BARRIER") |
| 146 | if dir == "" { |
| 147 | return nil |
| 148 | } |
| 149 | data, err := os.ReadFile(filepath.Join(dir, "hold")) |
| 150 | if err != nil { |
| 151 | return nil |
| 152 | } |
| 153 | f := strings.Fields(string(data)) |
| 154 | if len(f) < 2 || f[0] != service { |
| 155 | return nil |
| 156 | } |
| 157 | b := &barrier{dir: dir, stage: f[1]} |
| 158 | if len(f) > 2 { |
| 159 | b.prefix = f[2] |
| 160 | } |
| 161 | return b |
| 162 | } |
| 163 | |
| 164 | // matches reports whether a push updating refs is the barrier's. |
| 165 | func (b *barrier) matches(refs []string) bool { |
| 166 | for _, r := range refs { |
| 167 | if strings.HasPrefix(r, b.prefix) { |
| 168 | return true |
| 169 | } |
| 170 | } |
| 171 | return false |
| 172 | } |
| 173 | |
| 174 | // claim takes the barrier for this connection, and says what it matched. |
| 175 | // Only one connection's rename succeeds. |
| 176 | func (b *barrier) claim(what string) bool { |
| 177 | if os.Rename(filepath.Join(b.dir, "hold"), filepath.Join(b.dir, "held")) != nil { |
| 178 | return false |
| 179 | } |
| 180 | tmp := filepath.Join(b.dir, ".arrived") |
| 181 | if os.WriteFile(tmp, []byte(what+"\n"), 0o644) != nil || os.Rename(tmp, filepath.Join(b.dir, "arrived")) != nil { |
| 182 | return false |
| 183 | } |
| 184 | return true |
| 185 | } |
| 186 | |
| 187 | // wait waits for the test to release the barrier. |
| 188 | func (b *barrier) wait() error { |
| 189 | for deadline := time.Now().Add(releaseWait); time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) { |
| 190 | if _, err := os.Stat(filepath.Join(b.dir, "release")); err == nil { |
| 191 | return nil |
| 192 | } |
| 193 | } |
| 194 | return fmt.Errorf("the barrier in %s was never released", b.dir) |
| 195 | } |
| 196 | |
| 197 | // proxy serves a push through the real receive-pack and stands between it |
| 198 | // and the client. The side-band capabilities are taken out of |
| 199 | // receive-pack's advertisement, so its answer comes as plain pkt-lines. |
| 200 | // The commands the client sends are read for the refs they update, and |
| 201 | // passed on as they came, with the pack after them. receive-pack's answer |
| 202 | // is read whole before any of it is passed on, so a barrier that holds |
| 203 | // the push once origin has taken it holds the client too. |
| 204 | func proxy(git, repo string, env []string, b *barrier) error { |
| 205 | cmd := exec.Command(git, "receive-pack", repo) |
| 206 | cmd.Env, cmd.Stderr = env, os.Stderr |
| 207 | in, err := cmd.StdinPipe() |
| 208 | if err != nil { |
| 209 | return err |
| 210 | } |
| 211 | out, err := cmd.StdoutPipe() |
| 212 | if err != nil { |
| 213 | return err |
| 214 | } |
| 215 | if err := cmd.Start(); err != nil { |
| 216 | return err |
| 217 | } |
| 218 | server := bufio.NewReader(out) |
| 219 | stdout := bufio.NewWriter(os.Stdout) |
| 220 | for { |
| 221 | p, err := readPkt(server) |
| 222 | if err != nil { |
| 223 | return err |
| 224 | } |
| 225 | if p != nil { |
| 226 | if refs, caps, ok := bytes.Cut(p, []byte{0}); ok { |
| 227 | var kept []string |
| 228 | for _, c := range strings.Fields(string(caps)) { |
| 229 | if !strings.HasPrefix(c, "side-band") { |
| 230 | kept = append(kept, c) |
| 231 | } |
| 232 | } |
| 233 | p = []byte(string(refs) + "\x00" + strings.Join(kept, " ") + "\n") |
| 234 | } |
| 235 | } |
| 236 | writePkt(stdout, p) |
| 237 | if p == nil { |
| 238 | break |
| 239 | } |
| 240 | } |
| 241 | if err := stdout.Flush(); err != nil { |
| 242 | return err |
| 243 | } |
| 244 | |
| 245 | client := bufio.NewReader(os.Stdin) |
| 246 | var refs []string |
| 247 | for { |
| 248 | p, err := readPkt(client) |
| 249 | if err != nil { |
| 250 | break |
| 251 | } |
| 252 | writePkt(in, p) |
| 253 | if p == nil { |
| 254 | break |
| 255 | } |
| 256 | command, _, _ := bytes.Cut(p, []byte{0}) |
| 257 | if f := strings.Fields(string(command)); len(f) == 3 { |
| 258 | refs = append(refs, f[2]) |
| 259 | } |
| 260 | } |
| 261 | go func() { |
| 262 | io.Copy(in, client) |
| 263 | in.Close() |
| 264 | }() |
| 265 | |
| 266 | var answer [][]byte |
| 267 | for { |
| 268 | p, err := readPkt(server) |
| 269 | if err != nil { |
| 270 | break |
| 271 | } |
| 272 | answer = append(answer, p) |
| 273 | } |
| 274 | waitErr := cmd.Wait() |
| 275 | |
| 276 | if b.matches(refs) && b.claim(b.stage+" "+strings.Join(refs, " ")) { |
| 277 | switch b.stage { |
| 278 | case "taken": |
| 279 | if err := b.wait(); err != nil { |
| 280 | return err |
| 281 | } |
| 282 | case "drop": |
| 283 | var kept [][]byte |
| 284 | for _, p := range answer { |
| 285 | if !bytes.HasPrefix(p, []byte("ok ")) && !bytes.HasPrefix(p, []byte("ng ")) && !bytes.HasPrefix(p, []byte("option ")) { |
| 286 | kept = append(kept, p) |
| 287 | } |
| 288 | } |
| 289 | answer = kept |
| 290 | } |
| 291 | } |
| 292 | for _, p := range answer { |
| 293 | writePkt(stdout, p) |
| 294 | } |
| 295 | if err := stdout.Flush(); err != nil { |
| 296 | return err |
| 297 | } |
| 298 | if waitErr != nil { |
| 299 | os.Exit(1) |
| 300 | } |
| 301 | return nil |
| 302 | } |
| 303 | |
| 304 | // readPkt reads one pkt-line, nil for a flush. |
| 305 | func readPkt(r *bufio.Reader) ([]byte, error) { |
| 306 | var size [4]byte |
| 307 | if _, err := io.ReadFull(r, size[:]); err != nil { |
| 308 | return nil, err |
| 309 | } |
| 310 | n, err := strconv.ParseUint(string(size[:]), 16, 16) |
| 311 | if err != nil { |
| 312 | return nil, err |
| 313 | } |
| 314 | if n < 4 { |
| 315 | return nil, nil |
| 316 | } |
| 317 | p := make([]byte, n-4) |
| 318 | _, err = io.ReadFull(r, p) |
| 319 | return p, err |
| 320 | } |
| 321 | |
| 322 | // writePkt writes one pkt-line, a flush for nil. |
| 323 | func writePkt(w io.Writer, p []byte) { |
| 324 | if p == nil { |
| 325 | io.WriteString(w, "0000") |
| 326 | return |
| 327 | } |
| 328 | fmt.Fprintf(w, "%04x%s", len(p)+4, p) |
| 329 | } |