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