Debian Codegraph @

plumbing/format/packfile/scanner.go

raw
1 package packfile
2
3 import (
4 "bufio"
5 "bytes"
6 "crypto"
7 "errors"
8 "fmt"
9 gohash "hash"
10 "hash/crc32"
11 "io"
12
13 "github.com/go-git/go-git/v5/plumbing"
14 "github.com/go-git/go-git/v5/plumbing/hash"
15 "github.com/go-git/go-git/v5/utils/binary"
16 "github.com/go-git/go-git/v5/utils/ioutil"
17 "github.com/go-git/go-git/v5/utils/sync"
18 )
19
20 var (
21 // ErrEmptyPackfile is returned by ReadHeader when no data is found in the packfile
22 ErrEmptyPackfile = NewError("empty packfile")
23 // ErrBadSignature is returned by ReadHeader when the signature in the packfile is incorrect.
24 ErrBadSignature = NewError("malformed pack file signature")
25 // ErrUnsupportedVersion is returned by ReadHeader when the packfile version is
26 // different than VersionSupported.
27 ErrUnsupportedVersion = NewError("unsupported packfile version")
28 // ErrSeekNotSupported returned if seek is not support
29 ErrSeekNotSupported = NewError("not seek support")
30 // ErrMalformedPackFile is returned by the parser when the pack file is corrupted.
31 ErrMalformedPackFile = errors.New("malformed PACK file")
32 // ErrLengthOverflow is returned when a variable-length integer would not
33 // fit into its accumulator because the input declares more continuation
34 // bytes than the type can hold.
35 ErrLengthOverflow = errors.New("variable-length integer overflow")
36 // ErrInflatedSizeMismatch is returned when a packfile object inflates to
37 // more bytes than the size declared in its object header. A well-formed
38 // packfile never produces more data than the declared size; exceeding it
39 // indicates a structurally invalid entry.
40 ErrInflatedSizeMismatch = errors.New("packfile: inflated object exceeds declared size")
41 )
42
43 // boundedWriter passes writes through to w up to limit bytes total, then
44 // returns ErrInflatedSizeMismatch. It is used to enforce that a packfile
45 // object's inflated length does not exceed the size declared in its header.
46 type boundedWriter struct {
47 w io.Writer
48 limit int64
49 n int64
50 }
51
52 // Write forwards p to the underlying writer while keeping the running total
53 // at or below limit. On overrun it forwards the legal prefix and reports
54 // the number of bytes actually consumed alongside ErrInflatedSizeMismatch,
55 // matching the contract in io.Writer. A write error from the underlying
56 // writer during overrun-handling is joined with ErrInflatedSizeMismatch so
57 // it is not silently dropped.
58 func (b *boundedWriter) Write(p []byte) (int, error) {
59 if b.n+int64(len(p)) > b.limit {
60 remain := int(b.limit - b.n)
61 err := error(ErrInflatedSizeMismatch)
62 if remain > 0 {
63 n, werr := b.w.Write(p[:remain])
64 b.n += int64(n)
65 if werr != nil {
66 err = errors.Join(ErrInflatedSizeMismatch, werr)
67 }
68 return n, err
69 }
70 return 0, err
71 }
72 n, err := b.w.Write(p)
73 b.n += int64(n)
74 return n, err
75 }
76
77 // boundedReadCloser wraps a ReadCloser and reports ErrInflatedSizeMismatch
78 // once more than limit bytes have been read. It is used by the on-demand
79 // object reader returned from FSObject.Reader so that a lazy Read of a
80 // packfile object cannot stream past its declared inflated size.
81 //
82 // The implementation builds on io.LimitedReader with the standard
83 // overrun-detection trick: request limit+1 bytes from the underlying so
84 // that the moment the sentinel byte materializes (LimitedReader.N drops
85 // to zero) we know the source produced more than limit bytes.
86 type boundedReadCloser struct {
87 lr io.LimitedReader
88 closer io.Closer
89 overrun bool
90 }
91
92 // newBoundedReadCloser wraps rc so that the cumulative bytes returned from
93 // Read never exceed limit. The first call that would have returned a byte
94 // past limit instead returns ErrInflatedSizeMismatch; subsequent calls
95 // keep returning the same error. A negative limit is treated as zero, so
96 // the first byte produced by rc surfaces ErrInflatedSizeMismatch.
97 func newBoundedReadCloser(rc io.ReadCloser, limit int64) *boundedReadCloser {
98 if limit < 0 {
99 limit = 0
100 }
101 return &boundedReadCloser{
102 lr: io.LimitedReader{R: rc, N: limit + 1},
103 closer: rc,
104 }
105 }
106
107 // Read forwards Read up to the configured byte limit. When the underlying
108 // stream produces the limit+1 sentinel byte, the legal prefix is returned
109 // alongside ErrInflatedSizeMismatch; on subsequent calls only the error
110 // is returned.
111 func (b *boundedReadCloser) Read(p []byte) (int, error) {
112 if b.overrun {
113 return 0, ErrInflatedSizeMismatch
114 }
115 n, err := b.lr.Read(p)
116 if b.lr.N == 0 {
117 b.overrun = true
118 return n - 1, ErrInflatedSizeMismatch
119 }
120 return n, err
121 }
122
123 // Close closes the underlying ReadCloser.
124 func (b *boundedReadCloser) Close() error { return b.closer.Close() }
125
126 // ObjectHeader contains the information related to the object, this information
127 // is collected from the previous bytes to the content of the object.
128 type ObjectHeader struct {
129 Type plumbing.ObjectType
130 Offset int64
131 Length int64
132 Reference plumbing.Hash
133 OffsetReference int64
134 }
135
136 type Scanner struct {
137 r *scannerReader
138 crc gohash.Hash32
139 packHasher hash.Hash
140
141 // pendingObject is used to detect if an object has been read, or still
142 // is waiting to be read
143 pendingObject *ObjectHeader
144 version, objects uint32
145
146 // lsSeekable says if this scanner can do Seek or not, to have a Scanner
147 // seekable a r implementing io.Seeker is required
148 IsSeekable bool
149 }
150
151 // NewScanner returns a new Scanner based on a reader, if the given reader
152 // implements io.ReadSeeker the Scanner will be also Seekable
153 func NewScanner(r io.Reader) *Scanner {
154 _, ok := r.(io.ReadSeeker)
155
156 crc := crc32.NewIEEE()
157 hasher := hash.New(crypto.SHA1)
158 return &Scanner{
159 r: newScannerReader(r, io.MultiWriter(crc, hasher)),
160 crc: crc,
161 IsSeekable: ok,
162 packHasher: hasher,
163 }
164 }
165
166 func (s *Scanner) Reset(r io.Reader) {
167 _, ok := r.(io.ReadSeeker)
168
169 s.r.Reset(r)
170 s.crc.Reset()
171 s.packHasher.Reset()
172 s.IsSeekable = ok
173 s.pendingObject = nil
174 s.version = 0
175 s.objects = 0
176 }
177
178 // Header reads the whole packfile header (signature, version and object count).
179 // It returns the version and the object count and performs checks on the
180 // validity of the signature and the version fields.
181 func (s *Scanner) Header() (version, objects uint32, err error) {
182 if s.version != 0 {
183 return s.version, s.objects, nil
184 }
185
186 sig, err := s.readSignature()
187 if err != nil {
188 if err == io.EOF {
189 err = ErrEmptyPackfile
190 }
191
192 return
193 }
194
195 if !s.isValidSignature(sig) {
196 err = ErrBadSignature
197 return
198 }
199
200 version, err = s.readVersion()
201 s.version = version
202 if err != nil {
203 return
204 }
205
206 if !s.isSupportedVersion(version) {
207 err = ErrUnsupportedVersion.AddDetails("%d", version)
208 return
209 }
210
211 objects, err = s.readCount()
212 s.objects = objects
213 return
214 }
215
216 // readSignature reads a returns the signature field in the packfile.
217 func (s *Scanner) readSignature() ([]byte, error) {
218 sig := make([]byte, 4)
219 if _, err := io.ReadFull(s.r, sig); err != nil {
220 return []byte{}, err
221 }
222
223 return sig, nil
224 }
225
226 // isValidSignature returns if sig is a valid packfile signature.
227 func (s *Scanner) isValidSignature(sig []byte) bool {
228 return bytes.Equal(sig, signature)
229 }
230
231 // readVersion reads and returns the version field of a packfile.
232 func (s *Scanner) readVersion() (uint32, error) {
233 return binary.ReadUint32(s.r)
234 }
235
236 // isSupportedVersion returns whether version v is supported by the parser.
237 // The current supported version is VersionSupported, defined above.
238 func (s *Scanner) isSupportedVersion(v uint32) bool {
239 return v == VersionSupported
240 }
241
242 // readCount reads and returns the count of objects field of a packfile.
243 func (s *Scanner) readCount() (uint32, error) {
244 return binary.ReadUint32(s.r)
245 }
246
247 // SeekObjectHeader seeks to specified offset and returns the ObjectHeader
248 // for the next object in the reader
249 func (s *Scanner) SeekObjectHeader(offset int64) (*ObjectHeader, error) {
250 // if seeking we assume that you are not interested in the header
251 if s.version == 0 {
252 s.version = VersionSupported
253 }
254
255 if _, err := s.r.Seek(offset, io.SeekStart); err != nil {
256 return nil, err
257 }
258
259 h, err := s.nextObjectHeader()
260 if err != nil {
261 return nil, err
262 }
263
264 h.Offset = offset
265 return h, nil
266 }
267
268 // NextObjectHeader returns the ObjectHeader for the next object in the reader
269 func (s *Scanner) NextObjectHeader() (*ObjectHeader, error) {
270 if err := s.doPending(); err != nil {
271 return nil, err
272 }
273
274 offset, err := s.r.Seek(0, io.SeekCurrent)
275 if err != nil {
276 return nil, err
277 }
278
279 h, err := s.nextObjectHeader()
280 if err != nil {
281 return nil, err
282 }
283
284 h.Offset = offset
285 return h, nil
286 }
287
288 // nextObjectHeader returns the ObjectHeader for the next object in the reader
289 // without the Offset field
290 func (s *Scanner) nextObjectHeader() (*ObjectHeader, error) {
291 s.r.Flush()
292 s.crc.Reset()
293
294 h := &ObjectHeader{}
295 s.pendingObject = h
296
297 var err error
298 h.Offset, err = s.r.Seek(0, io.SeekCurrent)
299 if err != nil {
300 return nil, err
301 }
302
303 h.Type, h.Length, err = s.readObjectTypeAndLength()
304 if err != nil {
305 return nil, err
306 }
307
308 switch h.Type {
309 case plumbing.OFSDeltaObject:
310 no, err := binary.ReadVariableWidthInt(s.r)
311 if err != nil {
312 return nil, err
313 }
314
315 // An OFS-delta references a base object that appears earlier
316 // in the pack; the negative offset must be strictly positive
317 // and not larger than the current object's offset.
318 if no <= 0 || no > h.Offset {
319 return nil, fmt.Errorf("%w: invalid OFS delta offset", ErrMalformedPackFile)
320 }
321
322 h.OffsetReference = h.Offset - no
323 case plumbing.REFDeltaObject:
324 var err error
325 h.Reference, err = binary.ReadHash(s.r)
326 if err != nil {
327 return nil, err
328 }
329 }
330
331 return h, nil
332 }
333
334 func (s *Scanner) doPending() error {
335 if s.version == 0 {
336 var err error
337 s.version, s.objects, err = s.Header()
338 if err != nil {
339 return err
340 }
341 }
342
343 return s.discardObjectIfNeeded()
344 }
345
346 func (s *Scanner) discardObjectIfNeeded() error {
347 if s.pendingObject == nil {
348 return nil
349 }
350
351 h := s.pendingObject
352 n, _, err := s.NextObject(io.Discard)
353 if err != nil {
354 return err
355 }
356
357 if n != h.Length {
358 return fmt.Errorf(
359 "error discarding object, discarded %d, expected %d",
360 n, h.Length,
361 )
362 }
363
364 return nil
365 }
366
367 // ReadObjectTypeAndLength reads and returns the object type and the
368 // length field from an object entry in a packfile.
369 func (s *Scanner) readObjectTypeAndLength() (plumbing.ObjectType, int64, error) {
370 t, c, err := s.readType()
371 if err != nil {
372 return t, 0, err
373 }
374
375 l, err := s.readLength(c)
376
377 return t, l, err
378 }
379
380 func (s *Scanner) readType() (plumbing.ObjectType, byte, error) {
381 var c byte
382 var err error
383 if c, err = s.r.ReadByte(); err != nil {
384 return plumbing.ObjectType(0), 0, err
385 }
386
387 typ := parseType(c)
388
389 return typ, c, nil
390 }
391
392 func parseType(b byte) plumbing.ObjectType {
393 return plumbing.ObjectType((b & maskType) >> firstLengthBits)
394 }
395
396 // the length is codified in the last 4 bits of the first byte and in
397 // the last 7 bits of subsequent bytes. Last byte has a 0 MSB.
398 func (s *Scanner) readLength(first byte) (int64, error) {
399 length := int64(first & maskFirstLength)
400
401 c := first
402 shift := firstLengthBits
403 var err error
404 for c&maskContinue > 0 {
405 // Mirrors unpack_object_header_buffer in canonical Git's
406 // packfile.c: a continuation byte at shift > 64-7 cannot
407 // contribute without overflowing an int64.
408 if shift > 64-lengthBits {
409 return 0, fmt.Errorf("%w: %w", ErrMalformedPackFile, ErrLengthOverflow)
410 }
411
412 if c, err = s.r.ReadByte(); err != nil {
413 return 0, err
414 }
415
416 length += int64(c&maskLength) << shift
417 shift += lengthBits
418 }
419
420 return length, nil
421 }
422
423 // NextObject writes the content of the next object into the reader, returns
424 // the number of bytes written, the CRC32 of the content and an error, if any.
425 //
426 // When a prior NextObjectHeader has stashed the object header in
427 // pendingObject, the inflated stream is bounded by the header's declared
428 // length and surfaces ErrInflatedSizeMismatch on overrun.
429 func (s *Scanner) NextObject(w io.Writer) (written int64, crc32 uint32, err error) {
430 declaredSize := int64(-1)
431 if s.pendingObject != nil {
432 declaredSize = s.pendingObject.Length
433 }
434 s.pendingObject = nil
435 written, err = s.copyObject(w, declaredSize)
436
437 s.r.Flush()
438 crc32 = s.crc.Sum32()
439 s.crc.Reset()
440
441 return
442 }
443
444 // ReadObject returns a reader for the object content and an error.
445 //
446 // When a prior NextObjectHeader has stashed the object header in
447 // pendingObject, the returned reader is bounded by the header's declared
448 // length so callers cannot stream past the declared inflated size; an
449 // overrun surfaces ErrInflatedSizeMismatch on the byte just past the
450 // limit.
451 func (s *Scanner) ReadObject() (io.ReadCloser, error) {
452 declaredSize := int64(-1)
453 if s.pendingObject != nil {
454 declaredSize = s.pendingObject.Length
455 }
456 s.pendingObject = nil
457 zr, err := sync.GetZlibReader(s.r)
458 if err != nil {
459 return nil, fmt.Errorf("zlib reset error: %s", err)
460 }
461
462 rc := ioutil.NewReadCloserWithCloser(zr.Reader, func() error {
463 sync.PutZlibReader(zr)
464 return nil
465 })
466 if declaredSize >= 0 {
467 return newBoundedReadCloser(rc, declaredSize), nil
468 }
469 return rc, nil
470 }
471
472 // copyObject inflates a non-deltified object's zlib stream into w. When
473 // declaredSize is non-negative, the write sink is wrapped in a
474 // boundedWriter so an overrun surfaces ErrInflatedSizeMismatch instead
475 // of being silently appended.
476 func (s *Scanner) copyObject(w io.Writer, declaredSize int64) (n int64, err error) {
477 zr, err := sync.GetZlibReader(s.r)
478 defer sync.PutZlibReader(zr)
479
480 if err != nil {
481 return 0, fmt.Errorf("zlib reset error: %s", err)
482 }
483
484 defer ioutil.CheckClose(zr.Reader, &err)
485
486 sink := w
487 if declaredSize >= 0 {
488 sink = &boundedWriter{w: w, limit: declaredSize}
489 }
490
491 buf := sync.GetByteSlice()
492 n, err = io.CopyBuffer(sink, zr.Reader, *buf)
493 sync.PutByteSlice(buf)
494 return
495 }
496
497 // SeekFromStart sets a new offset from start, returns the old position before
498 // the change.
499 func (s *Scanner) SeekFromStart(offset int64) (previous int64, err error) {
500 // if seeking we assume that you are not interested in the header
501 if s.version == 0 {
502 s.version = VersionSupported
503 }
504
505 previous, err = s.r.Seek(0, io.SeekCurrent)
506 if err != nil {
507 return -1, err
508 }
509
510 _, err = s.r.Seek(offset, io.SeekStart)
511 return previous, err
512 }
513
514 // Checksum returns the checksum of the packfile
515 func (s *Scanner) Checksum() (plumbing.Hash, error) {
516 err := s.discardObjectIfNeeded()
517 if err != nil {
518 return plumbing.ZeroHash, err
519 }
520
521 s.r.Flush()
522 actual := plumbing.Hash(s.packHasher.Sum(nil))
523 packChecksum, err := binary.ReadHash(s.r)
524 if err != nil {
525 return plumbing.ZeroHash, err
526 }
527
528 if actual != packChecksum {
529 return plumbing.ZeroHash, fmt.Errorf("%w: checksum mismatch: %q instead of %q", ErrMalformedPackFile, packChecksum, actual)
530 }
531
532 return packChecksum, nil
533 }
534
535 // Close reads the reader until io.EOF
536 func (s *Scanner) Close() error {
537 buf := sync.GetByteSlice()
538 _, err := io.CopyBuffer(io.Discard, s.r, *buf)
539 sync.PutByteSlice(buf)
540
541 return err
542 }
543
544 // Flush is a no-op (deprecated)
545 func (s *Scanner) Flush() error {
546 return nil
547 }
548
549 // scannerReader has the following characteristics:
550 // - Provides an io.SeekReader impl for bufio.Reader, when the underlying
551 // reader supports it.
552 // - Keeps track of the current read position, for when the underlying reader
553 // isn't an io.SeekReader, but we still want to know the current offset.
554 // - Writes to the hash writer what it reads, with the aid of a smaller buffer.
555 // The buffer helps avoid a performance penalty for performing small writes
556 // to the crc32 hash writer.
557 type scannerReader struct {
558 reader io.Reader
559 writer io.Writer
560 rbuf *bufio.Reader
561 wbuf *bufio.Writer
562 offset int64
563 }
564
565 func newScannerReader(r io.Reader, w io.Writer) *scannerReader {
566 sr := &scannerReader{
567 rbuf: bufio.NewReader(nil),
568 wbuf: bufio.NewWriterSize(nil, 64),
569 writer: w,
570 }
571 sr.Reset(r)
572
573 return sr
574 }
575
576 func (r *scannerReader) Reset(reader io.Reader) {
577 r.reader = reader
578 r.rbuf.Reset(r.reader)
579 r.wbuf.Reset(r.writer)
580
581 r.offset = 0
582 if seeker, ok := r.reader.(io.ReadSeeker); ok {
583 r.offset, _ = seeker.Seek(0, io.SeekCurrent)
584 }
585 }
586
587 func (r *scannerReader) Read(p []byte) (n int, err error) {
588 n, err = r.rbuf.Read(p)
589
590 r.offset += int64(n)
591 if _, err := r.wbuf.Write(p[:n]); err != nil {
592 return n, err
593 }
594 return
595 }
596
597 func (r *scannerReader) ReadByte() (b byte, err error) {
598 b, err = r.rbuf.ReadByte()
599 if err == nil {
600 r.offset++
601 return b, r.wbuf.WriteByte(b)
602 }
603 return
604 }
605
606 func (r *scannerReader) Flush() error {
607 return r.wbuf.Flush()
608 }
609
610 // Seek seeks to a location. If the underlying reader is not an io.ReadSeeker,
611 // then only whence=io.SeekCurrent is supported, any other operation fails.
612 func (r *scannerReader) Seek(offset int64, whence int) (int64, error) {
613 var err error
614
615 if seeker, ok := r.reader.(io.ReadSeeker); !ok {
616 if whence != io.SeekCurrent || offset != 0 {
617 return -1, ErrSeekNotSupported
618 }
619 } else {
620 if whence == io.SeekCurrent && offset == 0 {
621 return r.offset, nil
622 }
623
624 r.offset, err = seeker.Seek(offset, whence)
625 r.rbuf.Reset(r.reader)
626 }
627
628 return r.offset, err
629 }