diff pwfile.c @ 20:efef93e54c5f

Automatically save the database when receiving a fatal signal
author Guido Berhoerster <guido+pwm@berhoerster.name>
date Wed, 06 Sep 2017 13:56:11 +0200
parents cf81eb0c2d5a
children ec01c579024a
line wrap: on
line diff
--- a/pwfile.c	Fri Sep 01 22:33:41 2017 +0200
+++ b/pwfile.c	Wed Sep 06 13:56:11 2017 +0200
@@ -381,8 +381,8 @@
 	pws3_file_set_header_field(file, save_host_field);
 }
 
-int
-pwfile_write_file(struct pwm_ctx *ctx)
+static int
+write_file(struct pwm_ctx *ctx, const char *filename)
 {
 	int	retval = -1;
 	char	*tmpfilename = NULL;
@@ -390,15 +390,7 @@
 	int	fd = -1;
 	FILE	*fp = NULL;
 
-	/* update password file metadata */
-	update_file_metadata(ctx->file);
-
-	/* make a backup copy of the existing password file */
-	if (make_backup_copy(ctx->filename) != 0) {
-		goto out;
-	}
-
-	xasprintf(&tmpfilename, "%s.XXXXXX", ctx->filename);
+	xasprintf(&tmpfilename, "%s.XXXXXX", filename);
 
 	/* create temporary file */
 	old_mode = umask(S_IRWXG | S_IRWXO);
@@ -440,7 +432,7 @@
 	}
 	if (retval == 0) {
 		/* rename temporary file and overwrite existing file */
-		if (rename(tmpfilename, ctx->filename) != 0) {
+		if (rename(tmpfilename, filename) != 0) {
 			warn("rename");
 			retval = -1;
 		}
@@ -450,6 +442,39 @@
 	}
 	free(tmpfilename);
 
+	return (retval);
+}
+
+int
+pwfile_write_autosave_file(struct pwm_ctx *ctx)
+{
+	int	retval;
+	char	*autosave_filename;
+
+	xasprintf(&autosave_filename, "%s/autosave.psafe3", ctx->dirname);
+
+	retval = write_file(ctx, autosave_filename);
+
+	free(autosave_filename);
+
+	return (retval);
+}
+
+int
+pwfile_write_file(struct pwm_ctx *ctx)
+{
+	int	retval;
+
+	/* update password file metadata */
+	update_file_metadata(ctx->file);
+
+	/* make a backup copy of the existing password file */
+	if (make_backup_copy(ctx->filename) != 0) {
+		return (-1);
+	}
+
+	retval = write_file(ctx, ctx->filename);
+
 	ctx->unsaved_changes = !!retval;
 
 	return (retval);