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