AVX2 optimized version of get_checksum1() for x86-64
[rsync.git] / rsync.c
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-2020 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_times;
36 extern int am_root;
37 extern int am_server;
38 extern int am_daemon;
39 extern int am_sender;
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 called_from_signal_handler;
47 extern int inc_recurse;
48 extern int inplace;
49 extern int flist_eof;
50 extern int file_old_total;
51 extern int keep_dirlinks;
52 extern int make_backups;
53 extern int sanitize_paths;
54 extern struct file_list *cur_flist, *first_flist, *dir_flist;
55 extern struct chmod_mode_struct *daemon_chmod_modes;
56 #ifdef ICONV_OPTION
57 extern char *iconv_opt;
58 #endif
59
60 #ifdef ICONV_CONST
61 iconv_t ic_chck = (iconv_t)-1;
62 # ifdef ICONV_OPTION
63 iconv_t ic_send = (iconv_t)-1, ic_recv = (iconv_t)-1;
64 # endif
65
66 #define UPDATED_OWNER (1<<0)
67 #define UPDATED_GROUP (1<<1)
68 #define UPDATED_MTIME (1<<2)
69 #define UPDATED_ATIME (1<<3)
70 #define UPDATED_ACLS  (1<<4)
71 #define UPDATED_MODE  (1<<5)
72
73 #define UPDATED_TIMES (UPDATED_MTIME|UPDATED_ATIME)
74
75 static const char *default_charset(void)
76 {
77 # if defined HAVE_LIBCHARSET_H && defined HAVE_LOCALE_CHARSET
78         return locale_charset();
79 # elif defined HAVE_LANGINFO_H && defined HAVE_NL_LANGINFO
80         return nl_langinfo(CODESET);
81 # else
82         return ""; /* Works with (at the very least) gnu iconv... */
83 # endif
84 }
85
86 void setup_iconv(void)
87 {
88         const char *defset = default_charset();
89 # ifdef ICONV_OPTION
90         const char *charset;
91         char *cp;
92 # endif
93
94         if (!am_server && !allow_8bit_chars) {
95                 /* It's OK if this fails... */
96                 ic_chck = iconv_open(defset, defset);
97
98                 if (DEBUG_GTE(ICONV, 2)) {
99                         if (ic_chck == (iconv_t)-1) {
100                                 rprintf(FINFO,
101                                         "msg checking via isprint()"
102                                         " (iconv_open(\"%s\", \"%s\") errno: %d)\n",
103                                         defset, defset, errno);
104                         } else {
105                                 rprintf(FINFO,
106                                         "msg checking charset: %s\n",
107                                         defset);
108                         }
109                 }
110         } else
111                 ic_chck = (iconv_t)-1;
112
113 # ifdef ICONV_OPTION
114         if (!iconv_opt)
115                 return;
116
117         if ((cp = strchr(iconv_opt, ',')) != NULL) {
118                 if (am_server) /* A local transfer needs this. */
119                         iconv_opt = cp + 1;
120                 else
121                         *cp = '\0';
122         }
123
124         if (!*iconv_opt || (*iconv_opt == '.' && iconv_opt[1] == '\0'))
125                 charset = defset;
126         else
127                 charset = iconv_opt;
128
129         if ((ic_send = iconv_open(UTF8_CHARSET, charset)) == (iconv_t)-1) {
130                 rprintf(FERROR, "iconv_open(\"%s\", \"%s\") failed\n",
131                         UTF8_CHARSET, charset);
132                 exit_cleanup(RERR_UNSUPPORTED);
133         }
134
135         if ((ic_recv = iconv_open(charset, UTF8_CHARSET)) == (iconv_t)-1) {
136                 rprintf(FERROR, "iconv_open(\"%s\", \"%s\") failed\n",
137                         charset, UTF8_CHARSET);
138                 exit_cleanup(RERR_UNSUPPORTED);
139         }
140
141         if (DEBUG_GTE(ICONV, 1)) {
142                 rprintf(FINFO, "[%s] charset: %s\n",
143                         who_am_i(), *charset ? charset : "[LOCALE]");
144         }
145 # endif
146 }
147
148 /* This function converts the chars in the "in" xbuf into characters in the
149  * "out" xbuf.  The ".len" chars of the "in" xbuf is used starting from its
150  * ".pos".  The ".size" of the "out" xbuf restricts how many characters can
151  * be stored, starting at its ".pos+.len" position.  Note that the last byte
152  * of the "out" xbuf is not used, which reserves space for a trailing '\0'
153  * (though it is up to the caller to store a trailing '\0', as needed).
154  *
155  * We return a 0 on success or a -1 on error.  An error also sets errno to
156  * E2BIG, EILSEQ, or EINVAL (see below); otherwise errno will be set to 0.
157  * The "in" xbuf is altered to update ".pos" and ".len".  The "out" xbuf has
158  * data appended, and its ".len" incremented (see below for a ".size" note).
159  *
160  * If ICB_CIRCULAR_OUT is set in "flags", the chars going into the "out" xbuf
161  * can wrap around to the start, and the xbuf may have its ".size" reduced
162  * (presumably by 1 byte) if the iconv code doesn't have space to store a
163  * multi-byte character at the physical end of the ".buf" (though no reducing
164  * happens if ".pos" is <= 1, since there is no room to wrap around).
165  *
166  * If ICB_EXPAND_OUT is set in "flags", the "out" xbuf will be allocated if
167  * empty, and (as long as ICB_CIRCULAR_OUT is not set) expanded if too small.
168  * This prevents the return of E2BIG (except for a circular xbuf).
169  *
170  * If ICB_INCLUDE_BAD is set in "flags", any badly-encoded chars are included
171  * verbatim in the "out" xbuf, so EILSEQ will not be returned.
172  *
173  * If ICB_INCLUDE_INCOMPLETE is set in "flags", any incomplete multi-byte
174  * chars are included, which ensures that EINVAL is not returned.
175  *
176  * If ICB_INIT is set, the iconv() conversion state is initialized prior to
177  * processing the characters. */
178 int iconvbufs(iconv_t ic, xbuf *in, xbuf *out, int flags)
179 {
180         ICONV_CONST char *ibuf;
181         size_t icnt, ocnt, opos;
182         char *obuf;
183
184         if (!out->size && flags & ICB_EXPAND_OUT) {
185                 size_t siz = ROUND_UP_1024(in->len * 2);
186                 alloc_xbuf(out, siz);
187         } else if (out->len+1 >= out->size) {
188                 /* There is no room to even start storing data. */
189                 if (!(flags & ICB_EXPAND_OUT) || flags & ICB_CIRCULAR_OUT) {
190                         errno = E2BIG;
191                         return -1;
192                 }
193                 realloc_xbuf(out, out->size + ROUND_UP_1024(in->len * 2));
194         }
195
196         if (flags & ICB_INIT)
197                 iconv(ic, NULL, 0, NULL, 0);
198
199         ibuf = in->buf + in->pos;
200         icnt = in->len;
201
202         opos = out->pos + out->len;
203         if (flags & ICB_CIRCULAR_OUT) {
204                 if (opos >= out->size) {
205                         opos -= out->size;
206                         /* We know that out->pos is not 0 due to the "no room" check
207                          * above, so this can't go "negative". */
208                         ocnt = out->pos - opos - 1;
209                 } else {
210                         /* Allow the use of all bytes to the physical end of the buffer
211                          * unless pos is 0, in which case we reserve our trailing '\0'. */
212                         ocnt = out->size - opos - (out->pos ? 0 : 1);
213                 }
214         } else
215                 ocnt = out->size - opos - 1;
216         obuf = out->buf + opos;
217
218         while (icnt) {
219                 while (iconv(ic, &ibuf, &icnt, &obuf, &ocnt) == (size_t)-1) {
220                         if (errno == EINTR)
221                                 continue;
222                         if (errno == EINVAL) {
223                                 if (!(flags & ICB_INCLUDE_INCOMPLETE))
224                                         goto finish;
225                                 if (!ocnt)
226                                         goto e2big;
227                         } else if (errno == EILSEQ) {
228                                 if (!(flags & ICB_INCLUDE_BAD))
229                                         goto finish;
230                                 if (!ocnt)
231                                         goto e2big;
232                         } else if (errno == E2BIG) {
233                                 size_t siz;
234                           e2big:
235                                 opos = obuf - out->buf;
236                                 if (flags & ICB_CIRCULAR_OUT && out->pos > 1 && opos > out->pos) {
237                                         /* We are in a divided circular buffer at the physical
238                                          * end with room to wrap to the start.  If iconv() refused
239                                          * to use one or more trailing bytes in the buffer, we
240                                          * set the size to ignore the unused bytes. */
241                                         if (opos < out->size)
242                                                 reduce_iobuf_size(out, opos);
243                                         obuf = out->buf;
244                                         ocnt = out->pos - 1;
245                                         continue;
246                                 }
247                                 if (!(flags & ICB_EXPAND_OUT) || flags & ICB_CIRCULAR_OUT) {
248                                         errno = E2BIG;
249                                         goto finish;
250                                 }
251                                 siz = ROUND_UP_1024(in->len * 2);
252                                 realloc_xbuf(out, out->size + siz);
253                                 obuf = out->buf + opos;
254                                 ocnt += siz;
255                                 continue;
256                         } else {
257                                 rsyserr(FERROR, errno, "unexpected error from iconv()");
258                                 exit_cleanup(RERR_UNSUPPORTED);
259                         }
260                         *obuf++ = *ibuf++;
261                         ocnt--, icnt--;
262                         if (!icnt)
263                                 break;
264                 }
265         }
266
267         errno = 0;
268
269   finish:
270         opos = obuf - out->buf;
271         if (flags & ICB_CIRCULAR_OUT && opos < out->pos)
272                 opos += out->size;
273         out->len = opos - out->pos;
274
275         in->len = icnt;
276         in->pos = ibuf - in->buf;
277
278         return errno ? -1 : 0;
279 }
280 #endif
281
282 void send_protected_args(int fd, char *args[])
283 {
284         int i;
285 #ifdef ICONV_OPTION
286         int convert = ic_send != (iconv_t)-1;
287         xbuf outbuf, inbuf;
288
289         if (convert)
290                 alloc_xbuf(&outbuf, 1024);
291 #endif
292
293         for (i = 0; args[i]; i++) {} /* find first NULL */
294         args[i] = "rsync"; /* set a new arg0 */
295         if (DEBUG_GTE(CMD, 1))
296                 print_child_argv("protected args:", args + i + 1);
297         do {
298                 if (!args[i][0])
299                         write_buf(fd, ".", 2);
300 #ifdef ICONV_OPTION
301                 else if (convert) {
302                         INIT_XBUF_STRLEN(inbuf, args[i]);
303                         iconvbufs(ic_send, &inbuf, &outbuf,
304                                   ICB_EXPAND_OUT | ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE | ICB_INIT);
305                         outbuf.buf[outbuf.len] = '\0';
306                         write_buf(fd, outbuf.buf, outbuf.len + 1);
307                         outbuf.len = 0;
308                 }
309 #endif
310                 else
311                         write_buf(fd, args[i], strlen(args[i]) + 1);
312         } while (args[++i]);
313         write_byte(fd, 0);
314
315 #ifdef ICONV_OPTION
316         if (convert)
317                 free(outbuf.buf);
318 #endif
319 }
320
321 int read_ndx_and_attrs(int f_in, int f_out, int *iflag_ptr, uchar *type_ptr,
322                        char *buf, int *len_ptr)
323 {
324         int len, iflags = 0;
325         struct file_list *flist;
326         uchar fnamecmp_type = FNAMECMP_FNAME;
327         int ndx;
328
329   read_loop:
330         while (1) {
331                 ndx = read_ndx(f_in);
332
333                 if (ndx >= 0)
334                         break;
335                 if (ndx == NDX_DONE)
336                         return ndx;
337                 if (ndx == NDX_DEL_STATS) {
338                         read_del_stats(f_in);
339                         if (am_sender && am_server)
340                                 write_del_stats(f_out);
341                         continue;
342                 }
343                 if (!inc_recurse || am_sender) {
344                         int last;
345                         if (first_flist)
346                                 last = first_flist->prev->ndx_start + first_flist->prev->used - 1;
347                         else
348                                 last = -1;
349                         rprintf(FERROR,
350                                 "Invalid file index: %d (%d - %d) [%s]\n",
351                                 ndx, NDX_DONE, last, who_am_i());
352                         exit_cleanup(RERR_PROTOCOL);
353                 }
354                 if (ndx == NDX_FLIST_EOF) {
355                         flist_eof = 1;
356                         if (DEBUG_GTE(FLIST, 3))
357                                 rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
358                         write_int(f_out, NDX_FLIST_EOF);
359                         continue;
360                 }
361                 ndx = NDX_FLIST_OFFSET - ndx;
362                 if (ndx < 0 || ndx >= dir_flist->used) {
363                         ndx = NDX_FLIST_OFFSET - ndx;
364                         rprintf(FERROR,
365                                 "Invalid dir index: %d (%d - %d) [%s]\n",
366                                 ndx, NDX_FLIST_OFFSET,
367                                 NDX_FLIST_OFFSET - dir_flist->used + 1,
368                                 who_am_i());
369                         exit_cleanup(RERR_PROTOCOL);
370                 }
371
372                 if (DEBUG_GTE(FLIST, 2)) {
373                         rprintf(FINFO, "[%s] receiving flist for dir %d\n",
374                                 who_am_i(), ndx);
375                 }
376                 /* Send all the data we read for this flist to the generator. */
377                 start_flist_forward(ndx);
378                 flist = recv_file_list(f_in, ndx);
379                 flist->parent_ndx = ndx;
380                 stop_flist_forward();
381         }
382
383         iflags = protocol_version >= 29 ? read_shortint(f_in)
384                    : ITEM_TRANSFER | ITEM_MISSING_DATA;
385
386         /* Support the protocol-29 keep-alive style. */
387         if (protocol_version < 30 && ndx == cur_flist->used && iflags == ITEM_IS_NEW) {
388                 if (am_sender)
389                         maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH);
390                 goto read_loop;
391         }
392
393         flist = flist_for_ndx(ndx, "read_ndx_and_attrs");
394         if (flist != cur_flist) {
395                 cur_flist = flist;
396                 if (am_sender) {
397                         file_old_total = cur_flist->used;
398                         for (flist = first_flist; flist != cur_flist; flist = flist->next)
399                                 file_old_total += flist->used;
400                 }
401         }
402
403         if (iflags & ITEM_BASIS_TYPE_FOLLOWS)
404                 fnamecmp_type = read_byte(f_in);
405         *type_ptr = fnamecmp_type;
406
407         if (iflags & ITEM_XNAME_FOLLOWS) {
408                 if ((len = read_vstring(f_in, buf, MAXPATHLEN)) < 0)
409                         exit_cleanup(RERR_PROTOCOL);
410
411                 if (sanitize_paths) {
412                         sanitize_path(buf, buf, "", 0, SP_DEFAULT);
413                         len = strlen(buf);
414                 }
415         } else {
416                 *buf = '\0';
417                 len = -1;
418         }
419         *len_ptr = len;
420
421         if (iflags & ITEM_TRANSFER) {
422                 int i = ndx - cur_flist->ndx_start;
423                 if (i < 0 || !S_ISREG(cur_flist->files[i]->mode)) {
424                         rprintf(FERROR,
425                                 "received request to transfer non-regular file: %d [%s]\n",
426                                 ndx, who_am_i());
427                         exit_cleanup(RERR_PROTOCOL);
428                 }
429         }
430
431         *iflag_ptr = iflags;
432         return ndx;
433 }
434
435 /*
436   free a sums struct
437   */
438 void free_sums(struct sum_struct *s)
439 {
440         if (s->sums) free(s->sums);
441         free(s);
442 }
443
444 /* This is only called when we aren't preserving permissions.  Figure out what
445  * the permissions should be and return them merged back into the mode. */
446 mode_t dest_mode(mode_t flist_mode, mode_t stat_mode, int dflt_perms,
447                  int exists)
448 {
449         int new_mode;
450         /* If the file already exists, we'll return the local permissions,
451          * possibly tweaked by the --executability option. */
452         if (exists) {
453                 new_mode = (flist_mode & ~CHMOD_BITS) | (stat_mode & CHMOD_BITS);
454                 if (preserve_executability && S_ISREG(flist_mode)) {
455                         /* If the source file is executable, grant execute
456                          * rights to everyone who can read, but ONLY if the
457                          * file isn't already executable. */
458                         if (!(flist_mode & 0111))
459                                 new_mode &= ~0111;
460                         else if (!(stat_mode & 0111))
461                                 new_mode |= (new_mode & 0444) >> 2;
462                 }
463         } else {
464                 /* Apply destination default permissions and turn
465                  * off special permissions. */
466                 new_mode = flist_mode & (~CHMOD_BITS | dflt_perms);
467         }
468         return new_mode;
469 }
470
471 int set_file_attrs(const char *fname, struct file_struct *file, stat_x *sxp,
472                    const char *fnamecmp, int flags)
473 {
474         int updated = 0;
475         stat_x sx2;
476         int change_uid, change_gid;
477         mode_t new_mode = file->mode;
478         int inherit;
479
480         if (!sxp) {
481                 if (dry_run)
482                         return 1;
483                 if (link_stat(fname, &sx2.st, 0) < 0) {
484                         rsyserr(FERROR_XFER, errno, "stat %s failed",
485                                 full_fname(fname));
486                         return 0;
487                 }
488                 init_stat_x(&sx2);
489                 sxp = &sx2;
490                 inherit = !preserve_perms;
491         } else
492                 inherit = !preserve_perms && file->flags & FLAG_DIR_CREATED;
493
494         if (inherit && S_ISDIR(new_mode) && sxp->st.st_mode & S_ISGID) {
495                 /* We just created this directory and its setgid
496                  * bit is on, so make sure it stays on. */
497                 new_mode |= S_ISGID;
498         }
499
500         if (daemon_chmod_modes && !S_ISLNK(new_mode))
501                 new_mode = tweak_mode(new_mode, daemon_chmod_modes);
502
503 #ifdef SUPPORT_ACLS
504         if (preserve_acls && !S_ISLNK(file->mode) && !ACL_READY(*sxp))
505                 get_acl(fname, sxp);
506 #endif
507
508         change_uid = am_root && uid_ndx && sxp->st.st_uid != (uid_t)F_OWNER(file);
509         change_gid = gid_ndx && !(file->flags & FLAG_SKIP_GROUP)
510                   && sxp->st.st_gid != (gid_t)F_GROUP(file);
511 #ifndef CAN_CHOWN_SYMLINK
512         if (S_ISLNK(sxp->st.st_mode)) {
513                 ;
514         } else
515 #endif
516         if (change_uid || change_gid) {
517                 if (DEBUG_GTE(OWN, 1)) {
518                         if (change_uid) {
519                                 rprintf(FINFO,
520                                         "set uid of %s from %u to %u\n",
521                                         fname, (unsigned)sxp->st.st_uid, F_OWNER(file));
522                         }
523                         if (change_gid) {
524                                 rprintf(FINFO,
525                                         "set gid of %s from %u to %u\n",
526                                         fname, (unsigned)sxp->st.st_gid, F_GROUP(file));
527                         }
528                 }
529                 if (am_root >= 0) {
530                         uid_t uid = change_uid ? (uid_t)F_OWNER(file) : sxp->st.st_uid;
531                         gid_t gid = change_gid ? (gid_t)F_GROUP(file) : sxp->st.st_gid;
532                         if (do_lchown(fname, uid, gid) != 0) {
533                                 /* We shouldn't have attempted to change uid
534                                  * or gid unless have the privilege. */
535                                 rsyserr(FERROR_XFER, errno, "%s %s failed",
536                                     change_uid ? "chown" : "chgrp",
537                                     full_fname(fname));
538                                 goto cleanup;
539                         }
540                         if (uid == (uid_t)-1 && sxp->st.st_uid != (uid_t)-1)
541                                 rprintf(FERROR_XFER, "uid 4294967295 (-1) is impossible to set on %s\n", full_fname(fname));
542                         if (gid == (gid_t)-1 && sxp->st.st_gid != (gid_t)-1)
543                                 rprintf(FERROR_XFER, "gid 4294967295 (-1) is impossible to set on %s\n", full_fname(fname));
544                         /* A lchown had been done, so we need to re-stat if
545                          * the destination had the setuid or setgid bits set
546                          * (due to the side effect of the chown call). */
547                         if (sxp->st.st_mode & (S_ISUID | S_ISGID)) {
548                                 link_stat(fname, &sxp->st,
549                                           keep_dirlinks && S_ISDIR(sxp->st.st_mode));
550                         }
551                 }
552                 if (change_uid)
553                     updated |= UPDATED_OWNER;
554                 if (change_gid)
555                     updated |= UPDATED_GROUP;
556         }
557
558 #ifdef SUPPORT_XATTRS
559         if (am_root < 0)
560                 set_stat_xattr(fname, file, new_mode);
561         if (preserve_xattrs && fnamecmp)
562                 set_xattr(fname, file, fnamecmp, sxp);
563 #endif
564
565         if (!preserve_times
566          || (!(preserve_times & PRESERVE_DIR_TIMES) && S_ISDIR(sxp->st.st_mode))
567          || (!(preserve_times & PRESERVE_LINK_TIMES) && S_ISLNK(sxp->st.st_mode)))
568                 flags |= ATTRS_SKIP_MTIME | ATTRS_SKIP_ATIME;
569         else if (sxp != &sx2)
570                 memcpy(&sx2.st, &sxp->st, sizeof (sx2.st));
571         if (!atimes_ndx || S_ISDIR(sxp->st.st_mode))
572                 flags |= ATTRS_SKIP_ATIME;
573         if (!(flags & ATTRS_SKIP_MTIME)
574          && (sxp->st.st_mtime != file->modtime
575 #ifdef ST_MTIME_NSEC
576           || (flags & ATTRS_SET_NANO && NSEC_BUMP(file) && (uint32)sxp->st.ST_MTIME_NSEC != F_MOD_NSEC(file))
577 #endif
578           )) {
579                 sx2.st.st_mtime = file->modtime;
580 #ifdef ST_MTIME_NSEC
581                 sx2.st.ST_MTIME_NSEC = F_MOD_NSEC_or_0(file);
582 #endif
583                 updated |= UPDATED_MTIME;
584         }
585         if (!(flags & ATTRS_SKIP_ATIME)) {
586                 time_t file_atime = F_ATIME(file);
587                 if (cmp_time(sxp->st.st_atime, 0, file_atime, 0) != 0) {
588                         sx2.st.st_atime = file_atime;
589 #ifdef ST_ATIME_NSEC
590                         sx2.st.ST_ATIME_NSEC = 0;
591 #endif
592                         updated |= UPDATED_ATIME;
593                 }
594         }
595         if (updated & UPDATED_TIMES) {
596                 int ret = set_times(fname, &sx2.st);
597                 if (ret < 0) {
598                         rsyserr(FERROR_XFER, errno, "failed to set times on %s",
599                                 full_fname(fname));
600                         goto cleanup;
601                 }
602                 if (ret > 0) { /* ret == 1 if symlink could not be set */
603                         updated &= ~UPDATED_TIMES;
604                         file->flags |= FLAG_TIME_FAILED;
605                 }
606         }
607
608 #ifdef SUPPORT_ACLS
609         /* It's OK to call set_acl() now, even for a dir, as the generator
610          * will enable owner-writability using chmod, if necessary.
611          * 
612          * If set_acl() changes permission bits in the process of setting
613          * an access ACL, it changes sxp->st.st_mode so we know whether we
614          * need to chmod(). */
615         if (preserve_acls && !S_ISLNK(new_mode)) {
616                 if (set_acl(fname, file, sxp, new_mode) > 0)
617                         updated |= UPDATED_ACLS;
618         }
619 #endif
620
621 #ifdef HAVE_CHMOD
622         if (!BITS_EQUAL(sxp->st.st_mode, new_mode, CHMOD_BITS)) {
623                 int ret = am_root < 0 ? 0 : do_chmod(fname, new_mode);
624                 if (ret < 0) {
625                         rsyserr(FERROR_XFER, errno,
626                                 "failed to set permissions on %s",
627                                 full_fname(fname));
628                         goto cleanup;
629                 }
630                 if (ret == 0) /* ret == 1 if symlink could not be set */
631                         updated |= UPDATED_MODE;
632         }
633 #endif
634
635         if (INFO_GTE(NAME, 2) && flags & ATTRS_REPORT) {
636                 if (updated)
637                         rprintf(FCLIENT, "%s\n", fname);
638                 else
639                         rprintf(FCLIENT, "%s is uptodate\n", fname);
640         }
641   cleanup:
642         if (sxp == &sx2)
643                 free_stat_x(&sx2);
644         return updated;
645 }
646
647 /* This is only called for SIGINT, SIGHUP, and SIGTERM. */
648 void sig_int(int sig_num)
649 {
650         called_from_signal_handler = 1;
651
652         /* KLUGE: if the user hits Ctrl-C while ssh is prompting
653          * for a password, then our cleanup's sending of a SIGUSR1
654          * signal to all our children may kill ssh before it has a
655          * chance to restore the tty settings (i.e. turn echo back
656          * on).  By sleeping for a short time, ssh gets a bigger
657          * chance to do the right thing.  If child processes are
658          * not ssh waiting for a password, then this tiny delay
659          * shouldn't hurt anything. */
660         msleep(400);
661
662         /* If we're an rsync daemon listener (not a daemon server),
663          * we'll exit with status 0 if we received SIGTERM. */
664         if (am_daemon && !am_server && sig_num == SIGTERM)
665                 exit_cleanup(0);
666
667         /* If the signal arrived on the server side (or for the receiver
668          * process on the client), we want to try to do a controlled shutdown
669          * that lets the client side (generator process) know what happened.
670          * To do this, we set a flag and let the normal process handle the
671          * shutdown.  We only attempt this if multiplexed IO is in effect and
672          * we didn't already set the flag. */
673         if (!got_kill_signal && (am_server || am_receiver)) {
674                 got_kill_signal = sig_num;
675                 called_from_signal_handler = 0;
676                 return;
677         }
678
679         exit_cleanup(RERR_SIGNAL);
680 }
681
682 /* Finish off a file transfer: renaming the file and setting the file's
683  * attributes (e.g. permissions, ownership, etc.).  If the robust_rename()
684  * call is forced to copy the temp file and partialptr is both non-NULL and
685  * not an absolute path, we stage the file into the partial-dir and then
686  * rename it into place.  This returns 1 on success or 0 on failure. */
687 int finish_transfer(const char *fname, const char *fnametmp,
688                     const char *fnamecmp, const char *partialptr,
689                     struct file_struct *file, int ok_to_set_time,
690                     int overwriting_basis)
691 {
692         int ret;
693         const char *temp_copy_name = partialptr && *partialptr != '/' ? partialptr : NULL;
694
695         if (inplace) {
696                 if (DEBUG_GTE(RECV, 1))
697                         rprintf(FINFO, "finishing %s\n", fname);
698                 fnametmp = fname;
699                 goto do_set_file_attrs;
700         }
701
702         if (make_backups > 0 && overwriting_basis) {
703                 int ok = make_backup(fname, False);
704                 if (!ok)
705                         exit_cleanup(RERR_FILEIO);
706                 if (ok == 1 && fnamecmp == fname)
707                         fnamecmp = get_backup_name(fname);
708         }
709
710         /* Change permissions before putting the file into place. */
711         set_file_attrs(fnametmp, file, NULL, fnamecmp,
712                        ok_to_set_time ? ATTRS_SET_NANO : ATTRS_SKIP_MTIME | ATTRS_SKIP_ATIME);
713
714         /* move tmp file over real file */
715         if (DEBUG_GTE(RECV, 1))
716                 rprintf(FINFO, "renaming %s to %s\n", fnametmp, fname);
717         ret = robust_rename(fnametmp, fname, temp_copy_name, file->mode);
718         if (ret < 0) {
719                 rsyserr(FERROR_XFER, errno, "%s %s -> \"%s\"",
720                         ret == -2 ? "copy" : "rename",
721                         full_fname(fnametmp), fname);
722                 if (!partialptr || (ret == -2 && temp_copy_name)
723                  || robust_rename(fnametmp, partialptr, NULL, file->mode) < 0)
724                         do_unlink(fnametmp);
725                 return 0;
726         }
727         if (ret == 0) {
728                 /* The file was moved into place (not copied), so it's done. */
729                 return 1;
730         }
731         /* The file was copied, so tweak the perms of the copied file.  If it
732          * was copied to partialptr, move it into its final destination. */
733         fnametmp = temp_copy_name ? temp_copy_name : fname;
734
735   do_set_file_attrs:
736         set_file_attrs(fnametmp, file, NULL, fnamecmp,
737                        ok_to_set_time ? ATTRS_SET_NANO : ATTRS_SKIP_MTIME | ATTRS_SKIP_ATIME);
738
739         if (temp_copy_name) {
740                 if (do_rename(fnametmp, fname) < 0) {
741                         rsyserr(FERROR_XFER, errno, "rename %s -> \"%s\"",
742                                 full_fname(fnametmp), fname);
743                         return 0;
744                 }
745                 handle_partial_dir(temp_copy_name, PDIR_DELETE);
746         }
747         return 1;
748 }
749
750 struct file_list *flist_for_ndx(int ndx, const char *fatal_error_loc)
751 {
752         struct file_list *flist = cur_flist;
753
754         if (!flist && !(flist = first_flist))
755                 goto not_found;
756
757         while (ndx < flist->ndx_start-1) {
758                 if (flist == first_flist)
759                         goto not_found;
760                 flist = flist->prev;
761         }
762         while (ndx >= flist->ndx_start + flist->used) {
763                 if (!(flist = flist->next))
764                         goto not_found;
765         }
766         return flist;
767
768   not_found:
769         if (fatal_error_loc) {
770                 int first, last;
771                 if (first_flist) {
772                         first = first_flist->ndx_start - 1;
773                         last = first_flist->prev->ndx_start + first_flist->prev->used - 1;
774                 } else {
775                         first = 0;
776                         last = -1;
777                 }
778                 rprintf(FERROR,
779                         "File-list index %d not in %d - %d (%s) [%s]\n",
780                         ndx, first, last, fatal_error_loc, who_am_i());
781                 exit_cleanup(RERR_PROTOCOL);
782         }
783         return NULL;
784 }
785
786 const char *who_am_i(void)
787 {
788         if (am_starting_up)
789                 return am_server ? "server" : "client";
790         return am_sender ? "sender"
791              : am_generator ? "generator"
792              : am_receiver ? "receiver"
793              : "Receiver"; /* pre-forked receiver */
794 }