From 871a2088dbfe89f8d2dabfd07b6cb42f88a042c6 Mon Sep 17 00:00:00 2001
From: ridiculousfish <corydoras@ridiculousfish.com>
Date: Sat, 26 Sep 2015 02:19:51 -0700
Subject: [PATCH] Preserve existing file permissions when rewriting a history
 file

Fixes #2335
---
 src/history.cpp | 14 ++++++++++++++
 1 file changed, 14 insertions(+)

Index: b/history.cpp
===================================================================
--- a/history.cpp	2015-12-16 17:56:57.768524402 +0200
+++ b/history.cpp	2015-12-16 17:59:28.795103186 +0200
@@ -1443,6 +1443,20 @@
             else
             {
                 wcstring new_name = history_filename(name, wcstring());
+
+                /* Ensure we maintain the ownership and permissions of the original (#2355).
+                 * If the stat fails, we assume (hope) our default permissions are correct. This
+                 * corresponds to e.g. someone running sudo -E as the very first command. If they
+                 * did, it would be tricky to set the permissions correctly. (bash doesn't get this
+                 * case right either). */
+                struct stat sbuf;
+                if (wstat(new_name, &sbuf) >= 0)
+                {
+                   /* Success */
+                    fchown(out_fd, sbuf.st_uid, sbuf.st_gid);
+                    fchmod(out_fd, sbuf.st_mode);
+                }
+
                 wrename(tmp_name, new_name);
             }
             close(out_fd);
