aboutsummaryrefslogtreecommitdiff
path: root/cmd/receivepack9418/request.go
blob: 57b55e306969ef70616b99cd1b1a6ba84030be44 (about) (plain) (blame)
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
package main

import (
	"bytes"
	"errors"
	"fmt"
	"strings"
)

type gitProtoRequest struct {
	Command         string
	Pathname        string
	Host            string
	ExtraParameters []string
}

func parseGitProtoRequestPayload(payload []byte) (gitProtoRequest, error) {
	parts := bytes.Split(payload, []byte{0})
	if len(parts) == 0 || len(parts[0]) == 0 {
		return gitProtoRequest{}, errors.New("missing command/path segment")
	}

	commandPath := string(parts[0])

	command, pathname, ok := strings.Cut(commandPath, " ")
	if !ok || command == "" || pathname == "" {
		return gitProtoRequest{}, fmt.Errorf("malformed command/path segment %q", commandPath)
	}

	req := gitProtoRequest{
		Command:  command,
		Pathname: pathname,
	}

	i := 1
	if i < len(parts) && strings.HasPrefix(string(parts[i]), "host=") {
		req.Host = strings.TrimPrefix(string(parts[i]), "host=")
		i++
	}

	// No tail left.
	if i >= len(parts) {
		return req, nil
	}

	// If there is tail, grammar requires one empty field before extras.
	if len(parts[i]) != 0 {
		return gitProtoRequest{}, fmt.Errorf("unexpected token %q after host/path", string(parts[i]))
	}

	i++
	for ; i < len(parts); i++ {
		if len(parts[i]) == 0 {
			continue
		}

		req.ExtraParameters = append(req.ExtraParameters, string(parts[i]))
	}

	return req, nil
}