comparison 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
comparison
equal deleted inserted replaced
19:5c6155c8e9b6 20:efef93e54c5f
379 err(1, "pws3_field_set_text"); 379 err(1, "pws3_field_set_text");
380 } 380 }
381 pws3_file_set_header_field(file, save_host_field); 381 pws3_file_set_header_field(file, save_host_field);
382 } 382 }
383 383
384 int 384 static int
385 pwfile_write_file(struct pwm_ctx *ctx) 385 write_file(struct pwm_ctx *ctx, const char *filename)
386 { 386 {
387 int retval = -1; 387 int retval = -1;
388 char *tmpfilename = NULL; 388 char *tmpfilename = NULL;
389 mode_t old_mode; 389 mode_t old_mode;
390 int fd = -1; 390 int fd = -1;
391 FILE *fp = NULL; 391 FILE *fp = NULL;
392 392
393 /* update password file metadata */ 393 xasprintf(&tmpfilename, "%s.XXXXXX", filename);
394 update_file_metadata(ctx->file);
395
396 /* make a backup copy of the existing password file */
397 if (make_backup_copy(ctx->filename) != 0) {
398 goto out;
399 }
400
401 xasprintf(&tmpfilename, "%s.XXXXXX", ctx->filename);
402 394
403 /* create temporary file */ 395 /* create temporary file */
404 old_mode = umask(S_IRWXG | S_IRWXO); 396 old_mode = umask(S_IRWXG | S_IRWXO);
405 fd = mkstemp(tmpfilename); 397 fd = mkstemp(tmpfilename);
406 if (fd == -1) { 398 if (fd == -1) {
438 if (fp != NULL) { 430 if (fp != NULL) {
439 fclose(fp); 431 fclose(fp);
440 } 432 }
441 if (retval == 0) { 433 if (retval == 0) {
442 /* rename temporary file and overwrite existing file */ 434 /* rename temporary file and overwrite existing file */
443 if (rename(tmpfilename, ctx->filename) != 0) { 435 if (rename(tmpfilename, filename) != 0) {
444 warn("rename"); 436 warn("rename");
445 retval = -1; 437 retval = -1;
446 } 438 }
447 } 439 }
448 if ((retval != 0) && ((fd != -1) || (fp != NULL))) { 440 if ((retval != 0) && ((fd != -1) || (fp != NULL))) {
449 unlink(tmpfilename); 441 unlink(tmpfilename);
450 } 442 }
451 free(tmpfilename); 443 free(tmpfilename);
444
445 return (retval);
446 }
447
448 int
449 pwfile_write_autosave_file(struct pwm_ctx *ctx)
450 {
451 int retval;
452 char *autosave_filename;
453
454 xasprintf(&autosave_filename, "%s/autosave.psafe3", ctx->dirname);
455
456 retval = write_file(ctx, autosave_filename);
457
458 free(autosave_filename);
459
460 return (retval);
461 }
462
463 int
464 pwfile_write_file(struct pwm_ctx *ctx)
465 {
466 int retval;
467
468 /* update password file metadata */
469 update_file_metadata(ctx->file);
470
471 /* make a backup copy of the existing password file */
472 if (make_backup_copy(ctx->filename) != 0) {
473 return (-1);
474 }
475
476 retval = write_file(ctx, ctx->filename);
452 477
453 ctx->unsaved_changes = !!retval; 478 ctx->unsaved_changes = !!retval;
454 479
455 return (retval); 480 return (retval);
456 } 481 }