Debian Codegraph @

plumbing/format/packfile/parser.go

raw
1 package packfile
2
3 import (
4 "bytes"
5 "errors"
6 "fmt"
7 "io"
8
9 "github.com/go-git/go-git/v5/plumbing"
10 "github.com/go-git/go-git/v5/plumbing/cache"
11 "github.com/go-git/go-git/v5/plumbing/storer"
12 "github.com/go-git/go-git/v5/utils/ioutil"
13 "github.com/go-git/go-git/v5/utils/sync"
14 )
15
16 var (
17 // ErrReferenceDeltaNotFound is returned when the reference delta is not
18 // found.
19 ErrReferenceDeltaNotFound = errors.New("reference delta not found")
20
21 // ErrNotSeekableSource is returned when the source for the parser is not
22 // seekable and a storage was not provided, so it can't be parsed.
23 ErrNotSeekableSource = errors.New("parser source is not seekable and storage was not provided")
24
25 // ErrDeltaNotCached is returned when the delta could not be found in cache.
26 ErrDeltaNotCached = errors.New("delta could not be found in cache")
27 )
28
29 // maxObjectPreallocBytes caps the up-front size hint passed to
30 // bytes.Buffer.Grow when staging an object's contents, so a malformed length
31 // cannot trigger a huge or out-of-range allocation. The buffer still grows
32 // dynamically as data is written; this is purely a hint cap.
33 const maxObjectPreallocBytes = 1 << 30 // 1 GiB
34
35 // maxObjectsPrealloc caps the up-front capacity reserved from the pack's
36 // declared object count, so a header advertising an absurd quantity cannot
37 // trigger a multi-gigabyte allocation. The slice and maps still grow
38 // organically beyond this hint.
39 const maxObjectsPrealloc = 1 << 16 // 64 Ki entries
40
41 // Match upstream Git's pack depth ceiling: pack-objects.h OE_DEPTH_BITS,
42 // enforced in builtin/pack-objects.c as (1 << OE_DEPTH_BITS) - 1.
43 const maxDeltaChainDepth = 4095
44
45 // growHint returns a non-negative int64 size, clamped to a sane upper bound,
46 // suitable for passing to bytes.Buffer.Grow.
47 func growHint(n int64) int {
48 switch {
49 case n <= 0:
50 return 0
51 case n > maxObjectPreallocBytes:
52 return maxObjectPreallocBytes
53 default:
54 return int(n)
55 }
56 }
57
58 // objectsHint returns a non-negative count, clamped to maxObjectsPrealloc,
59 // suitable for passing to make() as the capacity hint for slices or maps
60 // sized from a pack's declared object count.
61 func objectsHint(n uint32) int {
62 if n > maxObjectsPrealloc {
63 return maxObjectsPrealloc
64 }
65 return int(n)
66 }
67
68 // Observer interface is implemented by index encoders.
69 type Observer interface {
70 // OnHeader is called when a new packfile is opened.
71 OnHeader(count uint32) error
72 // OnInflatedObjectHeader is called for each object header read.
73 OnInflatedObjectHeader(t plumbing.ObjectType, objSize int64, pos int64) error
74 // OnInflatedObjectContent is called for each decoded object.
75 OnInflatedObjectContent(h plumbing.Hash, pos int64, crc uint32, content []byte) error
76 // OnFooter is called when decoding is done.
77 OnFooter(h plumbing.Hash) error
78 }
79
80 // Parser decodes a packfile and calls any observer associated to it. Is used
81 // to generate indexes.
82 type Parser struct {
83 storage storer.EncodedObjectStorer
84 scanner *Scanner
85 count uint32
86 oi []*objectInfo
87 oiByHash map[plumbing.Hash]*objectInfo
88 oiByOffset map[int64]*objectInfo
89
90 cache *cache.BufferLRU
91 // delta content by offset, only used if source is not seekable
92 deltas map[int64][]byte
93
94 ob []Observer
95 }
96
97 // NewParser creates a new Parser. The Scanner source must be seekable.
98 // If it's not, NewParserWithStorage should be used instead.
99 func NewParser(scanner *Scanner, ob ...Observer) (*Parser, error) {
100 return NewParserWithStorage(scanner, nil, ob...)
101 }
102
103 // NewParserWithStorage creates a new Parser. The scanner source must either
104 // be seekable or a storage must be provided.
105 func NewParserWithStorage(
106 scanner *Scanner,
107 storage storer.EncodedObjectStorer,
108 ob ...Observer,
109 ) (*Parser, error) {
110 if !scanner.IsSeekable && storage == nil {
111 return nil, ErrNotSeekableSource
112 }
113
114 var deltas map[int64][]byte
115 if !scanner.IsSeekable {
116 deltas = make(map[int64][]byte)
117 }
118
119 return &Parser{
120 storage: storage,
121 scanner: scanner,
122 ob: ob,
123 count: 0,
124 cache: cache.NewBufferLRUDefault(),
125 deltas: deltas,
126 }, nil
127 }
128
129 func (p *Parser) forEachObserver(f func(o Observer) error) error {
130 for _, o := range p.ob {
131 if err := f(o); err != nil {
132 return err
133 }
134 }
135 return nil
136 }
137
138 func (p *Parser) onHeader(count uint32) error {
139 return p.forEachObserver(func(o Observer) error {
140 return o.OnHeader(count)
141 })
142 }
143
144 func (p *Parser) onInflatedObjectHeader(
145 t plumbing.ObjectType,
146 objSize int64,
147 pos int64,
148 ) error {
149 return p.forEachObserver(func(o Observer) error {
150 return o.OnInflatedObjectHeader(t, objSize, pos)
151 })
152 }
153
154 func (p *Parser) onInflatedObjectContent(
155 h plumbing.Hash,
156 pos int64,
157 crc uint32,
158 content []byte,
159 ) error {
160 return p.forEachObserver(func(o Observer) error {
161 return o.OnInflatedObjectContent(h, pos, crc, content)
162 })
163 }
164
165 func (p *Parser) onFooter(h plumbing.Hash) error {
166 return p.forEachObserver(func(o Observer) error {
167 return o.OnFooter(h)
168 })
169 }
170
171 // Parse start decoding phase of the packfile.
172 func (p *Parser) Parse() (plumbing.Hash, error) {
173 if err := p.init(); err != nil {
174 return plumbing.ZeroHash, wrapEOF(err)
175 }
176
177 if err := p.indexObjects(); err != nil {
178 return plumbing.ZeroHash, wrapEOF(err)
179 }
180
181 checksum, err := p.scanner.Checksum()
182 if err != nil && err != io.EOF {
183 return plumbing.ZeroHash, wrapEOF(err)
184 }
185
186 if err := p.resolveDeltas(); err != nil {
187 return plumbing.ZeroHash, wrapEOF(err)
188 }
189
190 if err := p.onFooter(checksum); err != nil {
191 return plumbing.ZeroHash, wrapEOF(err)
192 }
193
194 return checksum, nil
195 }
196
197 func (p *Parser) init() error {
198 _, c, err := p.scanner.Header()
199 if err != nil {
200 return err
201 }
202
203 if err := p.onHeader(c); err != nil {
204 return err
205 }
206
207 p.count = c
208 hint := objectsHint(p.count)
209 p.oiByHash = make(map[plumbing.Hash]*objectInfo, hint)
210 p.oiByOffset = make(map[int64]*objectInfo, hint)
211 p.oi = make([]*objectInfo, 0, hint)
212
213 return nil
214 }
215
216 type objectHeaderWriter func(typ plumbing.ObjectType, sz int64) error
217
218 type lazyObjectWriter interface {
219 // LazyWriter enables an object to be lazily written.
220 // It returns:
221 // - w: a writer to receive the object's content.
222 // - lwh: a func to write the object header.
223 // - err: any error from the initial writer creation process.
224 //
225 // Note that if the object header is not written BEFORE the writer
226 // is used, this will result in an invalid object.
227 LazyWriter() (w io.WriteCloser, lwh objectHeaderWriter, err error)
228 }
229
230 func (p *Parser) indexObjects() error {
231 buf := sync.GetBytesBuffer()
232 defer sync.PutBytesBuffer(buf)
233
234 for i := uint32(0); i < p.count; i++ {
235 oh, err := p.scanner.NextObjectHeader()
236 if err != nil {
237 return err
238 }
239
240 delta := false
241 var ota *objectInfo
242 switch t := oh.Type; t {
243 case plumbing.OFSDeltaObject:
244 delta = true
245
246 parent, ok := p.oiByOffset[oh.OffsetReference]
247 if !ok {
248 return plumbing.ErrObjectNotFound
249 }
250
251 ota = newDeltaObject(oh.Offset, oh.Length, t, parent)
252 parent.Children = append(parent.Children, ota)
253 case plumbing.REFDeltaObject:
254 delta = true
255 parent, ok := p.oiByHash[oh.Reference]
256 if !ok {
257 // can't find referenced object in this pack file
258 // this must be a "thin" pack.
259 parent = &objectInfo{ // Placeholder parent
260 SHA1: oh.Reference,
261 ExternalRef: true, // mark as an external reference that must be resolved
262 Type: plumbing.AnyObject,
263 DiskType: plumbing.AnyObject,
264 }
265 p.oiByHash[oh.Reference] = parent
266 }
267 ota = newDeltaObject(oh.Offset, oh.Length, t, parent)
268 parent.Children = append(parent.Children, ota)
269
270 default:
271 ota = newBaseObject(oh.Offset, oh.Length, t)
272 }
273
274 hasher := plumbing.NewHasher(oh.Type, oh.Length)
275 writers := []io.Writer{hasher}
276 var obj *plumbing.MemoryObject
277
278 // Lazy writing is only available for non-delta objects.
279 if p.storage != nil && !delta {
280 // When a storage is set and supports lazy writing,
281 // use that instead of creating a memory object.
282 if low, ok := p.storage.(lazyObjectWriter); ok {
283 ow, lwh, err := low.LazyWriter()
284 if err != nil {
285 return err
286 }
287
288 if err = lwh(oh.Type, oh.Length); err != nil {
289 return err
290 }
291
292 defer ow.Close()
293 writers = append(writers, ow)
294 } else {
295 obj = new(plumbing.MemoryObject)
296 obj.SetSize(oh.Length)
297 obj.SetType(oh.Type)
298
299 writers = append(writers, obj)
300 }
301 }
302 if delta && !p.scanner.IsSeekable {
303 buf.Reset()
304 buf.Grow(growHint(oh.Length))
305 writers = append(writers, buf)
306 }
307
308 mw := io.MultiWriter(writers...)
309
310 _, crc, err := p.scanner.NextObject(mw)
311 if err != nil {
312 return err
313 }
314
315 // Non delta objects needs to be added into the storage. This
316 // is only required when lazy writing is not supported.
317 if obj != nil {
318 if _, err := p.storage.SetEncodedObject(obj); err != nil {
319 return err
320 }
321 }
322
323 ota.Crc32 = crc
324 ota.Length = oh.Length
325
326 if !delta {
327 sha1 := hasher.Sum()
328
329 // Move children of placeholder parent into actual parent, in case this
330 // was a non-external delta reference.
331 if placeholder, ok := p.oiByHash[sha1]; ok {
332 ota.Children = placeholder.Children
333 for _, c := range ota.Children {
334 c.Parent = ota
335 }
336 }
337
338 ota.SHA1 = sha1
339 p.oiByHash[ota.SHA1] = ota
340 }
341
342 if delta && !p.scanner.IsSeekable {
343 data := buf.Bytes()
344 p.deltas[oh.Offset] = make([]byte, len(data))
345 copy(p.deltas[oh.Offset], data)
346 }
347
348 p.oiByOffset[oh.Offset] = ota
349 p.oi = append(p.oi, ota)
350 }
351
352 return nil
353 }
354
355 func (p *Parser) resolveDeltas() error {
356 buf := sync.GetBytesBuffer()
357 defer sync.PutBytesBuffer(buf)
358
359 for _, obj := range p.oi {
360 if err := checkDeltaChainDepth(obj); err != nil {
361 return err
362 }
363
364 buf.Reset()
365 buf.Grow(growHint(obj.Length))
366 err := p.get(obj, buf)
367 if err != nil {
368 return err
369 }
370
371 if err := p.onInflatedObjectHeader(obj.Type, obj.Length, obj.Offset); err != nil {
372 return err
373 }
374
375 if err := p.onInflatedObjectContent(obj.SHA1, obj.Offset, obj.Crc32, nil); err != nil {
376 return err
377 }
378
379 if !obj.IsDelta() && len(obj.Children) > 0 {
380 // Dealing with an io.ReaderAt object, means we can
381 // create it once and reuse across all children.
382 r := bytes.NewReader(buf.Bytes())
383 for _, child := range obj.Children {
384 if err := checkDeltaChainDepth(child); err != nil {
385 return err
386 }
387 // Even though we are discarding the output, we still need to read it to
388 // so that the scanner can advance to the next object, and the SHA1 can be
389 // calculated.
390 if err := p.resolveObject(io.Discard, child, r); err != nil {
391 return err
392 }
393 p.resolveExternalRef(child)
394 }
395
396 // Remove the delta from the cache.
397 if obj.DiskType.IsDelta() && !p.scanner.IsSeekable {
398 delete(p.deltas, obj.Offset)
399 }
400 }
401 }
402
403 return nil
404 }
405
406 func checkDeltaChainDepth(o *objectInfo) error {
407 var depth int
408 for current := o; current != nil && current.DiskType.IsDelta(); current = current.Parent {
409 depth++
410 if depth > maxDeltaChainDepth {
411 return fmt.Errorf("%w: delta chain depth exceeds %d", ErrMalformedPackFile, maxDeltaChainDepth)
412 }
413 }
414 return nil
415 }
416
417 func (p *Parser) resolveExternalRef(o *objectInfo) {
418 if ref, ok := p.oiByHash[o.SHA1]; ok && ref.ExternalRef {
419 p.oiByHash[o.SHA1] = o
420 o.Children = ref.Children
421 for _, c := range o.Children {
422 c.Parent = o
423 }
424 }
425 }
426
427 func (p *Parser) get(o *objectInfo, buf *bytes.Buffer) (err error) {
428 if !o.ExternalRef { // skip cache check for placeholder parents
429 b, ok := p.cache.Get(o.Offset)
430 if ok {
431 _, err := buf.Write(b)
432 return err
433 }
434 }
435
436 // If it's not on the cache and is not a delta we can try to find it in the
437 // storage, if there's one. External refs must enter here.
438 if p.storage != nil && !o.Type.IsDelta() {
439 var e plumbing.EncodedObject
440 e, err = p.storage.EncodedObject(plumbing.AnyObject, o.SHA1)
441 if err != nil {
442 return err
443 }
444 o.Type = e.Type()
445
446 var r io.ReadCloser
447 r, err = e.Reader()
448 if err != nil {
449 return err
450 }
451
452 defer ioutil.CheckClose(r, &err)
453
454 _, err = buf.ReadFrom(io.LimitReader(r, e.Size()))
455 return err
456 }
457
458 if o.ExternalRef {
459 // we were not able to resolve a ref in a thin pack
460 return ErrReferenceDeltaNotFound
461 }
462
463 if o.DiskType.IsDelta() {
464 b := sync.GetBytesBuffer()
465 defer sync.PutBytesBuffer(b)
466 buf.Grow(growHint(o.Length))
467 err := p.get(o.Parent, b)
468 if err != nil {
469 return err
470 }
471
472 err = p.resolveObject(buf, o, bytes.NewReader(b.Bytes()))
473 if err != nil {
474 return err
475 }
476 } else {
477 err := p.readData(buf, o)
478 if err != nil {
479 return err
480 }
481 }
482
483 // If the scanner is seekable, caching this data into
484 // memory by offset seems wasteful.
485 // There is a trade-off to be considered here in terms
486 // of execution time vs memory consumption.
487 //
488 // TODO: improve seekable execution time, so that we can
489 // skip this cache.
490 if len(o.Children) > 0 {
491 data := make([]byte, buf.Len())
492 copy(data, buf.Bytes())
493 p.cache.Put(o.Offset, data)
494 }
495 return nil
496 }
497
498 // resolveObject resolves an object from base, using information
499 // provided by o.
500 //
501 // This call has the side-effect of changing field values
502 // from the object info o:
503 // - Type: OFSDeltaObject may become the target type (e.g. Blob).
504 // - Size: The size may be update with the target size.
505 // - Hash: Zero hashes will be calculated as part of the object
506 // resolution. Hence why this process can't be avoided even when w
507 // is an io.Discard.
508 //
509 // base must be an io.ReaderAt, which is a requirement from
510 // patchDeltaStream. The main reason being that reversing an
511 // delta object may lead to going backs and forths within base,
512 // which is not supported by io.Reader.
513 func (p *Parser) resolveObject(
514 w io.Writer,
515 o *objectInfo,
516 base io.ReaderAt,
517 ) error {
518 if !o.DiskType.IsDelta() {
519 return nil
520 }
521 buf := sync.GetBytesBuffer()
522 defer sync.PutBytesBuffer(buf)
523 err := p.readData(buf, o)
524 if err != nil {
525 return err
526 }
527
528 writers := []io.Writer{w}
529 var obj *plumbing.MemoryObject
530 var lwh objectHeaderWriter
531
532 if p.storage != nil {
533 if low, ok := p.storage.(lazyObjectWriter); ok {
534 ow, wh, err := low.LazyWriter()
535 if err != nil {
536 return err
537 }
538 lwh = wh
539
540 defer ow.Close()
541 writers = append(writers, ow)
542 } else {
543 obj = new(plumbing.MemoryObject)
544 ow, err := obj.Writer()
545 if err != nil {
546 return err
547 }
548
549 writers = append(writers, ow)
550 }
551 }
552
553 mw := io.MultiWriter(writers...)
554
555 err = applyPatchBase(o, base, buf, mw, lwh)
556 if err != nil {
557 return err
558 }
559
560 if obj != nil {
561 obj.SetType(o.Type)
562 obj.SetSize(o.Size()) // Size here is correct as it was populated by applyPatchBase.
563 if _, err := p.storage.SetEncodedObject(obj); err != nil {
564 return err
565 }
566 }
567 return err
568 }
569
570 func (p *Parser) readData(w io.Writer, o *objectInfo) error {
571 if !p.scanner.IsSeekable && o.DiskType.IsDelta() {
572 data, ok := p.deltas[o.Offset]
573 if !ok {
574 return ErrDeltaNotCached
575 }
576 _, err := w.Write(data)
577 return err
578 }
579
580 if _, err := p.scanner.SeekObjectHeader(o.Offset); err != nil {
581 return err
582 }
583
584 if _, _, err := p.scanner.NextObject(w); err != nil {
585 return err
586 }
587 return nil
588 }
589
590 func wrapEOF(err error) error {
591 if err == io.ErrUnexpectedEOF || err == io.EOF {
592 return fmt.Errorf("%w: %w", ErrMalformedPackFile, err)
593 }
594 return err
595 }
596
597 // applyPatchBase applies the patch to target.
598 //
599 // Note that ota will be updated based on the description in resolveObject.
600 func applyPatchBase(ota *objectInfo, base io.ReaderAt, delta io.Reader, target io.Writer, wh objectHeaderWriter) error {
601 if target == nil {
602 return fmt.Errorf("cannot apply patch against nil target")
603 }
604
605 typ := ota.Type
606 if ota.SHA1 == plumbing.ZeroHash {
607 typ = ota.Parent.Type
608 }
609
610 sz, h, err := patchDeltaWriter(target, base, delta, typ, wh)
611 if err != nil {
612 return err
613 }
614
615 if ota.SHA1 == plumbing.ZeroHash {
616 ota.Type = typ
617 ota.Length = int64(sz)
618 ota.SHA1 = h
619 }
620
621 return nil
622 }
623
624 type objectInfo struct {
625 Offset int64
626 Length int64
627 Type plumbing.ObjectType
628 DiskType plumbing.ObjectType
629 ExternalRef bool // indicates this is an external reference in a thin pack file
630
631 Crc32 uint32
632
633 Parent *objectInfo
634 Children []*objectInfo
635 SHA1 plumbing.Hash
636 }
637
638 func newBaseObject(offset, length int64, t plumbing.ObjectType) *objectInfo {
639 return newDeltaObject(offset, length, t, nil)
640 }
641
642 func newDeltaObject(
643 offset, length int64,
644 t plumbing.ObjectType,
645 parent *objectInfo,
646 ) *objectInfo {
647 obj := &objectInfo{
648 Offset: offset,
649 Length: length,
650 Type: t,
651 DiskType: t,
652 Crc32: 0,
653 Parent: parent,
654 }
655
656 return obj
657 }
658
659 func (o *objectInfo) IsDelta() bool {
660 return o.Type.IsDelta()
661 }
662
663 func (o *objectInfo) Size() int64 {
664 return o.Length
665 }