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