Debian Codegraph @

plumbing/transport/internal/common/common.go

raw
1 // Package common implements the git pack protocol with a pluggable transport.
2 // This is a low-level package to implement new transports. Use a concrete
3 // implementation instead (e.g. http, file, ssh).
4 //
5 // A simple example of usage can be found in the file package.
6 package common
7
8 import (
9 "bufio"
10 "context"
11 "errors"
12 "fmt"
13 "io"
14 "regexp"
15 "strings"
16 "time"
17
18 "github.com/go-git/go-git/v5/plumbing/format/pktline"
19 "github.com/go-git/go-git/v5/plumbing/protocol/packp"
20 "github.com/go-git/go-git/v5/plumbing/protocol/packp/capability"
21 "github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband"
22 "github.com/go-git/go-git/v5/plumbing/transport"
23 "github.com/go-git/go-git/v5/utils/ioutil"
24 )
25
26 const (
27 readErrorSecondsTimeout = 10
28 )
29
30 var (
31 ErrTimeoutExceeded = errors.New("timeout exceeded")
32 // stdErrSkipPattern is used for skipping lines from a command's stderr output.
33 // Any line matching this pattern will be skipped from further
34 // processing and not be returned to calling code.
35 stdErrSkipPattern = regexp.MustCompile("^remote:( =*){0,1}$")
36 )
37
38 // Commander creates Command instances. This is the main entry point for
39 // transport implementations.
40 type Commander interface {
41 // Command creates a new Command for the given git command and
42 // endpoint. cmd can be git-upload-pack or git-receive-pack. An
43 // error should be returned if the endpoint is not supported or the
44 // command cannot be created (e.g. binary does not exist, connection
45 // cannot be established).
46 Command(cmd string, ep *transport.Endpoint, auth transport.AuthMethod) (Command, error)
47 }
48
49 // Command is used for a single command execution.
50 // This interface is modeled after exec.Cmd and ssh.Session in the standard
51 // library.
52 type Command interface {
53 // StderrPipe returns a pipe that will be connected to the command's
54 // standard error when the command starts. It should not be called after
55 // Start.
56 StderrPipe() (io.Reader, error)
57 // StdinPipe returns a pipe that will be connected to the command's
58 // standard input when the command starts. It should not be called after
59 // Start. The pipe should be closed when no more input is expected.
60 StdinPipe() (io.WriteCloser, error)
61 // StdoutPipe returns a pipe that will be connected to the command's
62 // standard output when the command starts. It should not be called after
63 // Start.
64 StdoutPipe() (io.Reader, error)
65 // Start starts the specified command. It does not wait for it to
66 // complete.
67 Start() error
68 // Close closes the command and releases any resources used by it. It
69 // will block until the command exits.
70 Close() error
71 }
72
73 // CommandKiller expands the Command interface, enabling it for being killed.
74 type CommandKiller interface {
75 // Kill and close the session whatever the state it is. It will block until
76 // the command is terminated.
77 Kill() error
78 }
79
80 type client struct {
81 cmdr Commander
82 }
83
84 // NewClient creates a new client using the given Commander.
85 func NewClient(runner Commander) transport.Transport {
86 return &client{runner}
87 }
88
89 // NewUploadPackSession creates a new UploadPackSession.
90 func (c *client) NewUploadPackSession(ep *transport.Endpoint, auth transport.AuthMethod) (
91 transport.UploadPackSession, error) {
92
93 return c.newSession(transport.UploadPackServiceName, ep, auth)
94 }
95
96 // NewReceivePackSession creates a new ReceivePackSession.
97 func (c *client) NewReceivePackSession(ep *transport.Endpoint, auth transport.AuthMethod) (
98 transport.ReceivePackSession, error) {
99
100 return c.newSession(transport.ReceivePackServiceName, ep, auth)
101 }
102
103 type session struct {
104 Stdin io.WriteCloser
105 Stdout io.Reader
106 Command Command
107
108 isReceivePack bool
109 advRefs *packp.AdvRefs
110 packRun bool
111 finished bool
112 firstErrLine chan string
113 }
114
115 func (c *client) newSession(s string, ep *transport.Endpoint, auth transport.AuthMethod) (*session, error) {
116 cmd, err := c.cmdr.Command(s, ep, auth)
117 if err != nil {
118 return nil, err
119 }
120
121 stdin, err := cmd.StdinPipe()
122 if err != nil {
123 return nil, err
124 }
125
126 stdout, err := cmd.StdoutPipe()
127 if err != nil {
128 return nil, err
129 }
130
131 stderr, err := cmd.StderrPipe()
132 if err != nil {
133 return nil, err
134 }
135
136 if err := cmd.Start(); err != nil {
137 return nil, err
138 }
139
140 return &session{
141 Stdin: stdin,
142 Stdout: stdout,
143 Command: cmd,
144 firstErrLine: c.listenFirstError(stderr),
145 isReceivePack: s == transport.ReceivePackServiceName,
146 }, nil
147 }
148
149 func (c *client) listenFirstError(r io.Reader) chan string {
150 if r == nil {
151 return nil
152 }
153
154 errLine := make(chan string, 1)
155 go func() {
156 s := bufio.NewScanner(r)
157 for {
158 if s.Scan() {
159 line := s.Text()
160 if !stdErrSkipPattern.MatchString(line) {
161 errLine <- line
162 break
163 }
164 } else {
165 close(errLine)
166 break
167 }
168 }
169
170 _, _ = io.Copy(io.Discard, r)
171 }()
172
173 return errLine
174 }
175
176 func (s *session) AdvertisedReferences() (*packp.AdvRefs, error) {
177 return s.AdvertisedReferencesContext(context.TODO())
178 }
179
180 // AdvertisedReferences retrieves the advertised references from the server.
181 func (s *session) AdvertisedReferencesContext(ctx context.Context) (*packp.AdvRefs, error) {
182 if s.advRefs != nil {
183 return s.advRefs, nil
184 }
185
186 ar := packp.NewAdvRefs()
187 if err := ar.Decode(s.StdoutContext(ctx)); err != nil {
188 if err := s.handleAdvRefDecodeError(err); err != nil {
189 return nil, err
190 }
191 }
192
193 // Some servers like jGit, announce capabilities instead of returning an
194 // packp message with a flush. This verifies that we received a empty
195 // adv-refs, even it contains capabilities.
196 if !s.isReceivePack && ar.IsEmpty() {
197 return nil, transport.ErrEmptyRemoteRepository
198 }
199
200 transport.FilterUnsupportedCapabilities(ar.Capabilities)
201 s.advRefs = ar
202 return ar, nil
203 }
204
205 func (s *session) handleAdvRefDecodeError(err error) error {
206 var errLine *pktline.ErrorLine
207 if errors.As(err, &errLine) {
208 if isRepoNotFoundError(errLine.Text) {
209 return transport.ErrRepositoryNotFound
210 }
211
212 return errLine
213 }
214
215 // If repository is not found, we get empty stdout and server writes an
216 // error to stderr.
217 if errors.Is(err, packp.ErrEmptyInput) {
218 // TODO:(v6): handle this error in a better way.
219 // Instead of checking the stderr output for a specific error message,
220 // define an ExitError and embed the stderr output and exit (if one
221 // exists) in the error struct. Just like exec.ExitError.
222 s.finished = true
223 if err := s.checkNotFoundError(); err != nil {
224 return err
225 }
226
227 return io.ErrUnexpectedEOF
228 }
229
230 // For empty (but existing) repositories, we get empty advertised-references
231 // message. But valid. That is, it includes at least a flush.
232 if err == packp.ErrEmptyAdvRefs {
233 // Empty repositories are valid for git-receive-pack.
234 if s.isReceivePack {
235 return nil
236 }
237
238 if err := s.finish(); err != nil {
239 return err
240 }
241
242 return transport.ErrEmptyRemoteRepository
243 }
244
245 // Some server sends the errors as normal content (git protocol), so when
246 // we try to decode it fails, we need to check the content of it, to detect
247 // not found errors
248 if uerr, ok := err.(*packp.ErrUnexpectedData); ok {
249 if isRepoNotFoundError(string(uerr.Data)) {
250 return transport.ErrRepositoryNotFound
251 }
252 }
253
254 return err
255 }
256
257 // UploadPack performs a request to the server to fetch a packfile. A reader is
258 // returned with the packfile content. The reader must be closed after reading.
259 func (s *session) UploadPack(ctx context.Context, req *packp.UploadPackRequest) (*packp.UploadPackResponse, error) {
260 if req.IsEmpty() {
261 // XXX: IsEmpty means haves are a subset of wants, in that case we have
262 // everything we asked for. Close the connection and return nil.
263 if err := s.finish(); err != nil {
264 return nil, err
265 }
266 // TODO:(v6) return nil here
267 return nil, transport.ErrEmptyUploadPackRequest
268 }
269
270 if err := req.Validate(); err != nil {
271 return nil, err
272 }
273
274 if _, err := s.AdvertisedReferencesContext(ctx); err != nil {
275 return nil, err
276 }
277
278 s.packRun = true
279
280 in := s.StdinContext(ctx)
281 out := s.StdoutContext(ctx)
282
283 if err := uploadPack(in, out, req); err != nil {
284 return nil, err
285 }
286
287 r, err := ioutil.NonEmptyReader(out)
288 if err == ioutil.ErrEmptyReader {
289 if c, ok := s.Stdout.(io.Closer); ok {
290 _ = c.Close()
291 }
292
293 return nil, transport.ErrEmptyUploadPackRequest
294 }
295
296 if err != nil {
297 return nil, err
298 }
299
300 rc := ioutil.NewReadCloser(r, s)
301 return DecodeUploadPackResponse(rc, req)
302 }
303
304 func (s *session) StdinContext(ctx context.Context) io.WriteCloser {
305 return ioutil.NewWriteCloserOnError(
306 ioutil.NewContextWriteCloser(ctx, s.Stdin),
307 s.onError,
308 )
309 }
310
311 func (s *session) StdoutContext(ctx context.Context) io.Reader {
312 return ioutil.NewReaderOnError(
313 ioutil.NewContextReader(ctx, s.Stdout),
314 s.onError,
315 )
316 }
317
318 func (s *session) onError(err error) {
319 if k, ok := s.Command.(CommandKiller); ok {
320 _ = k.Kill()
321 }
322
323 _ = s.Close()
324 }
325
326 func (s *session) ReceivePack(ctx context.Context, req *packp.ReferenceUpdateRequest) (*packp.ReportStatus, error) {
327 if _, err := s.AdvertisedReferences(); err != nil {
328 return nil, err
329 }
330
331 s.packRun = true
332
333 w := s.StdinContext(ctx)
334 if err := req.Encode(w); err != nil {
335 return nil, err
336 }
337
338 if err := w.Close(); err != nil {
339 return nil, err
340 }
341
342 if !req.Capabilities.Supports(capability.ReportStatus) {
343 // If we don't have report-status, we can only
344 // check return value error.
345 return nil, s.Command.Close()
346 }
347
348 r := s.StdoutContext(ctx)
349
350 var d *sideband.Demuxer
351 if req.Capabilities.Supports(capability.Sideband64k) {
352 d = sideband.NewDemuxer(sideband.Sideband64k, r)
353 } else if req.Capabilities.Supports(capability.Sideband) {
354 d = sideband.NewDemuxer(sideband.Sideband, r)
355 }
356 if d != nil {
357 d.Progress = req.Progress
358 r = d
359 }
360
361 report := packp.NewReportStatus()
362 if err := report.Decode(r); err != nil {
363 return nil, err
364 }
365
366 if err := report.Error(); err != nil {
367 defer s.Close()
368 return report, err
369 }
370
371 return report, s.Command.Close()
372 }
373
374 func (s *session) finish() error {
375 if s.finished {
376 return nil
377 }
378
379 s.finished = true
380
381 // If we did not run a upload/receive-pack, we close the connection
382 // gracefully by sending a flush packet to the server. If the server
383 // operates correctly, it will exit with status 0.
384 if !s.packRun {
385 _, err := s.Stdin.Write(pktline.FlushPkt)
386 return err
387 }
388
389 return nil
390 }
391
392 func (s *session) Close() (err error) {
393 err = s.finish()
394
395 defer ioutil.CheckClose(s.Command, &err)
396 return
397 }
398
399 func (s *session) checkNotFoundError() error {
400 t := time.NewTicker(time.Second * readErrorSecondsTimeout)
401 defer t.Stop()
402
403 select {
404 case <-t.C:
405 return ErrTimeoutExceeded
406 case line, ok := <-s.firstErrLine:
407 if !ok || len(line) == 0 {
408 return nil
409 }
410
411 if isRepoNotFoundError(line) {
412 return transport.ErrRepositoryNotFound
413 }
414
415 // TODO:(v6): return server error just as it is without a prefix
416 return fmt.Errorf("unknown error: %s", line)
417 }
418 }
419
420 const (
421 githubRepoNotFoundErr = "Repository not found."
422 bitbucketRepoNotFoundErr = "repository does not exist."
423 localRepoNotFoundErr = "does not appear to be a git repository"
424 gitProtocolNotFoundErr = "Repository not found."
425 gitProtocolNoSuchErr = "no such repository"
426 gitProtocolAccessDeniedErr = "access denied"
427 gogsAccessDeniedErr = "Repository does not exist or you do not have access"
428 gitlabRepoNotFoundErr = "The project you were looking for could not be found"
429 )
430
431 func isRepoNotFoundError(s string) bool {
432 for _, err := range []string{
433 githubRepoNotFoundErr,
434 bitbucketRepoNotFoundErr,
435 localRepoNotFoundErr,
436 gitProtocolNotFoundErr,
437 gitProtocolNoSuchErr,
438 gitProtocolAccessDeniedErr,
439 gogsAccessDeniedErr,
440 gitlabRepoNotFoundErr,
441 } {
442 if strings.Contains(s, err) {
443 return true
444 }
445 }
446
447 return false
448 }
449
450 // uploadPack implements the git-upload-pack protocol.
451 func uploadPack(w io.WriteCloser, _ io.Reader, req *packp.UploadPackRequest) error {
452 // TODO support multi_ack mode
453 // TODO support multi_ack_detailed mode
454 // TODO support acks for common objects
455 // TODO build a proper state machine for all these processing options
456
457 if err := req.UploadRequest.Encode(w); err != nil {
458 return fmt.Errorf("sending upload-req message: %s", err)
459 }
460
461 if err := req.UploadHaves.Encode(w, true); err != nil {
462 return fmt.Errorf("sending haves message: %s", err)
463 }
464
465 if err := sendDone(w); err != nil {
466 return fmt.Errorf("sending done message: %s", err)
467 }
468
469 if err := w.Close(); err != nil {
470 return fmt.Errorf("closing input: %s", err)
471 }
472
473 return nil
474 }
475
476 func sendDone(w io.Writer) error {
477 e := pktline.NewEncoder(w)
478
479 return e.Encodef("done\n")
480 }
481
482 // DecodeUploadPackResponse decodes r into a new packp.UploadPackResponse
483 func DecodeUploadPackResponse(r io.ReadCloser, req *packp.UploadPackRequest) (
484 *packp.UploadPackResponse, error,
485 ) {
486 res := packp.NewUploadPackResponse(req)
487 if err := res.Decode(r); err != nil {
488 return nil, fmt.Errorf("error decoding upload-pack response: %s", err)
489 }
490
491 return res, nil
492 }