+/* Create a backup path from the given fname, putting the result into
+ * backup_dir_buf. Any new directories (compared to the prior backup
+ * path) are ensured to exist as directories, replacing anything else
+ * that may be in the way (e.g. a symlink). */
+static BOOL copy_valid_path(const char *fname)
+{
+ const char *f;
+ int flags;
+ BOOL ret = True;
+ stat_x sx;
+ char *b, *rel = backup_dir_buf + backup_dir_len, *name = rel;
+
+ for (f = fname, b = rel; *f && *f == *b; f++, b++) {
+ if (*b == '/')
+ name = b + 1;
+ }
+
+ if (stringjoin(rel, backup_dir_remainder, fname, backup_suffix, NULL) >= backup_dir_remainder) {
+ rprintf(FERROR, "backup filename too long\n");
+ *name = '\0';
+ return False;
+ }
+
+ for ( ; ; name = b + 1) {
+ if ((b = strchr(name, '/')) == NULL)
+ return True;
+ *b = '\0';
+
+ if (do_lstat(backup_dir_buf, &sx.st) < 0) {
+ if (errno == ENOENT)
+ break;
+ rsyserr(FERROR, errno, "backup lstat %s failed", backup_dir_buf);
+ *name = '\0';
+ return False;
+ }
+ if (!S_ISDIR(sx.st.st_mode)) {
+ flags = get_del_for_flag(sx.st.st_mode) | DEL_FOR_BACKUP | DEL_RECURSE;
+ if (delete_item(backup_dir_buf, sx.st.st_mode, flags) == 0)
+ break;
+ *name = '\0';
+ return False;
+ }
+
+ *b = '/';
+ }
+
+ init_stat_x(&sx);
+
+ for ( ; b; name = b + 1, b = strchr(name, '/')) {
+ *b = '\0';
+
+ if (mkdir_defmode(backup_dir_buf) < 0) {
+ rsyserr(FERROR, errno, "backup mkdir %s failed", backup_dir_buf);
+ *name = '\0';
+ ret = False;
+ break;
+ }
+
+ /* Try to transfer the directory settings of the actual dir
+ * that the files are coming from. */
+ if (x_stat(rel, &sx.st, NULL) < 0)
+ rsyserr(FERROR, errno, "backup stat %s failed", full_fname(rel));
+ else {
+ struct file_struct *file;
+ if (!(file = make_file(rel, NULL, NULL, 0, NO_FILTERS)))
+ continue;
+#ifdef SUPPORT_ACLS
+ if (preserve_acls && !S_ISLNK(file->mode)) {
+ get_acl(rel, &sx);
+ cache_tmp_acl(file, &sx);
+ free_acl(&sx);
+ }
+#endif
+#ifdef SUPPORT_XATTRS
+ if (preserve_xattrs) {
+ get_xattr(rel, &sx);
+ cache_tmp_xattr(file, &sx);
+ free_xattr(&sx);
+ }
+#endif
+ set_file_attrs(backup_dir_buf, file, NULL, NULL, 0);
+ unmake_file(file);
+ }
+
+ *b = '/';
+ }
+
+#ifdef SUPPORT_ACLS
+ uncache_tmp_acls();
+#endif
+#ifdef SUPPORT_XATTRS
+ uncache_tmp_xattrs();
+#endif
+
+ return ret;
+}
+
+/* Make a complete pathname for backup file and verify any new path elements. */
+char *get_backup_name(const char *fname)
+{
+ if (backup_dir) {
+ /* copy fname into backup_dir_buf while validating the dirs. */
+ if (copy_valid_path(fname))
+ return backup_dir_buf;
+ return NULL;
+ } else {
+ if (stringjoin(backup_dir_buf, MAXPATHLEN,
+ fname, backup_suffix, NULL) < MAXPATHLEN)
+ return backup_dir_buf;
+ }
+
+ rprintf(FERROR, "backup filename too long\n");
+ return NULL;
+}