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