Skip to content

Commit

Permalink
KffFile: replaced knownFile.read(..byte[]) with knownFile.readFully(b…
Browse files Browse the repository at this point in the history
…yte[]) to prevent bailing on incomplete reads.
  • Loading branch information
drivenflywheel committed Oct 10, 2023
1 parent 01a32da commit 22ece71
Showing 1 changed file with 9 additions and 9 deletions.
18 changes: 9 additions & 9 deletions src/main/java/emissary/kff/KffFile.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.EOFException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
Expand Down Expand Up @@ -139,8 +140,8 @@ public String getPreferredAlgorithm() {
private boolean binaryFileSearch(@Nonnull byte[] hash, long crc) {

// Initialize indexes for binary search
int low = 0;
int high = bSearchInitHigh;
long low = 0;
long high = bSearchInitHigh;

/* Buffer to hold a record */
byte[] rec = new byte[recordLength];
Expand All @@ -150,15 +151,11 @@ private boolean binaryFileSearch(@Nonnull byte[] hash, long crc) {
// Search until the indexes cross
while (low <= high) {
// Calculate the midpoint
int mid = (low + high) >> 1;
long mid = (low + high) >> 1;

// Multiply the index by the record length to get the buffer position and read the record
knownFile.seek(recordLength * mid);
int count = knownFile.read(rec);
if (count != recordLength) {
logger.warn("Short read on KffFile at {} read {} expected {}", (recordLength * mid), count, recordLength);
return false;
}
knownFile.readFully(rec);

// Compare the record with the target. Adjust the indexes accordingly.
int c = compare(rec, hash, crc);
Expand All @@ -170,6 +167,9 @@ private boolean binaryFileSearch(@Nonnull byte[] hash, long crc) {
return true;
}
}
} catch (EOFException e) {
// this shouldn't happen if we're synchronizing calls correctly
logger.warn("EOFException reading KffFile: {}", e.getLocalizedMessage());
} catch (IOException e) {
logger.warn("Exception reading KffFile", e);
} finally {
Expand Down Expand Up @@ -223,7 +223,7 @@ private int compare(byte[] record, byte[] hash, long crc) {
public boolean check(String fname, ChecksumResults csum) throws Exception {
byte[] hash = csum.getHash(myPreferredAlgorithm);
if (hash == null) {
logger.warn("Filter cannot be used, " + myPreferredAlgorithm + " not computed on " + fname);
logger.warn("Filter cannot be used, {} not computed on {}" , myPreferredAlgorithm, fname);
return false;
}
return binaryFileSearch(csum.getHash(myPreferredAlgorithm), csum.getCrc());
Expand Down

0 comments on commit 22ece71

Please sign in to comment.