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 package org.eclipse.jgit.transport;
47
48 import java.io.EOFException;
49 import java.io.IOException;
50 import java.io.InputStream;
51 import java.security.MessageDigest;
52 import java.text.MessageFormat;
53 import java.util.ArrayList;
54 import java.util.Arrays;
55 import java.util.Comparator;
56 import java.util.List;
57 import java.util.concurrent.TimeUnit;
58 import java.util.zip.DataFormatException;
59 import java.util.zip.Inflater;
60
61 import org.eclipse.jgit.errors.CorruptObjectException;
62 import org.eclipse.jgit.errors.MissingObjectException;
63 import org.eclipse.jgit.errors.TooLargeObjectInPackException;
64 import org.eclipse.jgit.internal.JGitText;
65 import org.eclipse.jgit.internal.storage.file.PackLock;
66 import org.eclipse.jgit.internal.storage.pack.BinaryDelta;
67 import org.eclipse.jgit.lib.AnyObjectId;
68 import org.eclipse.jgit.lib.BatchingProgressMonitor;
69 import org.eclipse.jgit.lib.BlobObjectChecker;
70 import org.eclipse.jgit.lib.Constants;
71 import org.eclipse.jgit.lib.InflaterCache;
72 import org.eclipse.jgit.lib.MutableObjectId;
73 import org.eclipse.jgit.lib.NullProgressMonitor;
74 import org.eclipse.jgit.lib.ObjectChecker;
75 import org.eclipse.jgit.lib.ObjectDatabase;
76 import org.eclipse.jgit.lib.ObjectId;
77 import org.eclipse.jgit.lib.ObjectIdOwnerMap;
78 import org.eclipse.jgit.lib.ObjectIdSubclassMap;
79 import org.eclipse.jgit.lib.ObjectLoader;
80 import org.eclipse.jgit.lib.ObjectReader;
81 import org.eclipse.jgit.lib.ObjectStream;
82 import org.eclipse.jgit.lib.ProgressMonitor;
83 import org.eclipse.jgit.util.BlockList;
84 import org.eclipse.jgit.util.IO;
85 import org.eclipse.jgit.util.LongMap;
86 import org.eclipse.jgit.util.NB;
87 import org.eclipse.jgit.util.sha1.SHA1;
88
89
90
91
92
93
94
95
96
97
98
99
100
101 public abstract class PackParser {
102
103 private static final int BUFFER_SIZE = 8192;
104
105
106 public static enum Source {
107
108 INPUT,
109
110
111 DATABASE;
112 }
113
114
115 private final ObjectDatabase objectDatabase;
116
117 private InflaterStream inflater;
118
119 private byte[] tempBuffer;
120
121 private byte[] hdrBuf;
122
123 private final SHA1 objectHasher = SHA1.newInstance();
124 private final MutableObjectId tempObjectId;
125
126 private InputStream in;
127
128 byte[] buf;
129
130
131 private long bBase;
132
133 private int bOffset;
134
135 int bAvail;
136
137 private ObjectChecker objCheck;
138
139 private boolean allowThin;
140
141 private boolean checkObjectCollisions;
142
143 private boolean needBaseObjectIds;
144
145 private boolean checkEofAfterPackFooter;
146
147 private boolean expectDataAfterPackFooter;
148
149 private long expectedObjectCount;
150
151 private PackedObjectInfo[] entries;
152
153
154
155
156
157
158
159
160 private ObjectIdSubclassMap<ObjectId> newObjectIds;
161
162 private int deltaCount;
163
164 private int entryCount;
165
166 private ObjectIdOwnerMap<DeltaChain> baseById;
167
168
169
170
171
172
173
174
175 private ObjectIdSubclassMap<ObjectId> baseObjectIds;
176
177 private LongMap<UnresolvedDelta> baseByPos;
178
179
180 private BlockList<PackedObjectInfo> collisionCheckObjs;
181
182 private MessageDigest packDigest;
183
184 private ObjectReader readCurs;
185
186
187 private String lockMessage;
188
189
190 private long maxObjectSizeLimit;
191
192 private final ReceivedPackStatistics.Builder stats =
193 new ReceivedPackStatistics.Builder();
194
195
196
197
198
199
200
201
202
203 protected PackParser(final ObjectDatabase odb, final InputStream src) {
204 objectDatabase = odb.newCachedDatabase();
205 in = src;
206
207 inflater = new InflaterStream();
208 readCurs = objectDatabase.newReader();
209 buf = new byte[BUFFER_SIZE];
210 tempBuffer = new byte[BUFFER_SIZE];
211 hdrBuf = new byte[64];
212 tempObjectId = new MutableObjectId();
213 packDigest = Constants.newMessageDigest();
214 checkObjectCollisions = true;
215 }
216
217
218
219
220
221
222 public boolean isAllowThin() {
223 return allowThin;
224 }
225
226
227
228
229
230
231
232
233
234
235 public void setAllowThin(final boolean allow) {
236 allowThin = allow;
237 }
238
239
240
241
242
243
244
245 protected boolean isCheckObjectCollisions() {
246 return checkObjectCollisions;
247 }
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270 protected void setCheckObjectCollisions(boolean check) {
271 checkObjectCollisions = check;
272 }
273
274
275
276
277
278
279
280
281
282
283
284 public void setNeedNewObjectIds(boolean b) {
285 if (b)
286 newObjectIds = new ObjectIdSubclassMap<>();
287 else
288 newObjectIds = null;
289 }
290
291 private boolean needNewObjectIds() {
292 return newObjectIds != null;
293 }
294
295
296
297
298
299
300
301
302
303
304
305
306 public void setNeedBaseObjectIds(boolean b) {
307 this.needBaseObjectIds = b;
308 }
309
310
311
312
313
314
315 public boolean isCheckEofAfterPackFooter() {
316 return checkEofAfterPackFooter;
317 }
318
319
320
321
322
323
324
325 public void setCheckEofAfterPackFooter(boolean b) {
326 checkEofAfterPackFooter = b;
327 }
328
329
330
331
332
333
334 public boolean isExpectDataAfterPackFooter() {
335 return expectDataAfterPackFooter;
336 }
337
338
339
340
341
342
343
344
345
346 public void setExpectDataAfterPackFooter(boolean e) {
347 expectDataAfterPackFooter = e;
348 }
349
350
351
352
353
354
355 public ObjectIdSubclassMap<ObjectId> getNewObjectIds() {
356 if (newObjectIds != null)
357 return newObjectIds;
358 return new ObjectIdSubclassMap<>();
359 }
360
361
362
363
364
365
366 public ObjectIdSubclassMap<ObjectId> getBaseObjectIds() {
367 if (baseObjectIds != null)
368 return baseObjectIds;
369 return new ObjectIdSubclassMap<>();
370 }
371
372
373
374
375
376
377
378
379
380
381
382 public void setObjectChecker(final ObjectChecker oc) {
383 objCheck = oc;
384 }
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402 public void setObjectChecking(final boolean on) {
403 setObjectChecker(on ? new ObjectChecker() : null);
404 }
405
406
407
408
409
410
411 public String getLockMessage() {
412 return lockMessage;
413 }
414
415
416
417
418
419
420
421
422 public void setLockMessage(String msg) {
423 lockMessage = msg;
424 }
425
426
427
428
429
430
431
432
433
434
435 public void setMaxObjectSizeLimit(long limit) {
436 maxObjectSizeLimit = limit;
437 }
438
439
440
441
442
443
444
445
446
447
448 public int getObjectCount() {
449 return entryCount;
450 }
451
452
453
454
455
456
457
458
459
460
461
462
463 public PackedObjectInfo getObject(int nth) {
464 return entries[nth];
465 }
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481 public List<PackedObjectInfo> getSortedObjectList(
482 Comparator<PackedObjectInfo> cmp) {
483 Arrays.sort(entries, 0, entryCount, cmp);
484 List<PackedObjectInfo> list = Arrays.asList(entries);
485 if (entryCount < entries.length)
486 list = list.subList(0, entryCount);
487 return list;
488 }
489
490
491
492
493
494
495
496
497
498
499
500 public long getPackSize() {
501 return -1;
502 }
503
504
505
506
507
508
509
510
511
512 public ReceivedPackStatistics getReceivedPackStatistics() {
513 return stats.build();
514 }
515
516
517
518
519
520
521
522
523
524
525
526
527
528 public final PackLock parse(ProgressMonitor progress) throws IOException {
529 return parse(progress, progress);
530 }
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547 public PackLock parse(ProgressMonitor receiving, ProgressMonitor resolving)
548 throws IOException {
549 if (receiving == null)
550 receiving = NullProgressMonitor.INSTANCE;
551 if (resolving == null)
552 resolving = NullProgressMonitor.INSTANCE;
553
554 if (receiving == resolving)
555 receiving.start(2 );
556 try {
557 readPackHeader();
558
559 entries = new PackedObjectInfo[(int) expectedObjectCount];
560 baseById = new ObjectIdOwnerMap<>();
561 baseByPos = new LongMap<>();
562 collisionCheckObjs = new BlockList<>();
563
564 receiving.beginTask(JGitText.get().receivingObjects,
565 (int) expectedObjectCount);
566 try {
567 for (int done = 0; done < expectedObjectCount; done++) {
568 indexOneObject();
569 receiving.update(1);
570 if (receiving.isCancelled())
571 throw new IOException(JGitText.get().downloadCancelled);
572 }
573 readPackFooter();
574 endInput();
575 } finally {
576 receiving.endTask();
577 }
578
579 if (!collisionCheckObjs.isEmpty()) {
580 checkObjectCollision();
581 }
582
583 if (deltaCount > 0) {
584 processDeltas(resolving);
585 }
586
587 packDigest = null;
588 baseById = null;
589 baseByPos = null;
590 } finally {
591 try {
592 if (readCurs != null)
593 readCurs.close();
594 } finally {
595 readCurs = null;
596 }
597
598 try {
599 inflater.release();
600 } finally {
601 inflater = null;
602 }
603 }
604 return null;
605 }
606
607 private void processDeltas(ProgressMonitor resolving) throws IOException {
608 if (resolving instanceof BatchingProgressMonitor) {
609 ((BatchingProgressMonitor) resolving).setDelayStart(1000,
610 TimeUnit.MILLISECONDS);
611 }
612 resolving.beginTask(JGitText.get().resolvingDeltas, deltaCount);
613 resolveDeltas(resolving);
614 if (entryCount < expectedObjectCount) {
615 if (!isAllowThin()) {
616 throw new IOException(MessageFormat.format(
617 JGitText.get().packHasUnresolvedDeltas,
618 Long.valueOf(expectedObjectCount - entryCount)));
619 }
620
621 resolveDeltasWithExternalBases(resolving);
622
623 if (entryCount < expectedObjectCount) {
624 throw new IOException(MessageFormat.format(
625 JGitText.get().packHasUnresolvedDeltas,
626 Long.valueOf(expectedObjectCount - entryCount)));
627 }
628 }
629 resolving.endTask();
630 }
631
632 private void resolveDeltas(final ProgressMonitor progress)
633 throws IOException {
634 final int last = entryCount;
635 for (int i = 0; i < last; i++) {
636 resolveDeltas(entries[i], progress);
637 if (progress.isCancelled())
638 throw new IOException(
639 JGitText.get().downloadCancelledDuringIndexing);
640 }
641 }
642
643 private void resolveDeltas(final PackedObjectInfo oe,
644 ProgressMonitor progress) throws IOException {
645 UnresolvedDelta children = firstChildOf(oe);
646 if (children == null)
647 return;
648
649 DeltaVisit visit = new DeltaVisit();
650 visit.nextChild = children;
651
652 ObjectTypeAndSize info = openDatabase(oe, new ObjectTypeAndSize());
653 switch (info.type) {
654 case Constants.OBJ_COMMIT:
655 case Constants.OBJ_TREE:
656 case Constants.OBJ_BLOB:
657 case Constants.OBJ_TAG:
658 visit.data = inflateAndReturn(Source.DATABASE, info.size);
659 visit.id = oe;
660 break;
661 default:
662 throw new IOException(MessageFormat.format(
663 JGitText.get().unknownObjectType,
664 Integer.valueOf(info.type)));
665 }
666
667 if (!checkCRC(oe.getCRC())) {
668 throw new IOException(MessageFormat.format(
669 JGitText.get().corruptionDetectedReReadingAt,
670 Long.valueOf(oe.getOffset())));
671 }
672
673 resolveDeltas(visit.next(), info.type, info, progress);
674 }
675
676 private void resolveDeltas(DeltaVisit visit, final int type,
677 ObjectTypeAndSize info, ProgressMonitor progress)
678 throws IOException {
679 stats.addDeltaObject(type);
680 do {
681 progress.update(1);
682 info = openDatabase(visit.delta, info);
683 switch (info.type) {
684 case Constants.OBJ_OFS_DELTA:
685 case Constants.OBJ_REF_DELTA:
686 break;
687
688 default:
689 throw new IOException(MessageFormat.format(
690 JGitText.get().unknownObjectType,
691 Integer.valueOf(info.type)));
692 }
693
694 byte[] delta = inflateAndReturn(Source.DATABASE, info.size);
695 checkIfTooLarge(type, BinaryDelta.getResultSize(delta));
696
697 visit.data = BinaryDelta.apply(visit.parent.data, delta);
698 delta = null;
699
700 if (!checkCRC(visit.delta.crc))
701 throw new IOException(MessageFormat.format(
702 JGitText.get().corruptionDetectedReReadingAt,
703 Long.valueOf(visit.delta.position)));
704
705 SHA1 objectDigest = objectHasher.reset();
706 objectDigest.update(Constants.encodedTypeString(type));
707 objectDigest.update((byte) ' ');
708 objectDigest.update(Constants.encodeASCII(visit.data.length));
709 objectDigest.update((byte) 0);
710 objectDigest.update(visit.data);
711 objectDigest.digest(tempObjectId);
712
713 verifySafeObject(tempObjectId, type, visit.data);
714 if (isCheckObjectCollisions() && readCurs.has(tempObjectId)) {
715 checkObjectCollision(tempObjectId, type, visit.data);
716 }
717
718 PackedObjectInfo oe;
719 oe = newInfo(tempObjectId, visit.delta, visit.parent.id);
720 oe.setOffset(visit.delta.position);
721 oe.setType(type);
722 onInflatedObjectData(oe, type, visit.data);
723 addObjectAndTrack(oe);
724 visit.id = oe;
725
726 visit.nextChild = firstChildOf(oe);
727 visit = visit.next();
728 } while (visit != null);
729 }
730
731 private final void checkIfTooLarge(int typeCode, long size)
732 throws IOException {
733 if (0 < maxObjectSizeLimit && maxObjectSizeLimit < size) {
734 switch (typeCode) {
735 case Constants.OBJ_COMMIT:
736 case Constants.OBJ_TREE:
737 case Constants.OBJ_BLOB:
738 case Constants.OBJ_TAG:
739 throw new TooLargeObjectInPackException(size, maxObjectSizeLimit);
740
741 case Constants.OBJ_OFS_DELTA:
742 case Constants.OBJ_REF_DELTA:
743 throw new TooLargeObjectInPackException(size, maxObjectSizeLimit);
744
745 default:
746 throw new IOException(MessageFormat.format(
747 JGitText.get().unknownObjectType,
748 Integer.valueOf(typeCode)));
749 }
750 }
751 if (size > Integer.MAX_VALUE - 8) {
752 throw new TooLargeObjectInPackException(size, Integer.MAX_VALUE - 8);
753 }
754 }
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772 protected ObjectTypeAndSize readObjectHeader(ObjectTypeAndSize info)
773 throws IOException {
774 int hdrPtr = 0;
775 int c = readFrom(Source.DATABASE);
776 hdrBuf[hdrPtr++] = (byte) c;
777
778 info.type = (c >> 4) & 7;
779 long sz = c & 15;
780 int shift = 4;
781 while ((c & 0x80) != 0) {
782 c = readFrom(Source.DATABASE);
783 hdrBuf[hdrPtr++] = (byte) c;
784 sz += ((long) (c & 0x7f)) << shift;
785 shift += 7;
786 }
787 info.size = sz;
788
789 switch (info.type) {
790 case Constants.OBJ_COMMIT:
791 case Constants.OBJ_TREE:
792 case Constants.OBJ_BLOB:
793 case Constants.OBJ_TAG:
794 onObjectHeader(Source.DATABASE, hdrBuf, 0, hdrPtr);
795 break;
796
797 case Constants.OBJ_OFS_DELTA:
798 c = readFrom(Source.DATABASE);
799 hdrBuf[hdrPtr++] = (byte) c;
800 while ((c & 128) != 0) {
801 c = readFrom(Source.DATABASE);
802 hdrBuf[hdrPtr++] = (byte) c;
803 }
804 onObjectHeader(Source.DATABASE, hdrBuf, 0, hdrPtr);
805 break;
806
807 case Constants.OBJ_REF_DELTA:
808 System.arraycopy(buf, fill(Source.DATABASE, 20), hdrBuf, hdrPtr, 20);
809 hdrPtr += 20;
810 use(20);
811 onObjectHeader(Source.DATABASE, hdrBuf, 0, hdrPtr);
812 break;
813
814 default:
815 throw new IOException(MessageFormat.format(
816 JGitText.get().unknownObjectType,
817 Integer.valueOf(info.type)));
818 }
819 return info;
820 }
821
822 private UnresolvedDelta removeBaseById(final AnyObjectId id) {
823 final DeltaChain d = baseById.get(id);
824 return d != null ? d.remove() : null;
825 }
826
827 private static UnresolvedDelta reverse(UnresolvedDelta c) {
828 UnresolvedDelta tail = null;
829 while (c != null) {
830 final UnresolvedDelta n = c.next;
831 c.next = tail;
832 tail = c;
833 c = n;
834 }
835 return tail;
836 }
837
838 private UnresolvedDelta firstChildOf(PackedObjectInfo oe) {
839 UnresolvedDelta a = reverse(removeBaseById(oe));
840 UnresolvedDelta b = reverse(baseByPos.remove(oe.getOffset()));
841
842 if (a == null)
843 return b;
844 if (b == null)
845 return a;
846
847 UnresolvedDelta first = null;
848 UnresolvedDelta last = null;
849 while (a != null || b != null) {
850 UnresolvedDelta curr;
851 if (b == null || (a != null && a.position < b.position)) {
852 curr = a;
853 a = a.next;
854 } else {
855 curr = b;
856 b = b.next;
857 }
858 if (last != null)
859 last.next = curr;
860 else
861 first = curr;
862 last = curr;
863 curr.next = null;
864 }
865 return first;
866 }
867
868 private void resolveDeltasWithExternalBases(final ProgressMonitor progress)
869 throws IOException {
870 growEntries(baseById.size());
871
872 if (needBaseObjectIds)
873 baseObjectIds = new ObjectIdSubclassMap<>();
874
875 final List<DeltaChain> missing = new ArrayList<>(64);
876 for (final DeltaChain baseId : baseById) {
877 if (baseId.head == null)
878 continue;
879
880 if (needBaseObjectIds)
881 baseObjectIds.add(baseId);
882
883 final ObjectLoader ldr;
884 try {
885 ldr = readCurs.open(baseId);
886 } catch (MissingObjectException notFound) {
887 missing.add(baseId);
888 continue;
889 }
890
891 final DeltaVisit visit = new DeltaVisit();
892 visit.data = ldr.getCachedBytes(Integer.MAX_VALUE);
893 visit.id = baseId;
894 final int typeCode = ldr.getType();
895 final PackedObjectInfo oe = newInfo(baseId, null, null);
896 oe.setType(typeCode);
897 if (onAppendBase(typeCode, visit.data, oe))
898 entries[entryCount++] = oe;
899 visit.nextChild = firstChildOf(oe);
900 resolveDeltas(visit.next(), typeCode,
901 new ObjectTypeAndSize(), progress);
902
903 if (progress.isCancelled())
904 throw new IOException(
905 JGitText.get().downloadCancelledDuringIndexing);
906 }
907
908 for (final DeltaChain base : missing) {
909 if (base.head != null)
910 throw new MissingObjectException(base, "delta base");
911 }
912
913 onEndThinPack();
914 }
915
916 private void growEntries(int extraObjects) {
917 final PackedObjectInfo[] ne;
918
919 ne = new PackedObjectInfo[(int) expectedObjectCount + extraObjects];
920 System.arraycopy(entries, 0, ne, 0, entryCount);
921 entries = ne;
922 }
923
924 private void readPackHeader() throws IOException {
925 if (expectDataAfterPackFooter) {
926 if (!in.markSupported())
927 throw new IOException(
928 JGitText.get().inputStreamMustSupportMark);
929 in.mark(buf.length);
930 }
931
932 final int hdrln = Constants.PACK_SIGNATURE.length + 4 + 4;
933 final int p = fill(Source.INPUT, hdrln);
934 for (int k = 0; k < Constants.PACK_SIGNATURE.length; k++)
935 if (buf[p + k] != Constants.PACK_SIGNATURE[k])
936 throw new IOException(JGitText.get().notAPACKFile);
937
938 final long vers = NB.decodeUInt32(buf, p + 4);
939 if (vers != 2 && vers != 3)
940 throw new IOException(MessageFormat.format(
941 JGitText.get().unsupportedPackVersion, Long.valueOf(vers)));
942 final long objectCount = NB.decodeUInt32(buf, p + 8);
943 use(hdrln);
944 setExpectedObjectCount(objectCount);
945 onPackHeader(objectCount);
946 }
947
948 private void readPackFooter() throws IOException {
949 sync();
950 final byte[] actHash = packDigest.digest();
951
952 final int c = fill(Source.INPUT, 20);
953 final byte[] srcHash = new byte[20];
954 System.arraycopy(buf, c, srcHash, 0, 20);
955 use(20);
956
957 if (bAvail != 0 && !expectDataAfterPackFooter)
958 throw new CorruptObjectException(MessageFormat.format(
959 JGitText.get().expectedEOFReceived,
960 "\\x" + Integer.toHexString(buf[bOffset] & 0xff)));
961 if (isCheckEofAfterPackFooter()) {
962 int eof = in.read();
963 if (0 <= eof)
964 throw new CorruptObjectException(MessageFormat.format(
965 JGitText.get().expectedEOFReceived,
966 "\\x" + Integer.toHexString(eof)));
967 } else if (bAvail > 0 && expectDataAfterPackFooter) {
968 in.reset();
969 IO.skipFully(in, bOffset);
970 }
971
972 if (!Arrays.equals(actHash, srcHash))
973 throw new CorruptObjectException(
974 JGitText.get().corruptObjectPackfileChecksumIncorrect);
975
976 onPackFooter(srcHash);
977 }
978
979
980 private void endInput() {
981 stats.setNumBytesRead(streamPosition());
982 in = null;
983 }
984
985
986 private void indexOneObject() throws IOException {
987 final long streamPosition = streamPosition();
988
989 int hdrPtr = 0;
990 int c = readFrom(Source.INPUT);
991 hdrBuf[hdrPtr++] = (byte) c;
992
993 final int typeCode = (c >> 4) & 7;
994 long sz = c & 15;
995 int shift = 4;
996 while ((c & 0x80) != 0) {
997 c = readFrom(Source.INPUT);
998 hdrBuf[hdrPtr++] = (byte) c;
999 sz += ((long) (c & 0x7f)) << shift;
1000 shift += 7;
1001 }
1002
1003 checkIfTooLarge(typeCode, sz);
1004
1005 switch (typeCode) {
1006 case Constants.OBJ_COMMIT:
1007 case Constants.OBJ_TREE:
1008 case Constants.OBJ_BLOB:
1009 case Constants.OBJ_TAG:
1010 stats.addWholeObject(typeCode);
1011 onBeginWholeObject(streamPosition, typeCode, sz);
1012 onObjectHeader(Source.INPUT, hdrBuf, 0, hdrPtr);
1013 whole(streamPosition, typeCode, sz);
1014 break;
1015
1016 case Constants.OBJ_OFS_DELTA: {
1017 stats.addOffsetDelta();
1018 c = readFrom(Source.INPUT);
1019 hdrBuf[hdrPtr++] = (byte) c;
1020 long ofs = c & 127;
1021 while ((c & 128) != 0) {
1022 ofs += 1;
1023 c = readFrom(Source.INPUT);
1024 hdrBuf[hdrPtr++] = (byte) c;
1025 ofs <<= 7;
1026 ofs += (c & 127);
1027 }
1028 final long base = streamPosition - ofs;
1029 onBeginOfsDelta(streamPosition, base, sz);
1030 onObjectHeader(Source.INPUT, hdrBuf, 0, hdrPtr);
1031 inflateAndSkip(Source.INPUT, sz);
1032 UnresolvedDelta n = onEndDelta();
1033 n.position = streamPosition;
1034 n.next = baseByPos.put(base, n);
1035 deltaCount++;
1036 break;
1037 }
1038
1039 case Constants.OBJ_REF_DELTA: {
1040 stats.addRefDelta();
1041 c = fill(Source.INPUT, 20);
1042 final ObjectId base = ObjectId.fromRaw(buf, c);
1043 System.arraycopy(buf, c, hdrBuf, hdrPtr, 20);
1044 hdrPtr += 20;
1045 use(20);
1046 DeltaChain r = baseById.get(base);
1047 if (r == null) {
1048 r = new DeltaChain(base);
1049 baseById.add(r);
1050 }
1051 onBeginRefDelta(streamPosition, base, sz);
1052 onObjectHeader(Source.INPUT, hdrBuf, 0, hdrPtr);
1053 inflateAndSkip(Source.INPUT, sz);
1054 UnresolvedDelta n = onEndDelta();
1055 n.position = streamPosition;
1056 r.add(n);
1057 deltaCount++;
1058 break;
1059 }
1060
1061 default:
1062 throw new IOException(
1063 MessageFormat.format(JGitText.get().unknownObjectType,
1064 Integer.valueOf(typeCode)));
1065 }
1066 }
1067
1068 private void whole(final long pos, final int type, final long sz)
1069 throws IOException {
1070 SHA1 objectDigest = objectHasher.reset();
1071 objectDigest.update(Constants.encodedTypeString(type));
1072 objectDigest.update((byte) ' ');
1073 objectDigest.update(Constants.encodeASCII(sz));
1074 objectDigest.update((byte) 0);
1075
1076 final byte[] data;
1077 if (type == Constants.OBJ_BLOB) {
1078 byte[] readBuffer = buffer();
1079 InputStream inf = inflate(Source.INPUT, sz);
1080 BlobObjectChecker checker = null;
1081 if (objCheck != null) {
1082 checker = objCheck.newBlobObjectChecker();
1083 }
1084 if (checker == null) {
1085 checker = BlobObjectChecker.NULL_CHECKER;
1086 }
1087 long cnt = 0;
1088 while (cnt < sz) {
1089 int r = inf.read(readBuffer);
1090 if (r <= 0)
1091 break;
1092 objectDigest.update(readBuffer, 0, r);
1093 checker.update(readBuffer, 0, r);
1094 cnt += r;
1095 }
1096 inf.close();
1097 objectDigest.digest(tempObjectId);
1098 checker.endBlob(tempObjectId);
1099 data = null;
1100 } else {
1101 data = inflateAndReturn(Source.INPUT, sz);
1102 objectDigest.update(data);
1103 objectDigest.digest(tempObjectId);
1104 verifySafeObject(tempObjectId, type, data);
1105 }
1106
1107 PackedObjectInfo obj = newInfo(tempObjectId, null, null);
1108 obj.setOffset(pos);
1109 obj.setType(type);
1110 onEndWholeObject(obj);
1111 if (data != null)
1112 onInflatedObjectData(obj, type, data);
1113 addObjectAndTrack(obj);
1114
1115 if (isCheckObjectCollisions()) {
1116 collisionCheckObjs.add(obj);
1117 }
1118 }
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132 protected void verifySafeObject(final AnyObjectId id, final int type,
1133 final byte[] data) throws CorruptObjectException {
1134 if (objCheck != null) {
1135 try {
1136 objCheck.check(id, type, data);
1137 } catch (CorruptObjectException e) {
1138 if (e.getErrorType() != null) {
1139 throw e;
1140 }
1141 throw new CorruptObjectException(
1142 MessageFormat.format(JGitText.get().invalidObject,
1143 Constants.typeString(type), id.name(),
1144 e.getMessage()),
1145 e);
1146 }
1147 }
1148 }
1149
1150 private void checkObjectCollision() throws IOException {
1151 for (PackedObjectInfo obj : collisionCheckObjs) {
1152 if (!readCurs.has(obj)) {
1153 continue;
1154 }
1155 checkObjectCollision(obj);
1156 }
1157 }
1158
1159 private void checkObjectCollision(PackedObjectInfo obj)
1160 throws IOException {
1161 ObjectTypeAndSize info = openDatabase(obj, new ObjectTypeAndSize());
1162 final byte[] readBuffer = buffer();
1163 final byte[] curBuffer = new byte[readBuffer.length];
1164 long sz = info.size;
1165 InputStream pck = null;
1166 try (ObjectStream cur = readCurs.open(obj, info.type).openStream()) {
1167 if (cur.getSize() != sz) {
1168 throw new IOException(MessageFormat.format(
1169 JGitText.get().collisionOn, obj.name()));
1170 }
1171 pck = inflate(Source.DATABASE, sz);
1172 while (0 < sz) {
1173 int n = (int) Math.min(readBuffer.length, sz);
1174 IO.readFully(cur, curBuffer, 0, n);
1175 IO.readFully(pck, readBuffer, 0, n);
1176 for (int i = 0; i < n; i++) {
1177 if (curBuffer[i] != readBuffer[i]) {
1178 throw new IOException(MessageFormat.format(JGitText
1179 .get().collisionOn, obj.name()));
1180 }
1181 }
1182 sz -= n;
1183 }
1184 } catch (MissingObjectException notLocal) {
1185
1186
1187
1188 } finally {
1189 if (pck != null) {
1190 pck.close();
1191 }
1192 }
1193 }
1194
1195 private void checkObjectCollision(AnyObjectId obj, int type, byte[] data)
1196 throws IOException {
1197 try {
1198 final ObjectLoader ldr = readCurs.open(obj, type);
1199 final byte[] existingData = ldr.getCachedBytes(data.length);
1200 if (!Arrays.equals(data, existingData)) {
1201 throw new IOException(MessageFormat.format(
1202 JGitText.get().collisionOn, obj.name()));
1203 }
1204 } catch (MissingObjectException notLocal) {
1205
1206
1207
1208 }
1209 }
1210
1211
1212 private long streamPosition() {
1213 return bBase + bOffset;
1214 }
1215
1216 private ObjectTypeAndSize openDatabase(PackedObjectInfo obj,
1217 ObjectTypeAndSize info) throws IOException {
1218 bOffset = 0;
1219 bAvail = 0;
1220 return seekDatabase(obj, info);
1221 }
1222
1223 private ObjectTypeAndSize openDatabase(UnresolvedDelta delta,
1224 ObjectTypeAndSize info) throws IOException {
1225 bOffset = 0;
1226 bAvail = 0;
1227 return seekDatabase(delta, info);
1228 }
1229
1230
1231 private int readFrom(final Source src) throws IOException {
1232 if (bAvail == 0)
1233 fill(src, 1);
1234 bAvail--;
1235 return buf[bOffset++] & 0xff;
1236 }
1237
1238
1239 void use(final int cnt) {
1240 bOffset += cnt;
1241 bAvail -= cnt;
1242 }
1243
1244
1245 int fill(final Source src, final int need) throws IOException {
1246 while (bAvail < need) {
1247 int next = bOffset + bAvail;
1248 int free = buf.length - next;
1249 if (free + bAvail < need) {
1250 switch (src) {
1251 case INPUT:
1252 sync();
1253 break;
1254 case DATABASE:
1255 if (bAvail > 0)
1256 System.arraycopy(buf, bOffset, buf, 0, bAvail);
1257 bOffset = 0;
1258 break;
1259 }
1260 next = bAvail;
1261 free = buf.length - next;
1262 }
1263 switch (src) {
1264 case INPUT:
1265 next = in.read(buf, next, free);
1266 break;
1267 case DATABASE:
1268 next = readDatabase(buf, next, free);
1269 break;
1270 }
1271 if (next <= 0)
1272 throw new EOFException(
1273 JGitText.get().packfileIsTruncatedNoParam);
1274 bAvail += next;
1275 }
1276 return bOffset;
1277 }
1278
1279
1280 private void sync() throws IOException {
1281 packDigest.update(buf, 0, bOffset);
1282 onStoreStream(buf, 0, bOffset);
1283 if (expectDataAfterPackFooter) {
1284 if (bAvail > 0) {
1285 in.reset();
1286 IO.skipFully(in, bOffset);
1287 bAvail = 0;
1288 }
1289 in.mark(buf.length);
1290 } else if (bAvail > 0)
1291 System.arraycopy(buf, bOffset, buf, 0, bAvail);
1292 bBase += bOffset;
1293 bOffset = 0;
1294 }
1295
1296
1297
1298
1299
1300
1301 protected byte[] buffer() {
1302 return tempBuffer;
1303 }
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319 protected PackedObjectInfo newInfo(AnyObjectId id, UnresolvedDelta delta,
1320 ObjectId deltaBase) {
1321 PackedObjectInfo oe = new PackedObjectInfo(id);
1322 if (delta != null)
1323 oe.setCRC(delta.crc);
1324 return oe;
1325 }
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340 protected void setExpectedObjectCount(long expectedObjectCount) {
1341 this.expectedObjectCount = expectedObjectCount;
1342 }
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365 protected abstract void onStoreStream(byte[] raw, int pos, int len)
1366 throws IOException;
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385 protected abstract void onObjectHeader(Source src, byte[] raw, int pos,
1386 int len) throws IOException;
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408 protected abstract void onObjectData(Source src, byte[] raw, int pos,
1409 int len) throws IOException;
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423 protected abstract void onInflatedObjectData(PackedObjectInfo obj,
1424 int typeCode, byte[] data) throws IOException;
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434 protected abstract void onPackHeader(long objCnt) throws IOException;
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445 protected abstract void onPackFooter(byte[] hash) throws IOException;
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468 protected abstract boolean onAppendBase(int typeCode, byte[] data,
1469 PackedObjectInfo info) throws IOException;
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481 protected abstract void onEndThinPack() throws IOException;
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498 protected abstract ObjectTypeAndSize seekDatabase(PackedObjectInfo obj,
1499 ObjectTypeAndSize info) throws IOException;
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516 protected abstract ObjectTypeAndSize seekDatabase(UnresolvedDelta delta,
1517 ObjectTypeAndSize info) throws IOException;
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533 protected abstract int readDatabase(byte[] dst, int pos, int cnt)
1534 throws IOException;
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552 protected abstract boolean checkCRC(int oldCRC);
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571 protected abstract void onBeginWholeObject(long streamPosition, int type,
1572 long inflatedSize) throws IOException;
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582 protected abstract void onEndWholeObject(PackedObjectInfo info)
1583 throws IOException;
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601 protected abstract void onBeginOfsDelta(long deltaStreamPosition,
1602 long baseStreamPosition, long inflatedSize) throws IOException;
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619 protected abstract void onBeginRefDelta(long deltaStreamPosition,
1620 AnyObjectId baseId, long inflatedSize) throws IOException;
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630 protected UnresolvedDelta onEndDelta() throws IOException {
1631 return new UnresolvedDelta();
1632 }
1633
1634
1635 public static class ObjectTypeAndSize {
1636
1637 public int type;
1638
1639
1640 public long size;
1641 }
1642
1643 private void inflateAndSkip(final Source src, final long inflatedSize)
1644 throws IOException {
1645 final InputStream inf = inflate(src, inflatedSize);
1646 IO.skipFully(inf, inflatedSize);
1647 inf.close();
1648 }
1649
1650 private byte[] inflateAndReturn(final Source src, final long inflatedSize)
1651 throws IOException {
1652 final byte[] dst = new byte[(int) inflatedSize];
1653 final InputStream inf = inflate(src, inflatedSize);
1654 IO.readFully(inf, dst, 0, dst.length);
1655 inf.close();
1656 return dst;
1657 }
1658
1659 private InputStream inflate(final Source src, final long inflatedSize)
1660 throws IOException {
1661 inflater.open(src, inflatedSize);
1662 return inflater;
1663 }
1664
1665 private static class DeltaChain extends ObjectIdOwnerMap.Entry {
1666 UnresolvedDelta head;
1667
1668 DeltaChain(final AnyObjectId id) {
1669 super(id);
1670 }
1671
1672 UnresolvedDelta remove() {
1673 final UnresolvedDelta r = head;
1674 if (r != null)
1675 head = null;
1676 return r;
1677 }
1678
1679 void add(final UnresolvedDelta d) {
1680 d.next = head;
1681 head = d;
1682 }
1683 }
1684
1685
1686 public static class UnresolvedDelta {
1687 long position;
1688
1689 int crc;
1690
1691 UnresolvedDelta next;
1692
1693
1694 public long getOffset() {
1695 return position;
1696 }
1697
1698
1699 public int getCRC() {
1700 return crc;
1701 }
1702
1703
1704
1705
1706
1707 public void setCRC(int crc32) {
1708 crc = crc32;
1709 }
1710 }
1711
1712 private static class DeltaVisit {
1713 final UnresolvedDelta delta;
1714
1715 ObjectId id;
1716
1717 byte[] data;
1718
1719 DeltaVisit parent;
1720
1721 UnresolvedDelta nextChild;
1722
1723 DeltaVisit() {
1724 this.delta = null;
1725 }
1726
1727 DeltaVisit(DeltaVisit parent) {
1728 this.parent = parent;
1729 this.delta = parent.nextChild;
1730 parent.nextChild = delta.next;
1731 }
1732
1733 DeltaVisit next() {
1734
1735 if (parent != null && parent.nextChild == null) {
1736 parent.data = null;
1737 parent = parent.parent;
1738 }
1739
1740 if (nextChild != null)
1741 return new DeltaVisit(this);
1742
1743
1744
1745 if (parent != null)
1746 return new DeltaVisit(parent);
1747 return null;
1748 }
1749 }
1750
1751 private void addObjectAndTrack(PackedObjectInfo oe) {
1752 entries[entryCount++] = oe;
1753 if (needNewObjectIds())
1754 newObjectIds.add(oe);
1755 }
1756
1757 private class InflaterStream extends InputStream {
1758 private final Inflater inf;
1759
1760 private final byte[] skipBuffer;
1761
1762 private Source src;
1763
1764 private long expectedSize;
1765
1766 private long actualSize;
1767
1768 private int p;
1769
1770 InflaterStream() {
1771 inf = InflaterCache.get();
1772 skipBuffer = new byte[512];
1773 }
1774
1775 void release() {
1776 inf.reset();
1777 InflaterCache.release(inf);
1778 }
1779
1780 void open(Source source, long inflatedSize) throws IOException {
1781 src = source;
1782 expectedSize = inflatedSize;
1783 actualSize = 0;
1784
1785 p = fill(src, 1);
1786 inf.setInput(buf, p, bAvail);
1787 }
1788
1789 @Override
1790 public long skip(long toSkip) throws IOException {
1791 long n = 0;
1792 while (n < toSkip) {
1793 final int cnt = (int) Math.min(skipBuffer.length, toSkip - n);
1794 final int r = read(skipBuffer, 0, cnt);
1795 if (r <= 0)
1796 break;
1797 n += r;
1798 }
1799 return n;
1800 }
1801
1802 @Override
1803 public int read() throws IOException {
1804 int n = read(skipBuffer, 0, 1);
1805 return n == 1 ? skipBuffer[0] & 0xff : -1;
1806 }
1807
1808 @Override
1809 public int read(byte[] dst, int pos, int cnt) throws IOException {
1810 try {
1811 int n = 0;
1812 while (n < cnt) {
1813 int r = inf.inflate(dst, pos + n, cnt - n);
1814 n += r;
1815 if (inf.finished())
1816 break;
1817 if (inf.needsInput()) {
1818 onObjectData(src, buf, p, bAvail);
1819 use(bAvail);
1820
1821 p = fill(src, 1);
1822 inf.setInput(buf, p, bAvail);
1823 } else if (r == 0) {
1824 throw new CorruptObjectException(MessageFormat.format(
1825 JGitText.get().packfileCorruptionDetected,
1826 JGitText.get().unknownZlibError));
1827 }
1828 }
1829 actualSize += n;
1830 return 0 < n ? n : -1;
1831 } catch (DataFormatException dfe) {
1832 throw new CorruptObjectException(MessageFormat.format(JGitText
1833 .get().packfileCorruptionDetected, dfe.getMessage()));
1834 }
1835 }
1836
1837 @Override
1838 public void close() throws IOException {
1839
1840
1841
1842
1843 if (read(skipBuffer) != -1 || actualSize != expectedSize) {
1844 throw new CorruptObjectException(MessageFormat.format(JGitText
1845 .get().packfileCorruptionDetected,
1846 JGitText.get().wrongDecompressedLength));
1847 }
1848
1849 int used = bAvail - inf.getRemaining();
1850 if (0 < used) {
1851 onObjectData(src, buf, p, used);
1852 use(used);
1853 }
1854
1855 inf.reset();
1856 }
1857 }
1858 }