Debian Codegraph @

rsync.c

raw symbols SCIP
1 /*
2 * Routines common to more than one of the rsync processes.
3 *
4 * Copyright (C) 1996 Andrew Tridgell
5 * Copyright (C) 1996 Paul Mackerras
6 * Copyright (C) 2003-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 #if defined HAVE_LIBCHARSET_H && defined HAVE_LOCALE_CHARSET
25 #include <libcharset.h>
26 #elif defined HAVE_LANGINFO_H && defined HAVE_NL_LANGINFO
27 #include <langinfo.h>
28 #endif
29
30 extern int dry_run;
31 extern int preserve_acls;
32 extern int preserve_xattrs;
33 extern int preserve_perms;
34 extern int preserve_executability;
35 extern int preserve_mtimes;
36 extern int omit_dir_times;
37 extern int omit_link_times;
38 extern int am_root;
39 extern int am_server;
40 extern int operator_path_resolve;
41 extern int am_daemon;
42 extern int am_sender;
43 extern int am_receiver;
44 extern int am_generator;
45 extern int am_starting_up;
46 extern int allow_8bit_chars;
47 extern int protocol_version;
48 extern int got_kill_signal;
49 extern int called_from_signal_handler;
50 extern int inc_recurse;
51 extern int inplace;
52 extern int flist_eof;
53 extern int file_old_total;
54 extern int keep_dirlinks;
55 extern int make_backups;
56 extern int sanitize_paths;
57 extern struct file_list *cur_flist, *first_flist, *dir_flist;
58 extern struct chmod_mode_struct *daemon_chmod_modes;
59 #ifdef ICONV_OPTION
60 extern char *iconv_opt;
61 #endif
62
63 #define UPDATED_OWNER (1<<0)
64 #define UPDATED_GROUP (1<<1)
65 #define UPDATED_MTIME (1<<2)
66 #define UPDATED_ATIME (1<<3)
67 #define UPDATED_ACLS (1<<4)
68 #define UPDATED_MODE (1<<5)
69 #define UPDATED_CRTIME (1<<6)
70
71 #ifdef ICONV_CONST
72 iconv_t ic_chck = (iconv_t)-1;
73 # ifdef ICONV_OPTION
74 iconv_t ic_send = (iconv_t)-1, ic_recv = (iconv_t)-1;
75 # endif
76
77 static const char *default_charset(void)
78 {
79 # if defined HAVE_LIBCHARSET_H && defined HAVE_LOCALE_CHARSET
80 return locale_charset();
81 # elif defined HAVE_LANGINFO_H && defined HAVE_NL_LANGINFO
82 return nl_langinfo(CODESET);
83 # else
84 return ""; /* Works with (at the very least) gnu iconv... */
85 # endif
86 }
87
88 void setup_iconv(void)
89 {
90 const char *defset = default_charset();
91 # ifdef ICONV_OPTION
92 const char *charset;
93 char *cp;
94 # endif
95
96 if (!am_server && !allow_8bit_chars) {
97 /* It's OK if this fails... */
98 ic_chck = iconv_open(defset, defset);
99
100 if (DEBUG_GTE(ICONV, 2)) {
101 if (ic_chck == (iconv_t)-1) {
102 rprintf(FINFO,
103 "msg checking via isprint()"
104 " (iconv_open(\"%s\", \"%s\") errno: %d)\n",
105 defset, defset, errno);
106 } else {
107 rprintf(FINFO,
108 "msg checking charset: %s\n",
109 defset);
110 }
111 }
112 } else
113 ic_chck = (iconv_t)-1;
114
115 # ifdef ICONV_OPTION
116 if (!iconv_opt)
117 return;
118
119 if ((cp = strchr(iconv_opt, ',')) != NULL) {
120 if (am_server) /* A local transfer needs this. */
121 iconv_opt = cp + 1;
122 else
123 *cp = '\0';
124 }
125
126 if (!*iconv_opt || (*iconv_opt == '.' && iconv_opt[1] == '\0'))
127 charset = defset;
128 else
129 charset = iconv_opt;
130
131 if ((ic_send = iconv_open(UTF8_CHARSET, charset)) == (iconv_t)-1) {
132 rprintf(FERROR, "iconv_open(\"%s\", \"%s\") failed\n",
133 UTF8_CHARSET, charset);
134 exit_cleanup(RERR_UNSUPPORTED);
135 }
136
137 if ((ic_recv = iconv_open(charset, UTF8_CHARSET)) == (iconv_t)-1) {
138 rprintf(FERROR, "iconv_open(\"%s\", \"%s\") failed\n",
139 charset, UTF8_CHARSET);
140 exit_cleanup(RERR_UNSUPPORTED);
141 }
142
143 if (DEBUG_GTE(ICONV, 1)) {
144 rprintf(FINFO, "[%s] charset: %s\n",
145 who_am_i(), *charset ? charset : "[LOCALE]");
146 }
147 # endif
148 }
149
150 /* This function converts the chars in the "in" xbuf into characters in the
151 * "out" xbuf. The ".len" chars of the "in" xbuf is used starting from its
152 * ".pos". The ".size" of the "out" xbuf restricts how many characters can
153 * be stored, starting at its ".pos+.len" position. Note that the last byte
154 * of the "out" xbuf is not used, which reserves space for a trailing '\0'
155 * (though it is up to the caller to store a trailing '\0', as needed).
156 *
157 * We return a 0 on success or a -1 on error. An error also sets errno to
158 * E2BIG, EILSEQ, or EINVAL (see below); otherwise errno will be set to 0.
159 * The "in" xbuf is altered to update ".pos" and ".len". The "out" xbuf has
160 * data appended, and its ".len" incremented (see below for a ".size" note).
161 *
162 * If ICB_CIRCULAR_OUT is set in "flags", the chars going into the "out" xbuf
163 * can wrap around to the start, and the xbuf may have its ".size" reduced
164 * (presumably by 1 byte) if the iconv code doesn't have space to store a
165 * multi-byte character at the physical end of the ".buf" (though no reducing
166 * happens if ".pos" is <= 1, since there is no room to wrap around).
167 *
168 * If ICB_EXPAND_OUT is set in "flags", the "out" xbuf will be allocated if
169 * empty, and (as long as ICB_CIRCULAR_OUT is not set) expanded if too small.
170 * This prevents the return of E2BIG (except for a circular xbuf).
171 *
172 * If ICB_INCLUDE_BAD is set in "flags", any badly-encoded chars are included
173 * verbatim in the "out" xbuf, so EILSEQ will not be returned.
174 *
175 * If ICB_INCLUDE_INCOMPLETE is set in "flags", any incomplete multi-byte
176 * chars are included, which ensures that EINVAL is not returned.
177 *
178 * If ICB_INIT is set, the iconv() conversion state is initialized prior to
179 * processing the characters. */
180 int iconvbufs(iconv_t ic, xbuf *in, xbuf *out, int flags)
181 {
182 ICONV_CONST char *ibuf;
183 size_t icnt, ocnt, opos;
184 char *obuf;
185
186 if (!out->size && flags & ICB_EXPAND_OUT) {
187 size_t siz = ROUND_UP_1024(in->len * 2);
188 alloc_xbuf(out, siz);
189 } else if (out->len+1 >= out->size) {
190 /* There is no room to even start storing data. */
191 if (!(flags & ICB_EXPAND_OUT) || flags & ICB_CIRCULAR_OUT) {
192 errno = E2BIG;
193 return -1;
194 }
195 realloc_xbuf(out, out->size + ROUND_UP_1024(in->len * 2));
196 }
197
198 if (flags & ICB_INIT)
199 iconv(ic, NULL, 0, NULL, 0);
200
201 ibuf = in->buf + in->pos;
202 icnt = in->len;
203
204 opos = out->pos + out->len;
205 if (flags & ICB_CIRCULAR_OUT) {
206 if (opos >= out->size) {
207 opos -= out->size;
208 /* We know that out->pos is not 0 due to the "no room" check
209 * above, so this can't go "negative". */
210 ocnt = out->pos - opos - 1;
211 } else {
212 /* Allow the use of all bytes to the physical end of the buffer
213 * unless pos is 0, in which case we reserve our trailing '\0'. */
214 ocnt = out->size - opos - (out->pos ? 0 : 1);
215 }
216 } else
217 ocnt = out->size - opos - 1;
218 obuf = out->buf + opos;
219
220 while (icnt) {
221 while (iconv(ic, &ibuf, &icnt, &obuf, &ocnt) == (size_t)-1) {
222 if (errno == EINTR)
223 continue;
224 if (errno == EINVAL) {
225 if (!(flags & ICB_INCLUDE_INCOMPLETE))
226 goto finish;
227 if (!ocnt)
228 goto e2big;
229 } else if (errno == EILSEQ) {
230 if (!(flags & ICB_INCLUDE_BAD))
231 goto finish;
232 if (!ocnt)
233 goto e2big;
234 } else if (errno == E2BIG) {
235 size_t siz;
236 e2big:
237 opos = obuf - out->buf;
238 if (flags & ICB_CIRCULAR_OUT && out->pos > 1 && opos > out->pos) {
239 /* We are in a divided circular buffer at the physical
240 * end with room to wrap to the start. If iconv() refused
241 * to use one or more trailing bytes in the buffer, we
242 * set the size to ignore the unused bytes. */
243 if (opos < out->size)
244 reduce_iobuf_size(out, opos);
245 obuf = out->buf;
246 ocnt = out->pos - 1;
247 continue;
248 }
249 if (!(flags & ICB_EXPAND_OUT) || flags & ICB_CIRCULAR_OUT) {
250 errno = E2BIG;
251 goto finish;
252 }
253 siz = ROUND_UP_1024(in->len * 2);
254 realloc_xbuf(out, out->size + siz);
255 obuf = out->buf + opos;
256 ocnt += siz;
257 continue;
258 } else {
259 rsyserr(FERROR, errno, "unexpected error from iconv()");
260 exit_cleanup(RERR_UNSUPPORTED);
261 }
262 *obuf++ = *ibuf++;
263 ocnt--, icnt--;
264 if (!icnt)
265 break;
266 }
267 }
268
269 errno = 0;
270
271 finish:
272 opos = obuf - out->buf;
273 if (flags & ICB_CIRCULAR_OUT && opos < out->pos)
274 opos += out->size;
275 out->len = opos - out->pos;
276
277 in->len = icnt;
278 in->pos = ibuf - in->buf;
279
280 return errno ? -1 : 0;
281 }
282 #endif
283
284 void send_protected_args(int fd, char *args[])
285 {
286 int i;
287 #ifdef ICONV_OPTION
288 int convert = ic_send != (iconv_t)-1;
289 xbuf outbuf, inbuf;
290
291 if (convert)
292 alloc_xbuf(&outbuf, 1024);
293 #endif
294
295 for (i = 0; args[i]; i++) {} /* find first NULL */
296 args[i] = "rsync"; /* set a new arg0 */
297 if (DEBUG_GTE(CMD, 1))
298 print_child_argv("protected args:", args + i + 1);
299 do {
300 if (!args[i][0])
301 write_buf(fd, ".", 2);
302 #ifdef ICONV_OPTION
303 else if (convert) {
304 INIT_XBUF_STRLEN(inbuf, args[i]);
305 iconvbufs(ic_send, &inbuf, &outbuf,
306 ICB_EXPAND_OUT | ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE | ICB_INIT);
307 outbuf.buf[outbuf.len] = '\0';
308 write_buf(fd, outbuf.buf, outbuf.len + 1);
309 outbuf.len = 0;
310 }
311 #endif
312 else
313 write_buf(fd, args[i], strlen(args[i]) + 1);
314 } while (args[++i]);
315 write_byte(fd, 0);
316
317 #ifdef ICONV_OPTION
318 if (convert)
319 free(outbuf.buf);
320 #endif
321 }
322
323 int read_ndx_and_attrs(int f_in, int f_out, int *iflag_ptr, uchar *type_ptr, char *buf, int *len_ptr)
324 {
325 int len, iflags = 0;
326 struct file_list *flist;
327 uchar fnamecmp_type = FNAMECMP_FNAME;
328 int ndx;
329
330 read_loop:
331 while (1) {
332 ndx = read_ndx(f_in);
333
334 if (ndx >= 0)
335 break;
336 if (ndx == NDX_DONE)
337 return ndx;
338 if (ndx == NDX_DEL_STATS) {
339 read_del_stats(f_in);
340 if (am_sender && am_server)
341 write_del_stats(f_out);
342 continue;
343 }
344 if (!inc_recurse || am_sender) {
345 int last;
346 if (first_flist)
347 last = first_flist->prev->ndx_start + first_flist->prev->used - 1;
348 else
349 last = -1;
350 rprintf(FERROR,
351 "Invalid file index: %d (%d - %d) [%s]\n",
352 ndx, NDX_DONE, last, who_am_i());
353 exit_cleanup(RERR_PROTOCOL);
354 }
355 if (ndx == NDX_FLIST_EOF) {
356 flist_eof = 1;
357 if (DEBUG_GTE(FLIST, 3))
358 rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
359 write_int(f_out, NDX_FLIST_EOF);
360 continue;
361 }
362 ndx = NDX_FLIST_OFFSET - ndx;
363 if (ndx < 0 || ndx >= dir_flist->used) {
364 ndx = NDX_FLIST_OFFSET - ndx;
365 rprintf(FERROR,
366 "Invalid dir index: %d (%d - %d) [%s]\n",
367 ndx, NDX_FLIST_OFFSET,
368 NDX_FLIST_OFFSET - dir_flist->used + 1,
369 who_am_i());
370 exit_cleanup(RERR_PROTOCOL);
371 }
372
373 if (DEBUG_GTE(FLIST, 2)) {
374 rprintf(FINFO, "[%s] receiving flist for dir %d\n",
375 who_am_i(), ndx);
376 }
377 /* Send all the data we read for this flist to the generator. */
378 start_flist_forward(ndx);
379 flist = recv_file_list(f_in, ndx);
380 flist->parent_ndx = ndx;
381 stop_flist_forward();
382 }
383
384 iflags = protocol_version >= 29 ? read_shortint(f_in)
385 : ITEM_TRANSFER | ITEM_MISSING_DATA;
386
387 /* Support the protocol-29 keep-alive style. */
388 if (protocol_version < 30 && ndx == cur_flist->used && iflags == ITEM_IS_NEW) {
389 if (am_sender)
390 maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH);
391 goto read_loop;
392 }
393
394 flist = flist_for_ndx(ndx, "read_ndx_and_attrs");
395 if (flist != cur_flist) {
396 cur_flist = flist;
397 if (am_sender) {
398 file_old_total = cur_flist->used;
399 for (flist = first_flist; flist != cur_flist; flist = flist->next)
400 file_old_total += flist->used;
401 }
402 }
403
404 if (iflags & ITEM_BASIS_TYPE_FOLLOWS)
405 fnamecmp_type = read_byte(f_in);
406 *type_ptr = fnamecmp_type;
407
408 if (iflags & ITEM_XNAME_FOLLOWS) {
409 if ((len = read_vstring(f_in, buf, MAXPATHLEN)) < 0)
410 exit_cleanup(RERR_PROTOCOL);
411
412 /* For a basis type (FNAMECMP_FUZZY and the alt-dest FNAMECMP_FUZZY+N)
413 * the xname is a peer-supplied leaf name that the receiver joins to
414 * an operator-chosen basedir (--link-dest / --compare-dest /
415 * --copy-dest, or the fuzzy dir) and opens as the delta basis. It
416 * must never contain a ".." (or leading "/") that escapes that dir:
417 * a malicious sender could otherwise walk the receiver's filesystem
418 * -- e.g. --link-dest=/backup with an xname of "../../etc/shadow" --
419 * and read an out-of-tree file as the basis (client-side
420 * arbitrary-read / FIFO-hang). Sanitize it always, not only in the
421 * daemon (sanitize_paths) case: the operator basedir may legitimately
422 * be relative (#915), but the wire-supplied leaf never needs "..".
423 * Only the basis types use xname as a path; other ITEM_XNAME_FOLLOWS
424 * uses (the hard-link "=> target" display name, which is often empty)
425 * are not paths and must be left byte-for-byte. */
426 if (fnamecmp_type >= FNAMECMP_FUZZY) {
427 sanitize_path(buf, buf, "", 0, SP_DEFAULT);
428 len = strlen(buf);
429 }
430 } else {
431 *buf = '\0';
432 len = -1;
433 }
434 *len_ptr = len;
435
436 if (iflags & ITEM_TRANSFER) {
437 int i = ndx - cur_flist->ndx_start;
438 if (i < 0 || !S_ISREG(cur_flist->files[i]->mode)) {
439 rprintf(FERROR,
440 "received request to transfer non-regular file: %d [%s]\n",
441 ndx, who_am_i());
442 exit_cleanup(RERR_PROTOCOL);
443 }
444 }
445
446 *iflag_ptr = iflags;
447 return ndx;
448 }
449
450 /*
451 free a sums struct
452 */
453 void free_sums(struct sum_struct *s)
454 {
455 if (s->sums) {
456 free(s->sums);
457 free(s->sum2_array);
458 }
459 free(s);
460 }
461
462 /* This is only called when we aren't preserving permissions. Figure out what
463 * the permissions should be and return them merged back into the mode. */
464 mode_t dest_mode(mode_t flist_mode, mode_t stat_mode, int dflt_perms,
465 int exists)
466 {
467 int new_mode;
468 /* If the file already exists, we'll return the local permissions,
469 * possibly tweaked by the --executability option. */
470 if (exists) {
471 new_mode = (flist_mode & ~CHMOD_BITS) | (stat_mode & CHMOD_BITS);
472 if (preserve_executability && S_ISREG(flist_mode)) {
473 /* If the source file is executable, grant execute
474 * rights to everyone who can read, but ONLY if the
475 * file isn't already executable. */
476 if (!(flist_mode & 0111))
477 new_mode &= ~0111;
478 else if (!(stat_mode & 0111))
479 new_mode |= (new_mode & 0444) >> 2;
480 }
481 } else {
482 /* Apply destination default permissions and turn
483 * off special permissions. */
484 new_mode = flist_mode & (~CHMOD_BITS | dflt_perms);
485 }
486 return new_mode;
487 }
488
489 static int same_mtime(struct file_struct *file, STRUCT_STAT *st, int extra_accuracy)
490 {
491 #ifdef ST_MTIME_NSEC
492 uint32 f1_nsec = F_MOD_NSEC_or_0(file);
493 uint32 f2_nsec = (uint32)st->ST_MTIME_NSEC;
494 #else
495 uint32 f1_nsec = 0, f2_nsec = 0;
496 #endif
497
498 if (extra_accuracy) /* ignore modify_window when setting the time after a transfer or checksum check */
499 return file->modtime == st->st_mtime && f1_nsec == f2_nsec;
500
501 return same_time(file->modtime, f1_nsec, st->st_mtime , f2_nsec);
502 }
503
504 int set_file_attrs(const char *fname, struct file_struct *file, stat_x *sxp,
505 const char *fnamecmp, int flags)
506 {
507 int updated = 0;
508 stat_x sx2;
509 int change_uid, change_gid;
510 mode_t new_mode = file->mode;
511 int inherit;
512 int dfd = -1; /* held dir fd for the entry's own dir, or -1 */
513 const char *leaf = NULL; /* leaf of fname relative to dfd */
514 int op_leaf_fd = -1; /* O_NOFOLLOW fd pinning a cross-tree operator leaf */
515 int op_pin = 0; /* drive chmod/chown off op_leaf_fd for a cross-tree leaf */
516 int op_refuse = 0; /* pin open hit the symlink-race signal: refuse, don't redirect */
517 #if defined SUPPORT_XATTRS || defined SUPPORT_ACLS
518 int held_fd = -1; /* held O_NOFOLLOW fd for fd-based xattr/ACL ops, or -1 */
519 int xattr_refuse = 0; /* no confined fd for a slashed path: skip path-based xattr/ACL */
520 #endif
521
522 if (!sxp) {
523 int sret, sdfd;
524 if (dry_run)
525 return 1;
526 /* Stat through the entry's held dir fd (like gen_entry_stat) so we
527 * don't re-walk the full path here; link_stat_at folds in no
528 * fake-super xattr, so only when am_root >= 0. */
529 if (am_root >= 0 && (sdfd = held_dfd_for(fname, file)) >= 0) {
530 const char *sl = strrchr(fname, '/');
531 sret = link_stat_at(sdfd, sl ? sl + 1 : fname, &sx2.st, 0);
532 } else
533 sret = link_stat(fname, &sx2.st, 0);
534 if (sret < 0) {
535 rsyserr(FERROR_XFER, errno, "stat %s failed",
536 full_fname(fname));
537 return 0;
538 }
539 init_stat_x(&sx2);
540 sxp = &sx2;
541 inherit = !preserve_perms;
542 } else
543 inherit = !preserve_perms && file->flags & FLAG_DIR_CREATED;
544
545 /* Resolve the entry's directory once; the chown/chmod/times ops below
546 * issue single-component *at() calls against it instead of re-resolving
547 * the full path each time. -1 => fall back to the full-path wrappers
548 * (cross-tree path such as --temp-dir/--backup-dir, or gated off). */
549 dfd = held_dfd_for(fname, file);
550 if (dfd >= 0) {
551 const char *slash = strrchr(fname, '/');
552 leaf = slash ? slash + 1 : fname;
553 }
554
555 #if defined SUPPORT_XATTRS || defined SUPPORT_ACLS
556 /* Pin a regular-file/dir/fifo entry via the held dir fd with O_NOFOLLOW so
557 * the xattr/ACL ops below act on the held inode (sys_f*xattr/fsetxattr),
558 * not a re-resolved path a parent-symlink race could redirect. O_NONBLOCK
559 * stops a raced FIFO blocking the open; O_NOFOLLOW refuses a raced symlink
560 * leaf. A symlink/socket/device leaf or no held dfd leaves held_fd == -1,
561 * and the ACL code then uses setxattrat(AT_SYMLINK_NOFOLLOW) or falls back.
562 * Under --fake-super the ACL store stays an l-variant xattr and ignores it. */
563 if (dfd >= 0
564 && (S_ISREG(sxp->st.st_mode) || S_ISDIR(sxp->st.st_mode) || S_ISFIFO(sxp->st.st_mode))
565 && (preserve_xattrs || am_root < 0
566 # ifdef SUPPORT_ACLS
567 || (preserve_acls && am_root >= 0)
568 # endif
569 ))
570 held_fd = openat(dfd, leaf, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_NOCTTY | O_CLOEXEC);
571
572 /* If the held-fd pin above missed (no cached dir fd -- a path deeper than the
573 * dirfd cache, or a raced leaf) but we are a confined receiver on a
574 * non-operator path, re-pin the leaf through the secure resolver so the
575 * xattr/ACL ops below drive fsetxattr off a confined fd -- NOT a raw path-based
576 * lsetxattr, which re-resolves the parent and lets a flipped dest/sub symlink
577 * land the xattr OUTSIDE the tree (copy-xattrs-symlink-race). If the secure
578 * re-pin also fails (a genuinely raced parent/leaf symlink), held_fd stays -1
579 * and xattr_refuse skips the path-based ops rather than redirecting them.
580 * (chmod/chown/times stay safe via their secure path wrappers; operator paths
581 * use op_pin/op_refuse below.) */
582 if (held_fd < 0 && !operator_path_resolve && secure_relpath_active()
583 && (S_ISREG(sxp->st.st_mode) || S_ISDIR(sxp->st.st_mode) || S_ISFIFO(sxp->st.st_mode))
584 && (preserve_xattrs || am_root < 0
585 # ifdef SUPPORT_ACLS
586 || (preserve_acls && am_root >= 0)
587 # endif
588 )) {
589 int odir = 0;
590 # ifdef O_DIRECTORY
591 if (S_ISDIR(sxp->st.st_mode))
592 odir = O_DIRECTORY;
593 # endif
594 held_fd = secure_relative_open(NULL, fname,
595 O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_NOCTTY | O_CLOEXEC | odir, 0);
596 if (held_fd < 0 && strchr(fname, '/'))
597 xattr_refuse = 1;
598 }
599 #endif
600
601 /* A cross-tree operator path (an absolute --backup-dir/--temp-dir/--*-dest
602 * leaf) has no held parent dfd, so the chmod/chown below would re-resolve the
603 * full path and could follow a parent component an attacker flips to a
604 * symlink mid-operation -- and an lchown through such a component even retags
605 * the planted symlink as ours (trust laundering that then defeats the
606 * owner-walk). Pin the leaf inode itself with an O_NOFOLLOW open via the
607 * operator owner-walk resolver and drive fchmod/fchown off that fd. A raced
608 * symlink leaf makes the open fail, leaving op_leaf_fd == -1: the metadata op
609 * is then refused, never redirected. --insecure-links opts back out (the
610 * resolver in do_open_at honours it), and a genuine symlink leaf (a symlink
611 * backup) keeps the existing l-variant path. */
612 /* Gate on the INTENDED type (new_mode), not the on-disk type (sxp->st): the
613 * attacker controls the latter via the flip, and a dir component that has
614 * just been flipped to a symlink must still take the pinned path so the
615 * O_NOFOLLOW open refuses it -- otherwise the lchown would launder it. */
616 op_pin = operator_path_resolve && dfd < 0 && !symlink_optout_allowed()
617 && (S_ISREG(new_mode) || S_ISDIR(new_mode) || S_ISFIFO(new_mode));
618 if (op_pin) {
619 op_leaf_fd = do_open_at(fname, O_RDONLY | O_NONBLOCK | O_NOCTTY | O_CLOEXEC, 0);
620 /* When running as root (the uid-0 trust-laundering case) an O_RDONLY open
621 * of a real owned reg/dir/fifo leaf never fails for permission reasons, so
622 * ANY failure here means the leaf is being raced (a symlink refused by
623 * O_NOFOLLOW / owner-walk -> ELOOP, or vanished mid-flip -> ENOENT):
624 * refuse, never redirect via a re-resolvable path. --fake-super
625 * (am_root < 0) is the same: the daemon owns the freshly-staged leaf it is
626 * about to set %stat/ACL/xattr metadata on, so any open failure is a race
627 * -- refuse rather than fall through to a path-based sys_lsetxattr that a
628 * flipped parent could redirect outside the module. A plain non-root
629 * operator (am_root == 0) can still hit a legitimate EACCES on an
630 * owned-but-unreadable leaf; there we only treat the explicit symlink-race
631 * signal (ELOOP) as a refusal and otherwise fall back to the legacy path
632 * op rather than spuriously failing a real file. */
633 if (op_leaf_fd < 0 && (am_root != 0 || errno == ELOOP))
634 op_refuse = 1;
635 #if defined SUPPORT_XATTRS || defined SUPPORT_ACLS
636 if (op_leaf_fd >= 0)
637 held_fd = op_leaf_fd; /* xattr/ACL ops below pin to this leaf fd too */
638 #endif
639 }
640
641 if (inherit && S_ISDIR(new_mode) && sxp->st.st_mode & S_ISGID) {
642 /* We just created this directory and its setgid
643 * bit is on, so make sure it stays on. */
644 new_mode |= S_ISGID;
645 }
646
647 if (daemon_chmod_modes && !S_ISLNK(new_mode))
648 new_mode = tweak_mode(new_mode, daemon_chmod_modes);
649
650 #ifdef SUPPORT_ACLS
651 if (preserve_acls && !S_ISLNK(file->mode) && !ACL_READY(*sxp) && !op_refuse && !xattr_refuse)
652 get_acl_fdat(held_fd, dfd, leaf, fname, sxp);
653 #endif
654
655 change_uid = am_root && uid_ndx && sxp->st.st_uid != (uid_t)F_OWNER(file);
656 change_gid = gid_ndx && !(file->flags & FLAG_SKIP_GROUP)
657 && sxp->st.st_gid != (gid_t)F_GROUP(file);
658 #ifndef CAN_CHOWN_SYMLINK
659 if (S_ISLNK(sxp->st.st_mode)) {
660 ;
661 } else
662 #endif
663 if (change_uid || change_gid) {
664 if (DEBUG_GTE(OWN, 1)) {
665 if (change_uid) {
666 rprintf(FINFO,
667 "set uid of %s from %u to %u\n",
668 fname, (unsigned)sxp->st.st_uid, F_OWNER(file));
669 }
670 if (change_gid) {
671 rprintf(FINFO,
672 "set gid of %s from %u to %u\n",
673 fname, (unsigned)sxp->st.st_gid, F_GROUP(file));
674 }
675 }
676 if (am_root >= 0) {
677 uid_t uid = change_uid ? (uid_t)F_OWNER(file) : sxp->st.st_uid;
678 gid_t gid = change_gid ? (gid_t)F_GROUP(file) : sxp->st.st_gid;
679 if ((op_leaf_fd >= 0 ? do_fchown(op_leaf_fd, uid, gid)
680 : op_refuse ? (errno = ELOOP, -1)
681 : dfd >= 0 ? do_lchown_atfd(dfd, leaf, uid, gid)
682 : do_lchown_at(fname, uid, gid)) != 0) {
683 /* We shouldn't have attempted to change uid
684 * or gid unless have the privilege. */
685 rsyserr(FERROR_XFER, errno, "%s %s failed",
686 change_uid ? "chown" : "chgrp",
687 full_fname(fname));
688 goto cleanup;
689 }
690 if (uid == (uid_t)-1 && sxp->st.st_uid != (uid_t)-1)
691 rprintf(FERROR_XFER, "uid 4294967295 (-1) is impossible to set on %s\n", full_fname(fname));
692 if (gid == (gid_t)-1 && sxp->st.st_gid != (gid_t)-1)
693 rprintf(FERROR_XFER, "gid 4294967295 (-1) is impossible to set on %s\n", full_fname(fname));
694 /* A lchown had been done, so we need to re-stat if
695 * the destination had the setuid or setgid bits set
696 * (due to the side effect of the chown call). */
697 if (sxp->st.st_mode & (S_ISUID | S_ISGID)) {
698 if (dfd >= 0)
699 link_stat_at(dfd, leaf, &sxp->st,
700 keep_dirlinks && S_ISDIR(sxp->st.st_mode));
701 else
702 link_stat(fname, &sxp->st,
703 keep_dirlinks && S_ISDIR(sxp->st.st_mode));
704 }
705 }
706 if (change_uid)
707 updated |= UPDATED_OWNER;
708 if (change_gid)
709 updated |= UPDATED_GROUP;
710 }
711
712 #ifdef SUPPORT_XATTRS
713 if (am_root < 0 && !op_refuse && !xattr_refuse)
714 set_stat_xattr(fname, file, new_mode, held_fd);
715 if (preserve_xattrs && fnamecmp && !op_refuse && !xattr_refuse)
716 set_xattr(fname, file, fnamecmp, sxp, held_fd);
717 #endif
718
719 if ((omit_dir_times && S_ISDIR(sxp->st.st_mode))
720 || (omit_link_times && S_ISLNK(sxp->st.st_mode)))
721 flags |= ATTRS_SKIP_MTIME | ATTRS_SKIP_ATIME | ATTRS_SKIP_CRTIME;
722 else {
723 if (!preserve_mtimes)
724 flags |= ATTRS_SKIP_MTIME;
725 if (!atimes_ndx || S_ISDIR(sxp->st.st_mode))
726 flags |= ATTRS_SKIP_ATIME;
727 /* Don't set the creation date on the root folder of an HFS+ volume. */
728 if (sxp->st.st_ino == 2 && S_ISDIR(sxp->st.st_mode))
729 flags |= ATTRS_SKIP_CRTIME;
730 }
731 if (sxp != &sx2)
732 memcpy(&sx2.st, &sxp->st, sizeof sx2.st);
733 if (!(flags & ATTRS_SKIP_MTIME) && !same_mtime(file, &sxp->st, flags & ATTRS_ACCURATE_TIME)) {
734 sx2.st.st_mtime = file->modtime;
735 #ifdef ST_MTIME_NSEC
736 sx2.st.ST_MTIME_NSEC = F_MOD_NSEC_or_0(file);
737 #endif
738 updated |= UPDATED_MTIME;
739 }
740 if (!(flags & ATTRS_SKIP_ATIME)) {
741 time_t file_atime = F_ATIME(file);
742 if (flags & ATTRS_ACCURATE_TIME || !same_time(sxp->st.st_atime, 0, file_atime, 0)) {
743 sx2.st.st_atime = file_atime;
744 #ifdef ST_ATIME_NSEC
745 sx2.st.ST_ATIME_NSEC = 0;
746 #endif
747 updated |= UPDATED_ATIME;
748 }
749 }
750 #ifdef SUPPORT_CRTIMES
751 if (crtimes_ndx && !(flags & ATTRS_SKIP_CRTIME)) {
752 time_t file_crtime = F_CRTIME(file);
753 if (sxp->crtime == 0)
754 sxp->crtime = get_create_time(fname, &sxp->st);
755 if (!same_time(sxp->crtime, 0L, file_crtime, 0L)) {
756 if (
757 #ifdef HAVE_GETATTRLIST
758 do_setattrlist_crtime(fname, file_crtime) == 0
759 #elif defined __CYGWIN__
760 do_SetFileTime(fname, file_crtime) == 0
761 #else
762 #error Unknown crtimes implementation
763 #endif
764 )
765 updated |= UPDATED_CRTIME;
766 }
767 }
768 #endif
769 if (updated & (UPDATED_MTIME|UPDATED_ATIME)) {
770 int ret;
771 #ifdef HAVE_FUTIMENS
772 if (op_leaf_fd >= 0)
773 ret = do_futimens(op_leaf_fd, &sx2.st);
774 else
775 #endif
776 if (op_refuse)
777 ret = (errno = ELOOP, -1);
778 else {
779 ret = dfd >= 0 ? set_times_at(dfd, leaf, &sx2.st) : -2;
780 if (ret == -2)
781 ret = set_times(fname, &sx2.st);
782 }
783 if (ret < 0) {
784 rsyserr(FERROR_XFER, errno, "failed to set times on %s", full_fname(fname));
785 goto cleanup;
786 }
787 if (ret > 0) { /* ret == 1 if symlink could not be set */
788 updated &= ~(UPDATED_MTIME|UPDATED_ATIME);
789 file->flags |= FLAG_TIME_FAILED;
790 }
791 }
792
793 #ifdef SUPPORT_ACLS
794 /* It's OK to call set_acl() now, even for a dir, as the generator
795 * will enable owner-writability using chmod, if necessary.
796 *
797 * If set_acl() changes permission bits in the process of setting
798 * an access ACL, it changes sxp->st.st_mode so we know whether we
799 * need to chmod(). */
800 if (preserve_acls && !S_ISLNK(new_mode) && !op_refuse && !xattr_refuse) {
801 if (set_acl_fdat(held_fd, dfd, leaf, fname, file, sxp, new_mode) > 0)
802 updated |= UPDATED_ACLS;
803 }
804 #endif
805
806 #ifdef HAVE_CHMOD
807 if (!BITS_EQUAL(sxp->st.st_mode, new_mode, CHMOD_BITS)) {
808 int ret = am_root < 0 ? 0
809 : op_leaf_fd >= 0 ? do_fchmod(op_leaf_fd, new_mode)
810 : op_refuse ? (errno = ELOOP, -1)
811 : dfd >= 0 && !S_ISLNK(new_mode) ? do_chmod_atfd(dfd, leaf, new_mode)
812 : do_chmod_at(fname, new_mode);
813 if (ret < 0) {
814 rsyserr(FERROR_XFER, errno,
815 "failed to set permissions on %s",
816 full_fname(fname));
817 goto cleanup;
818 }
819 if (ret == 0) /* ret == 1 if symlink could not be set */
820 updated |= UPDATED_MODE;
821 }
822 #endif
823
824 if (INFO_GTE(NAME, 2) && flags & ATTRS_REPORT) {
825 if (updated)
826 rprintf(FCLIENT, "%s\n", fname);
827 else
828 rprintf(FCLIENT, "%s is uptodate\n", fname);
829 }
830 cleanup:
831 #if defined SUPPORT_XATTRS || defined SUPPORT_ACLS
832 if (held_fd >= 0 && held_fd != op_leaf_fd) /* may alias op_leaf_fd (cross-tree) */
833 close(held_fd);
834 #endif
835 if (op_leaf_fd >= 0)
836 close(op_leaf_fd);
837 if (sxp == &sx2)
838 free_stat_x(&sx2);
839 return updated;
840 }
841
842 /* This is only called for SIGINT, SIGHUP, and SIGTERM. */
843 void sig_int(int sig_num)
844 {
845 called_from_signal_handler = 1;
846
847 /* KLUGE: if the user hits Ctrl-C while ssh is prompting
848 * for a password, then our cleanup's sending of a SIGUSR1
849 * signal to all our children may kill ssh before it has a
850 * chance to restore the tty settings (i.e. turn echo back
851 * on). By sleeping for a short time, ssh gets a bigger
852 * chance to do the right thing. If child processes are
853 * not ssh waiting for a password, then this tiny delay
854 * shouldn't hurt anything. */
855 msleep(400);
856
857 /* If we're an rsync daemon listener (not a daemon server),
858 * we'll exit with status 0 if we received SIGTERM. */
859 if (am_daemon && !am_server && sig_num == SIGTERM)
860 exit_cleanup(0);
861
862 /* If the signal arrived on the server side (or for the receiver
863 * process on the client), we want to try to do a controlled shutdown
864 * that lets the client side (generator process) know what happened.
865 * To do this, we set a flag and let the normal process handle the
866 * shutdown. We only attempt this if multiplexed IO is in effect and
867 * we didn't already set the flag. */
868 if (!got_kill_signal && (am_server || am_receiver)) {
869 got_kill_signal = sig_num;
870 called_from_signal_handler = 0;
871 return;
872 }
873
874 exit_cleanup(RERR_SIGNAL);
875 }
876
877 /* Finish off a file transfer: renaming the file and setting the file's
878 * attributes (e.g. permissions, ownership, etc.). If the robust_rename()
879 * call is forced to copy the temp file and partialptr is both non-NULL and
880 * not an absolute path, we stage the file into the partial-dir and then
881 * rename it into place. This returns 1 on success or 0 on failure. */
882 int finish_transfer(const char *fname, const char *fnametmp,
883 const char *fnamecmp, const char *partialptr,
884 struct file_struct *file, int ok_to_set_time,
885 int overwriting_basis)
886 {
887 int ret;
888 const char *temp_copy_name = partialptr && *partialptr != '/' ? partialptr : NULL;
889
890 if (inplace) {
891 if (DEBUG_GTE(RECV, 1))
892 rprintf(FINFO, "finishing %s\n", fname);
893 fnametmp = fname;
894 goto do_set_file_attrs;
895 }
896
897 if (make_backups > 0 && overwriting_basis) {
898 int ok = make_backup(fname, False);
899 if (!ok)
900 exit_cleanup(RERR_FILEIO);
901 if (ok == 1 && fnamecmp == fname)
902 fnamecmp = get_backup_name(fname);
903 }
904
905 /* Change permissions before putting the file into place. An absolute
906 * --temp-dir/--partial-dir leaves fnametmp on an operator path with no held
907 * dirfd, so resolve its metadata through the ownership walk (op_pin); a
908 * flipped temp-dir parent then can't redirect the chmod/chown/times/etc.
909 * (in-tree temps keep their held dirfd, so op_pin stays off there). */
910 operator_path_resolve = 1;
911 set_file_attrs(fnametmp, file, NULL, fnamecmp,
912 ok_to_set_time ? ATTRS_ACCURATE_TIME : ATTRS_SKIP_MTIME | ATTRS_SKIP_ATIME | ATTRS_SKIP_CRTIME);
913 operator_path_resolve = 0;
914
915 /* move tmp file over real file */
916 if (DEBUG_GTE(RECV, 1))
917 rprintf(FINFO, "renaming %s to %s\n", fnametmp, fname);
918 ret = robust_rename(fnametmp, fname, temp_copy_name, file->mode, file);
919 if (ret < 0) {
920 rsyserr(FERROR_XFER, errno, "%s %s -> \"%s\"",
921 ret == -2 ? "copy" : "rename",
922 full_fname(fnametmp), fname);
923 if (!partialptr || (ret == -2 && temp_copy_name)
924 || robust_rename(fnametmp, partialptr, NULL, file->mode, file) < 0)
925 do_unlink_at(fnametmp);
926 return 0;
927 }
928 if (ret == 0) {
929 /* The file was moved into place (not copied), so it's done. */
930 return 1;
931 }
932 /* The file was copied, so tweak the perms of the copied file. If it
933 * was copied to partialptr, move it into its final destination. */
934 fnametmp = temp_copy_name ? temp_copy_name : fname;
935
936 do_set_file_attrs:
937 set_file_attrs(fnametmp, file, NULL, fnamecmp,
938 ok_to_set_time ? ATTRS_ACCURATE_TIME : ATTRS_SKIP_MTIME | ATTRS_SKIP_ATIME | ATTRS_SKIP_CRTIME);
939
940 if (temp_copy_name) {
941 if (do_rename_at(fnametmp, fname) < 0) {
942 rsyserr(FERROR_XFER, errno, "rename %s -> \"%s\"",
943 full_fname(fnametmp), fname);
944 return 0;
945 }
946 handle_partial_dir(temp_copy_name, PDIR_DELETE);
947 }
948 return 1;
949 }
950
951 struct file_list *flist_for_ndx(int ndx, const char *fatal_error_loc)
952 {
953 struct file_list *flist = cur_flist;
954
955 if (!flist && !(flist = first_flist))
956 goto not_found;
957
958 while (ndx < flist->ndx_start-1) {
959 if (flist == first_flist)
960 goto not_found;
961 flist = flist->prev;
962 }
963 while (ndx >= flist->ndx_start + flist->used) {
964 if (!(flist = flist->next))
965 goto not_found;
966 }
967 return flist;
968
969 not_found:
970 if (fatal_error_loc) {
971 int first, last;
972 if (first_flist) {
973 first = first_flist->ndx_start - 1;
974 last = first_flist->prev->ndx_start + first_flist->prev->used - 1;
975 } else {
976 first = 0;
977 last = -1;
978 }
979 rprintf(FERROR,
980 "File-list index %d not in %d - %d (%s) [%s]\n",
981 ndx, first, last, fatal_error_loc, who_am_i());
982 exit_cleanup(RERR_PROTOCOL);
983 }
984 return NULL;
985 }
986
987 const char *who_am_i(void)
988 {
989 if (am_starting_up)
990 return am_server ? "server" : "client";
991 return am_sender ? "sender"
992 : am_generator ? "generator"
993 : am_receiver ? "receiver"
994 : "Receiver"; /* pre-forked receiver */
995 }