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(ObjectDatabase odb, 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(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(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(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(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(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(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 (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 (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(long pos, int type, 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 BlobObjectChecker checker = null;
1080 if (objCheck != null) {
1081 checker = objCheck.newBlobObjectChecker();
1082 }
1083 if (checker == null) {
1084 checker = BlobObjectChecker.NULL_CHECKER;
1085 }
1086 long cnt = 0;
1087 try (InputStream inf = inflate(Source.INPUT, sz)) {
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 }
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 try (ObjectStream cur = readCurs.open(obj, info.type).openStream()) {
1166 if (cur.getSize() != sz) {
1167 throw new IOException(MessageFormat.format(
1168 JGitText.get().collisionOn, obj.name()));
1169 }
1170 try (InputStream pck = inflate(Source.DATABASE, sz)) {
1171 while (0 < sz) {
1172 int n = (int) Math.min(readBuffer.length, sz);
1173 IO.readFully(cur, curBuffer, 0, n);
1174 IO.readFully(pck, readBuffer, 0, n);
1175 for (int i = 0; i < n; i++) {
1176 if (curBuffer[i] != readBuffer[i]) {
1177 throw new IOException(MessageFormat.format(
1178 JGitText.get().collisionOn, obj.name()));
1179 }
1180 }
1181 sz -= n;
1182 }
1183 }
1184 } catch (MissingObjectException notLocal) {
1185
1186
1187
1188 }
1189 }
1190
1191 private void checkObjectCollision(AnyObjectId obj, int type, byte[] data)
1192 throws IOException {
1193 try {
1194 final ObjectLoader ldr = readCurs.open(obj, type);
1195 final byte[] existingData = ldr.getCachedBytes(data.length);
1196 if (!Arrays.equals(data, existingData)) {
1197 throw new IOException(MessageFormat.format(
1198 JGitText.get().collisionOn, obj.name()));
1199 }
1200 } catch (MissingObjectException notLocal) {
1201
1202
1203
1204 }
1205 }
1206
1207
1208 private long streamPosition() {
1209 return bBase + bOffset;
1210 }
1211
1212 private ObjectTypeAndSize openDatabase(PackedObjectInfo obj,
1213 ObjectTypeAndSize info) throws IOException {
1214 bOffset = 0;
1215 bAvail = 0;
1216 return seekDatabase(obj, info);
1217 }
1218
1219 private ObjectTypeAndSize openDatabase(UnresolvedDelta delta,
1220 ObjectTypeAndSize info) throws IOException {
1221 bOffset = 0;
1222 bAvail = 0;
1223 return seekDatabase(delta, info);
1224 }
1225
1226
1227 private int readFrom(Source src) throws IOException {
1228 if (bAvail == 0)
1229 fill(src, 1);
1230 bAvail--;
1231 return buf[bOffset++] & 0xff;
1232 }
1233
1234
1235 void use(int cnt) {
1236 bOffset += cnt;
1237 bAvail -= cnt;
1238 }
1239
1240
1241 int fill(Source src, int need) throws IOException {
1242 while (bAvail < need) {
1243 int next = bOffset + bAvail;
1244 int free = buf.length - next;
1245 if (free + bAvail < need) {
1246 switch (src) {
1247 case INPUT:
1248 sync();
1249 break;
1250 case DATABASE:
1251 if (bAvail > 0)
1252 System.arraycopy(buf, bOffset, buf, 0, bAvail);
1253 bOffset = 0;
1254 break;
1255 }
1256 next = bAvail;
1257 free = buf.length - next;
1258 }
1259 switch (src) {
1260 case INPUT:
1261 next = in.read(buf, next, free);
1262 break;
1263 case DATABASE:
1264 next = readDatabase(buf, next, free);
1265 break;
1266 }
1267 if (next <= 0)
1268 throw new EOFException(
1269 JGitText.get().packfileIsTruncatedNoParam);
1270 bAvail += next;
1271 }
1272 return bOffset;
1273 }
1274
1275
1276 private void sync() throws IOException {
1277 packDigest.update(buf, 0, bOffset);
1278 onStoreStream(buf, 0, bOffset);
1279 if (expectDataAfterPackFooter) {
1280 if (bAvail > 0) {
1281 in.reset();
1282 IO.skipFully(in, bOffset);
1283 bAvail = 0;
1284 }
1285 in.mark(buf.length);
1286 } else if (bAvail > 0)
1287 System.arraycopy(buf, bOffset, buf, 0, bAvail);
1288 bBase += bOffset;
1289 bOffset = 0;
1290 }
1291
1292
1293
1294
1295
1296
1297 protected byte[] buffer() {
1298 return tempBuffer;
1299 }
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315 protected PackedObjectInfo newInfo(AnyObjectId id, UnresolvedDelta delta,
1316 ObjectId deltaBase) {
1317 PackedObjectInfo oe = new PackedObjectInfo(id);
1318 if (delta != null)
1319 oe.setCRC(delta.crc);
1320 return oe;
1321 }
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336 protected void setExpectedObjectCount(long expectedObjectCount) {
1337 this.expectedObjectCount = expectedObjectCount;
1338 }
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361 protected abstract void onStoreStream(byte[] raw, int pos, int len)
1362 throws IOException;
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381 protected abstract void onObjectHeader(Source src, byte[] raw, int pos,
1382 int len) throws IOException;
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404 protected abstract void onObjectData(Source src, byte[] raw, int pos,
1405 int len) throws IOException;
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419 protected abstract void onInflatedObjectData(PackedObjectInfo obj,
1420 int typeCode, byte[] data) throws IOException;
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430 protected abstract void onPackHeader(long objCnt) throws IOException;
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441 protected abstract void onPackFooter(byte[] hash) throws IOException;
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464 protected abstract boolean onAppendBase(int typeCode, byte[] data,
1465 PackedObjectInfo info) throws IOException;
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477 protected abstract void onEndThinPack() throws IOException;
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494 protected abstract ObjectTypeAndSize seekDatabase(PackedObjectInfo obj,
1495 ObjectTypeAndSize info) throws IOException;
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512 protected abstract ObjectTypeAndSize seekDatabase(UnresolvedDelta delta,
1513 ObjectTypeAndSize info) throws IOException;
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529 protected abstract int readDatabase(byte[] dst, int pos, int cnt)
1530 throws IOException;
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548 protected abstract boolean checkCRC(int oldCRC);
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567 protected abstract void onBeginWholeObject(long streamPosition, int type,
1568 long inflatedSize) throws IOException;
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578 protected abstract void onEndWholeObject(PackedObjectInfo info)
1579 throws IOException;
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597 protected abstract void onBeginOfsDelta(long deltaStreamPosition,
1598 long baseStreamPosition, long inflatedSize) throws IOException;
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615 protected abstract void onBeginRefDelta(long deltaStreamPosition,
1616 AnyObjectId baseId, long inflatedSize) throws IOException;
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626 protected UnresolvedDelta onEndDelta() throws IOException {
1627 return new UnresolvedDelta();
1628 }
1629
1630
1631 public static class ObjectTypeAndSize {
1632
1633 public int type;
1634
1635
1636 public long size;
1637 }
1638
1639 private void inflateAndSkip(Source src, long inflatedSize)
1640 throws IOException {
1641 try (InputStream inf = inflate(src, inflatedSize)) {
1642 IO.skipFully(inf, inflatedSize);
1643 }
1644 }
1645
1646 private byte[] inflateAndReturn(Source src, long inflatedSize)
1647 throws IOException {
1648 final byte[] dst = new byte[(int) inflatedSize];
1649 try (InputStream inf = inflate(src, inflatedSize)) {
1650 IO.readFully(inf, dst, 0, dst.length);
1651 }
1652 return dst;
1653 }
1654
1655 private InputStream inflate(Source src, long inflatedSize)
1656 throws IOException {
1657 inflater.open(src, inflatedSize);
1658 return inflater;
1659 }
1660
1661 private static class DeltaChain extends ObjectIdOwnerMap.Entry {
1662 UnresolvedDelta head;
1663
1664 DeltaChain(AnyObjectId id) {
1665 super(id);
1666 }
1667
1668 UnresolvedDelta remove() {
1669 final UnresolvedDelta r = head;
1670 if (r != null)
1671 head = null;
1672 return r;
1673 }
1674
1675 void add(UnresolvedDelta d) {
1676 d.next = head;
1677 head = d;
1678 }
1679 }
1680
1681
1682 public static class UnresolvedDelta {
1683 long position;
1684
1685 int crc;
1686
1687 UnresolvedDelta next;
1688
1689
1690 public long getOffset() {
1691 return position;
1692 }
1693
1694
1695 public int getCRC() {
1696 return crc;
1697 }
1698
1699
1700
1701
1702
1703 public void setCRC(int crc32) {
1704 crc = crc32;
1705 }
1706 }
1707
1708 private static class DeltaVisit {
1709 final UnresolvedDelta delta;
1710
1711 ObjectId id;
1712
1713 byte[] data;
1714
1715 DeltaVisit parent;
1716
1717 UnresolvedDelta nextChild;
1718
1719 DeltaVisit() {
1720 this.delta = null;
1721 }
1722
1723 DeltaVisit(DeltaVisit parent) {
1724 this.parent = parent;
1725 this.delta = parent.nextChild;
1726 parent.nextChild = delta.next;
1727 }
1728
1729 DeltaVisit next() {
1730
1731 if (parent != null && parent.nextChild == null) {
1732 parent.data = null;
1733 parent = parent.parent;
1734 }
1735
1736 if (nextChild != null)
1737 return new DeltaVisit(this);
1738
1739
1740
1741 if (parent != null)
1742 return new DeltaVisit(parent);
1743 return null;
1744 }
1745 }
1746
1747 private void addObjectAndTrack(PackedObjectInfo oe) {
1748 entries[entryCount++] = oe;
1749 if (needNewObjectIds())
1750 newObjectIds.add(oe);
1751 }
1752
1753 private class InflaterStream extends InputStream {
1754 private final Inflater inf;
1755
1756 private final byte[] skipBuffer;
1757
1758 private Source src;
1759
1760 private long expectedSize;
1761
1762 private long actualSize;
1763
1764 private int p;
1765
1766 InflaterStream() {
1767 inf = InflaterCache.get();
1768 skipBuffer = new byte[512];
1769 }
1770
1771 void release() {
1772 inf.reset();
1773 InflaterCache.release(inf);
1774 }
1775
1776 void open(Source source, long inflatedSize) throws IOException {
1777 src = source;
1778 expectedSize = inflatedSize;
1779 actualSize = 0;
1780
1781 p = fill(src, 1);
1782 inf.setInput(buf, p, bAvail);
1783 }
1784
1785 @Override
1786 public long skip(long toSkip) throws IOException {
1787 long n = 0;
1788 while (n < toSkip) {
1789 final int cnt = (int) Math.min(skipBuffer.length, toSkip - n);
1790 final int r = read(skipBuffer, 0, cnt);
1791 if (r <= 0)
1792 break;
1793 n += r;
1794 }
1795 return n;
1796 }
1797
1798 @Override
1799 public int read() throws IOException {
1800 int n = read(skipBuffer, 0, 1);
1801 return n == 1 ? skipBuffer[0] & 0xff : -1;
1802 }
1803
1804 @Override
1805 public int read(byte[] dst, int pos, int cnt) throws IOException {
1806 try {
1807 int n = 0;
1808 while (n < cnt) {
1809 int r = inf.inflate(dst, pos + n, cnt - n);
1810 n += r;
1811 if (inf.finished())
1812 break;
1813 if (inf.needsInput()) {
1814 onObjectData(src, buf, p, bAvail);
1815 use(bAvail);
1816
1817 p = fill(src, 1);
1818 inf.setInput(buf, p, bAvail);
1819 } else if (r == 0) {
1820 throw new CorruptObjectException(MessageFormat.format(
1821 JGitText.get().packfileCorruptionDetected,
1822 JGitText.get().unknownZlibError));
1823 }
1824 }
1825 actualSize += n;
1826 return 0 < n ? n : -1;
1827 } catch (DataFormatException dfe) {
1828 throw new CorruptObjectException(MessageFormat.format(JGitText
1829 .get().packfileCorruptionDetected, dfe.getMessage()));
1830 }
1831 }
1832
1833 @Override
1834 public void close() throws IOException {
1835
1836
1837
1838
1839 if (read(skipBuffer) != -1 || actualSize != expectedSize) {
1840 throw new CorruptObjectException(MessageFormat.format(JGitText
1841 .get().packfileCorruptionDetected,
1842 JGitText.get().wrongDecompressedLength));
1843 }
1844
1845 int used = bAvail - inf.getRemaining();
1846 if (0 < used) {
1847 onObjectData(src, buf, p, used);
1848 use(used);
1849 }
1850
1851 inf.reset();
1852 }
1853 }
1854 }