3ef004
diff --git a/xattrs.c b/xattrs.c
3ef004
index 508649c0..3c549192 100644
3ef004
--- a/xattrs.c
3ef004
+++ b/xattrs.c
3ef004
@@ -1055,7 +1055,7 @@ int set_xattr(const char *fname, const struct file_struct *file, const char *fna
3ef004
 {
3ef004
 	rsync_xa_list *glst = rsync_xal_l.items;
3ef004
 	item_list *lst;
3ef004
-	int ndx;
3ef004
+	int ndx, added_write_perm = 0;
3ef004
 
3ef004
 	if (dry_run)
3ef004
 		return 1; /* FIXME: --dry-run needs to compute this value */
3ef004
@@ -1084,10 +1084,23 @@ int set_xattr(const char *fname, const struct file_struct *file, const char *fna
3ef004
 	}
3ef004
 #endif
3ef004
 
3ef004
+	/* If the target file lacks write permission, we try to add it
3ef004
+	 * temporarily so we can change the extended attributes. */
3ef004
+	if (!am_root
3ef004
+#ifdef SUPPORT_LINKS
3ef004
+	 && !S_ISLNK(sxp->st.st_mode)
3ef004
+#endif
3ef004
+	 && access(fname, W_OK) < 0
3ef004
+	 && do_chmod(fname, (sxp->st.st_mode & CHMOD_BITS) | S_IWUSR) == 0)
3ef004
+		added_write_perm = 1;
3ef004
+
3ef004
 	ndx = F_XATTR(file);
3ef004
 	glst += ndx;
3ef004
 	lst = &glst->xa_items;
3ef004
-	return rsync_xal_set(fname, lst, fnamecmp, sxp);
3ef004
+	int return_value = rsync_xal_set(fname, lst, fnamecmp, sxp);
3ef004
+	if (added_write_perm) /* remove the temporary write permission */
3ef004
+		do_chmod(fname, sxp->st.st_mode);
3ef004
+	return return_value;
3ef004
 }
3ef004
 
3ef004
 #ifdef SUPPORT_ACLS