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