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