2 * Routines common to more than one of the rsync processes.
4 * Copyright (C) 1996 Andrew Tridgell
5 * Copyright (C) 1996 Paul Mackerras
6 * Copyright (C) 2003-2018 Wayne Davison
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.
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.
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.
24 #if defined HAVE_LIBCHARSET_H && defined HAVE_LOCALE_CHARSET
25 #include <libcharset.h>
26 #elif defined HAVE_LANGINFO_H && defined HAVE_NL_LANGINFO
31 extern int preserve_acls;
32 extern int preserve_xattrs;
33 extern int preserve_perms;
34 extern int preserve_executability;
35 extern int preserve_times;
40 extern int am_receiver;
41 extern int am_generator;
42 extern int am_starting_up;
43 extern int allow_8bit_chars;
44 extern int protocol_version;
45 extern int got_kill_signal;
46 extern int inc_recurse;
49 extern int file_old_total;
50 extern int keep_dirlinks;
51 extern int make_backups;
52 extern int sanitize_paths;
53 extern struct file_list *cur_flist, *first_flist, *dir_flist;
54 extern struct chmod_mode_struct *daemon_chmod_modes;
56 extern char *iconv_opt;
60 iconv_t ic_chck = (iconv_t)-1;
62 iconv_t ic_send = (iconv_t)-1, ic_recv = (iconv_t)-1;
65 static const char *default_charset(void)
67 # if defined HAVE_LIBCHARSET_H && defined HAVE_LOCALE_CHARSET
68 return locale_charset();
69 # elif defined HAVE_LANGINFO_H && defined HAVE_NL_LANGINFO
70 return nl_langinfo(CODESET);
72 return ""; /* Works with (at the very least) gnu iconv... */
76 void setup_iconv(void)
78 const char *defset = default_charset();
84 if (!am_server && !allow_8bit_chars) {
85 /* It's OK if this fails... */
86 ic_chck = iconv_open(defset, defset);
88 if (DEBUG_GTE(ICONV, 2)) {
89 if (ic_chck == (iconv_t)-1) {
91 "msg checking via isprint()"
92 " (iconv_open(\"%s\", \"%s\") errno: %d)\n",
93 defset, defset, errno);
96 "msg checking charset: %s\n",
101 ic_chck = (iconv_t)-1;
107 if ((cp = strchr(iconv_opt, ',')) != NULL) {
108 if (am_server) /* A local transfer needs this. */
114 if (!*iconv_opt || (*iconv_opt == '.' && iconv_opt[1] == '\0'))
119 if ((ic_send = iconv_open(UTF8_CHARSET, charset)) == (iconv_t)-1) {
120 rprintf(FERROR, "iconv_open(\"%s\", \"%s\") failed\n",
121 UTF8_CHARSET, charset);
122 exit_cleanup(RERR_UNSUPPORTED);
125 if ((ic_recv = iconv_open(charset, UTF8_CHARSET)) == (iconv_t)-1) {
126 rprintf(FERROR, "iconv_open(\"%s\", \"%s\") failed\n",
127 charset, UTF8_CHARSET);
128 exit_cleanup(RERR_UNSUPPORTED);
131 if (DEBUG_GTE(ICONV, 1)) {
132 rprintf(FINFO, "[%s] charset: %s\n",
133 who_am_i(), *charset ? charset : "[LOCALE]");
138 /* This function converts the chars in the "in" xbuf into characters in the
139 * "out" xbuf. The ".len" chars of the "in" xbuf is used starting from its
140 * ".pos". The ".size" of the "out" xbuf restricts how many characters can
141 * be stored, starting at its ".pos+.len" position. Note that the last byte
142 * of the "out" xbuf is not used, which reserves space for a trailing '\0'
143 * (though it is up to the caller to store a trailing '\0', as needed).
145 * We return a 0 on success or a -1 on error. An error also sets errno to
146 * E2BIG, EILSEQ, or EINVAL (see below); otherwise errno will be set to 0.
147 * The "in" xbuf is altered to update ".pos" and ".len". The "out" xbuf has
148 * data appended, and its ".len" incremented (see below for a ".size" note).
150 * If ICB_CIRCULAR_OUT is set in "flags", the chars going into the "out" xbuf
151 * can wrap around to the start, and the xbuf may have its ".size" reduced
152 * (presumably by 1 byte) if the iconv code doesn't have space to store a
153 * multi-byte character at the physical end of the ".buf" (though no reducing
154 * happens if ".pos" is <= 1, since there is no room to wrap around).
156 * If ICB_EXPAND_OUT is set in "flags", the "out" xbuf will be allocated if
157 * empty, and (as long as ICB_CIRCULAR_OUT is not set) expanded if too small.
158 * This prevents the return of E2BIG (except for a circular xbuf).
160 * If ICB_INCLUDE_BAD is set in "flags", any badly-encoded chars are included
161 * verbatim in the "out" xbuf, so EILSEQ will not be returned.
163 * If ICB_INCLUDE_INCOMPLETE is set in "flags", any incomplete multi-byte
164 * chars are included, which ensures that EINVAL is not returned.
166 * If ICB_INIT is set, the iconv() conversion state is initialized prior to
167 * processing the characters. */
168 int iconvbufs(iconv_t ic, xbuf *in, xbuf *out, int flags)
170 ICONV_CONST char *ibuf;
171 size_t icnt, ocnt, opos;
174 if (!out->size && flags & ICB_EXPAND_OUT) {
175 size_t siz = ROUND_UP_1024(in->len * 2);
176 alloc_xbuf(out, siz);
177 } else if (out->len+1 >= out->size) {
178 /* There is no room to even start storing data. */
179 if (!(flags & ICB_EXPAND_OUT) || flags & ICB_CIRCULAR_OUT) {
183 realloc_xbuf(out, out->size + ROUND_UP_1024(in->len * 2));
186 if (flags & ICB_INIT)
187 iconv(ic, NULL, 0, NULL, 0);
189 ibuf = in->buf + in->pos;
192 opos = out->pos + out->len;
193 if (flags & ICB_CIRCULAR_OUT) {
194 if (opos >= out->size) {
196 /* We know that out->pos is not 0 due to the "no room" check
197 * above, so this can't go "negative". */
198 ocnt = out->pos - opos - 1;
200 /* Allow the use of all bytes to the physical end of the buffer
201 * unless pos is 0, in which case we reserve our trailing '\0'. */
202 ocnt = out->size - opos - (out->pos ? 0 : 1);
205 ocnt = out->size - opos - 1;
206 obuf = out->buf + opos;
209 while (iconv(ic, &ibuf, &icnt, &obuf, &ocnt) == (size_t)-1) {
212 if (errno == EINVAL) {
213 if (!(flags & ICB_INCLUDE_INCOMPLETE))
217 } else if (errno == EILSEQ) {
218 if (!(flags & ICB_INCLUDE_BAD))
222 } else if (errno == E2BIG) {
225 opos = obuf - out->buf;
226 if (flags & ICB_CIRCULAR_OUT && out->pos > 1 && opos > out->pos) {
227 /* We are in a divided circular buffer at the physical
228 * end with room to wrap to the start. If iconv() refused
229 * to use one or more trailing bytes in the buffer, we
230 * set the size to ignore the unused bytes. */
231 if (opos < out->size)
232 reduce_iobuf_size(out, opos);
237 if (!(flags & ICB_EXPAND_OUT) || flags & ICB_CIRCULAR_OUT) {
241 siz = ROUND_UP_1024(in->len * 2);
242 realloc_xbuf(out, out->size + siz);
243 obuf = out->buf + opos;
247 rsyserr(FERROR, errno, "unexpected error from iconv()");
248 exit_cleanup(RERR_UNSUPPORTED);
260 opos = obuf - out->buf;
261 if (flags & ICB_CIRCULAR_OUT && opos < out->pos)
263 out->len = opos - out->pos;
266 in->pos = ibuf - in->buf;
268 return errno ? -1 : 0;
272 void send_protected_args(int fd, char *args[])
276 int convert = ic_send != (iconv_t)-1;
280 alloc_xbuf(&outbuf, 1024);
283 for (i = 0; args[i]; i++) {} /* find first NULL */
284 args[i] = "rsync"; /* set a new arg0 */
285 if (DEBUG_GTE(CMD, 1))
286 print_child_argv("protected args:", args + i + 1);
289 write_buf(fd, ".", 2);
292 INIT_XBUF_STRLEN(inbuf, args[i]);
293 iconvbufs(ic_send, &inbuf, &outbuf,
294 ICB_EXPAND_OUT | ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE | ICB_INIT);
295 outbuf.buf[outbuf.len] = '\0';
296 write_buf(fd, outbuf.buf, outbuf.len + 1);
301 write_buf(fd, args[i], strlen(args[i]) + 1);
311 int read_ndx_and_attrs(int f_in, int f_out, int *iflag_ptr, uchar *type_ptr,
312 char *buf, int *len_ptr)
315 struct file_list *flist;
316 uchar fnamecmp_type = FNAMECMP_FNAME;
321 ndx = read_ndx(f_in);
327 if (ndx == NDX_DEL_STATS) {
328 read_del_stats(f_in);
329 if (am_sender && am_server)
330 write_del_stats(f_out);
333 if (!inc_recurse || am_sender) {
336 last = first_flist->prev->ndx_start + first_flist->prev->used - 1;
340 "Invalid file index: %d (%d - %d) [%s]\n",
341 ndx, NDX_DONE, last, who_am_i());
342 exit_cleanup(RERR_PROTOCOL);
344 if (ndx == NDX_FLIST_EOF) {
346 if (DEBUG_GTE(FLIST, 3))
347 rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
348 write_int(f_out, NDX_FLIST_EOF);
351 ndx = NDX_FLIST_OFFSET - ndx;
352 if (ndx < 0 || ndx >= dir_flist->used) {
353 ndx = NDX_FLIST_OFFSET - ndx;
355 "Invalid dir index: %d (%d - %d) [%s]\n",
356 ndx, NDX_FLIST_OFFSET,
357 NDX_FLIST_OFFSET - dir_flist->used + 1,
359 exit_cleanup(RERR_PROTOCOL);
362 if (DEBUG_GTE(FLIST, 2)) {
363 rprintf(FINFO, "[%s] receiving flist for dir %d\n",
366 /* Send all the data we read for this flist to the generator. */
367 start_flist_forward(ndx);
368 flist = recv_file_list(f_in, ndx);
369 flist->parent_ndx = ndx;
370 stop_flist_forward();
373 iflags = protocol_version >= 29 ? read_shortint(f_in)
374 : ITEM_TRANSFER | ITEM_MISSING_DATA;
376 /* Support the protocol-29 keep-alive style. */
377 if (protocol_version < 30 && ndx == cur_flist->used && iflags == ITEM_IS_NEW) {
379 maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH);
383 flist = flist_for_ndx(ndx, "read_ndx_and_attrs");
384 if (flist != cur_flist) {
387 file_old_total = cur_flist->used;
388 for (flist = first_flist; flist != cur_flist; flist = flist->next)
389 file_old_total += flist->used;
393 if (iflags & ITEM_BASIS_TYPE_FOLLOWS)
394 fnamecmp_type = read_byte(f_in);
395 *type_ptr = fnamecmp_type;
397 if (iflags & ITEM_XNAME_FOLLOWS) {
398 if ((len = read_vstring(f_in, buf, MAXPATHLEN)) < 0)
399 exit_cleanup(RERR_PROTOCOL);
401 if (sanitize_paths) {
402 sanitize_path(buf, buf, "", 0, SP_DEFAULT);
411 if (iflags & ITEM_TRANSFER) {
412 int i = ndx - cur_flist->ndx_start;
413 if (i < 0 || !S_ISREG(cur_flist->files[i]->mode)) {
415 "received request to transfer non-regular file: %d [%s]\n",
417 exit_cleanup(RERR_PROTOCOL);
428 void free_sums(struct sum_struct *s)
430 if (s->sums) free(s->sums);
434 /* This is only called when we aren't preserving permissions. Figure out what
435 * the permissions should be and return them merged back into the mode. */
436 mode_t dest_mode(mode_t flist_mode, mode_t stat_mode, int dflt_perms,
440 /* If the file already exists, we'll return the local permissions,
441 * possibly tweaked by the --executability option. */
443 new_mode = (flist_mode & ~CHMOD_BITS) | (stat_mode & CHMOD_BITS);
444 if (preserve_executability && S_ISREG(flist_mode)) {
445 /* If the source file is executable, grant execute
446 * rights to everyone who can read, but ONLY if the
447 * file isn't already executable. */
448 if (!(flist_mode & 0111))
450 else if (!(stat_mode & 0111))
451 new_mode |= (new_mode & 0444) >> 2;
454 /* Apply destination default permissions and turn
455 * off special permissions. */
456 new_mode = flist_mode & (~CHMOD_BITS | dflt_perms);
461 int set_file_attrs(const char *fname, struct file_struct *file, stat_x *sxp,
462 const char *fnamecmp, int flags)
466 int change_uid, change_gid;
467 mode_t new_mode = file->mode;
473 if (link_stat(fname, &sx2.st, 0) < 0) {
474 rsyserr(FERROR_XFER, errno, "stat %s failed",
480 inherit = !preserve_perms;
482 inherit = !preserve_perms && file->flags & FLAG_DIR_CREATED;
484 if (inherit && S_ISDIR(new_mode) && sxp->st.st_mode & S_ISGID) {
485 /* We just created this directory and its setgid
486 * bit is on, so make sure it stays on. */
490 if (daemon_chmod_modes && !S_ISLNK(new_mode))
491 new_mode = tweak_mode(new_mode, daemon_chmod_modes);
494 if (preserve_acls && !S_ISLNK(file->mode) && !ACL_READY(*sxp))
498 change_uid = am_root && uid_ndx && sxp->st.st_uid != (uid_t)F_OWNER(file);
499 change_gid = gid_ndx && !(file->flags & FLAG_SKIP_GROUP)
500 && sxp->st.st_gid != (gid_t)F_GROUP(file);
501 #ifndef CAN_CHOWN_SYMLINK
502 if (S_ISLNK(sxp->st.st_mode)) {
506 if (change_uid || change_gid) {
507 if (DEBUG_GTE(OWN, 1)) {
510 "set uid of %s from %u to %u\n",
511 fname, (unsigned)sxp->st.st_uid, F_OWNER(file));
515 "set gid of %s from %u to %u\n",
516 fname, (unsigned)sxp->st.st_gid, F_GROUP(file));
520 uid_t uid = change_uid ? (uid_t)F_OWNER(file) : sxp->st.st_uid;
521 gid_t gid = change_gid ? (gid_t)F_GROUP(file) : sxp->st.st_gid;
522 if (do_lchown(fname, uid, gid) != 0) {
523 /* We shouldn't have attempted to change uid
524 * or gid unless have the privilege. */
525 rsyserr(FERROR_XFER, errno, "%s %s failed",
526 change_uid ? "chown" : "chgrp",
530 if (uid == (uid_t)-1 && sxp->st.st_uid != (uid_t)-1)
531 rprintf(FERROR_XFER, "uid 4294967295 (-1) is impossible to set on %s\n", full_fname(fname));
532 if (gid == (gid_t)-1 && sxp->st.st_gid != (gid_t)-1)
533 rprintf(FERROR_XFER, "gid 4294967295 (-1) is impossible to set on %s\n", full_fname(fname));
534 /* A lchown had been done, so we need to re-stat if
535 * the destination had the setuid or setgid bits set
536 * (due to the side effect of the chown call). */
537 if (sxp->st.st_mode & (S_ISUID | S_ISGID)) {
538 link_stat(fname, &sxp->st,
539 keep_dirlinks && S_ISDIR(sxp->st.st_mode));
545 #ifdef SUPPORT_XATTRS
547 set_stat_xattr(fname, file, new_mode);
548 if (preserve_xattrs && fnamecmp)
549 set_xattr(fname, file, fnamecmp, sxp);
553 || (!(preserve_times & PRESERVE_DIR_TIMES) && S_ISDIR(sxp->st.st_mode))
554 || (!(preserve_times & PRESERVE_LINK_TIMES) && S_ISLNK(sxp->st.st_mode)))
555 flags |= ATTRS_SKIP_MTIME;
556 if (!(flags & ATTRS_SKIP_MTIME)
557 && (sxp->st.st_mtime != file->modtime
559 || (flags & ATTRS_SET_NANO && NSEC_BUMP(file) && (uint32)sxp->st.ST_MTIME_NSEC != F_MOD_NSEC(file))
562 int ret = set_modtime(fname, file->modtime, F_MOD_NSEC(file), sxp->st.st_mode);
564 rsyserr(FERROR_XFER, errno, "failed to set times on %s",
568 if (ret == 0) /* ret == 1 if symlink could not be set */
571 file->flags |= FLAG_TIME_FAILED;
575 /* It's OK to call set_acl() now, even for a dir, as the generator
576 * will enable owner-writability using chmod, if necessary.
578 * If set_acl() changes permission bits in the process of setting
579 * an access ACL, it changes sxp->st.st_mode so we know whether we
580 * need to chmod(). */
581 if (preserve_acls && !S_ISLNK(new_mode)) {
582 if (set_acl(fname, file, sxp, new_mode) > 0)
588 if (!BITS_EQUAL(sxp->st.st_mode, new_mode, CHMOD_BITS)) {
589 int ret = am_root < 0 ? 0 : do_chmod(fname, new_mode);
591 rsyserr(FERROR_XFER, errno,
592 "failed to set permissions on %s",
596 if (ret == 0) /* ret == 1 if symlink could not be set */
601 if (INFO_GTE(NAME, 2) && flags & ATTRS_REPORT) {
603 rprintf(FCLIENT, "%s\n", fname);
605 rprintf(FCLIENT, "%s is uptodate\n", fname);
613 /* This is only called for SIGINT, SIGHUP, and SIGTERM. */
614 void sig_int(int sig_num)
616 /* KLUGE: if the user hits Ctrl-C while ssh is prompting
617 * for a password, then our cleanup's sending of a SIGUSR1
618 * signal to all our children may kill ssh before it has a
619 * chance to restore the tty settings (i.e. turn echo back
620 * on). By sleeping for a short time, ssh gets a bigger
621 * chance to do the right thing. If child processes are
622 * not ssh waiting for a password, then this tiny delay
623 * shouldn't hurt anything. */
626 /* If we're an rsync daemon listener (not a daemon server),
627 * we'll exit with status 0 if we received SIGTERM. */
628 if (am_daemon && !am_server && sig_num == SIGTERM)
631 /* If the signal arrived on the server side (or for the receiver
632 * process on the client), we want to try to do a controlled shutdown
633 * that lets the client side (generator process) know what happened.
634 * To do this, we set a flag and let the normal process handle the
635 * shutdown. We only attempt this if multiplexed IO is in effect and
636 * we didn't already set the flag. */
637 if (!got_kill_signal && (am_server || am_receiver)) {
638 got_kill_signal = sig_num;
642 exit_cleanup(RERR_SIGNAL);
645 /* Finish off a file transfer: renaming the file and setting the file's
646 * attributes (e.g. permissions, ownership, etc.). If the robust_rename()
647 * call is forced to copy the temp file and partialptr is both non-NULL and
648 * not an absolute path, we stage the file into the partial-dir and then
649 * rename it into place. This returns 1 on succcess or 0 on failure. */
650 int finish_transfer(const char *fname, const char *fnametmp,
651 const char *fnamecmp, const char *partialptr,
652 struct file_struct *file, int ok_to_set_time,
653 int overwriting_basis)
656 const char *temp_copy_name = partialptr && *partialptr != '/' ? partialptr : NULL;
659 if (DEBUG_GTE(RECV, 1))
660 rprintf(FINFO, "finishing %s\n", fname);
662 goto do_set_file_attrs;
665 if (make_backups > 0 && overwriting_basis) {
666 int ok = make_backup(fname, False);
668 exit_cleanup(RERR_FILEIO);
669 if (ok == 1 && fnamecmp == fname)
670 fnamecmp = get_backup_name(fname);
673 /* Change permissions before putting the file into place. */
674 set_file_attrs(fnametmp, file, NULL, fnamecmp,
675 ok_to_set_time ? ATTRS_SET_NANO : ATTRS_SKIP_MTIME);
677 /* move tmp file over real file */
678 if (DEBUG_GTE(RECV, 1))
679 rprintf(FINFO, "renaming %s to %s\n", fnametmp, fname);
680 ret = robust_rename(fnametmp, fname, temp_copy_name, file->mode);
682 rsyserr(FERROR_XFER, errno, "%s %s -> \"%s\"",
683 ret == -2 ? "copy" : "rename",
684 full_fname(fnametmp), fname);
685 if (!partialptr || (ret == -2 && temp_copy_name)
686 || robust_rename(fnametmp, partialptr, NULL, file->mode) < 0)
691 /* The file was moved into place (not copied), so it's done. */
694 /* The file was copied, so tweak the perms of the copied file. If it
695 * was copied to partialptr, move it into its final destination. */
696 fnametmp = temp_copy_name ? temp_copy_name : fname;
699 set_file_attrs(fnametmp, file, NULL, fnamecmp,
700 ok_to_set_time ? ATTRS_SET_NANO : ATTRS_SKIP_MTIME);
702 if (temp_copy_name) {
703 if (do_rename(fnametmp, fname) < 0) {
704 rsyserr(FERROR_XFER, errno, "rename %s -> \"%s\"",
705 full_fname(fnametmp), fname);
708 handle_partial_dir(temp_copy_name, PDIR_DELETE);
713 struct file_list *flist_for_ndx(int ndx, const char *fatal_error_loc)
715 struct file_list *flist = cur_flist;
717 if (!flist && !(flist = first_flist))
720 while (ndx < flist->ndx_start-1) {
721 if (flist == first_flist)
725 while (ndx >= flist->ndx_start + flist->used) {
726 if (!(flist = flist->next))
732 if (fatal_error_loc) {
735 first = first_flist->ndx_start - 1;
736 last = first_flist->prev->ndx_start + first_flist->prev->used - 1;
742 "File-list index %d not in %d - %d (%s) [%s]\n",
743 ndx, first, last, fatal_error_loc, who_am_i());
744 exit_cleanup(RERR_PROTOCOL);
749 const char *who_am_i(void)
752 return am_server ? "server" : "client";
753 return am_sender ? "sender"
754 : am_generator ? "generator"
755 : am_receiver ? "receiver"
756 : "Receiver"; /* pre-forked receiver */