From 418aa564ebff70c1d118a5d3307a6d0b147ff7a2 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?P=C3=A1draig=20Brady?= <P@draigBrady.com>
Date: Mon, 3 Apr 2023 18:06:22 +0100
Subject: [PATCH] backupfile: fix bug when renaming from subdirectory

* lib/backupfile.c (backup_internal): Ensure we use the
appropriate offset if operating on a subdirectory,
i.e., on an updated sdir.
Fixes https://bugs.gnu.org/62607
---
 ChangeLog        | 8 ++++++++
 lib/backupfile.c | 7 ++++---
 2 files changed, 12 insertions(+), 3 deletions(-)

diff --git a/lib/backupfile.c b/lib/backupfile.c
index 9cca271343..5bcf924414 100644
--- a/lib/backupfile.c
+++ b/lib/backupfile.c
@@ -331,7 +331,7 @@ backupfile_internal (int dir_fd, char const *file,
     return s;
 
   DIR *dirp = NULL;
-  int sdir = dir_fd;
+  int sdir = -1;
   idx_t base_max = 0;
   while (true)
     {
@@ -370,9 +370,10 @@ backupfile_internal (int dir_fd, char const *file,
       if (! rename)
         break;
 
-      idx_t offset = backup_type == simple_backups ? 0 : base_offset;
+      dir_fd = sdir < 0 ? dir_fd : sdir;
+      idx_t offset = sdir < 0 ? 0 : base_offset;
       unsigned flags = backup_type == simple_backups ? 0 : RENAME_NOREPLACE;
-      if (renameatu (sdir, file + offset, sdir, s + offset, flags) == 0)
+      if (renameatu (dir_fd, file + offset, dir_fd, s + offset, flags) == 0)
         break;
       int e = errno;
       if (! (e == EEXIST && extended))
-- 
2.26.2

