We need to provide iconvbufs() anytime ICONV_CONST is defined.
[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-2007 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 verbose;
31 extern int dry_run;
32 extern int preserve_acls;
33 extern int preserve_xattrs;
34 extern int preserve_perms;
35 extern int preserve_executability;
36 extern int preserve_times;
37 extern int am_root;
38 extern int am_server;
39 extern int am_sender;
40 extern int am_generator;
41 extern int am_starting_up;
42 extern int allow_8bit_chars;
43 extern int protocol_version;
44 extern int uid_ndx;
45 extern int gid_ndx;
46 extern int inc_recurse;
47 extern int inplace;
48 extern int flist_eof;
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
84                 /* It's OK if this fails... */
85                 ic_chck = iconv_open(defset, defset);
86
87                 if (verbose > 3) {
88                         if (ic_chck == (iconv_t)-1) {
89                                 rprintf(FINFO,
90                                         "note: iconv_open(\"%s\", \"%s\") failed (%d)"
91                                         " -- using isprint() instead of iconv().\n",
92                                         defset, defset, errno);
93                         } else {
94                                 rprintf(FINFO,
95                                         "note: iconv_open(\"%s\", \"%s\") succeeded.\n",
96                                         defset, defset);
97                         }
98                 }
99         }
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 (verbose > 1) {
130                 rprintf(FINFO, "%s charset: %s\n",
131                         am_server ? "server" : "client",
132                         *charset ? charset : "[LOCALE]");
133         }
134 # endif
135 }
136
137 /* This function converts the characters in the "in" xbuf into characters
138  * in the "out" xbuf.  The "len" of the "in" xbuf is used starting from its
139  * "pos".  The "size" of the "out" xbuf restricts how many characters can be
140  * stored, starting at its "pos+len" position.  Note that the last byte of
141  * the buffer is never used, which reserves space for a terminating '\0'.
142  * We return a 0 on success or a -1 on error.  An error also sets errno to
143  * E2BIG, EILSEQ, or EINVAL (see below); otherwise errno will be set to 0.
144  * The "in" xbuf is altered to update "pos" and "len".  The "out" xbuf has
145  * data appended, and its "len" incremented.   If ICB_EXPAND_OUT is set in
146  * "flags", the "out" xbuf will also be allocated if empty, and expanded if
147  * too small (so E2BIG will not be returned).  If ICB_INCLUDE_BAD is set in
148  * "flags", any badly-encoded chars are included verbatim in the "out" xbuf,
149  * so EILSEQ will not be returned.  Likewise for ICB_INCLUDE_INCOMPLETE with
150  * respect to an incomplete multi-byte char at the end, which ensures that
151  * EINVAL is not returned.  Anytime "in.pos" is 0 we will reset the iconv()
152  * state prior to processing the characters. */
153 int iconvbufs(iconv_t ic, xbuf *in, xbuf *out, int flags)
154 {
155         ICONV_CONST char *ibuf;
156         size_t icnt, ocnt;
157         char *obuf;
158
159         if (!out->size && flags & ICB_EXPAND_OUT)
160                 alloc_xbuf(out, 1024);
161
162         if (!in->pos)
163                 iconv(ic, NULL, 0, NULL, 0);
164
165         ibuf = in->buf + in->pos;
166         icnt = in->len;
167
168         obuf = out->buf + (out->pos + out->len);
169         ocnt = out->size - (out->pos + out->len) - 1;
170
171         while (icnt) {
172                 while (iconv(ic, &ibuf, &icnt, &obuf, &ocnt) == (size_t)-1) {
173                         if (errno == EINTR)
174                                 continue;
175                         if (errno == EINVAL) {
176                                 if (!(flags & ICB_INCLUDE_INCOMPLETE))
177                                         goto finish;
178                         } else if (errno == EILSEQ) {
179                                 if (!(flags & ICB_INCLUDE_BAD))
180                                         goto finish;
181                         } else {
182                                 size_t opos = obuf - out->buf;
183                                 if (!(flags & ICB_EXPAND_OUT)) {
184                                         errno = E2BIG;
185                                         goto finish;
186                                 }
187                                 realloc_xbuf(out, out->size + 1024);
188                                 obuf = out->buf + opos;
189                                 ocnt += 1024;
190                                 continue;
191                         }
192                         *obuf++ = *ibuf++;
193                         ocnt--, icnt--;
194                 }
195         }
196
197         errno = 0;
198
199   finish:
200         in->len = icnt;
201         in->pos = ibuf - in->buf;
202         out->len = obuf - out->buf - out->pos;
203
204         return errno ? -1 : 0;
205 }
206 #endif
207
208 int read_ndx_and_attrs(int f_in, int *iflag_ptr, uchar *type_ptr,
209                        char *buf, int *len_ptr)
210 {
211         int len, iflags = 0;
212         struct file_list *flist;
213         uchar fnamecmp_type = FNAMECMP_FNAME;
214         int ndx;
215
216   read_loop:
217         while (1) {
218                 ndx = read_ndx(f_in);
219
220                 if (ndx >= 0)
221                         break;
222                 if (ndx == NDX_DONE)
223                         return ndx;
224                 if (!inc_recurse || am_sender)
225                         goto invalid_ndx;
226                 if (ndx == NDX_FLIST_EOF) {
227                         flist_eof = 1;
228                         send_msg(MSG_FLIST_EOF, "", 0, 0);
229                         continue;
230                 }
231                 ndx = NDX_FLIST_OFFSET - ndx;
232                 if (ndx < 0 || ndx >= dir_flist->used) {
233                         ndx = NDX_FLIST_OFFSET - ndx;
234                         rprintf(FERROR,
235                                 "[%s] Invalid dir index: %d (%d - %d)\n",
236                                 who_am_i(), ndx, NDX_FLIST_OFFSET,
237                                 NDX_FLIST_OFFSET - dir_flist->used + 1);
238                         exit_cleanup(RERR_PROTOCOL);
239                 }
240
241                 /* Send everything read from f_in to msg_fd_out. */
242                 send_msg_int(MSG_FLIST, ndx);
243                 start_flist_forward(f_in);
244                 if (verbose > 3) {
245                         rprintf(FINFO, "[%s] receiving flist for dir %d\n",
246                                 who_am_i(), ndx);
247                 }
248                 flist = recv_file_list(f_in);
249                 flist->parent_ndx = ndx;
250                 stop_flist_forward();
251         }
252
253         iflags = protocol_version >= 29 ? read_shortint(f_in)
254                    : ITEM_TRANSFER | ITEM_MISSING_DATA;
255
256         /* Honor the old-style keep-alive indicator. */
257         if (protocol_version < 30
258          && ndx == cur_flist->used && iflags == ITEM_IS_NEW) {
259                 if (am_sender)
260                         maybe_send_keepalive();
261                 goto read_loop;
262         }
263
264         if (!(flist = flist_for_ndx(ndx))) {
265           invalid_ndx:
266                 rprintf(FERROR,
267                         "Invalid file index: %d (%d - %d) with iflags %x [%s]\n",
268                         ndx, first_flist->ndx_start - 1, first_flist->prev->ndx_end,
269                         iflags, who_am_i());
270                 exit_cleanup(RERR_PROTOCOL);
271         }
272         cur_flist = flist;
273
274         if (iflags & ITEM_BASIS_TYPE_FOLLOWS)
275                 fnamecmp_type = read_byte(f_in);
276         *type_ptr = fnamecmp_type;
277
278         if (iflags & ITEM_XNAME_FOLLOWS) {
279                 if ((len = read_vstring(f_in, buf, MAXPATHLEN)) < 0)
280                         exit_cleanup(RERR_PROTOCOL);
281         } else {
282                 *buf = '\0';
283                 len = -1;
284         }
285         *len_ptr = len;
286
287         if (iflags & ITEM_TRANSFER) {
288                 int i = ndx - cur_flist->ndx_start;
289                 if (i < 0 || !S_ISREG(cur_flist->files[i]->mode)) {
290                         rprintf(FERROR,
291                                 "received request to transfer non-regular file: %d [%s]\n",
292                                 ndx, who_am_i());
293                         exit_cleanup(RERR_PROTOCOL);
294                 }
295         }
296
297         *iflag_ptr = iflags;
298         return ndx;
299 }
300
301 /*
302   free a sums struct
303   */
304 void free_sums(struct sum_struct *s)
305 {
306         if (s->sums) free(s->sums);
307         free(s);
308 }
309
310 /* This is only called when we aren't preserving permissions.  Figure out what
311  * the permissions should be and return them merged back into the mode. */
312 mode_t dest_mode(mode_t flist_mode, mode_t stat_mode, int dflt_perms,
313                  int exists)
314 {
315         int new_mode;
316         /* If the file already exists, we'll return the local permissions,
317          * possibly tweaked by the --executability option. */
318         if (exists) {
319                 new_mode = (flist_mode & ~CHMOD_BITS) | (stat_mode & CHMOD_BITS);
320                 if (preserve_executability && S_ISREG(flist_mode)) {
321                         /* If the source file is executable, grant execute
322                          * rights to everyone who can read, but ONLY if the
323                          * file isn't already executable. */
324                         if (!(flist_mode & 0111))
325                                 new_mode &= ~0111;
326                         else if (!(stat_mode & 0111))
327                                 new_mode |= (new_mode & 0444) >> 2;
328                 }
329         } else {
330                 /* Apply destination default permissions and turn
331                  * off special permissions. */
332                 new_mode = flist_mode & (~CHMOD_BITS | dflt_perms);
333         }
334         return new_mode;
335 }
336
337 int set_file_attrs(const char *fname, struct file_struct *file, stat_x *sxp,
338                    const char *fnamecmp, int flags)
339 {
340         int updated = 0;
341         stat_x sx2;
342         int change_uid, change_gid;
343         mode_t new_mode = file->mode;
344         int inherit;
345
346         if (!sxp) {
347                 if (dry_run)
348                         return 1;
349                 if (link_stat(fname, &sx2.st, 0) < 0) {
350                         rsyserr(FERROR, errno, "stat %s failed",
351                                 full_fname(fname));
352                         return 0;
353                 }
354 #ifdef SUPPORT_ACLS
355                 sx2.acc_acl = sx2.def_acl = NULL;
356 #endif
357 #ifdef SUPPORT_XATTRS
358                 sx2.xattr = NULL;
359 #endif
360                 sxp = &sx2;
361                 inherit = !preserve_perms;
362         } else
363                 inherit = !preserve_perms && file->flags & FLAG_DIR_CREATED;
364
365         if (inherit && S_ISDIR(new_mode) && sxp->st.st_mode & S_ISGID) {
366                 /* We just created this directory and its setgid
367                  * bit is on, so make sure it stays on. */
368                 new_mode |= S_ISGID;
369         }
370
371 #ifdef SUPPORT_ACLS
372         if (preserve_acls && !S_ISLNK(file->mode) && !ACL_READY(*sxp))
373                 get_acl(fname, sxp);
374 #endif
375
376 #ifdef SUPPORT_XATTRS
377         if (preserve_xattrs && fnamecmp)
378                 set_xattr(fname, file, fnamecmp, sxp);
379         if (am_root < 0)
380                 set_stat_xattr(fname, file);
381 #endif
382
383         if (!preserve_times || (S_ISDIR(sxp->st.st_mode) && preserve_times == 1))
384                 flags |= ATTRS_SKIP_MTIME;
385         if (!(flags & ATTRS_SKIP_MTIME)
386             && cmp_time(sxp->st.st_mtime, file->modtime) != 0) {
387                 int ret = set_modtime(fname, file->modtime, sxp->st.st_mode);
388                 if (ret < 0) {
389                         rsyserr(FERROR, errno, "failed to set times on %s",
390                                 full_fname(fname));
391                         goto cleanup;
392                 }
393                 if (ret == 0) /* ret == 1 if symlink could not be set */
394                         updated = 1;
395         }
396
397         change_uid = am_root && uid_ndx && sxp->st.st_uid != (uid_t)F_OWNER(file);
398         change_gid = gid_ndx && !(file->flags & FLAG_SKIP_GROUP)
399                   && sxp->st.st_gid != (gid_t)F_GROUP(file);
400 #if !defined HAVE_LCHOWN && !defined CHOWN_MODIFIES_SYMLINK
401         if (S_ISLNK(sxp->st.st_mode)) {
402                 ;
403         } else
404 #endif
405         if (change_uid || change_gid) {
406                 if (verbose > 2) {
407                         if (change_uid) {
408                                 rprintf(FINFO,
409                                         "set uid of %s from %u to %u\n",
410                                         fname, (unsigned)sxp->st.st_uid, F_OWNER(file));
411                         }
412                         if (change_gid) {
413                                 rprintf(FINFO,
414                                         "set gid of %s from %u to %u\n",
415                                         fname, (unsigned)sxp->st.st_gid, F_GROUP(file));
416                         }
417                 }
418                 if (am_root < 0) {
419                         ;
420                 } else if (do_lchown(fname,
421                     change_uid ? (uid_t)F_OWNER(file) : sxp->st.st_uid,
422                     change_gid ? (gid_t)F_GROUP(file) : sxp->st.st_gid) != 0) {
423                         /* shouldn't have attempted to change uid or gid
424                          * unless have the privilege */
425                         rsyserr(FERROR, errno, "%s %s failed",
426                             change_uid ? "chown" : "chgrp",
427                             full_fname(fname));
428                         goto cleanup;
429                 } else
430                 /* a lchown had been done - we have to re-stat if the
431                  * destination had the setuid or setgid bits set due
432                  * to the side effect of the chown call */
433                 if (sxp->st.st_mode & (S_ISUID | S_ISGID)) {
434                         link_stat(fname, &sxp->st,
435                                   keep_dirlinks && S_ISDIR(sxp->st.st_mode));
436                 }
437                 updated = 1;
438         }
439
440         if (daemon_chmod_modes && !S_ISLNK(new_mode))
441                 new_mode = tweak_mode(new_mode, daemon_chmod_modes);
442
443 #ifdef SUPPORT_ACLS
444         /* It's OK to call set_acl() now, even for a dir, as the generator
445          * will enable owner-writability using chmod, if necessary.
446          * 
447          * If set_acl() changes permission bits in the process of setting
448          * an access ACL, it changes sxp->st.st_mode so we know whether we
449          * need to chmod(). */
450         if (preserve_acls && !S_ISLNK(new_mode) && set_acl(fname, file, sxp) == 0)
451                 updated = 1;
452 #endif
453
454 #ifdef HAVE_CHMOD
455         if (!BITS_EQUAL(sxp->st.st_mode, new_mode, CHMOD_BITS)) {
456                 int ret = am_root < 0 ? 0 : do_chmod(fname, new_mode);
457                 if (ret < 0) {
458                         rsyserr(FERROR, errno,
459                                 "failed to set permissions on %s",
460                                 full_fname(fname));
461                         goto cleanup;
462                 }
463                 if (ret == 0) /* ret == 1 if symlink could not be set */
464                         updated = 1;
465         }
466 #endif
467
468         if (verbose > 1 && flags & ATTRS_REPORT) {
469                 if (updated)
470                         rprintf(FCLIENT, "%s\n", fname);
471                 else
472                         rprintf(FCLIENT, "%s is uptodate\n", fname);
473         }
474   cleanup:
475         if (sxp == &sx2) {
476 #ifdef SUPPORT_ACLS
477                 if (preserve_acls)
478                         free_acl(&sx2);
479 #endif
480 #ifdef SUPPORT_XATTRS
481                 if (preserve_xattrs)
482                         free_xattr(&sx2);
483 #endif
484         }
485         return updated;
486 }
487
488 RETSIGTYPE sig_int(UNUSED(int val))
489 {
490         /* KLUGE: if the user hits Ctrl-C while ssh is prompting
491          * for a password, then our cleanup's sending of a SIGUSR1
492          * signal to all our children may kill ssh before it has a
493          * chance to restore the tty settings (i.e. turn echo back
494          * on).  By sleeping for a short time, ssh gets a bigger
495          * chance to do the right thing.  If child processes are
496          * not ssh waiting for a password, then this tiny delay
497          * shouldn't hurt anything. */
498         msleep(400);
499         exit_cleanup(RERR_SIGNAL);
500 }
501
502 /* Finish off a file transfer: renaming the file and setting the file's
503  * attributes (e.g. permissions, ownership, etc.).  If partialptr is not
504  * NULL and the robust_rename() call is forced to copy the temp file, we
505  * stage the file into the partial-dir and then rename it into place. */
506 void finish_transfer(const char *fname, const char *fnametmp,
507                      const char *fnamecmp, const char *partialptr,
508                      struct file_struct *file, int ok_to_set_time,
509                      int overwriting_basis)
510 {
511         int ret;
512
513         if (inplace) {
514                 if (verbose > 2)
515                         rprintf(FINFO, "finishing %s\n", fname);
516                 fnametmp = fname;
517                 goto do_set_file_attrs;
518         }
519
520         if (make_backups > 0 && overwriting_basis && !make_backup(fname))
521                 return;
522
523         /* Change permissions before putting the file into place. */
524         set_file_attrs(fnametmp, file, NULL, fnamecmp,
525                        ok_to_set_time ? 0 : ATTRS_SKIP_MTIME);
526
527         /* move tmp file over real file */
528         if (verbose > 2)
529                 rprintf(FINFO, "renaming %s to %s\n", fnametmp, fname);
530         ret = robust_rename(fnametmp, fname, partialptr,
531                             file->mode & INITACCESSPERMS);
532         if (ret < 0) {
533                 rsyserr(FERROR, errno, "%s %s -> \"%s\"",
534                         ret == -2 ? "copy" : "rename",
535                         full_fname(fnametmp), fname);
536                 do_unlink(fnametmp);
537                 return;
538         }
539         if (ret == 0) {
540                 /* The file was moved into place (not copied), so it's done. */
541                 return;
542         }
543         /* The file was copied, so tweak the perms of the copied file.  If it
544          * was copied to partialptr, move it into its final destination. */
545         fnametmp = partialptr ? partialptr : fname;
546
547   do_set_file_attrs:
548         set_file_attrs(fnametmp, file, NULL, fnamecmp,
549                        ok_to_set_time ? 0 : ATTRS_SKIP_MTIME);
550
551         if (partialptr) {
552                 if (do_rename(fnametmp, fname) < 0) {
553                         rsyserr(FERROR, errno, "rename %s -> \"%s\"",
554                                 full_fname(fnametmp), fname);
555                 } else
556                         handle_partial_dir(partialptr, PDIR_DELETE);
557         }
558 }
559
560 struct file_list *flist_for_ndx(int ndx)
561 {
562         struct file_list *flist = cur_flist;
563
564         if (!flist && !(flist = first_flist))
565                 return NULL;
566
567         while (ndx < flist->ndx_start-1) {
568                 if (flist == first_flist)
569                         return NULL;
570                 flist = flist->prev;
571         }
572         while (ndx > flist->ndx_end) {
573                 if (!(flist = flist->next))
574                         return NULL;
575         }
576         return flist;
577 }
578
579 const char *who_am_i(void)
580 {
581         if (am_starting_up)
582                 return am_server ? "server" : "client";
583         return am_sender ? "sender" : am_generator ? "generator" : "receiver";
584 }