Don't force nanoseconds if a file wasn't transferred or checksummed.
[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-2018 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 inc_recurse;
47 extern int inplace;
48 extern int flist_eof;
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;
55 #ifdef ICONV_OPTION
56 extern char *iconv_opt;
57 #endif
58
59 #ifdef ICONV_CONST
60 iconv_t ic_chck = (iconv_t)-1;
61 # ifdef ICONV_OPTION
62 iconv_t ic_send = (iconv_t)-1, ic_recv = (iconv_t)-1;
63 # endif
64
65 static const char *default_charset(void)
66 {
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);
71 # else
72         return ""; /* Works with (at the very least) gnu iconv... */
73 # endif
74 }
75
76 void setup_iconv(void)
77 {
78         const char *defset = default_charset();
79 # ifdef ICONV_OPTION
80         const char *charset;
81         char *cp;
82 # endif
83
84         if (!am_server && !allow_8bit_chars) {
85                 /* It's OK if this fails... */
86                 ic_chck = iconv_open(defset, defset);
87
88                 if (DEBUG_GTE(ICONV, 2)) {
89                         if (ic_chck == (iconv_t)-1) {
90                                 rprintf(FINFO,
91                                         "msg checking via isprint()"
92                                         " (iconv_open(\"%s\", \"%s\") errno: %d)\n",
93                                         defset, defset, errno);
94                         } else {
95                                 rprintf(FINFO,
96                                         "msg checking charset: %s\n",
97                                         defset);
98                         }
99                 }
100         } else
101                 ic_chck = (iconv_t)-1;
102
103 # ifdef ICONV_OPTION
104         if (!iconv_opt)
105                 return;
106
107         if ((cp = strchr(iconv_opt, ',')) != NULL) {
108                 if (am_server) /* A local transfer needs this. */
109                         iconv_opt = cp + 1;
110                 else
111                         *cp = '\0';
112         }
113
114         if (!*iconv_opt || (*iconv_opt == '.' && iconv_opt[1] == '\0'))
115                 charset = defset;
116         else
117                 charset = iconv_opt;
118
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);
123         }
124
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);
129         }
130
131         if (DEBUG_GTE(ICONV, 1)) {
132                 rprintf(FINFO, "[%s] charset: %s\n",
133                         who_am_i(), *charset ? charset : "[LOCALE]");
134         }
135 # endif
136 }
137
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).
144  *
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).
149  *
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).
155  *
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).
159  *
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.
162  *
163  * If ICB_INCLUDE_INCOMPLETE is set in "flags", any incomplete multi-byte
164  * chars are included, which ensures that EINVAL is not returned.
165  *
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)
169 {
170         ICONV_CONST char *ibuf;
171         size_t icnt, ocnt, opos;
172         char *obuf;
173
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) {
180                         errno = E2BIG;
181                         return -1;
182                 }
183                 realloc_xbuf(out, out->size + ROUND_UP_1024(in->len * 2));
184         }
185
186         if (flags & ICB_INIT)
187                 iconv(ic, NULL, 0, NULL, 0);
188
189         ibuf = in->buf + in->pos;
190         icnt = in->len;
191
192         opos = out->pos + out->len;
193         if (flags & ICB_CIRCULAR_OUT) {
194                 if (opos >= out->size) {
195                         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;
199                 } else {
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);
203                 }
204         } else
205                 ocnt = out->size - opos - 1;
206         obuf = out->buf + opos;
207
208         while (icnt) {
209                 while (iconv(ic, &ibuf, &icnt, &obuf, &ocnt) == (size_t)-1) {
210                         if (errno == EINTR)
211                                 continue;
212                         if (errno == EINVAL) {
213                                 if (!(flags & ICB_INCLUDE_INCOMPLETE))
214                                         goto finish;
215                                 if (!ocnt)
216                                         goto e2big;
217                         } else if (errno == EILSEQ) {
218                                 if (!(flags & ICB_INCLUDE_BAD))
219                                         goto finish;
220                                 if (!ocnt)
221                                         goto e2big;
222                         } else if (errno == E2BIG) {
223                                 size_t siz;
224                           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);
233                                         obuf = out->buf;
234                                         ocnt = out->pos - 1;
235                                         continue;
236                                 }
237                                 if (!(flags & ICB_EXPAND_OUT) || flags & ICB_CIRCULAR_OUT) {
238                                         errno = E2BIG;
239                                         goto finish;
240                                 }
241                                 siz = ROUND_UP_1024(in->len * 2);
242                                 realloc_xbuf(out, out->size + siz);
243                                 obuf = out->buf + opos;
244                                 ocnt += siz;
245                                 continue;
246                         } else {
247                                 rsyserr(FERROR, errno, "unexpected error from iconv()");
248                                 exit_cleanup(RERR_UNSUPPORTED);
249                         }
250                         *obuf++ = *ibuf++;
251                         ocnt--, icnt--;
252                         if (!icnt)
253                                 break;
254                 }
255         }
256
257         errno = 0;
258
259   finish:
260         opos = obuf - out->buf;
261         if (flags & ICB_CIRCULAR_OUT && opos < out->pos)
262                 opos += out->size;
263         out->len = opos - out->pos;
264
265         in->len = icnt;
266         in->pos = ibuf - in->buf;
267
268         return errno ? -1 : 0;
269 }
270 #endif
271
272 void send_protected_args(int fd, char *args[])
273 {
274         int i;
275 #ifdef ICONV_OPTION
276         int convert = ic_send != (iconv_t)-1;
277         xbuf outbuf, inbuf;
278
279         if (convert)
280                 alloc_xbuf(&outbuf, 1024);
281 #endif
282
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);
287         do {
288                 if (!args[i][0])
289                         write_buf(fd, ".", 2);
290 #ifdef ICONV_OPTION
291                 else if (convert) {
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);
297                         outbuf.len = 0;
298                 }
299 #endif
300                 else
301                         write_buf(fd, args[i], strlen(args[i]) + 1);
302         } while (args[++i]);
303         write_byte(fd, 0);
304
305 #ifdef ICONV_OPTION
306         if (convert)
307                 free(outbuf.buf);
308 #endif
309 }
310
311 int read_ndx_and_attrs(int f_in, int f_out, int *iflag_ptr, uchar *type_ptr,
312                        char *buf, int *len_ptr)
313 {
314         int len, iflags = 0;
315         struct file_list *flist;
316         uchar fnamecmp_type = FNAMECMP_FNAME;
317         int ndx;
318
319   read_loop:
320         while (1) {
321                 ndx = read_ndx(f_in);
322
323                 if (ndx >= 0)
324                         break;
325                 if (ndx == NDX_DONE)
326                         return ndx;
327                 if (ndx == NDX_DEL_STATS) {
328                         read_del_stats(f_in);
329                         if (am_sender && am_server)
330                                 write_del_stats(f_out);
331                         continue;
332                 }
333                 if (!inc_recurse || am_sender) {
334                         int last;
335                         if (first_flist)
336                                 last = first_flist->prev->ndx_start + first_flist->prev->used - 1;
337                         else
338                                 last = -1;
339                         rprintf(FERROR,
340                                 "Invalid file index: %d (%d - %d) [%s]\n",
341                                 ndx, NDX_DONE, last, who_am_i());
342                         exit_cleanup(RERR_PROTOCOL);
343                 }
344                 if (ndx == NDX_FLIST_EOF) {
345                         flist_eof = 1;
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);
349                         continue;
350                 }
351                 ndx = NDX_FLIST_OFFSET - ndx;
352                 if (ndx < 0 || ndx >= dir_flist->used) {
353                         ndx = NDX_FLIST_OFFSET - ndx;
354                         rprintf(FERROR,
355                                 "Invalid dir index: %d (%d - %d) [%s]\n",
356                                 ndx, NDX_FLIST_OFFSET,
357                                 NDX_FLIST_OFFSET - dir_flist->used + 1,
358                                 who_am_i());
359                         exit_cleanup(RERR_PROTOCOL);
360                 }
361
362                 if (DEBUG_GTE(FLIST, 2)) {
363                         rprintf(FINFO, "[%s] receiving flist for dir %d\n",
364                                 who_am_i(), ndx);
365                 }
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();
371         }
372
373         iflags = protocol_version >= 29 ? read_shortint(f_in)
374                    : ITEM_TRANSFER | ITEM_MISSING_DATA;
375
376         /* Support the protocol-29 keep-alive style. */
377         if (protocol_version < 30 && ndx == cur_flist->used && iflags == ITEM_IS_NEW) {
378                 if (am_sender)
379                         maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH);
380                 goto read_loop;
381         }
382
383         flist = flist_for_ndx(ndx, "read_ndx_and_attrs");
384         if (flist != cur_flist) {
385                 cur_flist = flist;
386                 if (am_sender) {
387                         file_old_total = cur_flist->used;
388                         for (flist = first_flist; flist != cur_flist; flist = flist->next)
389                                 file_old_total += flist->used;
390                 }
391         }
392
393         if (iflags & ITEM_BASIS_TYPE_FOLLOWS)
394                 fnamecmp_type = read_byte(f_in);
395         *type_ptr = fnamecmp_type;
396
397         if (iflags & ITEM_XNAME_FOLLOWS) {
398                 if ((len = read_vstring(f_in, buf, MAXPATHLEN)) < 0)
399                         exit_cleanup(RERR_PROTOCOL);
400
401                 if (sanitize_paths) {
402                         sanitize_path(buf, buf, "", 0, SP_DEFAULT);
403                         len = strlen(buf);
404                 }
405         } else {
406                 *buf = '\0';
407                 len = -1;
408         }
409         *len_ptr = len;
410
411         if (iflags & ITEM_TRANSFER) {
412                 int i = ndx - cur_flist->ndx_start;
413                 if (i < 0 || !S_ISREG(cur_flist->files[i]->mode)) {
414                         rprintf(FERROR,
415                                 "received request to transfer non-regular file: %d [%s]\n",
416                                 ndx, who_am_i());
417                         exit_cleanup(RERR_PROTOCOL);
418                 }
419         }
420
421         *iflag_ptr = iflags;
422         return ndx;
423 }
424
425 /*
426   free a sums struct
427   */
428 void free_sums(struct sum_struct *s)
429 {
430         if (s->sums) free(s->sums);
431         free(s);
432 }
433
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,
437                  int exists)
438 {
439         int new_mode;
440         /* If the file already exists, we'll return the local permissions,
441          * possibly tweaked by the --executability option. */
442         if (exists) {
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))
449                                 new_mode &= ~0111;
450                         else if (!(stat_mode & 0111))
451                                 new_mode |= (new_mode & 0444) >> 2;
452                 }
453         } else {
454                 /* Apply destination default permissions and turn
455                  * off special permissions. */
456                 new_mode = flist_mode & (~CHMOD_BITS | dflt_perms);
457         }
458         return new_mode;
459 }
460
461 int set_file_attrs(const char *fname, struct file_struct *file, stat_x *sxp,
462                    const char *fnamecmp, int flags)
463 {
464         int updated = 0;
465         stat_x sx2;
466         int change_uid, change_gid;
467         mode_t new_mode = file->mode;
468         int inherit;
469
470         if (!sxp) {
471                 if (dry_run)
472                         return 1;
473                 if (link_stat(fname, &sx2.st, 0) < 0) {
474                         rsyserr(FERROR_XFER, errno, "stat %s failed",
475                                 full_fname(fname));
476                         return 0;
477                 }
478                 init_stat_x(&sx2);
479                 sxp = &sx2;
480                 inherit = !preserve_perms;
481         } else
482                 inherit = !preserve_perms && file->flags & FLAG_DIR_CREATED;
483
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. */
487                 new_mode |= S_ISGID;
488         }
489
490         if (daemon_chmod_modes && !S_ISLNK(new_mode))
491                 new_mode = tweak_mode(new_mode, daemon_chmod_modes);
492
493 #ifdef SUPPORT_ACLS
494         if (preserve_acls && !S_ISLNK(file->mode) && !ACL_READY(*sxp))
495                 get_acl(fname, sxp);
496 #endif
497
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)) {
503                 ;
504         } else
505 #endif
506         if (change_uid || change_gid) {
507                 if (DEBUG_GTE(OWN, 1)) {
508                         if (change_uid) {
509                                 rprintf(FINFO,
510                                         "set uid of %s from %u to %u\n",
511                                         fname, (unsigned)sxp->st.st_uid, F_OWNER(file));
512                         }
513                         if (change_gid) {
514                                 rprintf(FINFO,
515                                         "set gid of %s from %u to %u\n",
516                                         fname, (unsigned)sxp->st.st_gid, F_GROUP(file));
517                         }
518                 }
519                 if (am_root >= 0) {
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",
527                                     full_fname(fname));
528                                 goto cleanup;
529                         }
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));
540                         }
541                 }
542                 updated = 1;
543         }
544
545 #ifdef SUPPORT_XATTRS
546         if (am_root < 0)
547                 set_stat_xattr(fname, file, new_mode);
548         if (preserve_xattrs && fnamecmp)
549                 set_xattr(fname, file, fnamecmp, sxp);
550 #endif
551
552         if (!preserve_times
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
558 #ifdef ST_MTIME_NSEC
559           || (flags & ATTRS_SET_NANO && NSEC_BUMP(file) && (uint32)sxp->st.ST_MTIME_NSEC != F_MOD_NSEC(file))
560 #endif
561           )) {
562                 int ret = set_modtime(fname, file->modtime, F_MOD_NSEC(file), sxp->st.st_mode);
563                 if (ret < 0) {
564                         rsyserr(FERROR_XFER, errno, "failed to set times on %s",
565                                 full_fname(fname));
566                         goto cleanup;
567                 }
568                 if (ret == 0) /* ret == 1 if symlink could not be set */
569                         updated = 1;
570                 else
571                         file->flags |= FLAG_TIME_FAILED;
572         }
573
574 #ifdef SUPPORT_ACLS
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.
577          * 
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)
583                         updated = 1;
584         }
585 #endif
586
587 #ifdef HAVE_CHMOD
588         if (!BITS_EQUAL(sxp->st.st_mode, new_mode, CHMOD_BITS)) {
589                 int ret = am_root < 0 ? 0 : do_chmod(fname, new_mode);
590                 if (ret < 0) {
591                         rsyserr(FERROR_XFER, errno,
592                                 "failed to set permissions on %s",
593                                 full_fname(fname));
594                         goto cleanup;
595                 }
596                 if (ret == 0) /* ret == 1 if symlink could not be set */
597                         updated = 1;
598         }
599 #endif
600
601         if (INFO_GTE(NAME, 2) && flags & ATTRS_REPORT) {
602                 if (updated)
603                         rprintf(FCLIENT, "%s\n", fname);
604                 else
605                         rprintf(FCLIENT, "%s is uptodate\n", fname);
606         }
607   cleanup:
608         if (sxp == &sx2)
609                 free_stat_x(&sx2);
610         return updated;
611 }
612
613 /* This is only called for SIGINT, SIGHUP, and SIGTERM. */
614 void sig_int(int sig_num)
615 {
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. */
624         msleep(400);
625
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)
629                 exit_cleanup(0);
630
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;
639                 return;
640         }
641
642         exit_cleanup(RERR_SIGNAL);
643 }
644
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)
654 {
655         int ret;
656         const char *temp_copy_name = partialptr && *partialptr != '/' ? partialptr : NULL;
657
658         if (inplace) {
659                 if (DEBUG_GTE(RECV, 1))
660                         rprintf(FINFO, "finishing %s\n", fname);
661                 fnametmp = fname;
662                 goto do_set_file_attrs;
663         }
664
665         if (make_backups > 0 && overwriting_basis) {
666                 int ok = make_backup(fname, False);
667                 if (!ok)
668                         exit_cleanup(RERR_FILEIO);
669                 if (ok == 1 && fnamecmp == fname)
670                         fnamecmp = get_backup_name(fname);
671         }
672
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);
676
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);
681         if (ret < 0) {
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)
687                         do_unlink(fnametmp);
688                 return 0;
689         }
690         if (ret == 0) {
691                 /* The file was moved into place (not copied), so it's done. */
692                 return 1;
693         }
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;
697
698   do_set_file_attrs:
699         set_file_attrs(fnametmp, file, NULL, fnamecmp,
700                        ok_to_set_time ? ATTRS_SET_NANO : ATTRS_SKIP_MTIME);
701
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);
706                         return 0;
707                 }
708                 handle_partial_dir(temp_copy_name, PDIR_DELETE);
709         }
710         return 1;
711 }
712
713 struct file_list *flist_for_ndx(int ndx, const char *fatal_error_loc)
714 {
715         struct file_list *flist = cur_flist;
716
717         if (!flist && !(flist = first_flist))
718                 goto not_found;
719
720         while (ndx < flist->ndx_start-1) {
721                 if (flist == first_flist)
722                         goto not_found;
723                 flist = flist->prev;
724         }
725         while (ndx >= flist->ndx_start + flist->used) {
726                 if (!(flist = flist->next))
727                         goto not_found;
728         }
729         return flist;
730
731   not_found:
732         if (fatal_error_loc) {
733                 int first, last;
734                 if (first_flist) {
735                         first = first_flist->ndx_start - 1;
736                         last = first_flist->prev->ndx_start + first_flist->prev->used - 1;
737                 } else {
738                         first = 0;
739                         last = -1;
740                 }
741                 rprintf(FERROR,
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);
745         }
746         return NULL;
747 }
748
749 const char *who_am_i(void)
750 {
751         if (am_starting_up)
752                 return am_server ? "server" : "client";
753         return am_sender ? "sender"
754              : am_generator ? "generator"
755              : am_receiver ? "receiver"
756              : "Receiver"; /* pre-forked receiver */
757 }