Add safety check for local --remove-source-files.
[rsync.git] / xattrs.c
1 /*
2  * Extended Attribute support for rsync.
3  * Written by Jay Fenlason, vaguely based on the ACLs patch.
4  *
5  * Copyright (C) 2004 Red Hat, Inc.
6  * Copyright (C) 2006-2022 Wayne Davison
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with this program; if not, visit the http://fsf.org website.
20  */
21
22 #include "rsync.h"
23 #include "ifuncs.h"
24 #include "inums.h"
25 #include "lib/sysxattrs.h"
26
27 #ifdef SUPPORT_XATTRS
28
29 extern int dry_run;
30 extern int am_root;
31 extern int am_sender;
32 extern int am_generator;
33 extern int read_only;
34 extern int list_only;
35 extern int preserve_xattrs;
36 extern int preserve_links;
37 extern int preserve_devices;
38 extern int preserve_specials;
39 extern int checksum_seed;
40 extern int saw_xattr_filter;
41
42 #define RSYNC_XAL_INITIAL 5
43 #define RSYNC_XAL_LIST_INITIAL 100
44
45 #define MAX_FULL_DATUM 32
46
47 #define HAS_PREFIX(str, prfx) (*(str) == *(prfx) && strncmp(str, prfx, sizeof (prfx) - 1) == 0)
48
49 #define XATTR_ABBREV(x) ((size_t)((x).name - (x).datum) < (x).datum_len)
50
51 #define XSTATE_ABBREV   1
52 #define XSTATE_DONE     2
53 #define XSTATE_TODO     3
54
55 #define USER_PREFIX "user."
56 #define UPRE_LEN ((int)sizeof USER_PREFIX - 1)
57 #define SYSTEM_PREFIX "system."
58 #define SPRE_LEN ((int)sizeof SYSTEM_PREFIX - 1)
59
60 #ifdef HAVE_LINUX_XATTRS
61 #define MIGHT_NEED_RPRE (am_root <= 0)
62 #define RSYNC_PREFIX USER_PREFIX "rsync."
63 #else
64 #define MIGHT_NEED_RPRE am_root
65 #define RSYNC_PREFIX "rsync."
66 #endif
67 #define RPRE_LEN ((int)sizeof RSYNC_PREFIX - 1)
68
69 #define XSTAT_SUFFIX "stat"
70 #define XSTAT_ATTR RSYNC_PREFIX "%" XSTAT_SUFFIX
71 #define XACC_ACL_SUFFIX "aacl"
72 #define XACC_ACL_ATTR RSYNC_PREFIX "%" XACC_ACL_SUFFIX
73 #define XDEF_ACL_SUFFIX "dacl"
74 #define XDEF_ACL_ATTR RSYNC_PREFIX "%" XDEF_ACL_SUFFIX
75
76 typedef struct {
77         char *datum, *name;
78         size_t datum_len, name_len;
79         int num;
80 } rsync_xa;
81
82 struct _rsync_xa_list;
83
84 typedef struct _rsync_xa_list_ref {
85         struct _rsync_xa_list_ref *next;
86         int ndx;
87 } rsync_xa_list_ref;
88
89 typedef struct _rsync_xa_list {
90         int ndx;
91         int64 key;
92         item_list xa_items;
93 } rsync_xa_list;
94
95 static size_t namebuf_len = 0;
96 static char *namebuf = NULL;
97
98 static const rsync_xa_list empty_xa_list = {
99         .xa_items = EMPTY_ITEM_LIST,
100 };
101 static const item_list empty_xattr = EMPTY_ITEM_LIST;
102 static item_list rsync_xal_l = EMPTY_ITEM_LIST;
103 static struct hashtable *rsync_xal_h = NULL;
104
105 static size_t prior_xattr_count = (size_t)-1;
106
107 /* ------------------------------------------------------------------------- */
108
109 static void rsync_xal_free(item_list *xalp)
110 {
111         size_t i;
112         rsync_xa *rxas = xalp->items;
113
114         if (!xalp->malloced)
115                 return;
116
117         for (i = 0; i < xalp->count; i++) {
118                 free(rxas[i].datum);
119                 /*free(rxas[i].name);*/
120         }
121         free(xalp->items);
122 }
123
124 void free_xattr(stat_x *sxp)
125 {
126         if (!sxp->xattr)
127                 return;
128         rsync_xal_free(sxp->xattr);
129         free(sxp->xattr);
130         sxp->xattr = NULL;
131 }
132
133 static int rsync_xal_compare_names(const void *x1, const void *x2)
134 {
135         const rsync_xa *xa1 = x1;
136         const rsync_xa *xa2 = x2;
137         return strcmp(xa1->name, xa2->name);
138 }
139
140 static ssize_t get_xattr_names(const char *fname)
141 {
142         ssize_t list_len;
143         int64 arg;
144
145         if (!namebuf) {
146                 namebuf_len = 1024;
147                 namebuf = new_array(char, namebuf_len);
148         }
149
150         while (1) {
151                 /* The length returned includes all the '\0' terminators. */
152                 list_len = sys_llistxattr(fname, namebuf, namebuf_len);
153                 if (list_len >= 0) {
154                         if ((size_t)list_len <= namebuf_len)
155                                 break;
156                 } else if (errno == ENOTSUP)
157                         return 0;
158                 else if (errno != ERANGE) {
159                         arg = namebuf_len;
160                   got_error:
161                         rsyserr(FERROR_XFER, errno,
162                                 "get_xattr_names: llistxattr(%s,%s) failed",
163                                 full_fname(fname), big_num(arg));
164                         return -1;
165                 }
166                 list_len = sys_llistxattr(fname, NULL, 0);
167                 if (list_len < 0) {
168                         arg = 0;
169                         goto got_error;
170                 }
171                 if (namebuf_len)
172                         free(namebuf);
173                 namebuf_len = list_len + 1024;
174                 namebuf = new_array(char, namebuf_len);
175         }
176
177         return list_len;
178 }
179
180 /* On entry, the *len_ptr parameter contains the size of the extra space we
181  * should allocate when we create a buffer for the data.  On exit, it contains
182  * the length of the datum. */
183 static char *get_xattr_data(const char *fname, const char *name, size_t *len_ptr, int no_missing_error)
184 {
185         size_t datum_len = sys_lgetxattr(fname, name, NULL, 0);
186         size_t extra_len = *len_ptr;
187         char *ptr;
188
189         *len_ptr = datum_len;
190
191         if (datum_len == (size_t)-1) {
192                 if (errno == ENOTSUP || no_missing_error)
193                         return NULL;
194                 rsyserr(FERROR_XFER, errno,
195                         "get_xattr_data: lgetxattr(%s,\"%s\",0) failed",
196                         full_fname(fname), name);
197                 return NULL;
198         }
199
200         if (!datum_len && !extra_len)
201                 extra_len = 1; /* request non-zero amount of memory */
202         if (SIZE_MAX - datum_len < extra_len)
203                 overflow_exit("get_xattr_data");
204         ptr = new_array(char, datum_len + extra_len);
205
206         if (datum_len) {
207                 size_t len = sys_lgetxattr(fname, name, ptr, datum_len);
208                 if (len != datum_len) {
209                         if (len == (size_t)-1) {
210                                 rsyserr(FERROR_XFER, errno,
211                                         "get_xattr_data: lgetxattr(%s,\"%s\",%ld) failed",
212                                         full_fname(fname), name, (long)datum_len);
213                         } else {
214                                 rprintf(FERROR_XFER,
215                                         "get_xattr_data: lgetxattr(%s,\"%s\",%ld) returned %ld\n",
216                                         full_fname(fname), name,
217                                         (long)datum_len, (long)len);
218                         }
219                         free(ptr);
220                         return NULL;
221                 }
222         }
223
224         return ptr;
225 }
226
227 static int rsync_xal_get(const char *fname, item_list *xalp)
228 {
229         ssize_t list_len, name_len;
230         size_t datum_len, name_offset;
231         char *name, *ptr;
232 #ifdef HAVE_LINUX_XATTRS
233         int user_only = am_sender ? 0 : !am_root;
234 #endif
235         rsync_xa *rxa;
236         int count;
237
238         /* This puts the name list into the "namebuf" buffer. */
239         if ((list_len = get_xattr_names(fname)) < 0)
240                 return -1;
241
242         for (name = namebuf; list_len > 0; name += name_len) {
243                 name_len = strlen(name) + 1;
244                 list_len -= name_len;
245
246                 if (saw_xattr_filter) {
247                         if (name_is_excluded(name, NAME_IS_XATTR, ALL_FILTERS))
248                                 continue;
249                 }
250 #ifdef HAVE_LINUX_XATTRS
251                 /* Choose between ignoring the system namespace or (non-root) ignoring any non-user namespace. */
252                 else if (user_only ? !HAS_PREFIX(name, USER_PREFIX) : HAS_PREFIX(name, SYSTEM_PREFIX))
253                         continue;
254 #endif
255
256                 /* No rsync.%FOO attributes are copied w/o 2 -X options. */
257                 if (name_len > RPRE_LEN && name[RPRE_LEN] == '%' && HAS_PREFIX(name, RSYNC_PREFIX)) {
258                         if ((am_sender && preserve_xattrs < 2)
259                          || (am_root < 0
260                           && (strcmp(name+RPRE_LEN+1, XSTAT_SUFFIX) == 0
261                            || strcmp(name+RPRE_LEN+1, XACC_ACL_SUFFIX) == 0
262                            || strcmp(name+RPRE_LEN+1, XDEF_ACL_SUFFIX) == 0)))
263                                 continue;
264                 }
265
266                 datum_len = name_len; /* Pass extra size to get_xattr_data() */
267                 if (!(ptr = get_xattr_data(fname, name, &datum_len, 0)))
268                         return -1;
269
270                 if (datum_len > MAX_FULL_DATUM) {
271                         /* For large datums, we store a flag and a checksum. */
272                         name_offset = 1 + MAX_DIGEST_LEN;
273                         sum_init(-1, checksum_seed);
274                         sum_update(ptr, datum_len);
275                         free(ptr);
276
277                         ptr = new_array(char, name_offset + name_len);
278                         *ptr = XSTATE_ABBREV;
279                         sum_end(ptr + 1);
280                 } else
281                         name_offset = datum_len;
282
283                 rxa = EXPAND_ITEM_LIST(xalp, rsync_xa, RSYNC_XAL_INITIAL);
284                 rxa->name = ptr + name_offset;
285                 memcpy(rxa->name, name, name_len);
286                 rxa->datum = ptr;
287                 rxa->name_len = name_len;
288                 rxa->datum_len = datum_len;
289         }
290         count = xalp->count;
291         rxa = xalp->items;
292         if (count > 1)
293                 qsort(rxa, count, sizeof (rsync_xa), rsync_xal_compare_names);
294         for (rxa += count-1; count; count--, rxa--)
295                 rxa->num = count;
296         return 0;
297 }
298
299 /* Read the xattr(s) for this filename. */
300 int get_xattr(const char *fname, stat_x *sxp)
301 {
302         sxp->xattr = new(item_list);
303         *sxp->xattr = empty_xattr;
304
305         if (S_ISREG(sxp->st.st_mode) || S_ISDIR(sxp->st.st_mode)) {
306                 /* Everyone supports this. */
307         } else if (S_ISLNK(sxp->st.st_mode)) {
308 #ifndef NO_SYMLINK_XATTRS
309                 if (!preserve_links)
310 #endif
311                         return 0;
312         } else if (IS_SPECIAL(sxp->st.st_mode)) {
313 #ifndef NO_SPECIAL_XATTRS
314                 if (!preserve_specials)
315 #endif
316                         return 0;
317         } else if (IS_DEVICE(sxp->st.st_mode)) {
318 #ifndef NO_DEVICE_XATTRS
319                 if (!preserve_devices)
320 #endif
321                         return 0;
322         } else if (IS_MISSING_FILE(sxp->st))
323                 return 0;
324
325         if (rsync_xal_get(fname, sxp->xattr) < 0) {
326                 free_xattr(sxp);
327                 return -1;
328         }
329         return 0;
330 }
331
332 int copy_xattrs(const char *source, const char *dest)
333 {
334         ssize_t list_len, name_len;
335         size_t datum_len;
336         char *name, *ptr;
337 #ifdef HAVE_LINUX_XATTRS
338         int user_only = am_sender ? 0 : am_root <= 0;
339 #endif
340
341         /* This puts the name list into the "namebuf" buffer. */
342         if ((list_len = get_xattr_names(source)) < 0)
343                 return -1;
344
345         for (name = namebuf; list_len > 0; name += name_len) {
346                 name_len = strlen(name) + 1;
347                 list_len -= name_len;
348
349                 if (saw_xattr_filter) {
350                         if (name_is_excluded(name, NAME_IS_XATTR, ALL_FILTERS))
351                                 continue;
352                 }
353 #ifdef HAVE_LINUX_XATTRS
354                 /* Choose between ignoring the system namespace or (non-root) ignoring any non-user namespace. */
355                 else if (user_only ? !HAS_PREFIX(name, USER_PREFIX) : HAS_PREFIX(name, SYSTEM_PREFIX))
356                         continue;
357 #endif
358
359                 datum_len = 0;
360                 if (!(ptr = get_xattr_data(source, name, &datum_len, 0)))
361                         return -1;
362                 if (sys_lsetxattr(dest, name, ptr, datum_len) < 0) {
363                         int save_errno = errno ? errno : EINVAL;
364                         rsyserr(FERROR_XFER, errno,
365                                 "copy_xattrs: lsetxattr(%s,\"%s\") failed",
366                                 full_fname(dest), name);
367                         errno = save_errno;
368                         return -1;
369                 }
370                 free(ptr);
371         }
372
373         return 0;
374 }
375
376 static int64 xattr_lookup_hash(const item_list *xalp)
377 {
378         const rsync_xa *rxas = xalp->items;
379         size_t i;
380         int64 key = hashlittle(&xalp->count, sizeof xalp->count);
381
382         for (i = 0; i < xalp->count; i++) {
383                 key += hashlittle(rxas[i].name, rxas[i].name_len);
384                 if (rxas[i].datum_len > MAX_FULL_DATUM)
385                         key += hashlittle(rxas[i].datum, MAX_DIGEST_LEN);
386                 else
387                         key += hashlittle(rxas[i].datum, rxas[i].datum_len);
388         }
389
390         if (key == 0) {
391                 /* This is very unlikely, but we should never
392                  * return 0 as hashtable_find() doesn't like it. */
393                 return 1;
394         }
395
396         return key;
397 }
398
399 static int find_matching_xattr(const item_list *xalp)
400 {
401         const struct ht_int64_node *node;
402         const rsync_xa_list_ref *ref;
403         int64 key;
404
405         if (rsync_xal_h == NULL)
406                 return -1;
407
408         key = xattr_lookup_hash(xalp);
409
410         node = hashtable_find(rsync_xal_h, key, NULL);
411         if (node == NULL)
412                 return -1;
413
414         if (node->data == NULL)
415                 return -1;
416
417         for (ref = node->data; ref != NULL; ref = ref->next) {
418                 const rsync_xa_list *ptr = rsync_xal_l.items;
419                 const rsync_xa *rxas1;
420                 const rsync_xa *rxas2 = xalp->items;
421                 size_t j;
422
423                 ptr += ref->ndx;
424                 rxas1 = ptr->xa_items.items;
425
426                 /* Wrong number of elements? */
427                 if (ptr->xa_items.count != xalp->count)
428                         continue;
429                 /* any elements different? */
430                 for (j = 0; j < xalp->count; j++) {
431                         if (rxas1[j].name_len != rxas2[j].name_len
432                          || rxas1[j].datum_len != rxas2[j].datum_len
433                          || strcmp(rxas1[j].name, rxas2[j].name))
434                                 break;
435                         if (rxas1[j].datum_len > MAX_FULL_DATUM) {
436                                 if (memcmp(rxas1[j].datum + 1,
437                                            rxas2[j].datum + 1,
438                                            MAX_DIGEST_LEN) != 0)
439                                         break;
440                         } else {
441                                 if (memcmp(rxas1[j].datum, rxas2[j].datum,
442                                            rxas2[j].datum_len))
443                                         break;
444                         }
445                 }
446                 /* no differences found.  This is The One! */
447                 if (j == xalp->count)
448                         return ref->ndx;
449         }
450
451         return -1;
452 }
453
454 /* Store *xalp on the end of rsync_xal_l */
455 static int rsync_xal_store(item_list *xalp)
456 {
457         struct ht_int64_node *node;
458         int ndx = rsync_xal_l.count; /* pre-incremented count */
459         rsync_xa_list *new_list = EXPAND_ITEM_LIST(&rsync_xal_l, rsync_xa_list, RSYNC_XAL_LIST_INITIAL);
460         rsync_xa_list_ref *new_ref;
461         /* Since the following call starts a new list, we know it will hold the
462          * entire initial-count, not just enough space for one new item. */
463         *new_list = empty_xa_list;
464         (void)EXPAND_ITEM_LIST(&new_list->xa_items, rsync_xa, xalp->count);
465         memcpy(new_list->xa_items.items, xalp->items, xalp->count * sizeof (rsync_xa));
466         new_list->xa_items.count = xalp->count;
467         xalp->count = 0;
468
469         new_list->ndx = ndx;
470         new_list->key = xattr_lookup_hash(&new_list->xa_items);
471
472         if (rsync_xal_h == NULL)
473                 rsync_xal_h = hashtable_create(512, HT_KEY64);
474         if (rsync_xal_h == NULL)
475                 out_of_memory("rsync_xal_h hashtable_create()");
476
477         new_ref = new0(rsync_xa_list_ref);
478         new_ref->ndx = ndx;
479
480         node = hashtable_find(rsync_xal_h, new_list->key, new_ref);
481         if (node->data != (void*)new_ref) {
482                 rsync_xa_list_ref *ref = node->data;
483
484                 while (ref != NULL) {
485                         if (ref->next != NULL) {
486                                 ref = ref->next;
487                                 continue;
488                         }
489
490                         ref->next = new_ref;
491                         break;
492                 }
493         }
494
495         return ndx;
496 }
497
498 /* Send the make_xattr()-generated xattr list for this flist entry. */
499 int send_xattr(int f, stat_x *sxp)
500 {
501         int ndx = find_matching_xattr(sxp->xattr);
502
503         /* Send 0 (-1 + 1) to indicate that literal xattr data follows. */
504         write_varint(f, ndx + 1);
505
506         if (ndx < 0) {
507                 rsync_xa *rxa;
508                 int count = sxp->xattr->count;
509                 write_varint(f, count);
510                 for (rxa = sxp->xattr->items; count--; rxa++) {
511                         size_t name_len = rxa->name_len;
512                         const char *name = rxa->name;
513                         /* Strip the rsync prefix from disguised namespaces. */
514                         if (name_len > RPRE_LEN
515 #ifdef HAVE_LINUX_XATTRS
516                          && am_root < 0
517 #endif
518                          && name[RPRE_LEN] != '%' && HAS_PREFIX(name, RSYNC_PREFIX)) {
519                                 name += RPRE_LEN;
520                                 name_len -= RPRE_LEN;
521                         }
522 #ifndef HAVE_LINUX_XATTRS
523                         else {
524                                 /* Put everything else in the user namespace. */
525                                 name_len += UPRE_LEN;
526                         }
527 #endif
528                         write_varint(f, name_len);
529                         write_varint(f, rxa->datum_len);
530 #ifndef HAVE_LINUX_XATTRS
531                         if (name_len > rxa->name_len) {
532                                 write_buf(f, USER_PREFIX, UPRE_LEN);
533                                 name_len -= UPRE_LEN;
534                         }
535 #endif
536                         write_buf(f, name, name_len);
537                         if (rxa->datum_len > MAX_FULL_DATUM)
538                                 write_buf(f, rxa->datum + 1, MAX_DIGEST_LEN);
539                         else
540                                 write_bigbuf(f, rxa->datum, rxa->datum_len);
541                 }
542                 ndx = rsync_xal_store(sxp->xattr); /* adds item to rsync_xal_l */
543         }
544
545         return ndx;
546 }
547
548 /* Return a flag indicating if we need to change a file's xattrs.  If
549  * "find_all" is specified, also mark any abbreviated xattrs that we
550  * need so that send_xattr_request() can tell the sender about them. */
551 int xattr_diff(struct file_struct *file, stat_x *sxp, int find_all)
552 {
553         const rsync_xa_list *glst = rsync_xal_l.items;
554         const item_list *lst;
555         rsync_xa *snd_rxa, *rec_rxa;
556         int snd_cnt, rec_cnt;
557         int cmp, same, xattrs_equal = 1;
558
559         if (sxp && XATTR_READY(*sxp)) {
560                 rec_rxa = sxp->xattr->items;
561                 rec_cnt = sxp->xattr->count;
562         } else {
563                 rec_rxa = NULL;
564                 rec_cnt = 0;
565         }
566
567         if (F_XATTR(file) >= 0) {
568                 glst += F_XATTR(file);
569                 lst = &glst->xa_items;
570         } else
571                 lst = &empty_xattr;
572
573         snd_rxa = lst->items;
574         snd_cnt = lst->count;
575
576         /* If the count of the sender's xattrs is different from our
577          * (receiver's) xattrs, the lists are not the same. */
578         if (snd_cnt != rec_cnt) {
579                 if (!find_all)
580                         return 1;
581                 xattrs_equal = 0;
582         }
583
584         while (snd_cnt) {
585                 cmp = rec_cnt ? strcmp(snd_rxa->name, rec_rxa->name) : -1;
586                 if (cmp > 0)
587                         same = 0;
588                 else if (snd_rxa->datum_len > MAX_FULL_DATUM) {
589                         same = cmp == 0 && snd_rxa->datum_len == rec_rxa->datum_len
590                             && memcmp(snd_rxa->datum + 1, rec_rxa->datum + 1,
591                                       MAX_DIGEST_LEN) == 0;
592                         /* Flag unrequested items that we need. */
593                         if (!same && find_all && snd_rxa->datum[0] == XSTATE_ABBREV)
594                                 snd_rxa->datum[0] = XSTATE_TODO;
595                 } else {
596                         same = cmp == 0 && snd_rxa->datum_len == rec_rxa->datum_len
597                             && memcmp(snd_rxa->datum, rec_rxa->datum,
598                                       snd_rxa->datum_len) == 0;
599                 }
600                 if (!same) {
601                         if (!find_all)
602                                 return 1;
603                         xattrs_equal = 0;
604                 }
605
606                 if (cmp <= 0) {
607                         snd_rxa++;
608                         snd_cnt--;
609                 }
610                 if (cmp >= 0) {
611                         rec_rxa++;
612                         rec_cnt--;
613                 }
614         }
615
616         if (rec_cnt)
617                 xattrs_equal = 0;
618
619         return !xattrs_equal;
620 }
621
622 /* When called by the generator (with a NULL fname), this tells the sender
623  * all the abbreviated xattr values we need.  When called by the sender
624  * (with a non-NULL fname), we send all the extra xattr data it needs.
625  * The generator may also call with f_out < 0 to just change all the
626  * XSTATE_ABBREV states into XSTATE_DONE. */
627 void send_xattr_request(const char *fname, struct file_struct *file, int f_out)
628 {
629         const rsync_xa_list *glst = rsync_xal_l.items;
630         const item_list *lst;
631         int cnt, prior_req = 0;
632         rsync_xa *rxa;
633
634         glst += F_XATTR(file);
635         lst = &glst->xa_items;
636
637         for (rxa = lst->items, cnt = lst->count; cnt--; rxa++) {
638                 if (rxa->datum_len <= MAX_FULL_DATUM)
639                         continue;
640                 switch (rxa->datum[0]) {
641                 case XSTATE_ABBREV:
642                         /* Items left abbreviated matched the sender's checksum, so
643                          * the receiver will cache the local data for future use. */
644                         if (am_generator)
645                                 rxa->datum[0] = XSTATE_DONE;
646                         continue;
647                 case XSTATE_TODO:
648                         assert(f_out >= 0);
649                         break;
650                 default:
651                         continue;
652                 }
653
654                 /* Flag that we handled this abbreviated item. */
655                 rxa->datum[0] = XSTATE_DONE;
656
657                 write_varint(f_out, rxa->num - prior_req);
658                 prior_req = rxa->num;
659
660                 if (fname) {
661                         size_t len = 0;
662                         char *ptr;
663
664                         /* Re-read the long datum. */
665                         if (!(ptr = get_xattr_data(fname, rxa->name, &len, 0))) {
666                                 rprintf(FERROR_XFER, "failed to re-read xattr %s for %s\n", rxa->name, fname);
667                                 write_varint(f_out, 0);
668                                 continue;
669                         }
670
671                         write_varint(f_out, len); /* length might have changed! */
672                         write_bigbuf(f_out, ptr, len);
673                         free(ptr);
674                 }
675         }
676
677         if (f_out >= 0)
678                 write_byte(f_out, 0); /* end the list */
679 }
680
681 /* When called by the sender, read the request from the generator and mark
682  * any needed xattrs with a flag that lets us know they need to be sent to
683  * the receiver.  When called by the receiver, reads the sent data and
684  * stores it in place of its checksum. */
685 int recv_xattr_request(struct file_struct *file, int f_in)
686 {
687         const rsync_xa_list *glst = rsync_xal_l.items;
688         const item_list *lst;
689         char *old_datum, *name;
690         rsync_xa *rxa;
691         int rel_pos, cnt, num, got_xattr_data = 0;
692
693         if (F_XATTR(file) < 0) {
694                 rprintf(FERROR, "recv_xattr_request: internal data error!\n");
695                 exit_cleanup(RERR_PROTOCOL);
696         }
697         glst += F_XATTR(file);
698         lst = &glst->xa_items;
699
700         cnt = lst->count;
701         rxa = lst->items;
702         num = 0;
703         while ((rel_pos = read_varint(f_in)) != 0) {
704                 num += rel_pos;
705                 if (am_sender) {
706                         /* The sender-related num values are only in order on the sender.
707                          * We use that order here to scan forward or backward as needed. */
708                         if (rel_pos < 0) {
709                                 while (cnt < (int)lst->count && rxa->num > num) {
710                                         rxa--;
711                                         cnt++;
712                                 }
713                         } else {
714                                 while (cnt > 1 && rxa->num < num) {
715                                         rxa++;
716                                         cnt--;
717                                 }
718                         }
719                 } else {
720                         int j;
721                         /* The receiving side has no known num order, so we just scan
722                          * forward (w/wrap) and hope that the next value is near by. */
723                         for (j = lst->count; j > 1 && rxa->num != num; j--) {
724                                 if (--cnt)
725                                         rxa++;
726                                 else {
727                                         cnt = lst->count;
728                                         rxa = lst->items;
729                                 }
730                         }
731                 }
732                 if (!cnt || rxa->num != num) {
733                         rprintf(FERROR, "[%s] could not find xattr #%d for %s\n",
734                                 who_am_i(), num, f_name(file, NULL));
735                         exit_cleanup(RERR_PROTOCOL);
736                 }
737                 if (!XATTR_ABBREV(*rxa) || rxa->datum[0] != XSTATE_ABBREV) {
738                         rprintf(FERROR, "[%s] internal abbrev error on %s (%s, len=%ld)!\n",
739                                 who_am_i(), f_name(file, NULL), rxa->name, (long)rxa->datum_len);
740                         exit_cleanup(RERR_PROTOCOL);
741                 }
742
743                 if (am_sender) {
744                         rxa->datum[0] = XSTATE_TODO;
745                         continue;
746                 }
747
748                 old_datum = rxa->datum;
749                 rxa->datum_len = read_varint(f_in);
750
751                 if (SIZE_MAX - rxa->name_len < rxa->datum_len)
752                         overflow_exit("recv_xattr_request");
753                 rxa->datum = new_array(char, rxa->datum_len + rxa->name_len);
754                 name = rxa->datum + rxa->datum_len;
755                 memcpy(name, rxa->name, rxa->name_len);
756                 rxa->name = name;
757                 free(old_datum);
758                 read_buf(f_in, rxa->datum, rxa->datum_len);
759                 got_xattr_data = 1;
760         }
761
762         return got_xattr_data;
763 }
764
765 /* ------------------------------------------------------------------------- */
766
767 /* receive and build the rsync_xattr_lists */
768 void receive_xattr(int f, struct file_struct *file)
769 {
770         static item_list temp_xattr = EMPTY_ITEM_LIST;
771         int count, num;
772 #ifdef HAVE_LINUX_XATTRS
773         int need_sort = 0;
774 #else
775         int need_sort = 1;
776 #endif
777         int ndx = read_varint(f);
778
779         if (ndx < 0 || (size_t)ndx > rsync_xal_l.count) {
780                 rprintf(FERROR, "receive_xattr: xa index %d out of"
781                         " range for %s\n", ndx, f_name(file, NULL));
782                 exit_cleanup(RERR_STREAMIO);
783         }
784
785         if (ndx != 0) {
786                 F_XATTR(file) = ndx - 1;
787                 return;
788         }
789
790         if ((count = read_varint(f)) != 0) {
791                 (void)EXPAND_ITEM_LIST(&temp_xattr, rsync_xa, count);
792                 temp_xattr.count = 0;
793         }
794
795         for (num = 1; num <= count; num++) {
796                 char *ptr, *name;
797                 rsync_xa *rxa;
798                 size_t name_len = read_varint(f);
799                 size_t datum_len = read_varint(f);
800                 size_t dget_len = datum_len > MAX_FULL_DATUM ? 1 + MAX_DIGEST_LEN : datum_len;
801                 size_t extra_len = MIGHT_NEED_RPRE ? RPRE_LEN : 0;
802                 if (SIZE_MAX - dget_len < extra_len || SIZE_MAX - dget_len - extra_len < name_len)
803                         overflow_exit("receive_xattr");
804                 ptr = new_array(char, dget_len + extra_len + name_len);
805                 name = ptr + dget_len + extra_len;
806                 read_buf(f, name, name_len);
807                 if (name_len < 1 || name[name_len-1] != '\0') {
808                         rprintf(FERROR, "Invalid xattr name received (missing trailing \\0).\n");
809                         exit_cleanup(RERR_FILEIO);
810                 }
811                 if (dget_len == datum_len)
812                         read_buf(f, ptr, dget_len);
813                 else {
814                         *ptr = XSTATE_ABBREV;
815                         read_buf(f, ptr + 1, MAX_DIGEST_LEN);
816                 }
817
818                 if (saw_xattr_filter) {
819                         if (name_is_excluded(name, NAME_IS_XATTR, ALL_FILTERS)) {
820                                 free(ptr);
821                                 continue;
822                         }
823                 }
824 #ifdef HAVE_LINUX_XATTRS
825                 /* Non-root can only save the user namespace. */
826                 if (am_root <= 0 && !HAS_PREFIX(name, USER_PREFIX)) {
827                         if (!am_root && !saw_xattr_filter) {
828                                 free(ptr);
829                                 continue;
830                         }
831                         name -= RPRE_LEN;
832                         name_len += RPRE_LEN;
833                         memcpy(name, RSYNC_PREFIX, RPRE_LEN);
834                         need_sort = 1;
835                 }
836 #else
837                 /* This OS only has a user namespace, so we either
838                  * strip the user prefix, or we put a non-user
839                  * namespace inside our rsync hierarchy. */
840                 if (HAS_PREFIX(name, USER_PREFIX)) {
841                         name += UPRE_LEN;
842                         name_len -= UPRE_LEN;
843                 } else if (am_root) {
844                         name -= RPRE_LEN;
845                         name_len += RPRE_LEN;
846                         memcpy(name, RSYNC_PREFIX, RPRE_LEN);
847                 } else {
848                         free(ptr);
849                         continue;
850                 }
851 #endif
852                 /* No rsync.%FOO attributes are copied w/o 2 -X options. */
853                 if (preserve_xattrs < 2 && name_len > RPRE_LEN
854                  && name[RPRE_LEN] == '%' && HAS_PREFIX(name, RSYNC_PREFIX)) {
855                         free(ptr);
856                         continue;
857                 }
858
859                 rxa = EXPAND_ITEM_LIST(&temp_xattr, rsync_xa, 1);
860                 rxa->name = name;
861                 rxa->datum = ptr;
862                 rxa->name_len = name_len;
863                 rxa->datum_len = datum_len;
864                 rxa->num = num;
865         }
866
867         if (need_sort && count > 1)
868                 qsort(temp_xattr.items, count, sizeof (rsync_xa), rsync_xal_compare_names);
869
870         ndx = rsync_xal_store(&temp_xattr); /* adds item to rsync_xal_l */
871
872         F_XATTR(file) = ndx;
873 }
874
875 /* Turn the xattr data in stat_x into cached xattr data, setting the index
876  * values in the file struct. */
877 void cache_tmp_xattr(struct file_struct *file, stat_x *sxp)
878 {
879         int ndx;
880
881         if (!sxp->xattr)
882                 return;
883
884         if (prior_xattr_count == (size_t)-1)
885                 prior_xattr_count = rsync_xal_l.count;
886         ndx = find_matching_xattr(sxp->xattr);
887         if (ndx < 0)
888                 rsync_xal_store(sxp->xattr); /* adds item to rsync_xal_l */
889
890         F_XATTR(file) = ndx;
891 }
892
893 void uncache_tmp_xattrs(void)
894 {
895         if (prior_xattr_count != (size_t)-1) {
896                 rsync_xa_list *xa_list_item = rsync_xal_l.items;
897                 rsync_xa_list *xa_list_start = xa_list_item + prior_xattr_count;
898                 xa_list_item += rsync_xal_l.count;
899                 rsync_xal_l.count = prior_xattr_count;
900                 while (xa_list_item-- > xa_list_start) {
901                         struct ht_int64_node *node;
902                         rsync_xa_list_ref *ref;
903
904                         rsync_xal_free(&xa_list_item->xa_items);
905
906                         if (rsync_xal_h == NULL)
907                                 continue;
908
909                         node = hashtable_find(rsync_xal_h, xa_list_item->key, NULL);
910                         if (node == NULL)
911                                 continue;
912
913                         if (node->data == NULL)
914                                 continue;
915
916                         ref = node->data;
917                         if (xa_list_item->ndx == ref->ndx) {
918                                 /* xa_list_item is the first in the list. */
919                                 node->data = ref->next;
920                                 free(ref);
921                                 continue;
922                         }
923
924                         while (1) {
925                                 rsync_xa_list_ref *next = ref->next;
926                                 if (next == NULL)
927                                         break;
928                                 if (xa_list_item->ndx == next->ndx) {
929                                         ref->next = next->next;
930                                         free(next);
931                                         break;
932                                 }
933                                 ref = next;
934                         }
935                 }
936                 prior_xattr_count = (size_t)-1;
937         }
938 }
939
940 static int rsync_xal_set(const char *fname, item_list *xalp,
941                          const char *fnamecmp, stat_x *sxp)
942 {
943         rsync_xa *rxas = xalp->items;
944         ssize_t list_len;
945         size_t i, len;
946         char *name, *ptr, sum[MAX_DIGEST_LEN];
947 #ifdef HAVE_LINUX_XATTRS
948         int user_only = am_root <= 0;
949 #endif
950         size_t name_len;
951         int ret = 0;
952
953         /* This puts the current name list into the "namebuf" buffer. */
954         if ((list_len = get_xattr_names(fname)) < 0)
955                 return -1;
956
957         for (i = 0; i < xalp->count; i++) {
958                 name = rxas[i].name;
959
960                 if (XATTR_ABBREV(rxas[i])) {
961                         int sum_len;
962                         /* See if the fnamecmp version is identical. */
963                         len = name_len = rxas[i].name_len;
964                         if ((ptr = get_xattr_data(fnamecmp, name, &len, 1)) == NULL) {
965                           still_abbrev:
966                                 if (am_generator)
967                                         continue;
968                                 rprintf(FERROR, "Missing abbreviated xattr value, %s, for %s\n",
969                                         rxas[i].name, full_fname(fname));
970                                 ret = -1;
971                                 continue;
972                         }
973                         if (len != rxas[i].datum_len) {
974                                 free(ptr);
975                                 goto still_abbrev;
976                         }
977
978                         sum_init(-1, checksum_seed);
979                         sum_update(ptr, len);
980                         sum_len = sum_end(sum);
981                         if (memcmp(sum, rxas[i].datum + 1, sum_len) != 0) {
982                                 free(ptr);
983                                 goto still_abbrev;
984                         }
985
986                         if (fname == fnamecmp)
987                                 ; /* Value is already set when identical */
988                         else if (sys_lsetxattr(fname, name, ptr, len) < 0) {
989                                 rsyserr(FERROR_XFER, errno,
990                                         "rsync_xal_set: lsetxattr(%s,\"%s\") failed",
991                                         full_fname(fname), name);
992                                 ret = -1;
993                         } else /* make sure caller sets mtime */
994                                 sxp->st.st_mtime = (time_t)-1;
995
996                         if (am_generator) { /* generator items stay abbreviated */
997                                 free(ptr);
998                                 continue;
999                         }
1000
1001                         memcpy(ptr + len, name, name_len);
1002                         free(rxas[i].datum);
1003
1004                         rxas[i].name = name = ptr + len;
1005                         rxas[i].datum = ptr;
1006                         continue;
1007                 }
1008
1009                 if (sys_lsetxattr(fname, name, rxas[i].datum, rxas[i].datum_len) < 0) {
1010                         rsyserr(FERROR_XFER, errno,
1011                                 "rsync_xal_set: lsetxattr(%s,\"%s\") failed",
1012                                 full_fname(fname), name);
1013                         ret = -1;
1014                 } else /* make sure caller sets mtime */
1015                         sxp->st.st_mtime = (time_t)-1;
1016         }
1017
1018         /* Remove any extraneous names. */
1019         for (name = namebuf; list_len > 0; name += name_len) {
1020                 name_len = strlen(name) + 1;
1021                 list_len -= name_len;
1022
1023                 if (saw_xattr_filter) {
1024                         if (name_is_excluded(name, NAME_IS_XATTR, ALL_FILTERS))
1025                                 continue;
1026                 }
1027 #ifdef HAVE_LINUX_XATTRS
1028                 /* Choose between ignoring the system namespace or (non-root) ignoring any non-user namespace. */
1029                 else if (user_only ? !HAS_PREFIX(name, USER_PREFIX) : HAS_PREFIX(name, SYSTEM_PREFIX))
1030                         continue;
1031 #endif
1032                 if (am_root < 0 && name_len > RPRE_LEN && name[RPRE_LEN] == '%' && strcmp(name, XSTAT_ATTR) == 0)
1033                         continue;
1034
1035                 for (i = 0; i < xalp->count; i++) {
1036                         if (strcmp(name, rxas[i].name) == 0)
1037                                 break;
1038                 }
1039                 if (i == xalp->count) {
1040                         if (sys_lremovexattr(fname, name) < 0) {
1041                                 rsyserr(FERROR_XFER, errno,
1042                                         "rsync_xal_set: lremovexattr(%s,\"%s\") failed",
1043                                         full_fname(fname), name);
1044                                 ret = -1;
1045                         } else /* make sure caller sets mtime */
1046                                 sxp->st.st_mtime = (time_t)-1;
1047                 }
1048         }
1049
1050         return ret;
1051 }
1052
1053 /* Set extended attributes on indicated filename. */
1054 int set_xattr(const char *fname, const struct file_struct *file, const char *fnamecmp, stat_x *sxp)
1055 {
1056         rsync_xa_list *glst = rsync_xal_l.items;
1057         item_list *lst;
1058         int ndx, added_write_perm = 0;
1059
1060         if (dry_run)
1061                 return 1; /* FIXME: --dry-run needs to compute this value */
1062
1063         if (read_only || list_only) {
1064                 errno = EROFS;
1065                 return -1;
1066         }
1067
1068 #ifdef NO_SPECIAL_XATTRS
1069         if (IS_SPECIAL(sxp->st.st_mode)) {
1070                 errno = ENOTSUP;
1071                 return -1;
1072         }
1073 #endif
1074 #ifdef NO_DEVICE_XATTRS
1075         if (IS_DEVICE(sxp->st.st_mode)) {
1076                 errno = ENOTSUP;
1077                 return -1;
1078         }
1079 #endif
1080 #ifdef NO_SYMLINK_XATTRS
1081         if (S_ISLNK(sxp->st.st_mode)) {
1082                 errno = ENOTSUP;
1083                 return -1;
1084         }
1085 #endif
1086
1087         /* If the target file lacks write permission, we try to add it
1088          * temporarily so we can change the extended attributes. */
1089         if (!am_root
1090 #ifdef SUPPORT_LINKS
1091          && !S_ISLNK(sxp->st.st_mode)
1092 #endif
1093          && access(fname, W_OK) < 0
1094          && do_chmod(fname, (sxp->st.st_mode & CHMOD_BITS) | S_IWUSR) == 0)
1095                 added_write_perm = 1;
1096
1097         ndx = F_XATTR(file);
1098         glst += ndx;
1099         lst = &glst->xa_items;
1100         int return_value = rsync_xal_set(fname, lst, fnamecmp, sxp);
1101         if (added_write_perm) /* remove the temporary write permission */
1102                 do_chmod(fname, sxp->st.st_mode);
1103         return return_value;
1104 }
1105
1106 #ifdef SUPPORT_ACLS
1107 char *get_xattr_acl(const char *fname, int is_access_acl, size_t *len_p)
1108 {
1109         const char *name = is_access_acl ? XACC_ACL_ATTR : XDEF_ACL_ATTR;
1110         *len_p = 0; /* no extra data alloc needed from get_xattr_data() */
1111         return get_xattr_data(fname, name, len_p, 1);
1112 }
1113
1114 int set_xattr_acl(const char *fname, int is_access_acl, const char *buf, size_t buf_len)
1115 {
1116         const char *name = is_access_acl ? XACC_ACL_ATTR : XDEF_ACL_ATTR;
1117         if (sys_lsetxattr(fname, name, buf, buf_len) < 0) {
1118                 rsyserr(FERROR_XFER, errno,
1119                         "set_xattr_acl: lsetxattr(%s,\"%s\") failed",
1120                         full_fname(fname), name);
1121                 return -1;
1122         }
1123         return 0;
1124 }
1125
1126 int del_def_xattr_acl(const char *fname)
1127 {
1128         return sys_lremovexattr(fname, XDEF_ACL_ATTR);
1129 }
1130 #endif
1131
1132 int get_stat_xattr(const char *fname, int fd, STRUCT_STAT *fst, STRUCT_STAT *xst)
1133 {
1134         unsigned int mode;
1135         int rdev_major, rdev_minor, uid, gid, len;
1136         char buf[256];
1137
1138         if (am_root >= 0 || IS_DEVICE(fst->st_mode) || IS_SPECIAL(fst->st_mode))
1139                 return -1;
1140
1141         if (xst)
1142                 *xst = *fst;
1143         else
1144                 xst = fst;
1145         if (fname) {
1146                 fd = -1;
1147                 len = sys_lgetxattr(fname, XSTAT_ATTR, buf, sizeof buf - 1);
1148         } else {
1149                 fname = "fd";
1150                 len = sys_fgetxattr(fd, XSTAT_ATTR, buf, sizeof buf - 1);
1151         }
1152         if (len >= (int)sizeof buf) {
1153                 len = -1;
1154                 errno = ERANGE;
1155         }
1156         if (len < 0) {
1157                 if (errno == ENOTSUP || errno == ENOATTR)
1158                         return -1;
1159                 if (errno == EPERM && S_ISLNK(fst->st_mode)) {
1160                         xst->st_uid = 0;
1161                         xst->st_gid = 0;
1162                         return 0;
1163                 }
1164                 rsyserr(FERROR_XFER, errno, "failed to read xattr %s for %s",
1165                         XSTAT_ATTR, full_fname(fname));
1166                 return -1;
1167         }
1168         buf[len] = '\0';
1169
1170         if (sscanf(buf, "%o %d,%d %d:%d",
1171                    &mode, &rdev_major, &rdev_minor, &uid, &gid) != 5) {
1172                 rprintf(FERROR, "Corrupt %s xattr attached to %s: \"%s\"\n",
1173                         XSTAT_ATTR, full_fname(fname), buf);
1174                 exit_cleanup(RERR_FILEIO);
1175         }
1176
1177         xst->st_mode = from_wire_mode(mode);
1178         xst->st_rdev = MAKEDEV(rdev_major, rdev_minor);
1179         xst->st_uid = uid;
1180         xst->st_gid = gid;
1181
1182         return 0;
1183 }
1184
1185 int set_stat_xattr(const char *fname, struct file_struct *file, mode_t new_mode)
1186 {
1187         STRUCT_STAT fst, xst;
1188         dev_t rdev;
1189         mode_t mode, fmode;
1190
1191         if (dry_run)
1192                 return 0;
1193
1194         if (read_only || list_only) {
1195                 rsyserr(FERROR_XFER, EROFS, "failed to write xattr %s for %s",
1196                         XSTAT_ATTR, full_fname(fname));
1197                 return -1;
1198         }
1199
1200         if (x_lstat(fname, &fst, &xst) < 0) {
1201                 rsyserr(FERROR_XFER, errno, "failed to re-stat %s",
1202                         full_fname(fname));
1203                 return -1;
1204         }
1205
1206         fst.st_mode &= (_S_IFMT | CHMOD_BITS);
1207         fmode = new_mode & (_S_IFMT | CHMOD_BITS);
1208
1209         if (IS_DEVICE(fmode)) {
1210                 uint32 *devp = F_RDEV_P(file);
1211                 rdev = MAKEDEV(DEV_MAJOR(devp), DEV_MINOR(devp));
1212         } else
1213                 rdev = 0;
1214
1215         /* Dump the special permissions and enable full owner access. */
1216         mode = (fst.st_mode & _S_IFMT) | (fmode & ACCESSPERMS)
1217              | (S_ISDIR(fst.st_mode) ? 0700 : 0600);
1218         if (fst.st_mode != mode)
1219                 do_chmod(fname, mode);
1220         if (!IS_DEVICE(fst.st_mode))
1221                 fst.st_rdev = 0; /* just in case */
1222
1223         if (mode == fmode && fst.st_rdev == rdev
1224          && fst.st_uid == F_OWNER(file) && fst.st_gid == F_GROUP(file)) {
1225                 /* xst.st_mode will be 0 if there's no current stat xattr */
1226                 if (xst.st_mode && sys_lremovexattr(fname, XSTAT_ATTR) < 0) {
1227                         rsyserr(FERROR_XFER, errno,
1228                                 "delete of stat xattr failed for %s",
1229                                 full_fname(fname));
1230                         return -1;
1231                 }
1232                 return 0;
1233         }
1234
1235         if (xst.st_mode != fmode || xst.st_rdev != rdev
1236          || xst.st_uid != F_OWNER(file) || xst.st_gid != F_GROUP(file)) {
1237                 char buf[256];
1238                 int len = snprintf(buf, sizeof buf, "%o %u,%u %u:%u",
1239                         to_wire_mode(fmode),
1240                         (int)major(rdev), (int)minor(rdev),
1241                         F_OWNER(file), F_GROUP(file));
1242                 if (sys_lsetxattr(fname, XSTAT_ATTR, buf, len) < 0) {
1243                         if (errno == EPERM && S_ISLNK(fst.st_mode))
1244                                 return 0;
1245                         rsyserr(FERROR_XFER, errno,
1246                                 "failed to write xattr %s for %s",
1247                                 XSTAT_ATTR, full_fname(fname));
1248                         return -1;
1249                 }
1250         }
1251
1252         return 0;
1253 }
1254
1255 int x_stat(const char *fname, STRUCT_STAT *fst, STRUCT_STAT *xst)
1256 {
1257         int ret = do_stat(fname, fst);
1258         if ((ret < 0 || get_stat_xattr(fname, -1, fst, xst) < 0) && xst)
1259                 xst->st_mode = 0;
1260         return ret;
1261 }
1262
1263 int x_lstat(const char *fname, STRUCT_STAT *fst, STRUCT_STAT *xst)
1264 {
1265         int ret = do_lstat(fname, fst);
1266         if ((ret < 0 || get_stat_xattr(fname, -1, fst, xst) < 0) && xst)
1267                 xst->st_mode = 0;
1268         return ret;
1269 }
1270
1271 int x_fstat(int fd, STRUCT_STAT *fst, STRUCT_STAT *xst)
1272 {
1273         int ret = do_fstat(fd, fst);
1274         if ((ret < 0 || get_stat_xattr(NULL, fd, fst, xst) < 0) && xst)
1275                 xst->st_mode = 0;
1276         return ret;
1277 }
1278
1279 #endif /* SUPPORT_XATTRS */