Support reading first SHA-1 from large FETCH_HEAD files

When reading refs, avoid reading huge files that were put there
accidentally, but still read the top of e.g. FETCH_HEAD, which
may be longer than our limit. We're only interested in the first line
anyway.

Bug: 340880
Change-Id: I11029b9b443f22019bf80bd3dd942b48b531bc11
Signed-off-by: Carsten Pfieffer <carsten.pfeiffer@gebit.de>
Signed-off-by: Chris Aniszczyk <caniszczyk@gmail.com>
This commit is contained in:
Carsten Pfeiffer 2011-03-16 16:57:35 +01:00 committed by Chris Aniszczyk
parent 1e03d52f33
commit 11e2e746c1
2 changed files with 46 additions and 1 deletions

View File

@ -850,9 +850,10 @@ private LooseRef scanRef(LooseRef ref, String name) throws IOException {
} else if (modified == 0)
return null;
final int limit = 4096;
final byte[] buf;
try {
buf = IO.readFully(path, 4096);
buf = IO.readSome(path, limit);
} catch (FileNotFoundException noFile) {
return null; // doesn't exist; not a reference.
}
@ -862,6 +863,9 @@ private LooseRef scanRef(LooseRef ref, String name) throws IOException {
return null; // empty file; not a reference.
if (isSymRef(buf, n)) {
if (n == limit)
return null; // possibly truncated ref
// trim trailing whitespace
while (0 < n && Character.isWhitespace(buf[n - 1]))
n--;

View File

@ -77,6 +77,47 @@ public static final byte[] readFully(final File path)
return IO.readFully(path, Integer.MAX_VALUE);
}
/**
* Read at most limit bytes from the local file into memory as a byte array.
*
* @param path
* location of the file to read.
* @param limit
* maximum number of bytes to read, if the file is larger than
* only the first limit number of bytes are returned
* @return complete contents of the requested local file. If the contents
* exceeds the limit, then only the limit is returned.
* @throws FileNotFoundException
* the file does not exist.
* @throws IOException
* the file exists, but its contents cannot be read.
*/
public static final byte[] readSome(final File path, final int limit)
throws FileNotFoundException, IOException {
FileInputStream in = new FileInputStream(path);
try {
byte[] buf = new byte[limit];
int cnt = 0;
for (;;) {
int n = in.read(buf, cnt, buf.length - cnt);
if (n <= 0)
break;
cnt += n;
}
if (cnt == buf.length)
return buf;
byte[] res = new byte[cnt];
System.arraycopy(buf, 0, res, 0, cnt);
return res;
} finally {
try {
in.close();
} catch (IOException ignored) {
// do nothing
}
}
}
/**
* Read an entire local file into memory as a byte array.
*