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 9fb3be2
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 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,26 +140,23 @@ 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];

reentrantLock.lock();
long pos = 0L;
try {
// 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 +168,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

0 comments on commit 9fb3be2

Please sign in to comment.