Harden JsonFileSessionStore against nulls/Gson oddities

This commit is contained in:
Kenzie Togami 2019-09-23 11:46:24 -07:00
parent 982caaffab
commit fa25ad22cd
No known key found for this signature in database
GPG Key ID: 5D200B325E157A81

View File

@ -88,7 +88,15 @@ public class JsonFileSessionStore implements SessionStore {
try (Closer closer = Closer.create()) {
FileReader fr = closer.register(new FileReader(file));
BufferedReader br = closer.register(new BufferedReader(fr));
return gson.fromJson(br, LocalSession.class);
LocalSession session = gson.fromJson(br, LocalSession.class);
if (session == null) {
log.warn("Loaded a null session from {}, creating new session", file);
if (!file.delete()) {
log.warn("Failed to delete corrupted session {}", file);
}
session = new LocalSession();
}
return session;
} catch (JsonParseException e) {
throw new IOException(e);
} catch (FileNotFoundException e) {
@ -98,6 +106,7 @@ public class JsonFileSessionStore implements SessionStore {
@Override
public void save(UUID id, LocalSession session) throws IOException {
checkNotNull(session);
File finalFile = getPath(id);
File tempFile = new File(finalFile.getParentFile(), finalFile.getName() + ".tmp");
@ -115,6 +124,10 @@ public class JsonFileSessionStore implements SessionStore {
}
}
if (tempFile.length() == 0) {
throw new IllegalStateException("Gson wrote zero bytes");
}
if (!tempFile.renameTo(finalFile)) {
log.warn("Failed to rename temporary session file to " + finalFile.getPath());
}