Home

ugit @22cdff623a8ec2342b9f90cc60f4d66f0e7ec712 - refs - log -
-
https://git.jolheiser.com/ugit.git
The code powering this h*ckin' site
ugit / internal / git / protocol.go
- raw
  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
package git

import (
	"bufio"
	"context"
	"fmt"
	"io"
	"strconv"
	"strings"

	"github.com/go-git/go-billy/v5/osfs"
	"github.com/go-git/go-git/v5"
	"github.com/go-git/go-git/v5/plumbing/format/pktline"
	"github.com/go-git/go-git/v5/plumbing/protocol/packp"
	"github.com/go-git/go-git/v5/plumbing/protocol/packp/capability"
	"github.com/go-git/go-git/v5/plumbing/serverinfo"
	"github.com/go-git/go-git/v5/plumbing/transport"
	"github.com/go-git/go-git/v5/plumbing/transport/server"
	"github.com/go-git/go-git/v5/storage/filesystem"
	"github.com/go-git/go-git/v5/utils/ioutil"
)

// ReadWriteContexter is the interface required to operate on git protocols
type ReadWriteContexter interface {
	io.ReadWriteCloser
	Context() context.Context
}

// Protocol handles the endpoint and server of the git protocols
type Protocol struct {
	endpoint *transport.Endpoint
	server   transport.Transport
}

// NewProtocol constructs a Protocol for a given repo
func NewProtocol(repoPath string) (Protocol, error) {
	endpoint, err := transport.NewEndpoint("/")
	if err != nil {
		return Protocol{}, err
	}
	fs := osfs.New(repoPath)
	loader := server.NewFilesystemLoader(fs)
	gitServer := server.NewServer(loader)
	return Protocol{
		endpoint: endpoint,
		server:   gitServer,
	}, nil
}

// HTTPInfoRefs handles the inforef part of the HTTP protocol
func (p Protocol) HTTPInfoRefs(rwc ReadWriteContexter) error {
	session, err := p.server.NewUploadPackSession(p.endpoint, nil)
	if err != nil {
		return err
	}
	defer ioutil.CheckClose(rwc, &err)
	return p.infoRefs(rwc, session, "# service=git-upload-pack")
}

func (p Protocol) infoRefs(rwc ReadWriteContexter, session transport.UploadPackSession, prefix string) error {
	ar, err := session.AdvertisedReferencesContext(rwc.Context())
	if err != nil {
		return err
	}

	if prefix != "" {
		ar.Prefix = [][]byte{
			[]byte(prefix),
			pktline.Flush,
		}
	}

	if err := ar.Encode(rwc); err != nil {
		return err
	}

	return nil
}

// HTTPUploadPack handles the upload-pack process for HTTP
func (p Protocol) HTTPUploadPack(rwc ReadWriteContexter) error {
	return p.uploadPack(rwc, false)
}

// SSHUploadPack handles the upload-pack process for SSH
func (p Protocol) SSHUploadPack(rwc ReadWriteContexter) error {
	return p.uploadPack(rwc, true)
}

func (p Protocol) uploadPack(rwc ReadWriteContexter, ssh bool) error {
	session, err := p.server.NewUploadPackSession(p.endpoint, nil)
	if err != nil {
		return err
	}
	defer ioutil.CheckClose(rwc, &err)

	if ssh {
		if err := p.infoRefs(rwc, session, ""); err != nil {
			return err
		}
	}

	req := packp.NewUploadPackRequest()
	if err := req.Decode(rwc); err != nil {
		return err
	}

	var resp *packp.UploadPackResponse
	resp, err = session.UploadPack(rwc.Context(), req)
	if err != nil {
		return err
	}

	if err := resp.Encode(rwc); err != nil {
		return fmt.Errorf("could not encode upload pack: %w", err)
	}

	return nil
}

// SSHReceivePack handles the receive-pack process for SSH
func (p Protocol) SSHReceivePack(rwc ReadWriteContexter, repo *Repo) error {
	buf := bufio.NewReader(rwc)

	session, err := p.server.NewReceivePackSession(p.endpoint, nil)
	if err != nil {
		return err
	}

	ar, err := session.AdvertisedReferencesContext(rwc.Context())
	if err != nil {
		return fmt.Errorf("internal error in advertised references: %w", err)
	}
	_ = ar.Capabilities.Set(capability.PushOptions)
	_ = ar.Capabilities.Set("no-thin")

	if err := ar.Encode(rwc); err != nil {
		return fmt.Errorf("error in advertised references encoding: %w", err)
	}

	req := packp.NewReferenceUpdateRequest()
	_ = req.Capabilities.Set(capability.ReportStatus)
	if err := req.Decode(buf); err != nil {
		// FIXME this is a hack, but go-git doesn't accept a 0000 if there are no refs to update
		if !strings.EqualFold(err.Error(), "capabilities delimiter not found") {
			return fmt.Errorf("error decoding: %w", err)
		}
	}

	// FIXME also a hack, if the next bytes are PACK then we have a packfile, otherwise assume it's push options
	peek, err := buf.Peek(4)
	if err != nil {
		return err
	}
	if string(peek) != "PACK" {
		s := pktline.NewScanner(buf)
		for s.Scan() {
			val := string(s.Bytes())
			if val == "" {
				break
			}
			if s.Err() != nil {
				return s.Err()
			}
			parts := strings.SplitN(val, "=", 2)
			req.Options = append(req.Options, &packp.Option{
				Key:   parts[0],
				Value: parts[1],
			})
		}
	}

	if err := handlePushOptions(repo, req.Options); err != nil {
		return fmt.Errorf("could not handle push options: %w", err)
	}

	// FIXME if there are only delete commands, there is no packfile and ReceivePack will block forever
	noPack := true
	for _, c := range req.Commands {
		if c.Action() != packp.Delete {
			noPack = false
			break
		}
	}
	if noPack {
		req.Packfile = nil
	}

	rs, err := session.ReceivePack(rwc.Context(), req)
	if err != nil {
		return fmt.Errorf("error in receive pack: %w", err)
	}

	if err := rs.Encode(rwc); err != nil {
		return fmt.Errorf("could not encode receive pack: %w", err)
	}

	return nil
}

func handlePushOptions(repo *Repo, opts []*packp.Option) error {
	var changed bool
	for _, opt := range opts {
		switch strings.ToLower(opt.Key) {
		case "desc", "description":
			changed = repo.Meta.Description != opt.Value
			repo.Meta.Description = opt.Value
		case "private":
			private, err := strconv.ParseBool(opt.Value)
			if err != nil {
				continue
			}
			changed = repo.Meta.Private != private
			repo.Meta.Private = private
		}
	}
	if changed {
		return repo.SaveMeta()
	}
	return nil
}

// UpdateServerInfo handles updating server info for the git repo
func UpdateServerInfo(repo string) error {
	r, err := git.PlainOpen(repo)
	if err != nil {
		return err
	}
	fs := r.Storer.(*filesystem.Storage).Filesystem()
	return serverinfo.UpdateServerInfo(r.Storer, fs)
}