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