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