Skip to content

Commit 7e5287a

Browse files
authored
Fix journal checksum validation (#216)
1 parent 7f04288 commit 7e5287a

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

db.go

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1077,6 +1077,7 @@ func (db *DB) CommitJournal(mode JournalMode) error {
10771077
} else if err != nil {
10781078
return fmt.Errorf("cannot read truncated database page: pgno=%d err=%w", pgno, err)
10791079
}
1080+
10801081
postApplyChecksum ^= ltx.ChecksumPage(pgno, buf)
10811082
}
10821083

@@ -1903,11 +1904,18 @@ func (r *JournalReader) ReadFrame() (pgno uint32, data []byte, err error) {
19031904
} else if err != nil {
19041905
return 0, nil, err
19051906
}
1906-
r.frameN--
1907-
r.offset += int64(n)
19081907

19091908
pgno = binary.BigEndian.Uint32(r.frame[0:])
19101909
data = r.frame[4 : len(r.frame)-4]
1910+
chksum := binary.BigEndian.Uint32(r.frame[len(r.frame)-4:])
1911+
1912+
if chksum != JournalChecksum(data, r.nonce) {
1913+
return 0, nil, io.EOF
1914+
}
1915+
1916+
r.frameN--
1917+
r.offset += int64(n)
1918+
19111919
return pgno, data, nil
19121920
}
19131921

litefs.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -353,3 +353,12 @@ func WALChecksum(bo binary.ByteOrder, s0, s1 uint32, b []byte) (uint32, uint32)
353353
}
354354
return s0, s1
355355
}
356+
357+
// JournalChecksum returns the checksum used by the journal format.
358+
func JournalChecksum(data []byte, initial uint32) uint32 {
359+
chksum := initial
360+
for i := len(data) - 200; i > 0; i -= 200 {
361+
chksum += uint32(data[i])
362+
}
363+
return chksum
364+
}

0 commit comments

Comments
 (0)