Merge pull request #306 from alexbakker/atomic-file

Protect writes of the vault file against corruption with AtomicFile
This commit is contained in:
Michael Schättgen 2020-02-24 21:31:21 +01:00 committed by GitHub
commit e38121efee
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -3,13 +3,13 @@ package com.beemdevelopment.aegis.vault;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import androidx.core.util.AtomicFile;
import com.beemdevelopment.aegis.services.NotificationService; import com.beemdevelopment.aegis.services.NotificationService;
import org.json.JSONObject; import org.json.JSONObject;
import java.io.DataInputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
@ -41,12 +41,9 @@ public class VaultManager {
public void load() throws VaultManagerException { public void load() throws VaultManagerException {
assertState(true, false); assertState(true, false);
try (FileInputStream file = _context.openFileInput(FILENAME)) { AtomicFile file = new AtomicFile(new File(_context.getFilesDir(), FILENAME));
byte[] fileBytes = new byte[(int) file.getChannel().size()]; try {
DataInputStream stream = new DataInputStream(file); byte[] fileBytes = file.readFully();
stream.readFully(fileBytes);
stream.close();
_file = VaultFile.fromBytes(fileBytes); _file = VaultFile.fromBytes(fileBytes);
_encrypt = _file.isEncrypted(); _encrypt = _file.isEncrypted();
if (!isEncryptionEnabled()) { if (!isEncryptionEnabled()) {
@ -77,11 +74,19 @@ public class VaultManager {
} }
} }
public static void save(Context context, VaultFile file) throws VaultManagerException { public static void save(Context context, VaultFile vaultFile) throws VaultManagerException {
byte[] bytes = file.toBytes(); byte[] bytes = vaultFile.toBytes();
try (FileOutputStream stream = context.openFileOutput(FILENAME, Context.MODE_PRIVATE)) { AtomicFile file = new AtomicFile(new File(context.getFilesDir(), FILENAME));
FileOutputStream stream = null;
try {
stream = file.startWrite();
stream.write(bytes); stream.write(bytes);
file.finishWrite(stream);
} catch (IOException e) { } catch (IOException e) {
if (stream != null) {
file.failWrite(stream);
}
throw new VaultManagerException(e); throw new VaultManagerException(e);
} }
} }