Improved the --iconv description.
[rsync/rsync.git] / options.c
1 /*
2  * Command-line (and received via daemon-socket) option parsing.
3  *
4  * Copyright (C) 1998-2001 Andrew Tridgell <tridge@samba.org>
5  * Copyright (C) 2000, 2001, 2002 Martin Pool <mbp@samba.org>
6  * Copyright (C) 2002-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 version 2 as
10  * published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along
18  * with this program; if not, write to the Free Software Foundation, Inc.,
19  * 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
20  */
21
22 #include "rsync.h"
23 #include <popt.h>
24 #include "zlib/zlib.h"
25
26 extern int module_id;
27 extern int sanitize_paths;
28 extern struct filter_list_struct filter_list;
29 extern struct filter_list_struct server_filter_list;
30
31 int make_backups = 0;
32
33 /**
34  * If 1, send the whole file as literal data rather than trying to
35  * create an incremental diff.
36  *
37  * If -1, then look at whether we're local or remote and go by that.
38  *
39  * @sa disable_deltas_p()
40  **/
41 int whole_file = -1;
42
43 int append_mode = 0;
44 int keep_dirlinks = 0;
45 int copy_dirlinks = 0;
46 int copy_links = 0;
47 int preserve_links = 0;
48 int preserve_hard_links = 0;
49 int preserve_acls = 0;
50 int preserve_xattrs = 0;
51 int preserve_perms = 0;
52 int preserve_executability = 0;
53 int preserve_devices = 0;
54 int preserve_specials = 0;
55 int preserve_uid = 0;
56 int preserve_gid = 0;
57 int preserve_times = 0;
58 int omit_dir_times = 0;
59 int update_only = 0;
60 int cvs_exclude = 0;
61 int dry_run = 0;
62 int do_xfers = 1;
63 int ignore_times = 0;
64 int delete_mode = 0;
65 int delete_during = 0;
66 int delete_before = 0;
67 int delete_after = 0;
68 int delete_excluded = 0;
69 int remove_source_files = 0;
70 int one_file_system = 0;
71 int protocol_version = PROTOCOL_VERSION;
72 int sparse_files = 0;
73 int do_compression = 0;
74 int def_compress_level = Z_DEFAULT_COMPRESSION;
75 int am_root = 0; /* 0 = normal, 1 = root, 2 = --super, -1 = --fake-super */
76 int am_server = 0;
77 int am_sender = 0;
78 int am_generator = 0;
79 int am_starting_up = 1;
80 int relative_paths = -1;
81 int implied_dirs = 1;
82 int numeric_ids = 0;
83 int allow_8bit_chars = 0;
84 int force_delete = 0;
85 int io_timeout = 0;
86 int allowed_lull = 0;
87 int prune_empty_dirs = 0;
88 char *files_from = NULL;
89 int filesfrom_fd = -1;
90 char *filesfrom_host = NULL;
91 int eol_nulls = 0;
92 int human_readable = 0;
93 int recurse = 0;
94 int allow_inc_recurse = 1;
95 int xfer_dirs = -1;
96 int am_daemon = 0;
97 int daemon_over_rsh = 0;
98 int do_stats = 0;
99 int do_progress = 0;
100 int keep_partial = 0;
101 int safe_symlinks = 0;
102 int copy_unsafe_links = 0;
103 int size_only = 0;
104 int daemon_bwlimit = 0;
105 int bwlimit = 0;
106 int fuzzy_basis = 0;
107 size_t bwlimit_writemax = 0;
108 int ignore_existing = 0;
109 int ignore_non_existing = 0;
110 int need_messages_from_generator = 0;
111 int max_delete = -1;
112 OFF_T max_size = 0;
113 OFF_T min_size = 0;
114 int ignore_errors = 0;
115 int modify_window = 0;
116 int blocking_io = -1;
117 int checksum_seed = 0;
118 int inplace = 0;
119 int delay_updates = 0;
120 long block_size = 0; /* "long" because popt can't set an int32. */
121
122 /** Network address family. **/
123 #ifdef INET6
124 int default_af_hint = 0;        /* Any protocol */
125 #else
126 int default_af_hint = AF_INET;  /* Must use IPv4 */
127 #endif
128
129 /** Do not go into the background when run as --daemon.  Good
130  * for debugging and required for running as a service on W32,
131  * or under Unix process-monitors. **/
132 int no_detach
133 #if defined _WIN32 || defined __WIN32__
134         = 1;
135 #else
136         = 0;
137 #endif
138
139 int write_batch = 0;
140 int read_batch = 0;
141 int backup_dir_len = 0;
142 int backup_suffix_len;
143 unsigned int backup_dir_remainder;
144
145 char *backup_suffix = NULL;
146 char *tmpdir = NULL;
147 char *partial_dir = NULL;
148 char *basis_dir[MAX_BASIS_DIRS+1];
149 char *config_file = NULL;
150 char *shell_cmd = NULL;
151 char *logfile_name = NULL;
152 char *logfile_format = NULL;
153 char *stdout_format = NULL;
154 char *password_file = NULL;
155 char *rsync_path = RSYNC_PATH;
156 char *backup_dir = NULL;
157 char backup_dir_buf[MAXPATHLEN];
158 char *sockopts = NULL;
159 int rsync_port = 0;
160 int compare_dest = 0;
161 int copy_dest = 0;
162 int link_dest = 0;
163 int basis_dir_cnt = 0;
164 char *dest_option = NULL;
165
166 int verbose = 0;
167 int quiet = 0;
168 int output_motd = 1;
169 int log_before_transfer = 0;
170 int stdout_format_has_i = 0;
171 int stdout_format_has_o_or_i = 0;
172 int logfile_format_has_i = 0;
173 int logfile_format_has_o_or_i = 0;
174 int always_checksum = 0;
175 int list_only = 0;
176
177 #define MAX_BATCH_NAME_LEN 256  /* Must be less than MAXPATHLEN-13 */
178 char *batch_name = NULL;
179
180 #ifdef ICONV_OPTION
181 int need_unsorted_flist = 0;
182 char *iconv_opt = ICONV_OPTION;
183 #endif
184
185 struct chmod_mode_struct *chmod_modes = NULL;
186
187 static int daemon_opt;   /* sets am_daemon after option error-reporting */
188 static int F_option_cnt = 0;
189 static int modify_window_set;
190 static int itemize_changes = 0;
191 static int refused_delete, refused_archive_part, refused_compress;
192 static int refused_partial, refused_progress, refused_delete_before;
193 static int refused_delete_during;
194 static int refused_inplace;
195 static char *max_size_arg, *min_size_arg;
196 static char tmp_partialdir[] = ".~tmp~";
197
198 /** Local address to bind.  As a character string because it's
199  * interpreted by the IPv6 layer: should be a numeric IP4 or IP6
200  * address, or a hostname. **/
201 char *bind_address;
202
203
204 static void print_rsync_version(enum logcode f)
205 {
206         char *subprotocol = "";
207         char const *got_socketpair = "no ";
208         char const *have_inplace = "no ";
209         char const *hardlinks = "no ";
210         char const *acls = "no ";
211         char const *xattrs = "no ";
212         char const *links = "no ";
213         char const *iconv = "no ";
214         char const *ipv6 = "no ";
215         STRUCT_STAT *dumstat;
216
217 #if SUBPROTOCOL_VERSION != 0
218         asprintf(&subprotocol, ".PR%d", SUBPROTOCOL_VERSION);
219 #endif
220 #ifdef HAVE_SOCKETPAIR
221         got_socketpair = "";
222 #endif
223 #ifdef HAVE_FTRUNCATE
224         have_inplace = "";
225 #endif
226 #ifdef SUPPORT_HARD_LINKS
227         hardlinks = "";
228 #endif
229 #ifdef SUPPORT_ACLS
230         acls = "";
231 #endif
232 #ifdef SUPPORT_XATTRS
233         xattrs = "";
234 #endif
235 #ifdef SUPPORT_LINKS
236         links = "";
237 #endif
238 #ifdef INET6
239         ipv6 = "";
240 #endif
241 #ifdef ICONV_OPTION
242         iconv = "";
243 #endif
244
245         rprintf(f, "%s  version %s  protocol version %d%s\n",
246                 RSYNC_NAME, RSYNC_VERSION, PROTOCOL_VERSION, subprotocol);
247         rprintf(f, "Copyright (C) 1996-2007 by Andrew Tridgell, Wayne Davison, and others.\n");
248         rprintf(f, "Web site: http://rsync.samba.org/\n");
249         rprintf(f, "Capabilities:\n");
250         rprintf(f, "    %d-bit files, %d-bit inums, %d-bit timestamps, %d-bit long ints,\n",
251                 (int)(sizeof (OFF_T) * 8),
252                 (int)(sizeof dumstat->st_ino * 8), /* Don't check ino_t! */
253                 (int)(sizeof (time_t) * 8),
254                 (int)(sizeof (int64) * 8));
255         rprintf(f, "    %ssocketpairs, %shardlinks, %ssymlinks, %sIPv6, batchfiles, %sinplace,\n",
256                 got_socketpair, hardlinks, links, ipv6, have_inplace);
257         rprintf(f, "    %sappend, %sACLs, %sxattrs, %siconv\n",
258                 have_inplace, acls, xattrs, iconv);
259
260 #ifdef MAINTAINER_MODE
261         rprintf(f, "Panic Action: \"%s\"\n", get_panic_action());
262 #endif
263
264 #if SIZEOF_INT64 < 8
265         rprintf(f, "WARNING: no 64-bit integers on this platform!\n");
266 #endif
267         if (sizeof (int64) != SIZEOF_INT64) {
268                 rprintf(f,
269                         "WARNING: size mismatch in SIZEOF_INT64 define (%d != %d)\n",
270                         (int) SIZEOF_INT64, (int) sizeof (int64));
271         }
272
273         rprintf(f,"\n");
274         rprintf(f,"rsync comes with ABSOLUTELY NO WARRANTY.  This is free software, and you\n");
275         rprintf(f,"are welcome to redistribute it under certain conditions.  See the GNU\n");
276         rprintf(f,"General Public Licence for details.\n");
277 }
278
279
280 void usage(enum logcode F)
281 {
282   print_rsync_version(F);
283
284   rprintf(F,"\n");
285   rprintf(F,"rsync is a file transfer program capable of efficient remote update\n");
286   rprintf(F,"via a fast differencing algorithm.\n");
287
288   rprintf(F,"\n");
289   rprintf(F,"Usage: rsync [OPTION]... SRC [SRC]... DEST\n");
290   rprintf(F,"  or   rsync [OPTION]... SRC [SRC]... [USER@]HOST:DEST\n");
291   rprintf(F,"  or   rsync [OPTION]... SRC [SRC]... [USER@]HOST::DEST\n");
292   rprintf(F,"  or   rsync [OPTION]... SRC [SRC]... rsync://[USER@]HOST[:PORT]/DEST\n");
293   rprintf(F,"  or   rsync [OPTION]... [USER@]HOST:SRC [DEST]\n");
294   rprintf(F,"  or   rsync [OPTION]... [USER@]HOST::SRC [DEST]\n");
295   rprintf(F,"  or   rsync [OPTION]... rsync://[USER@]HOST[:PORT]/SRC [DEST]\n");
296   rprintf(F,"The ':' usages connect via remote shell, while '::' & 'rsync://' usages connect\n");
297   rprintf(F,"to an rsync daemon, and require SRC or DEST to start with a module name.\n");
298   rprintf(F,"\n");
299   rprintf(F,"Options\n");
300   rprintf(F," -v, --verbose               increase verbosity\n");
301   rprintf(F," -q, --quiet                 suppress non-error messages\n");
302   rprintf(F,"     --no-motd               suppress daemon-mode MOTD (see manpage caveat)\n");
303   rprintf(F," -c, --checksum              skip based on checksum, not mod-time & size\n");
304   rprintf(F," -a, --archive               archive mode; equals -rlptgoD (no -H,-A,-X)\n");
305   rprintf(F,"     --no-OPTION             turn off an implied OPTION (e.g. --no-D)\n");
306   rprintf(F," -r, --recursive             recurse into directories\n");
307   rprintf(F," -R, --relative              use relative path names\n");
308   rprintf(F,"     --no-implied-dirs       don't send implied dirs with --relative\n");
309   rprintf(F," -b, --backup                make backups (see --suffix & --backup-dir)\n");
310   rprintf(F,"     --backup-dir=DIR        make backups into hierarchy based in DIR\n");
311   rprintf(F,"     --suffix=SUFFIX         set backup suffix (default %s w/o --backup-dir)\n",BACKUP_SUFFIX);
312   rprintf(F," -u, --update                skip files that are newer on the receiver\n");
313   rprintf(F,"     --inplace               update destination files in-place (SEE MAN PAGE)\n");
314   rprintf(F,"     --append                append data onto shorter files\n");
315   rprintf(F," -d, --dirs                  transfer directories without recursing\n");
316   rprintf(F," -l, --links                 copy symlinks as symlinks\n");
317   rprintf(F," -L, --copy-links            transform symlink into referent file/dir\n");
318   rprintf(F,"     --copy-unsafe-links     only \"unsafe\" symlinks are transformed\n");
319   rprintf(F,"     --safe-links            ignore symlinks that point outside the source tree\n");
320   rprintf(F," -k, --copy-dirlinks         transform symlink to a dir into referent dir\n");
321   rprintf(F," -K, --keep-dirlinks         treat symlinked dir on receiver as dir\n");
322   rprintf(F," -H, --hard-links            preserve hard links\n");
323   rprintf(F," -p, --perms                 preserve permissions\n");
324   rprintf(F," -E, --executability         preserve the file's executability\n");
325   rprintf(F,"     --chmod=CHMOD           affect file and/or directory permissions\n");
326 #ifdef SUPPORT_ACLS
327   rprintf(F," -A, --acls                  preserve ACLs (implies --perms)\n");
328 #endif
329 #ifdef SUPPORT_XATTRS
330   rprintf(F," -X, --xattrs                preserve extended attributes (implies --perms)\n");
331 #endif
332   rprintf(F," -o, --owner                 preserve owner (super-user only)\n");
333   rprintf(F," -g, --group                 preserve group\n");
334   rprintf(F,"     --devices               preserve device files (super-user only)\n");
335   rprintf(F,"     --specials              preserve special files\n");
336   rprintf(F," -D                          same as --devices --specials\n");
337   rprintf(F," -t, --times                 preserve times\n");
338   rprintf(F," -O, --omit-dir-times        omit directories when preserving times\n");
339   rprintf(F,"     --super                 receiver attempts super-user activities\n");
340 #ifdef SUPPORT_XATTRS
341   rprintf(F,"     --fake-super            store/recover privileged attrs using xattrs\n");
342 #endif
343   rprintf(F," -S, --sparse                handle sparse files efficiently\n");
344   rprintf(F," -n, --dry-run               show what would have been transferred\n");
345   rprintf(F," -W, --whole-file            copy files whole (without rsync algorithm)\n");
346   rprintf(F," -x, --one-file-system       don't cross filesystem boundaries\n");
347   rprintf(F," -B, --block-size=SIZE       force a fixed checksum block-size\n");
348   rprintf(F," -e, --rsh=COMMAND           specify the remote shell to use\n");
349   rprintf(F,"     --rsync-path=PROGRAM    specify the rsync to run on the remote machine\n");
350   rprintf(F,"     --existing              skip creating new files on receiver\n");
351   rprintf(F,"     --ignore-existing       skip updating files that already exist on receiver\n");
352   rprintf(F,"     --remove-source-files   sender removes synchronized files (non-dirs)\n");
353   rprintf(F,"     --del                   an alias for --delete-during\n");
354   rprintf(F,"     --delete                delete extraneous files from destination dirs\n");
355   rprintf(F,"     --delete-before         receiver deletes before transfer, not during\n");
356   rprintf(F,"     --delete-during         receiver deletes during transfer (default)\n");
357   rprintf(F,"     --delete-delay          find deletions during, delete after\n");
358   rprintf(F,"     --delete-after          receiver deletes after transfer, not during\n");
359   rprintf(F,"     --delete-excluded       also delete excluded files from destination dirs\n");
360   rprintf(F,"     --ignore-errors         delete even if there are I/O errors\n");
361   rprintf(F,"     --force                 force deletion of directories even if not empty\n");
362   rprintf(F,"     --max-delete=NUM        don't delete more than NUM files\n");
363   rprintf(F,"     --max-size=SIZE         don't transfer any file larger than SIZE\n");
364   rprintf(F,"     --min-size=SIZE         don't transfer any file smaller than SIZE\n");
365   rprintf(F,"     --partial               keep partially transferred files\n");
366   rprintf(F,"     --partial-dir=DIR       put a partially transferred file into DIR\n");
367   rprintf(F,"     --delay-updates         put all updated files into place at transfer's end\n");
368   rprintf(F," -m, --prune-empty-dirs      prune empty directory chains from the file-list\n");
369   rprintf(F,"     --numeric-ids           don't map uid/gid values by user/group name\n");
370   rprintf(F,"     --timeout=TIME          set I/O timeout in seconds\n");
371   rprintf(F," -I, --ignore-times          don't skip files that match in size and mod-time\n");
372   rprintf(F,"     --size-only             skip files that match in size\n");
373   rprintf(F,"     --modify-window=NUM     compare mod-times with reduced accuracy\n");
374   rprintf(F," -T, --temp-dir=DIR          create temporary files in directory DIR\n");
375   rprintf(F," -y, --fuzzy                 find similar file for basis if no dest file\n");
376   rprintf(F,"     --compare-dest=DIR      also compare destination files relative to DIR\n");
377   rprintf(F,"     --copy-dest=DIR         ... and include copies of unchanged files\n");
378   rprintf(F,"     --link-dest=DIR         hardlink to files in DIR when unchanged\n");
379   rprintf(F," -z, --compress              compress file data during the transfer\n");
380   rprintf(F,"     --compress-level=NUM    explicitly set compression level\n");
381   rprintf(F," -C, --cvs-exclude           auto-ignore files the same way CVS does\n");
382   rprintf(F," -f, --filter=RULE           add a file-filtering RULE\n");
383   rprintf(F," -F                          same as --filter='dir-merge /.rsync-filter'\n");
384   rprintf(F,"                             repeated: --filter='- .rsync-filter'\n");
385   rprintf(F,"     --exclude=PATTERN       exclude files matching PATTERN\n");
386   rprintf(F,"     --exclude-from=FILE     read exclude patterns from FILE\n");
387   rprintf(F,"     --include=PATTERN       don't exclude files matching PATTERN\n");
388   rprintf(F,"     --include-from=FILE     read include patterns from FILE\n");
389   rprintf(F,"     --files-from=FILE       read list of source-file names from FILE\n");
390   rprintf(F," -0, --from0                 all *-from/filter files are delimited by 0s\n");
391   rprintf(F,"     --address=ADDRESS       bind address for outgoing socket to daemon\n");
392   rprintf(F,"     --port=PORT             specify double-colon alternate port number\n");
393   rprintf(F,"     --sockopts=OPTIONS      specify custom TCP options\n");
394   rprintf(F,"     --blocking-io           use blocking I/O for the remote shell\n");
395   rprintf(F,"     --stats                 give some file-transfer stats\n");
396   rprintf(F," -8, --8-bit-output          leave high-bit chars unescaped in output\n");
397   rprintf(F," -h, --human-readable        output numbers in a human-readable format\n");
398   rprintf(F,"     --progress              show progress during transfer\n");
399   rprintf(F," -P                          same as --partial --progress\n");
400   rprintf(F," -i, --itemize-changes       output a change-summary for all updates\n");
401   rprintf(F,"     --out-format=FORMAT     output updates using the specified FORMAT\n");
402   rprintf(F,"     --log-file=FILE         log what we're doing to the specified FILE\n");
403   rprintf(F,"     --log-file-format=FMT   log updates using the specified FMT\n");
404   rprintf(F,"     --password-file=FILE    read daemon-access password from FILE\n");
405   rprintf(F,"     --list-only             list the files instead of copying them\n");
406   rprintf(F,"     --bwlimit=KBPS          limit I/O bandwidth; KBytes per second\n");
407   rprintf(F,"     --write-batch=FILE      write a batched update to FILE\n");
408   rprintf(F,"     --only-write-batch=FILE like --write-batch but w/o updating destination\n");
409   rprintf(F,"     --read-batch=FILE       read a batched update from FILE\n");
410   rprintf(F,"     --protocol=NUM          force an older protocol version to be used\n");
411 #ifdef ICONV_OPTION
412   rprintf(F,"     --iconv=CONVERT_SPEC    request charset conversion of filesnames\n");
413 #endif
414 #ifdef INET6
415   rprintf(F," -4, --ipv4                  prefer IPv4\n");
416   rprintf(F," -6, --ipv6                  prefer IPv6\n");
417 #endif
418   rprintf(F,"     --version               print version number\n");
419   rprintf(F,"(-h) --help                  show this help (-h works with no other options)\n");
420
421   rprintf(F,"\n");
422   rprintf(F,"Use \"rsync --daemon --help\" to see the daemon-mode command-line options.\n");
423   rprintf(F,"Please see the rsync(1) and rsyncd.conf(5) man pages for full documentation.\n");
424   rprintf(F,"See http://rsync.samba.org/ for updates, bug reports, and answers\n");
425 }
426
427 enum {OPT_VERSION = 1000, OPT_DAEMON, OPT_SENDER, OPT_EXCLUDE, OPT_EXCLUDE_FROM,
428       OPT_FILTER, OPT_COMPARE_DEST, OPT_COPY_DEST, OPT_LINK_DEST, OPT_HELP,
429       OPT_INCLUDE, OPT_INCLUDE_FROM, OPT_MODIFY_WINDOW, OPT_MIN_SIZE, OPT_CHMOD,
430       OPT_READ_BATCH, OPT_WRITE_BATCH, OPT_ONLY_WRITE_BATCH, OPT_MAX_SIZE,
431       OPT_NO_D,
432       OPT_SERVER, OPT_REFUSED_BASE = 9000};
433
434 static struct poptOption long_options[] = {
435   /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
436   {"help",             0,  POPT_ARG_NONE,   0, OPT_HELP, 0, 0 },
437   {"version",          0,  POPT_ARG_NONE,   0, OPT_VERSION, 0, 0},
438   {"verbose",         'v', POPT_ARG_NONE,   0, 'v', 0, 0 },
439   {"no-verbose",       0,  POPT_ARG_VAL,    &verbose, 0, 0, 0 },
440   {"no-v",             0,  POPT_ARG_VAL,    &verbose, 0, 0, 0 },
441   {"quiet",           'q', POPT_ARG_NONE,   0, 'q', 0, 0 },
442   {"motd",             0,  POPT_ARG_VAL,    &output_motd, 1, 0, 0 },
443   {"no-motd",          0,  POPT_ARG_VAL,    &output_motd, 0, 0, 0 },
444   {"stats",            0,  POPT_ARG_NONE,   &do_stats, 0, 0, 0 },
445   {"human-readable",  'h', POPT_ARG_NONE,   0, 'h', 0, 0},
446   {"dry-run",         'n', POPT_ARG_NONE,   &dry_run, 0, 0, 0 },
447   {"archive",         'a', POPT_ARG_NONE,   0, 'a', 0, 0 },
448   {"recursive",       'r', POPT_ARG_VAL,    &recurse, 2, 0, 0 },
449   {"no-recursive",     0,  POPT_ARG_VAL,    &recurse, 0, 0, 0 },
450   {"ir",               0,  POPT_ARG_VAL,    &allow_inc_recurse, 1, 0, 0 },
451   {"inc-recursive",    0,  POPT_ARG_VAL,    &allow_inc_recurse, 1, 0, 0 },
452   {"no-ir",            0,  POPT_ARG_VAL,    &allow_inc_recurse, 0, 0, 0 },
453   {"no-inc-recursive", 0,  POPT_ARG_VAL,    &allow_inc_recurse, 0, 0, 0 },
454   {"no-r",             0,  POPT_ARG_VAL,    &recurse, 0, 0, 0 },
455   {"dirs",            'd', POPT_ARG_VAL,    &xfer_dirs, 2, 0, 0 },
456   {"no-dirs",          0,  POPT_ARG_VAL,    &xfer_dirs, 0, 0, 0 },
457   {"no-d",             0,  POPT_ARG_VAL,    &xfer_dirs, 0, 0, 0 },
458   {"perms",           'p', POPT_ARG_VAL,    &preserve_perms, 1, 0, 0 },
459   {"no-perms",         0,  POPT_ARG_VAL,    &preserve_perms, 0, 0, 0 },
460   {"no-p",             0,  POPT_ARG_VAL,    &preserve_perms, 0, 0, 0 },
461   {"executability",   'E', POPT_ARG_NONE,   &preserve_executability, 0, 0, 0 },
462   {"acls",            'A', POPT_ARG_NONE,   0, 'A', 0, 0 },
463   {"no-acls",          0,  POPT_ARG_VAL,    &preserve_acls, 0, 0, 0 },
464   {"no-A",             0,  POPT_ARG_VAL,    &preserve_acls, 0, 0, 0 },
465   {"xattrs",          'X', POPT_ARG_NONE,   0, 'X', 0, 0 },
466   {"no-xattrs",        0,  POPT_ARG_VAL,    &preserve_xattrs, 0, 0, 0 },
467   {"no-X",             0,  POPT_ARG_VAL,    &preserve_xattrs, 0, 0, 0 },
468   {"times",           't', POPT_ARG_VAL,    &preserve_times, 1, 0, 0 },
469   {"no-times",         0,  POPT_ARG_VAL,    &preserve_times, 0, 0, 0 },
470   {"no-t",             0,  POPT_ARG_VAL,    &preserve_times, 0, 0, 0 },
471   {"omit-dir-times",  'O', POPT_ARG_VAL,    &omit_dir_times, 2, 0, 0 },
472   {"modify-window",    0,  POPT_ARG_INT,    &modify_window, OPT_MODIFY_WINDOW, 0, 0 },
473   {"super",            0,  POPT_ARG_VAL,    &am_root, 2, 0, 0 },
474   {"no-super",         0,  POPT_ARG_VAL,    &am_root, 0, 0, 0 },
475   {"fake-super",       0,  POPT_ARG_VAL,    &am_root, -1, 0, 0 },
476   {"owner",           'o', POPT_ARG_VAL,    &preserve_uid, 1, 0, 0 },
477   {"no-owner",         0,  POPT_ARG_VAL,    &preserve_uid, 0, 0, 0 },
478   {"no-o",             0,  POPT_ARG_VAL,    &preserve_uid, 0, 0, 0 },
479   {"group",           'g', POPT_ARG_VAL,    &preserve_gid, 1, 0, 0 },
480   {"no-group",         0,  POPT_ARG_VAL,    &preserve_gid, 0, 0, 0 },
481   {"no-g",             0,  POPT_ARG_VAL,    &preserve_gid, 0, 0, 0 },
482   {0,                 'D', POPT_ARG_NONE,   0, 'D', 0, 0 },
483   {"no-D",             0,  POPT_ARG_NONE,   0, OPT_NO_D, 0, 0 },
484   {"devices",          0,  POPT_ARG_VAL,    &preserve_devices, 1, 0, 0 },
485   {"no-devices",       0,  POPT_ARG_VAL,    &preserve_devices, 0, 0, 0 },
486   {"specials",         0,  POPT_ARG_VAL,    &preserve_specials, 1, 0, 0 },
487   {"no-specials",      0,  POPT_ARG_VAL,    &preserve_specials, 0, 0, 0 },
488   {"links",           'l', POPT_ARG_VAL,    &preserve_links, 1, 0, 0 },
489   {"no-links",         0,  POPT_ARG_VAL,    &preserve_links, 0, 0, 0 },
490   {"no-l",             0,  POPT_ARG_VAL,    &preserve_links, 0, 0, 0 },
491   {"copy-links",      'L', POPT_ARG_NONE,   &copy_links, 0, 0, 0 },
492   {"copy-unsafe-links",0,  POPT_ARG_NONE,   &copy_unsafe_links, 0, 0, 0 },
493   {"safe-links",       0,  POPT_ARG_NONE,   &safe_symlinks, 0, 0, 0 },
494   {"copy-dirlinks",   'k', POPT_ARG_NONE,   &copy_dirlinks, 0, 0, 0 },
495   {"keep-dirlinks",   'K', POPT_ARG_NONE,   &keep_dirlinks, 0, 0, 0 },
496   {"hard-links",      'H', POPT_ARG_NONE,   0, 'H', 0, 0 },
497   {"no-hard-links",    0,  POPT_ARG_VAL,    &preserve_hard_links, 0, 0, 0 },
498   {"no-H",             0,  POPT_ARG_VAL,    &preserve_hard_links, 0, 0, 0 },
499   {"relative",        'R', POPT_ARG_VAL,    &relative_paths, 1, 0, 0 },
500   {"no-relative",      0,  POPT_ARG_VAL,    &relative_paths, 0, 0, 0 },
501   {"no-R",             0,  POPT_ARG_VAL,    &relative_paths, 0, 0, 0 },
502   {"implied-dirs",     0,  POPT_ARG_VAL,    &implied_dirs, 1, 0, 0 },
503   {"no-implied-dirs",  0,  POPT_ARG_VAL,    &implied_dirs, 0, 0, 0 },
504   {"chmod",            0,  POPT_ARG_STRING, 0, OPT_CHMOD, 0, 0 },
505   {"ignore-times",    'I', POPT_ARG_NONE,   &ignore_times, 0, 0, 0 },
506   {"size-only",        0,  POPT_ARG_NONE,   &size_only, 0, 0, 0 },
507   {"one-file-system", 'x', POPT_ARG_NONE,   0, 'x', 0, 0 },
508   {"update",          'u', POPT_ARG_NONE,   &update_only, 0, 0, 0 },
509   {"existing",         0,  POPT_ARG_NONE,   &ignore_non_existing, 0, 0, 0 },
510   {"ignore-non-existing",0,POPT_ARG_NONE,   &ignore_non_existing, 0, 0, 0 },
511   {"ignore-existing",  0,  POPT_ARG_NONE,   &ignore_existing, 0, 0, 0 },
512   {"max-size",         0,  POPT_ARG_STRING, &max_size_arg, OPT_MAX_SIZE, 0, 0 },
513   {"min-size",         0,  POPT_ARG_STRING, &min_size_arg, OPT_MIN_SIZE, 0, 0 },
514   {"sparse",          'S', POPT_ARG_NONE,   &sparse_files, 0, 0, 0 },
515   {"inplace",          0,  POPT_ARG_NONE,   &inplace, 0, 0, 0 },
516   {"append",           0,  POPT_ARG_VAL,    &append_mode, 1, 0, 0 },
517   {"del",              0,  POPT_ARG_NONE,   &delete_during, 0, 0, 0 },
518   {"delete",           0,  POPT_ARG_NONE,   &delete_mode, 0, 0, 0 },
519   {"delete-before",    0,  POPT_ARG_NONE,   &delete_before, 0, 0, 0 },
520   {"delete-during",    0,  POPT_ARG_VAL,    &delete_during, 1, 0, 0 },
521   {"delete-delay",     0,  POPT_ARG_VAL,    &delete_during, 2, 0, 0 },
522   {"delete-after",     0,  POPT_ARG_NONE,   &delete_after, 0, 0, 0 },
523   {"delete-excluded",  0,  POPT_ARG_NONE,   &delete_excluded, 0, 0, 0 },
524   {"remove-sent-files",0,  POPT_ARG_VAL,    &remove_source_files, 2, 0, 0 }, /* deprecated */
525   {"remove-source-files",0,POPT_ARG_VAL,    &remove_source_files, 1, 0, 0 },
526   {"force",            0,  POPT_ARG_NONE,   &force_delete, 0, 0, 0 },
527   {"ignore-errors",    0,  POPT_ARG_NONE,   &ignore_errors, 0, 0, 0 },
528   {"max-delete",       0,  POPT_ARG_INT,    &max_delete, 0, 0, 0 },
529   {0,                 'F', POPT_ARG_NONE,   0, 'F', 0, 0 },
530   {"filter",          'f', POPT_ARG_STRING, 0, OPT_FILTER, 0, 0 },
531   {"exclude",          0,  POPT_ARG_STRING, 0, OPT_EXCLUDE, 0, 0 },
532   {"include",          0,  POPT_ARG_STRING, 0, OPT_INCLUDE, 0, 0 },
533   {"exclude-from",     0,  POPT_ARG_STRING, 0, OPT_EXCLUDE_FROM, 0, 0 },
534   {"include-from",     0,  POPT_ARG_STRING, 0, OPT_INCLUDE_FROM, 0, 0 },
535   {"cvs-exclude",     'C', POPT_ARG_NONE,   &cvs_exclude, 0, 0, 0 },
536   {"whole-file",      'W', POPT_ARG_VAL,    &whole_file, 1, 0, 0 },
537   {"no-whole-file",    0,  POPT_ARG_VAL,    &whole_file, 0, 0, 0 },
538   {"no-W",             0,  POPT_ARG_VAL,    &whole_file, 0, 0, 0 },
539   {"checksum",        'c', POPT_ARG_NONE,   &always_checksum, 0, 0, 0 },
540   {"block-size",      'B', POPT_ARG_LONG,   &block_size, 0, 0, 0 },
541   {"compare-dest",     0,  POPT_ARG_STRING, 0, OPT_COMPARE_DEST, 0, 0 },
542   {"copy-dest",        0,  POPT_ARG_STRING, 0, OPT_COPY_DEST, 0, 0 },
543   {"link-dest",        0,  POPT_ARG_STRING, 0, OPT_LINK_DEST, 0, 0 },
544   {"fuzzy",           'y', POPT_ARG_NONE,   &fuzzy_basis, 0, 0, 0 },
545   {"compress",        'z', POPT_ARG_NONE,   0, 'z', 0, 0 },
546   {"compress-level",   0,  POPT_ARG_INT,    &def_compress_level, 'z', 0, 0 },
547   {0,                 'P', POPT_ARG_NONE,   0, 'P', 0, 0 },
548   {"progress",         0,  POPT_ARG_VAL,    &do_progress, 1, 0, 0 },
549   {"no-progress",      0,  POPT_ARG_VAL,    &do_progress, 0, 0, 0 },
550   {"partial",          0,  POPT_ARG_VAL,    &keep_partial, 1, 0, 0 },
551   {"no-partial",       0,  POPT_ARG_VAL,    &keep_partial, 0, 0, 0 },
552   {"partial-dir",      0,  POPT_ARG_STRING, &partial_dir, 0, 0, 0 },
553   {"delay-updates",    0,  POPT_ARG_NONE,   &delay_updates, 0, 0, 0 },
554   {"prune-empty-dirs",'m', POPT_ARG_NONE,   &prune_empty_dirs, 0, 0, 0 },
555   {"log-file",         0,  POPT_ARG_STRING, &logfile_name, 0, 0, 0 },
556   {"log-file-format",  0,  POPT_ARG_STRING, &logfile_format, 0, 0, 0 },
557   {"out-format",       0,  POPT_ARG_STRING, &stdout_format, 0, 0, 0 },
558   {"log-format",       0,  POPT_ARG_STRING, &stdout_format, 0, 0, 0 }, /* DEPRECATED */
559   {"itemize-changes", 'i', POPT_ARG_NONE,   0, 'i', 0, 0 },
560   {"bwlimit",          0,  POPT_ARG_INT,    &bwlimit, 0, 0, 0 },
561   {"backup",          'b', POPT_ARG_NONE,   &make_backups, 0, 0, 0 },
562   {"backup-dir",       0,  POPT_ARG_STRING, &backup_dir, 0, 0, 0 },
563   {"suffix",           0,  POPT_ARG_STRING, &backup_suffix, 0, 0, 0 },
564   {"list-only",        0,  POPT_ARG_VAL,    &list_only, 2, 0, 0 },
565   {"read-batch",       0,  POPT_ARG_STRING, &batch_name, OPT_READ_BATCH, 0, 0 },
566   {"write-batch",      0,  POPT_ARG_STRING, &batch_name, OPT_WRITE_BATCH, 0, 0 },
567   {"only-write-batch", 0,  POPT_ARG_STRING, &batch_name, OPT_ONLY_WRITE_BATCH, 0, 0 },
568   {"files-from",       0,  POPT_ARG_STRING, &files_from, 0, 0, 0 },
569   {"from0",           '0', POPT_ARG_NONE,   &eol_nulls, 0, 0, 0},
570   {"numeric-ids",      0,  POPT_ARG_NONE,   &numeric_ids, 0, 0, 0 },
571   {"timeout",          0,  POPT_ARG_INT,    &io_timeout, 0, 0, 0 },
572   {"rsh",             'e', POPT_ARG_STRING, &shell_cmd, 0, 0, 0 },
573   {"rsync-path",       0,  POPT_ARG_STRING, &rsync_path, 0, 0, 0 },
574   {"temp-dir",        'T', POPT_ARG_STRING, &tmpdir, 0, 0, 0 },
575 #ifdef ICONV_OPTION
576   {"iconv",            0,  POPT_ARG_STRING, &iconv_opt, 0, 0, 0 },
577 #endif
578 #ifdef INET6
579   {"ipv4",            '4', POPT_ARG_VAL,    &default_af_hint, AF_INET, 0, 0 },
580   {"ipv6",            '6', POPT_ARG_VAL,    &default_af_hint, AF_INET6, 0, 0 },
581 #endif
582   {"8-bit-output",    '8', POPT_ARG_NONE,   &allow_8bit_chars, 0, 0, 0 },
583   {"address",          0,  POPT_ARG_STRING, &bind_address, 0, 0, 0 },
584   {"port",             0,  POPT_ARG_INT,    &rsync_port, 0, 0, 0 },
585   {"sockopts",         0,  POPT_ARG_STRING, &sockopts, 0, 0, 0 },
586   {"password-file",    0,  POPT_ARG_STRING, &password_file, 0, 0, 0 },
587   {"blocking-io",      0,  POPT_ARG_VAL,    &blocking_io, 1, 0, 0 },
588   {"no-blocking-io",   0,  POPT_ARG_VAL,    &blocking_io, 0, 0, 0 },
589   {"protocol",         0,  POPT_ARG_INT,    &protocol_version, 0, 0, 0 },
590   {"checksum-seed",    0,  POPT_ARG_INT,    &checksum_seed, 0, 0, 0 },
591   {"server",           0,  POPT_ARG_NONE,   0, OPT_SERVER, 0, 0 },
592   {"sender",           0,  POPT_ARG_NONE,   0, OPT_SENDER, 0, 0 },
593   /* All the following options switch us into daemon-mode option-parsing. */
594   {"config",           0,  POPT_ARG_STRING, 0, OPT_DAEMON, 0, 0 },
595   {"daemon",           0,  POPT_ARG_NONE,   0, OPT_DAEMON, 0, 0 },
596   {"detach",           0,  POPT_ARG_NONE,   0, OPT_DAEMON, 0, 0 },
597   {"no-detach",        0,  POPT_ARG_NONE,   0, OPT_DAEMON, 0, 0 },
598   {0,0,0,0, 0, 0, 0}
599 };
600
601 static void daemon_usage(enum logcode F)
602 {
603   print_rsync_version(F);
604
605   rprintf(F,"\n");
606   rprintf(F,"Usage: rsync --daemon [OPTION]...\n");
607   rprintf(F,"     --address=ADDRESS       bind to the specified address\n");
608   rprintf(F,"     --bwlimit=KBPS          limit I/O bandwidth; KBytes per second\n");
609   rprintf(F,"     --config=FILE           specify alternate rsyncd.conf file\n");
610   rprintf(F,"     --no-detach             do not detach from the parent\n");
611   rprintf(F,"     --port=PORT             listen on alternate port number\n");
612   rprintf(F,"     --log-file=FILE         override the \"log file\" setting\n");
613   rprintf(F,"     --log-file-format=FMT   override the \"log format\" setting\n");
614   rprintf(F,"     --sockopts=OPTIONS      specify custom TCP options\n");
615   rprintf(F," -v, --verbose               increase verbosity\n");
616 #ifdef INET6
617   rprintf(F," -4, --ipv4                  prefer IPv4\n");
618   rprintf(F," -6, --ipv6                  prefer IPv6\n");
619 #endif
620   rprintf(F,"     --help                  show this help screen\n");
621
622   rprintf(F,"\n");
623   rprintf(F,"If you were not trying to invoke rsync as a daemon, avoid using any of the\n");
624   rprintf(F,"daemon-specific rsync options.  See also the rsyncd.conf(5) man page.\n");
625 }
626
627 static struct poptOption long_daemon_options[] = {
628   /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
629   {"address",          0,  POPT_ARG_STRING, &bind_address, 0, 0, 0 },
630   {"bwlimit",          0,  POPT_ARG_INT,    &daemon_bwlimit, 0, 0, 0 },
631   {"config",           0,  POPT_ARG_STRING, &config_file, 0, 0, 0 },
632   {"daemon",           0,  POPT_ARG_NONE,   &daemon_opt, 0, 0, 0 },
633 #ifdef INET6
634   {"ipv4",            '4', POPT_ARG_VAL,    &default_af_hint, AF_INET, 0, 0 },
635   {"ipv6",            '6', POPT_ARG_VAL,    &default_af_hint, AF_INET6, 0, 0 },
636 #endif
637   {"detach",           0,  POPT_ARG_VAL,    &no_detach, 0, 0, 0 },
638   {"log-file",         0,  POPT_ARG_STRING, &logfile_name, 0, 0, 0 },
639   {"log-file-format",  0,  POPT_ARG_STRING, &logfile_format, 0, 0, 0 },
640   {"no-detach",        0,  POPT_ARG_VAL,    &no_detach, 1, 0, 0 },
641   {"port",             0,  POPT_ARG_INT,    &rsync_port, 0, 0, 0 },
642   {"sockopts",         0,  POPT_ARG_STRING, &sockopts, 0, 0, 0 },
643   {"protocol",         0,  POPT_ARG_INT,    &protocol_version, 0, 0, 0 },
644   {"server",           0,  POPT_ARG_NONE,   &am_server, 0, 0, 0 },
645   {"temp-dir",        'T', POPT_ARG_STRING, &tmpdir, 0, 0, 0 },
646   {"verbose",         'v', POPT_ARG_NONE,   0, 'v', 0, 0 },
647   {"no-verbose",       0,  POPT_ARG_VAL,    &verbose, 0, 0, 0 },
648   {"no-v",             0,  POPT_ARG_VAL,    &verbose, 0, 0, 0 },
649   {"help",            'h', POPT_ARG_NONE,   0, 'h', 0, 0 },
650   {0,0,0,0, 0, 0, 0}
651 };
652
653
654 static char err_buf[200];
655
656
657 /**
658  * Store the option error message, if any, so that we can log the
659  * connection attempt (which requires parsing the options), and then
660  * show the error later on.
661  **/
662 void option_error(void)
663 {
664         if (!err_buf[0]) {
665                 strlcpy(err_buf, "Error parsing options: option may "
666                         "be supported on client but not on server?\n",
667                         sizeof err_buf);
668         }
669
670         rprintf(FERROR, RSYNC_NAME ": %s", err_buf);
671         msleep(20);
672 }
673
674
675 /**
676  * Tweak the option table to disable all options that the rsyncd.conf
677  * file has told us to refuse.
678  **/
679 static void set_refuse_options(char *bp)
680 {
681         struct poptOption *op;
682         char *cp, shortname[2];
683         int is_wild, found_match;
684
685         shortname[1] = '\0';
686
687         while (1) {
688                 while (*bp == ' ') bp++;
689                 if (!*bp)
690                         break;
691                 if ((cp = strchr(bp, ' ')) != NULL)
692                         *cp= '\0';
693                 is_wild = strpbrk(bp, "*?[") != NULL;
694                 found_match = 0;
695                 for (op = long_options; ; op++) {
696                         *shortname = op->shortName;
697                         if (!op->longName && !*shortname)
698                                 break;
699                         if ((op->longName && wildmatch(bp, op->longName))
700                             || (*shortname && wildmatch(bp, shortname))) {
701                                 if (op->argInfo == POPT_ARG_VAL)
702                                         op->argInfo = POPT_ARG_NONE;
703                                 op->val = (op - long_options) + OPT_REFUSED_BASE;
704                                 found_match = 1;
705                                 /* These flags are set to let us easily check
706                                  * an implied option later in the code. */
707                                 switch (*shortname) {
708                                 case 'r': case 'd': case 'l': case 'p':
709                                 case 't': case 'g': case 'o': case 'D':
710                                         refused_archive_part = op->val;
711                                         break;
712                                 case 'z':
713                                         refused_compress = op->val;
714                                         break;
715                                 case '\0':
716                                         if (wildmatch("delete", op->longName))
717                                                 refused_delete = op->val;
718                                         else if (wildmatch("delete-before", op->longName))
719                                                 refused_delete_before = op->val;
720                                         else if (wildmatch("delete-during", op->longName))
721                                                 refused_delete_during = op->val;
722                                         else if (wildmatch("partial", op->longName))
723                                                 refused_partial = op->val;
724                                         else if (wildmatch("progress", op->longName))
725                                                 refused_progress = op->val;
726                                         else if (wildmatch("inplace", op->longName))
727                                                 refused_inplace = op->val;
728                                         break;
729                                 }
730                                 if (!is_wild)
731                                         break;
732                         }
733                 }
734                 if (!found_match) {
735                         rprintf(FLOG, "No match for refuse-options string \"%s\"\n",
736                                 bp);
737                 }
738                 if (!cp)
739                         break;
740                 *cp = ' ';
741                 bp = cp + 1;
742         }
743 }
744
745
746 static int count_args(const char **argv)
747 {
748         int i = 0;
749
750         if (argv) {
751                 while (argv[i] != NULL)
752                         i++;
753         }
754
755         return i;
756 }
757
758
759 static OFF_T parse_size_arg(char **size_arg, char def_suf)
760 {
761         int reps, mult, make_compatible = 0;
762         const char *arg;
763         OFF_T size = 1;
764
765         for (arg = *size_arg; isDigit(arg); arg++) {}
766         if (*arg == '.')
767                 for (arg++; isDigit(arg); arg++) {}
768         switch (*arg && *arg != '+' && *arg != '-' ? *arg++ : def_suf) {
769         case 'b': case 'B':
770                 reps = 0;
771                 break;
772         case 'k': case 'K':
773                 reps = 1;
774                 break;
775         case 'm': case 'M':
776                 reps = 2;
777                 break;
778         case 'g': case 'G':
779                 reps = 3;
780                 break;
781         default:
782                 return -1;
783         }
784         if (*arg == 'b' || *arg == 'B')
785                 mult = 1000, make_compatible = 1, arg++;
786         else if (!*arg || *arg == '+' || *arg == '-')
787                 mult = 1024;
788         else if (strncasecmp(arg, "ib", 2) == 0)
789                 mult = 1024, arg += 2;
790         else
791                 return -1;
792         while (reps--)
793                 size *= mult;
794         size *= atof(*size_arg);
795         if ((*arg == '+' || *arg == '-') && arg[1] == '1')
796                 size += atoi(arg), make_compatible = 1, arg += 2;
797         if (*arg)
798                 return -1;
799         if (size > 0 && make_compatible) {
800                 /* We convert this manually because we may need %lld precision,
801                  * and that's not a portable sprintf() escape. */
802                 char buf[128], *s = buf + sizeof buf - 1;
803                 OFF_T num = size;
804                 *s = '\0';
805                 while (num) {
806                         *--s = (char)(num % 10) + '0';
807                         num /= 10;
808                 }
809                 if (!(*size_arg = strdup(s)))
810                         out_of_memory("parse_size_arg");
811         }
812         return size;
813 }
814
815
816 static void create_refuse_error(int which)
817 {
818         /* The "which" value is the index + OPT_REFUSED_BASE. */
819         struct poptOption *op = &long_options[which - OPT_REFUSED_BASE];
820         int n = snprintf(err_buf, sizeof err_buf,
821                          "The server is configured to refuse --%s\n",
822                          op->longName) - 1;
823         if (op->shortName) {
824                 snprintf(err_buf + n, sizeof err_buf - n,
825                          " (-%c)\n", op->shortName);
826         }
827 }
828
829
830 /**
831  * Process command line arguments.  Called on both local and remote.
832  *
833  * @retval 1 if all options are OK; with globals set to appropriate
834  * values
835  *
836  * @retval 0 on error, with err_buf containing an explanation
837  **/
838 int parse_arguments(int *argc, const char ***argv, int frommain)
839 {
840         int opt;
841         char *ref = lp_refuse_options(module_id);
842         const char *arg;
843         poptContext pc;
844
845         if (ref && *ref)
846                 set_refuse_options(ref);
847         if (am_daemon)
848                 set_refuse_options("log-file*");
849
850 #ifdef ICONV_OPTION
851         if (!am_daemon && (arg = getenv("RSYNC_ICONV")) != NULL && *arg)
852                 iconv_opt = strdup(arg);
853 #endif
854
855         /* TODO: Call poptReadDefaultConfig; handle errors. */
856
857         /* The context leaks in case of an error, but if there's a
858          * problem we always exit anyhow. */
859         pc = poptGetContext(RSYNC_NAME, *argc, *argv, long_options, 0);
860         poptReadDefaultConfig(pc, 0);
861
862         while ((opt = poptGetNextOpt(pc)) != -1) {
863                 /* most options are handled automatically by popt;
864                  * only special cases are returned and listed here. */
865
866                 switch (opt) {
867                 case OPT_VERSION:
868                         print_rsync_version(FINFO);
869                         exit_cleanup(0);
870
871                 case OPT_SERVER:
872                         if (!am_server) {
873                                 /* Disable popt aliases on the server side and
874                                  * then start parsing the options again. */
875                                 poptFreeContext(pc);
876                                 pc = poptGetContext(RSYNC_NAME, *argc, *argv,
877                                                     long_options, 0);
878                                 am_server = 1;
879                         }
880 #ifdef ICONV_OPTION
881                         iconv_opt = NULL;
882 #endif
883                         break;
884
885                 case OPT_SENDER:
886                         if (!am_server) {
887                                 usage(FERROR);
888                                 exit_cleanup(RERR_SYNTAX);
889                         }
890                         am_sender = 1;
891                         break;
892
893                 case OPT_DAEMON:
894                         if (am_daemon) {
895                                 strlcpy(err_buf,
896                                         "Attempt to hack rsync thwarted!\n",
897                                         sizeof err_buf);
898                                 return 0;
899                         }
900 #ifdef ICONV_OPTION
901                         iconv_opt = NULL;
902 #endif
903                         poptFreeContext(pc);
904                         pc = poptGetContext(RSYNC_NAME, *argc, *argv,
905                                             long_daemon_options, 0);
906                         while ((opt = poptGetNextOpt(pc)) != -1) {
907                                 switch (opt) {
908                                 case 'h':
909                                         daemon_usage(FINFO);
910                                         exit_cleanup(0);
911
912                                 case 'v':
913                                         verbose++;
914                                         break;
915
916                                 default:
917                                         rprintf(FERROR,
918                                             "rsync: %s: %s (in daemon mode)\n",
919                                             poptBadOption(pc, POPT_BADOPTION_NOALIAS),
920                                             poptStrerror(opt));
921                                         goto daemon_error;
922                                 }
923                         }
924
925                         if (tmpdir && strlen(tmpdir) >= MAXPATHLEN - 10) {
926                                 snprintf(err_buf, sizeof err_buf,
927                                          "the --temp-dir path is WAY too long.\n");
928                                 return 0;
929                         }
930
931                         if (!daemon_opt) {
932                                 rprintf(FERROR, "Daemon option(s) used without --daemon.\n");
933                             daemon_error:
934                                 rprintf(FERROR,
935                                     "(Type \"rsync --daemon --help\" for assistance with daemon mode.)\n");
936                                 exit_cleanup(RERR_SYNTAX);
937                         }
938
939                         *argv = poptGetArgs(pc);
940                         *argc = count_args(*argv);
941                         am_starting_up = 0;
942                         daemon_opt = 0;
943                         am_daemon = 1;
944                         return 1;
945
946                 case OPT_MODIFY_WINDOW:
947                         /* The value has already been set by popt, but
948                          * we need to remember that we're using a
949                          * non-default setting. */
950                         modify_window_set = 1;
951                         break;
952
953                 case OPT_FILTER:
954                         parse_rule(&filter_list, poptGetOptArg(pc), 0, 0);
955                         break;
956
957                 case OPT_EXCLUDE:
958                         parse_rule(&filter_list, poptGetOptArg(pc),
959                                    0, XFLG_OLD_PREFIXES);
960                         break;
961
962                 case OPT_INCLUDE:
963                         parse_rule(&filter_list, poptGetOptArg(pc),
964                                    MATCHFLG_INCLUDE, XFLG_OLD_PREFIXES);
965                         break;
966
967                 case OPT_EXCLUDE_FROM:
968                 case OPT_INCLUDE_FROM:
969                         arg = poptGetOptArg(pc);
970                         if (sanitize_paths)
971                                 arg = sanitize_path(NULL, arg, NULL, 0, NULL);
972                         if (server_filter_list.head) {
973                                 char *cp = strdup(arg);
974                                 if (!cp)
975                                         out_of_memory("parse_arguments");
976                                 if (!*cp)
977                                         goto options_rejected;
978                                 clean_fname(cp, 1);
979                                 if (check_filter(&server_filter_list, cp, 0) < 0)
980                                         goto options_rejected;
981                                 free(cp);
982                         }
983                         parse_filter_file(&filter_list, arg,
984                                 opt == OPT_INCLUDE_FROM ? MATCHFLG_INCLUDE : 0,
985                                 XFLG_FATAL_ERRORS | XFLG_OLD_PREFIXES);
986                         break;
987
988                 case 'a':
989                         if (refused_archive_part) {
990                                 create_refuse_error(refused_archive_part);
991                                 return 0;
992                         }
993                         if (!recurse) /* preserve recurse == 2 */
994                                 recurse = 1;
995 #ifdef SUPPORT_LINKS
996                         preserve_links = 1;
997 #endif
998                         preserve_perms = 1;
999                         preserve_times = 1;
1000                         preserve_gid = 1;
1001                         preserve_uid = 1;
1002                         preserve_devices = 1;
1003                         preserve_specials = 1;
1004                         break;
1005
1006                 case 'D':
1007                         preserve_devices = preserve_specials = 1;
1008                         break;
1009
1010                 case OPT_NO_D:
1011                         preserve_devices = preserve_specials = 0;
1012                         break;
1013
1014                 case 'h':
1015                         human_readable++;
1016                         break;
1017
1018                 case 'H':
1019                         preserve_hard_links++;
1020                         break;
1021
1022                 case 'i':
1023                         itemize_changes++;
1024                         break;
1025
1026                 case 'v':
1027                         verbose++;
1028                         break;
1029
1030                 case 'q':
1031                         if (frommain)
1032                                 quiet++;
1033                         break;
1034
1035                 case 'x':
1036                         one_file_system++;
1037                         break;
1038
1039                 case 'F':
1040                         switch (++F_option_cnt) {
1041                         case 1:
1042                                 parse_rule(&filter_list,": /.rsync-filter",0,0);
1043                                 break;
1044                         case 2:
1045                                 parse_rule(&filter_list,"- .rsync-filter",0,0);
1046                                 break;
1047                         }
1048                         break;
1049
1050                 case 'P':
1051                         if (refused_partial || refused_progress) {
1052                                 create_refuse_error(refused_partial
1053                                     ? refused_partial : refused_progress);
1054                                 return 0;
1055                         }
1056                         do_progress = 1;
1057                         keep_partial = 1;
1058                         break;
1059
1060                 case 'z':
1061                         if (def_compress_level < Z_DEFAULT_COMPRESSION
1062                          || def_compress_level > Z_BEST_COMPRESSION) {
1063                                 snprintf(err_buf, sizeof err_buf,
1064                                         "--compress-level value is invalid: %d\n",
1065                                         def_compress_level);
1066                                 return 0;
1067                         }
1068                         do_compression = def_compress_level != Z_NO_COMPRESSION;
1069                         if (do_compression && refused_compress) {
1070                                 create_refuse_error(refused_compress);
1071                                 return 0;
1072                         }
1073                         break;
1074
1075                 case OPT_WRITE_BATCH:
1076                         /* batch_name is already set */
1077                         write_batch = 1;
1078                         break;
1079
1080                 case OPT_ONLY_WRITE_BATCH:
1081                         /* batch_name is already set */
1082                         write_batch = -1;
1083                         break;
1084
1085                 case OPT_READ_BATCH:
1086                         /* batch_name is already set */
1087                         read_batch = 1;
1088                         break;
1089
1090                 case OPT_MAX_SIZE:
1091                         if ((max_size = parse_size_arg(&max_size_arg, 'b')) <= 0) {
1092                                 snprintf(err_buf, sizeof err_buf,
1093                                         "--max-size value is invalid: %s\n",
1094                                         max_size_arg);
1095                                 return 0;
1096                         }
1097                         break;
1098
1099                 case OPT_MIN_SIZE:
1100                         if ((min_size = parse_size_arg(&min_size_arg, 'b')) <= 0) {
1101                                 snprintf(err_buf, sizeof err_buf,
1102                                         "--min-size value is invalid: %s\n",
1103                                         min_size_arg);
1104                                 return 0;
1105                         }
1106                         break;
1107
1108                 case OPT_LINK_DEST:
1109 #ifdef SUPPORT_HARD_LINKS
1110                         link_dest = 1;
1111                         dest_option = "--link-dest";
1112                         goto set_dest_dir;
1113 #else
1114                         snprintf(err_buf, sizeof err_buf,
1115                                  "hard links are not supported on this %s\n",
1116                                  am_server ? "server" : "client");
1117                         return 0;
1118 #endif
1119
1120                 case OPT_COPY_DEST:
1121                         copy_dest = 1;
1122                         dest_option = "--copy-dest";
1123                         goto set_dest_dir;
1124
1125                 case OPT_COMPARE_DEST:
1126                         compare_dest = 1;
1127                         dest_option = "--compare-dest";
1128                 set_dest_dir:
1129                         if (basis_dir_cnt >= MAX_BASIS_DIRS) {
1130                                 snprintf(err_buf, sizeof err_buf,
1131                                         "ERROR: at most %d %s args may be specified\n",
1132                                         MAX_BASIS_DIRS, dest_option);
1133                                 return 0;
1134                         }
1135                         /* We defer sanitizing this arg until we know what
1136                          * our destination directory is going to be. */
1137                         basis_dir[basis_dir_cnt++] = (char *)poptGetOptArg(pc);
1138                         break;
1139
1140                 case OPT_CHMOD:
1141                         arg = poptGetOptArg(pc);
1142                         if (!parse_chmod(arg, &chmod_modes)) {
1143                                 snprintf(err_buf, sizeof err_buf,
1144                                     "Invalid argument passed to --chmod (%s)\n",
1145                                     arg);
1146                                 return 0;
1147                         }
1148                         break;
1149
1150                 case OPT_HELP:
1151                         usage(FINFO);
1152                         exit_cleanup(0);
1153
1154                 case 'A':
1155 #ifdef SUPPORT_ACLS
1156                         preserve_acls = 1;
1157                         preserve_perms = 1;
1158                         break;
1159 #else
1160                         /* FIXME: this should probably be ignored with a
1161                          * warning and then countermeasures taken to
1162                          * restrict group and other access in the presence
1163                          * of any more restrictive ACLs, but this is safe
1164                          * for now */
1165                         snprintf(err_buf,sizeof(err_buf),
1166                                  "ACLs are not supported on this %s\n",
1167                                  am_server ? "server" : "client");
1168                         return 0;
1169 #endif
1170
1171                 case 'X':
1172 #ifdef SUPPORT_XATTRS
1173                         preserve_xattrs = 1;
1174                         preserve_perms = 1;
1175                         break;
1176 #else
1177                         snprintf(err_buf,sizeof(err_buf),
1178                                  "extended attributes are not supported on this %s\n",
1179                                  am_server ? "server" : "client");
1180                         return 0;
1181 #endif
1182
1183                 default:
1184                         /* A large opt value means that set_refuse_options()
1185                          * turned this option off. */
1186                         if (opt >= OPT_REFUSED_BASE) {
1187                                 create_refuse_error(opt);
1188                                 return 0;
1189                         }
1190                         snprintf(err_buf, sizeof err_buf, "%s%s: %s\n",
1191                                  am_server ? "on remote machine: " : "",
1192                                  poptBadOption(pc, POPT_BADOPTION_NOALIAS),
1193                                  poptStrerror(opt));
1194                         return 0;
1195                 }
1196         }
1197
1198         if (human_readable && *argc == 2) {
1199                 /* Allow the old meaning of 'h' (--help) on its own. */
1200                 usage(FINFO);
1201                 exit_cleanup(0);
1202         }
1203
1204 #ifdef ICONV_OPTION
1205         if (iconv_opt) {
1206                 if (!am_server && strcmp(iconv_opt, "-") == 0)
1207                         iconv_opt = NULL;
1208                 else
1209                         need_unsorted_flist = 1;
1210         }
1211 #endif
1212
1213 #ifndef SUPPORT_LINKS
1214         if (preserve_links && !am_sender) {
1215                 snprintf(err_buf, sizeof err_buf,
1216                          "symlinks are not supported on this %s\n",
1217                          am_server ? "server" : "client");
1218                 return 0;
1219         }
1220 #endif
1221
1222 #ifndef SUPPORT_HARD_LINKS
1223         if (preserve_hard_links) {
1224                 snprintf(err_buf, sizeof err_buf,
1225                          "hard links are not supported on this %s\n",
1226                          am_server ? "server" : "client");
1227                 return 0;
1228         }
1229 #endif
1230
1231 #ifndef SUPPORT_XATTRS
1232         if (am_root < 0) {
1233                 snprintf(err_buf, sizeof err_buf,
1234                          "--fake-super requires an rsync with extended attributes enabled\n");
1235                 return 0;
1236         }
1237 #endif
1238
1239         if (write_batch && read_batch) {
1240                 snprintf(err_buf, sizeof err_buf,
1241                         "--write-batch and --read-batch can not be used together\n");
1242                 return 0;
1243         }
1244         if (write_batch > 0 || read_batch) {
1245                 if (am_server) {
1246                         rprintf(FINFO,
1247                                 "ignoring --%s-batch option sent to server\n",
1248                                 write_batch ? "write" : "read");
1249                         /* We don't actually exit_cleanup(), so that we can
1250                          * still service older version clients that still send
1251                          * batch args to server. */
1252                         read_batch = write_batch = 0;
1253                         batch_name = NULL;
1254                 } else if (dry_run)
1255                         write_batch = 0;
1256         }
1257         if (read_batch && files_from) {
1258                 snprintf(err_buf, sizeof err_buf,
1259                         "--read-batch cannot be used with --files-from\n");
1260                 return 0;
1261         }
1262         if (batch_name && strlen(batch_name) > MAX_BATCH_NAME_LEN) {
1263                 snprintf(err_buf, sizeof err_buf,
1264                         "the batch-file name must be %d characters or less.\n",
1265                         MAX_BATCH_NAME_LEN);
1266                 return 0;
1267         }
1268
1269         if (tmpdir && strlen(tmpdir) >= MAXPATHLEN - 10) {
1270                 snprintf(err_buf, sizeof err_buf,
1271                          "the --temp-dir path is WAY too long.\n");
1272                 return 0;
1273         }
1274
1275         if (compare_dest + copy_dest + link_dest > 1) {
1276                 snprintf(err_buf, sizeof err_buf,
1277                         "You may not mix --compare-dest, --copy-dest, and --link-dest.\n");
1278                 return 0;
1279         }
1280
1281         if (files_from) {
1282                 if (recurse == 1) /* preserve recurse == 2 */
1283                         recurse = 0;
1284                 if (xfer_dirs < 0)
1285                         xfer_dirs = 1;
1286         }
1287
1288         if (xfer_dirs < 1)
1289                 xfer_dirs = recurse || list_only;
1290
1291         if (relative_paths < 0)
1292                 relative_paths = files_from? 1 : 0;
1293         if (!relative_paths)
1294                 implied_dirs = 0;
1295
1296         if (delete_before + !!delete_during + delete_after > 1) {
1297                 snprintf(err_buf, sizeof err_buf,
1298                         "You may not combine multiple --delete-WHEN options.\n");
1299                 return 0;
1300         }
1301         if (delete_before || delete_during || delete_after)
1302                 delete_mode = 1;
1303         else if (delete_mode || delete_excluded) {
1304                 /* Only choose now between before & during if one is refused. */
1305                 if (refused_delete_before) {
1306                         if (!refused_delete_during)
1307                                 delete_during = 1;
1308                         else {
1309                                 create_refuse_error(refused_delete_before);
1310                                 return 0;
1311                         }
1312                 } else if (refused_delete_during)
1313                         delete_before = 1;
1314                 delete_mode = 1;
1315         }
1316         if (!xfer_dirs && delete_mode) {
1317                 snprintf(err_buf, sizeof err_buf,
1318                         "--delete does not work without -r or -d.\n");
1319                 return 0;
1320         }
1321
1322         if (delete_mode && refused_delete) {
1323                 create_refuse_error(refused_delete);
1324                 return 0;
1325         }
1326
1327         if (remove_source_files) {
1328                 /* We only want to infer this refusal of --remove-source-files
1329                  * via the refusal of "delete", not any of the "delete-FOO"
1330                  * options. */
1331                 if (refused_delete && am_sender) {
1332                         create_refuse_error(refused_delete);
1333                         return 0;
1334                 }
1335                 need_messages_from_generator = 1;
1336         }
1337
1338         *argv = poptGetArgs(pc);
1339         *argc = count_args(*argv);
1340
1341         if (sanitize_paths) {
1342                 int i;
1343                 for (i = *argc; i-- > 0; )
1344                         (*argv)[i] = sanitize_path(NULL, (*argv)[i], "", 0, NULL);
1345                 if (tmpdir)
1346                         tmpdir = sanitize_path(NULL, tmpdir, NULL, 0, NULL);
1347                 if (backup_dir)
1348                         backup_dir = sanitize_path(NULL, backup_dir, NULL, 0, NULL);
1349         }
1350         if (server_filter_list.head && !am_sender) {
1351                 struct filter_list_struct *elp = &server_filter_list;
1352                 if (tmpdir) {
1353                         if (!*tmpdir)
1354                                 goto options_rejected;
1355                         clean_fname(tmpdir, 1);
1356                         if (check_filter(elp, tmpdir, 1) < 0)
1357                                 goto options_rejected;
1358                 }
1359                 if (backup_dir) {
1360                         if (!*backup_dir)
1361                                 goto options_rejected;
1362                         clean_fname(backup_dir, 1);
1363                         if (check_filter(elp, backup_dir, 1) < 0)
1364                                 goto options_rejected;
1365                 }
1366         }
1367
1368         if (!backup_suffix)
1369                 backup_suffix = backup_dir ? "" : BACKUP_SUFFIX;
1370         backup_suffix_len = strlen(backup_suffix);
1371         if (strchr(backup_suffix, '/') != NULL) {
1372                 snprintf(err_buf, sizeof err_buf,
1373                         "--suffix cannot contain slashes: %s\n",
1374                         backup_suffix);
1375                 return 0;
1376         }
1377         if (backup_dir) {
1378                 backup_dir_len = strlcpy(backup_dir_buf, backup_dir, sizeof backup_dir_buf);
1379                 backup_dir_remainder = sizeof backup_dir_buf - backup_dir_len;
1380                 if (backup_dir_remainder < 32) {
1381                         snprintf(err_buf, sizeof err_buf,
1382                                 "the --backup-dir path is WAY too long.\n");
1383                         return 0;
1384                 }
1385                 if (backup_dir_buf[backup_dir_len - 1] != '/') {
1386                         backup_dir_buf[backup_dir_len++] = '/';
1387                         backup_dir_buf[backup_dir_len] = '\0';
1388                 }
1389                 if (verbose > 1 && !am_sender)
1390                         rprintf(FINFO, "backup_dir is %s\n", backup_dir_buf);
1391         } else if (!backup_suffix_len && (!am_server || !am_sender)) {
1392                 snprintf(err_buf, sizeof err_buf,
1393                         "--suffix cannot be a null string without --backup-dir\n");
1394                 return 0;
1395         } else if (make_backups && delete_mode && !delete_excluded && !am_server) {
1396                 snprintf(backup_dir_buf, sizeof backup_dir_buf,
1397                         "P *%s", backup_suffix);
1398                 parse_rule(&filter_list, backup_dir_buf, 0, 0);
1399         }
1400         if (make_backups && !backup_dir)
1401                 omit_dir_times = 1;
1402
1403         if (stdout_format) {
1404                 if (am_server && log_format_has(stdout_format, 'I'))
1405                         stdout_format_has_i = 2;
1406                 else if (log_format_has(stdout_format, 'i'))
1407                         stdout_format_has_i = itemize_changes | 1;
1408                 if (!log_format_has(stdout_format, 'b')
1409                  && !log_format_has(stdout_format, 'c'))
1410                         log_before_transfer = !am_server;
1411         } else if (itemize_changes) {
1412                 stdout_format = "%i %n%L";
1413                 stdout_format_has_i = itemize_changes;
1414                 log_before_transfer = !am_server;
1415         }
1416
1417         if (do_progress && !verbose && !log_before_transfer && !am_server)
1418                 verbose = 1;
1419
1420         if (dry_run)
1421                 do_xfers = 0;
1422
1423         set_io_timeout(io_timeout);
1424
1425         if (verbose && !stdout_format) {
1426                 stdout_format = "%n%L";
1427                 log_before_transfer = !am_server;
1428         }
1429         if (stdout_format_has_i || log_format_has(stdout_format, 'o'))
1430                 stdout_format_has_o_or_i = 1;
1431
1432         if (logfile_name && !am_daemon) {
1433                 if (!logfile_format) {
1434                         logfile_format = "%i %n%L";
1435                         logfile_format_has_i = logfile_format_has_o_or_i = 1;
1436                 } else {
1437                         if (log_format_has(logfile_format, 'i'))
1438                                 logfile_format_has_i = 1;
1439                         if (logfile_format_has_i || log_format_has(logfile_format, 'o'))
1440                                 logfile_format_has_o_or_i = 1;
1441                 }
1442                 log_init(0);
1443         } else if (!am_daemon)
1444                 logfile_format = NULL;
1445
1446         if (daemon_bwlimit && (!bwlimit || bwlimit > daemon_bwlimit))
1447                 bwlimit = daemon_bwlimit;
1448         if (bwlimit) {
1449                 bwlimit_writemax = (size_t)bwlimit * 128;
1450                 if (bwlimit_writemax < 512)
1451                         bwlimit_writemax = 512;
1452         }
1453
1454         if (sparse_files && inplace) {
1455                 /* Note: we don't check for this below, because --append is
1456                  * OK with --sparse (as long as redos are handled right). */
1457                 snprintf(err_buf, sizeof err_buf,
1458                          "--sparse cannot be used with --inplace\n");
1459                 return 0;
1460         }
1461
1462         if (append_mode) {
1463                 if (whole_file > 0) {
1464                         snprintf(err_buf, sizeof err_buf,
1465                                  "--append cannot be used with --whole-file\n");
1466                         return 0;
1467                 }
1468                 if (refused_inplace) {
1469                         create_refuse_error(refused_inplace);
1470                         return 0;
1471                 }
1472                 inplace = 1;
1473         }
1474
1475         if (delay_updates && !partial_dir)
1476                 partial_dir = tmp_partialdir;
1477
1478         if (inplace) {
1479 #ifdef HAVE_FTRUNCATE
1480                 if (partial_dir) {
1481                         snprintf(err_buf, sizeof err_buf,
1482                                  "--%s cannot be used with --%s\n",
1483                                  append_mode ? "append" : "inplace",
1484                                  delay_updates ? "delay-updates" : "partial-dir");
1485                         return 0;
1486                 }
1487                 /* --inplace implies --partial for refusal purposes, but we
1488                  * clear the keep_partial flag for internal logic purposes. */
1489                 if (refused_partial) {
1490                         create_refuse_error(refused_partial);
1491                         return 0;
1492                 }
1493                 keep_partial = 0;
1494 #else
1495                 snprintf(err_buf, sizeof err_buf,
1496                          "--%s is not supported on this %s\n",
1497                          append_mode ? "append" : "inplace",
1498                          am_server ? "server" : "client");
1499                 return 0;
1500 #endif
1501         } else {
1502                 if (keep_partial && !partial_dir && !am_server) {
1503                         if ((arg = getenv("RSYNC_PARTIAL_DIR")) != NULL && *arg)
1504                                 partial_dir = strdup(arg);
1505                 }
1506                 if (partial_dir) {
1507                         if (*partial_dir)
1508                                 clean_fname(partial_dir, 1);
1509                         if (!*partial_dir || strcmp(partial_dir, ".") == 0)
1510                                 partial_dir = NULL;
1511                         if (!partial_dir && refused_partial) {
1512                                 create_refuse_error(refused_partial);
1513                                 return 0;
1514                         }
1515                         keep_partial = 1;
1516                 }
1517         }
1518
1519         if (files_from) {
1520                 char *h, *p;
1521                 int q;
1522                 if (*argc > 2 || (!am_daemon && *argc == 1)) {
1523                         usage(FERROR);
1524                         exit_cleanup(RERR_SYNTAX);
1525                 }
1526                 if (strcmp(files_from, "-") == 0) {
1527                         filesfrom_fd = 0;
1528                         if (am_server)
1529                                 filesfrom_host = ""; /* reading from socket */
1530                 } else if ((p = check_for_hostspec(files_from, &h, &q)) != 0) {
1531                         if (am_server) {
1532                                 snprintf(err_buf, sizeof err_buf,
1533                                         "The --files-from sent to the server cannot specify a host.\n");
1534                                 return 0;
1535                         }
1536                         files_from = p;
1537                         filesfrom_host = h;
1538                         if (strcmp(files_from, "-") == 0) {
1539                                 snprintf(err_buf, sizeof err_buf,
1540                                         "Invalid --files-from remote filename\n");
1541                                 return 0;
1542                         }
1543                 } else {
1544                         if (sanitize_paths)
1545                                 files_from = sanitize_path(NULL, files_from, NULL, 0, NULL);
1546                         if (server_filter_list.head) {
1547                                 if (!*files_from)
1548                                         goto options_rejected;
1549                                 clean_fname(files_from, 1);
1550                                 if (check_filter(&server_filter_list, files_from, 0) < 0)
1551                                         goto options_rejected;
1552                         }
1553                         filesfrom_fd = open(files_from, O_RDONLY|O_BINARY);
1554                         if (filesfrom_fd < 0) {
1555                                 snprintf(err_buf, sizeof err_buf,
1556                                         "failed to open files-from file %s: %s\n",
1557                                         files_from, strerror(errno));
1558                                 return 0;
1559                         }
1560                 }
1561         }
1562
1563         am_starting_up = 0;
1564
1565         return 1;
1566
1567   options_rejected:
1568         snprintf(err_buf, sizeof err_buf,
1569                 "Your options have been rejected by the server.\n");
1570         return 0;
1571 }
1572
1573
1574 /**
1575  * Construct a filtered list of options to pass through from the
1576  * client to the server.
1577  *
1578  * This involves setting options that will tell the server how to
1579  * behave, and also filtering out options that are processed only
1580  * locally.
1581  **/
1582 void server_options(char **args,int *argc)
1583 {
1584         static char argstr[64];
1585         int ac = *argc;
1586         char *arg;
1587
1588         int i, x;
1589
1590         if (blocking_io == -1)
1591                 blocking_io = 0;
1592
1593         /* This should always remain first on the server's command-line. */
1594         args[ac++] = "--server";
1595
1596         if (daemon_over_rsh) {
1597                 args[ac++] = "--daemon";
1598                 *argc = ac;
1599                 /* if we're passing --daemon, we're done */
1600                 return;
1601         }
1602
1603         if (!am_sender)
1604                 args[ac++] = "--sender";
1605
1606         x = 1;
1607         argstr[0] = '-';
1608         for (i = 0; i < verbose; i++)
1609                 argstr[x++] = 'v';
1610
1611         /* the -q option is intentionally left out */
1612         if (make_backups)
1613                 argstr[x++] = 'b';
1614         if (update_only)
1615                 argstr[x++] = 'u';
1616         if (!do_xfers) /* Note: NOT "dry_run"! */
1617                 argstr[x++] = 'n';
1618         if (preserve_links)
1619                 argstr[x++] = 'l';
1620         if (xfer_dirs > (recurse || !delete_mode || !am_sender ? 1 : 0))
1621                 argstr[x++] = 'd';
1622         if (am_sender) {
1623                 if (keep_dirlinks)
1624                         argstr[x++] = 'K';
1625                 if (prune_empty_dirs)
1626                         argstr[x++] = 'm';
1627                 if (omit_dir_times == 2)
1628                         argstr[x++] = 'O';
1629         } else {
1630                 if (copy_links)
1631                         argstr[x++] = 'L';
1632                 if (copy_dirlinks)
1633                         argstr[x++] = 'k';
1634         }
1635
1636         if (whole_file > 0)
1637                 argstr[x++] = 'W';
1638         /* We don't need to send --no-whole-file, because it's the
1639          * default for remote transfers, and in any case old versions
1640          * of rsync will not understand it. */
1641
1642         if (preserve_hard_links) {
1643                 argstr[x++] = 'H';
1644                 if (preserve_hard_links > 1)
1645                         argstr[x++] = 'H';
1646         }
1647         if (preserve_uid)
1648                 argstr[x++] = 'o';
1649         if (preserve_gid)
1650                 argstr[x++] = 'g';
1651         if (preserve_devices) /* ignore preserve_specials here */
1652                 argstr[x++] = 'D';
1653         if (preserve_times)
1654                 argstr[x++] = 't';
1655         if (preserve_perms)
1656                 argstr[x++] = 'p';
1657         else if (preserve_executability && am_sender)
1658                 argstr[x++] = 'E';
1659 #ifdef SUPPORT_ACLS
1660         if (preserve_acls)
1661                 argstr[x++] = 'A';
1662 #endif
1663 #ifdef SUPPORT_XATTRS
1664         if (preserve_xattrs)
1665                 argstr[x++] = 'X';
1666 #endif
1667         if (recurse)
1668                 argstr[x++] = 'r';
1669         if (always_checksum)
1670                 argstr[x++] = 'c';
1671         if (cvs_exclude)
1672                 argstr[x++] = 'C';
1673         if (ignore_times)
1674                 argstr[x++] = 'I';
1675         if (relative_paths)
1676                 argstr[x++] = 'R';
1677         if (one_file_system) {
1678                 argstr[x++] = 'x';
1679                 if (one_file_system > 1)
1680                         argstr[x++] = 'x';
1681         }
1682         if (sparse_files)
1683                 argstr[x++] = 'S';
1684         if (do_compression)
1685                 argstr[x++] = 'z';
1686
1687         /* This is a complete hack - blame Rusty.  FIXME!
1688          * This hack is only needed for older rsync versions that
1689          * don't understand the --list-only option. */
1690         if (list_only == 1 && !recurse)
1691                 argstr[x++] = 'r';
1692
1693 #if SUBPROTOCOL_VERSION != 0
1694         /* If we're speaking a pre-release version of a protocol, we tell
1695          * the server about this by (ab)using the -e option. */
1696         if (protocol_version == PROTOCOL_VERSION) {
1697                 x += snprintf(argstr+x, sizeof argstr - x,
1698                               "e%d.%d", PROTOCOL_VERSION, SUBPROTOCOL_VERSION);
1699         }
1700 #endif
1701
1702         argstr[x] = '\0';
1703
1704         if (x != 1)
1705                 args[ac++] = argstr;
1706
1707         if (list_only > 1)
1708                 args[ac++] = "--list-only";
1709
1710         /* This makes sure that the remote rsync can handle deleting with -d
1711          * sans -r because the --no-r option was added at the same time. */
1712         if (xfer_dirs && !recurse && delete_mode && am_sender)
1713                 args[ac++] = "--no-r";
1714
1715         if (do_compression && def_compress_level != Z_DEFAULT_COMPRESSION) {
1716                 if (asprintf(&arg, "--compress-level=%d", def_compress_level) < 0)
1717                         goto oom;
1718                 args[ac++] = arg;
1719         }
1720
1721         if (preserve_devices) {
1722                 /* Note: sending "--devices" would not be backward-compatible. */
1723                 if (!preserve_specials)
1724                         args[ac++] = "--no-specials"; /* -D is already set. */
1725         } else if (preserve_specials)
1726                 args[ac++] = "--specials";
1727
1728         /* The server side doesn't use our log-format, but in certain
1729          * circumstances they need to know a little about the option. */
1730         if (stdout_format && am_sender) {
1731                 /* Use --log-format, not --out-format, for compatibility. */
1732                 if (stdout_format_has_i > 1)
1733                         args[ac++] = "--log-format=%i%I";
1734                 else if (stdout_format_has_i)
1735                         args[ac++] = "--log-format=%i";
1736                 else if (stdout_format_has_o_or_i)
1737                         args[ac++] = "--log-format=%o";
1738                 else if (!verbose)
1739                         args[ac++] = "--log-format=X";
1740         }
1741
1742 #ifdef ICONV_OPTION
1743         if (iconv_opt) {
1744                 char *set = strchr(iconv_opt, ',');
1745                 if (set)
1746                         set++;
1747                 else
1748                         set = iconv_opt;
1749                 if (asprintf(&arg, "--iconv=%s", set) < 0)
1750                         goto oom;
1751                 args[ac++] = arg;
1752         }
1753 #endif
1754
1755         if (block_size) {
1756                 if (asprintf(&arg, "-B%lu", block_size) < 0)
1757                         goto oom;
1758                 args[ac++] = arg;
1759         }
1760
1761         if (max_delete >= 0 && am_sender) {
1762                 if (asprintf(&arg, "--max-delete=%d", max_delete) < 0)
1763                         goto oom;
1764                 args[ac++] = arg;
1765         }
1766
1767         if (min_size && am_sender) {
1768                 args[ac++] = "--min-size";
1769                 args[ac++] = min_size_arg;
1770         }
1771
1772         if (max_size && am_sender) {
1773                 args[ac++] = "--max-size";
1774                 args[ac++] = max_size_arg;
1775         }
1776
1777         if (io_timeout) {
1778                 if (asprintf(&arg, "--timeout=%d", io_timeout) < 0)
1779                         goto oom;
1780                 args[ac++] = arg;
1781         }
1782
1783         if (bwlimit) {
1784                 if (asprintf(&arg, "--bwlimit=%d", bwlimit) < 0)
1785                         goto oom;
1786                 args[ac++] = arg;
1787         }
1788
1789         if (backup_dir) {
1790                 args[ac++] = "--backup-dir";
1791                 args[ac++] = backup_dir;
1792         }
1793
1794         /* Only send --suffix if it specifies a non-default value. */
1795         if (strcmp(backup_suffix, backup_dir ? "" : BACKUP_SUFFIX) != 0) {
1796                 /* We use the following syntax to avoid weirdness with '~'. */
1797                 if (asprintf(&arg, "--suffix=%s", backup_suffix) < 0)
1798                         goto oom;
1799                 args[ac++] = arg;
1800         }
1801
1802         if (am_sender) {
1803                 if (delete_before)
1804                         args[ac++] = "--delete-before";
1805                 else if (delete_during == 2)
1806                         args[ac++] = "--delete-delay";
1807                 else if (delete_during)
1808                         args[ac++] = "--delete-during";
1809                 else if (delete_after)
1810                         args[ac++] = "--delete-after";
1811                 else if (delete_mode && !delete_excluded)
1812                         args[ac++] = "--delete";
1813                 if (delete_excluded)
1814                         args[ac++] = "--delete-excluded";
1815                 if (force_delete)
1816                         args[ac++] = "--force";
1817                 if (write_batch < 0)
1818                         args[ac++] = "--only-write-batch=X";
1819                 if (am_root > 1)
1820                         args[ac++] = "--super";
1821                 if (size_only)
1822                         args[ac++] = "--size-only";
1823         }
1824
1825         if (modify_window_set) {
1826                 if (asprintf(&arg, "--modify-window=%d", modify_window) < 0)
1827                         goto oom;
1828                 args[ac++] = arg;
1829         }
1830
1831         if (checksum_seed) {
1832                 if (asprintf(&arg, "--checksum-seed=%d", checksum_seed) < 0)
1833                         goto oom;
1834                 args[ac++] = arg;
1835         }
1836
1837         if (partial_dir && am_sender) {
1838                 if (partial_dir != tmp_partialdir) {
1839                         args[ac++] = "--partial-dir";
1840                         args[ac++] = partial_dir;
1841                 }
1842                 if (delay_updates)
1843                         args[ac++] = "--delay-updates";
1844         } else if (keep_partial && am_sender)
1845                 args[ac++] = "--partial";
1846
1847         if (ignore_errors)
1848                 args[ac++] = "--ignore-errors";
1849
1850         if (copy_unsafe_links)
1851                 args[ac++] = "--copy-unsafe-links";
1852
1853         if (safe_symlinks)
1854                 args[ac++] = "--safe-links";
1855
1856         if (numeric_ids)
1857                 args[ac++] = "--numeric-ids";
1858
1859         if (ignore_existing && am_sender)
1860                 args[ac++] = "--ignore-existing";
1861
1862         /* Backward compatibility: send --existing, not --ignore-non-existing. */
1863         if (ignore_non_existing && am_sender)
1864                 args[ac++] = "--existing";
1865
1866         if (append_mode)
1867                 args[ac++] = "--append";
1868         else if (inplace)
1869                 args[ac++] = "--inplace";
1870
1871         if (tmpdir && am_sender) {
1872                 args[ac++] = "--temp-dir";
1873                 args[ac++] = tmpdir;
1874         }
1875
1876         if (basis_dir[0] && am_sender) {
1877                 /* the server only needs this option if it is not the sender,
1878                  *   and it may be an older version that doesn't know this
1879                  *   option, so don't send it if client is the sender.
1880                  */
1881                 int i;
1882                 for (i = 0; i < basis_dir_cnt; i++) {
1883                         args[ac++] = dest_option;
1884                         args[ac++] = basis_dir[i];
1885                 }
1886         }
1887
1888         if (files_from && (!am_sender || filesfrom_host)) {
1889                 if (filesfrom_host) {
1890                         args[ac++] = "--files-from";
1891                         args[ac++] = files_from;
1892                         if (eol_nulls)
1893                                 args[ac++] = "--from0";
1894                 } else {
1895                         args[ac++] = "--files-from=-";
1896                         args[ac++] = "--from0";
1897                 }
1898                 if (!relative_paths)
1899                         args[ac++] = "--no-relative";
1900         }
1901         if (relative_paths && !implied_dirs && !am_sender)
1902                 args[ac++] = "--no-implied-dirs";
1903
1904         if (fuzzy_basis && am_sender)
1905                 args[ac++] = "--fuzzy";
1906
1907         if (remove_source_files == 1)
1908                 args[ac++] = "--remove-source-files";
1909         else if (remove_source_files)
1910                 args[ac++] = "--remove-sent-files";
1911
1912         *argc = ac;
1913         return;
1914
1915     oom:
1916         out_of_memory("server_options");
1917 }
1918
1919 /* Look for a HOST specfication of the form "HOST:PATH", "HOST::PATH", or
1920  * "rsync://HOST:PORT/PATH".  If found, *host_ptr will be set to some allocated
1921  * memory with the HOST.  If a daemon-accessing spec was specified, the value
1922  * of *port_ptr will contain a non-0 port number, otherwise it will be set to
1923  * 0.  The return value is a pointer to the PATH.  Note that the HOST spec can
1924  * be an IPv6 literal address enclosed in '[' and ']' (such as "[::1]" or
1925  * "[::ffff:127.0.0.1]") which is returned without the '[' and ']'. */
1926 char *check_for_hostspec(char *s, char **host_ptr, int *port_ptr)
1927 {
1928         char *p;
1929         int not_host;
1930         int hostlen;
1931
1932         if (port_ptr && strncasecmp(URL_PREFIX, s, strlen(URL_PREFIX)) == 0) {
1933                 char *path;
1934                 s += strlen(URL_PREFIX);
1935                 if ((p = strchr(s, '/')) != NULL) {
1936                         hostlen = p - s;
1937                         path = p + 1;
1938                 } else {
1939                         hostlen = strlen(s);
1940                         path = "";
1941                 }
1942                 if (*s == '[' && (p = strchr(s, ']')) != NULL) {
1943                         s++;
1944                         hostlen = p - s;
1945                         if (p[1] == ':')
1946                                 *port_ptr = atoi(p+2);
1947                 } else {
1948                         if ((p = strchr(s, ':')) != NULL) {
1949                                 hostlen = p - s;
1950                                 *port_ptr = atoi(p+1);
1951                         }
1952                 }
1953                 if (!*port_ptr)
1954                         *port_ptr = RSYNC_PORT;
1955                 *host_ptr = new_array(char, hostlen + 1);
1956                 strlcpy(*host_ptr, s, hostlen + 1);
1957                 return path;
1958         }
1959
1960         if (*s == '[' && (p = strchr(s, ']')) != NULL && p[1] == ':') {
1961                 s++;
1962                 hostlen = p - s;
1963                 *p = '\0';
1964                 not_host = strchr(s, '/') || !strchr(s, ':');
1965                 *p = ']';
1966                 if (not_host)
1967                         return NULL;
1968                 p++;
1969         } else {
1970                 if (!(p = strchr(s, ':')))
1971                         return NULL;
1972                 hostlen = p - s;
1973                 *p = '\0';
1974                 not_host = strchr(s, '/') != NULL;
1975                 *p = ':';
1976                 if (not_host)
1977                         return NULL;
1978         }
1979
1980         *host_ptr = new_array(char, hostlen + 1);
1981         strlcpy(*host_ptr, s, hostlen + 1);
1982
1983         if (p[1] == ':') {
1984                 if (port_ptr && !*port_ptr)
1985                         *port_ptr = RSYNC_PORT;
1986                 return p + 2;
1987         }
1988         if (port_ptr)
1989                 *port_ptr = 0;
1990
1991         return p + 1;
1992 }