+ if(block && !strncmp(buf, "-----END ", 9))
+ block = false;
+ }
+
+ if(w)
+ if(fclose(w) < 0)
+ error = true;
+ if(ferror(r) || fclose(r) < 0)
+ error = true;
+
+ if(disabled) {
+ if(!w || error) {
+ fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
+ if(w)
+ unlink(tmpfile);
+ return;
+ }
+
+#ifdef HAVE_MINGW
+ // We cannot atomically replace files on Windows.
+ char bakfile[PATH_MAX] = "";
+ snprintf(bakfile, sizeof bakfile, "%s.bak", filename);
+ if(rename(filename, bakfile) || rename(tmpfile, filename)) {
+ rename(bakfile, filename);
+#else
+ if(rename(tmpfile, filename)) {
+#endif
+ fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
+ } else {
+#ifdef HAVE_MINGW
+ unlink(bakfile);
+#endif
+ fprintf(stderr, "Warning: old key(s) found and disabled.\n");
+ }
+ }
+
+ unlink(tmpfile);
+}
+
+static FILE *ask_and_open(const char *filename, const char *what, const char *mode, bool ask, mode_t perms) {
+ FILE *r;
+ char *directory;
+ char buf[PATH_MAX];
+ char buf2[PATH_MAX];
+
+ /* Check stdin and stdout */
+ if(ask && tty) {
+ /* Ask for a file and/or directory name. */
+ fprintf(stderr, "Please enter a file to save %s to [%s]: ", what, filename);
+
+ if(fgets(buf, sizeof buf, stdin) == NULL) {
+ fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
+ return NULL;
+ }
+
+ size_t len = strlen(buf);
+ if(len)
+ buf[--len] = 0;
+
+ if(len)
+ filename = buf;
+ }
+
+#ifdef HAVE_MINGW
+ if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
+#else
+ if(filename[0] != '/') {
+#endif
+ /* The directory is a relative path or a filename. */
+ directory = get_current_dir_name();
+ snprintf(buf2, sizeof buf2, "%s" SLASH "%s", directory, filename);
+ filename = buf2;
+ }
+
+ disable_old_keys(filename, what);
+
+ /* Open it first to keep the inode busy */
+
+ r = fopenmask(filename, mode, perms);
+
+ if(!r) {
+ fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
+ return NULL;
+ }
+
+ return r;
+}