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