A repeated `--old-args` does more escape disabling.
[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-2022 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 "itypes.h"
24 #include "ifuncs.h"
25 #include <popt.h>
26
27 extern int module_id;
28 extern int local_server;
29 extern int sanitize_paths;
30 extern unsigned int module_dirlen;
31 extern filter_rule_list filter_list;
32 extern filter_rule_list daemon_filter_list;
33
34 int make_backups = 0;
35
36 /**
37  * If 1, send the whole file as literal data rather than trying to
38  * create an incremental diff.
39  *
40  * If -1, then look at whether we're local or remote and go by that.
41  *
42  * @sa disable_deltas_p()
43  **/
44 int whole_file = -1;
45
46 int append_mode = 0;
47 int keep_dirlinks = 0;
48 int copy_dirlinks = 0;
49 int copy_links = 0;
50 int write_devices = 0;
51 int preserve_links = 0;
52 int preserve_hard_links = 0;
53 int preserve_acls = 0;
54 int preserve_xattrs = 0;
55 int preserve_perms = 0;
56 int preserve_executability = 0;
57 int preserve_devices = 0;
58 int preserve_specials = 0;
59 int preserve_uid = 0;
60 int preserve_gid = 0;
61 int preserve_mtimes = 0;
62 int preserve_atimes = 0;
63 int preserve_crtimes = 0;
64 int omit_dir_times = 0;
65 int omit_link_times = 0;
66 int update_only = 0;
67 int open_noatime = 0;
68 int cvs_exclude = 0;
69 int dry_run = 0;
70 int do_xfers = 1;
71 int do_fsync = 0;
72 int ignore_times = 0;
73 int delete_mode = 0;
74 int delete_during = 0;
75 int delete_before = 0;
76 int delete_after = 0;
77 int delete_excluded = 0;
78 int remove_source_files = 0;
79 int one_file_system = 0;
80 int protocol_version = PROTOCOL_VERSION;
81 int sparse_files = 0;
82 int preallocate_files = 0;
83 int do_compression = 0;
84 int do_compression_level = CLVL_NOT_SPECIFIED;
85 int am_root = 0; /* 0 = normal, 1 = root, 2 = --super, -1 = --fake-super */
86 int am_server = 0;
87 int am_sender = 0;
88 int am_starting_up = 1;
89 int relative_paths = -1;
90 int implied_dirs = 1;
91 int missing_args = 0; /* 0 = FERROR_XFER, 1 = ignore, 2 = delete */
92 int numeric_ids = 0;
93 int msgs2stderr = 2; /* Default: send errors to stderr for local & remote-shell transfers */
94 int saw_stderr_opt = 0;
95 int allow_8bit_chars = 0;
96 int force_delete = 0;
97 int io_timeout = 0;
98 int prune_empty_dirs = 0;
99 int use_qsort = 0;
100 char *files_from = NULL;
101 int filesfrom_fd = -1;
102 char *filesfrom_host = NULL;
103 int eol_nulls = 0;
104 int protect_args = -1;
105 int old_style_args = -1;
106 int human_readable = 1;
107 int recurse = 0;
108 int mkpath_dest_arg = 0;
109 int allow_inc_recurse = 1;
110 int xfer_dirs = -1;
111 int am_daemon = 0;
112 int connect_timeout = 0;
113 int keep_partial = 0;
114 int safe_symlinks = 0;
115 int copy_unsafe_links = 0;
116 int munge_symlinks = 0;
117 int size_only = 0;
118 int daemon_bwlimit = 0;
119 int bwlimit = 0;
120 int fuzzy_basis = 0;
121 size_t bwlimit_writemax = 0;
122 int ignore_existing = 0;
123 int ignore_non_existing = 0;
124 int need_messages_from_generator = 0;
125 int max_delete = INT_MIN;
126 OFF_T max_size = -1;
127 OFF_T min_size = -1;
128 int ignore_errors = 0;
129 int modify_window = 0;
130 int blocking_io = -1;
131 int checksum_seed = 0;
132 int inplace = 0;
133 int delay_updates = 0;
134 int32 block_size = 0;
135 time_t stop_at_utime = 0;
136 char *skip_compress = NULL;
137 char *copy_as = NULL;
138 item_list dparam_list = EMPTY_ITEM_LIST;
139
140 /** Network address family. **/
141 int default_af_hint
142 #ifdef INET6
143         = 0;            /* Any protocol */
144 #else
145         = AF_INET;      /* Must use IPv4 */
146 # ifdef AF_INET6
147 #  undef AF_INET6
148 # endif
149 # define AF_INET6 AF_INET /* make -6 option a no-op */
150 #endif
151
152 /** Do not go into the background when run as --daemon.  Good
153  * for debugging and required for running as a service on W32,
154  * or under Unix process-monitors. **/
155 int no_detach
156 #if defined _WIN32 || defined __WIN32__
157         = 1;
158 #else
159         = 0;
160 #endif
161
162 int write_batch = 0;
163 int read_batch = 0;
164 int backup_dir_len = 0;
165 int backup_suffix_len;
166 unsigned int backup_dir_remainder;
167
168 char *backup_suffix = NULL;
169 char *tmpdir = NULL;
170 char *partial_dir = NULL;
171 char *basis_dir[MAX_BASIS_DIRS+1];
172 char *config_file = NULL;
173 char *shell_cmd = NULL;
174 char *logfile_name = NULL;
175 char *logfile_format = NULL;
176 char *stdout_format = NULL;
177 char *password_file = NULL;
178 char *early_input_file = NULL;
179 char *rsync_path = RSYNC_PATH;
180 char *backup_dir = NULL;
181 char backup_dir_buf[MAXPATHLEN];
182 char *sockopts = NULL;
183 char *usermap = NULL;
184 char *groupmap = NULL;
185 int rsync_port = 0;
186 int alt_dest_type = 0;
187 int basis_dir_cnt = 0;
188
189 #define DEFAULT_MAX_ALLOC (1024L * 1024 * 1024)
190 size_t max_alloc = DEFAULT_MAX_ALLOC;
191 char *max_alloc_arg;
192
193 static int version_opt_cnt = 0;
194 static int remote_option_alloc = 0;
195 int remote_option_cnt = 0;
196 const char **remote_options = NULL;
197 const char *checksum_choice = NULL;
198 const char *compress_choice = NULL;
199
200 int quiet = 0;
201 int output_motd = 1;
202 int log_before_transfer = 0;
203 int stdout_format_has_i = 0;
204 int stdout_format_has_o_or_i = 0;
205 int logfile_format_has_i = 0;
206 int logfile_format_has_o_or_i = 0;
207 int always_checksum = 0;
208 int list_only = 0;
209
210 #define MAX_BATCH_NAME_LEN 256  /* Must be less than MAXPATHLEN-13 */
211 char *batch_name = NULL;
212
213 int need_unsorted_flist = 0;
214 char *iconv_opt =
215 #ifdef ICONV_OPTION
216                 ICONV_OPTION;
217 #else
218                 NULL;
219 #endif
220
221 struct chmod_mode_struct *chmod_modes = NULL;
222
223 static const char *debug_verbosity[] = {
224         /*0*/ NULL,
225         /*1*/ NULL,
226         /*2*/ "BIND,CMD,CONNECT,DEL,DELTASUM,DUP,FILTER,FLIST,ICONV",
227         /*3*/ "ACL,BACKUP,CONNECT2,DELTASUM2,DEL2,EXIT,FILTER2,FLIST2,FUZZY,GENR,OWN,RECV,SEND,TIME",
228         /*4*/ "CMD2,DELTASUM3,DEL3,EXIT2,FLIST3,ICONV2,OWN2,PROTO,TIME2",
229         /*5*/ "CHDIR,DELTASUM4,FLIST4,FUZZY2,HASH,HLINK",
230 };
231
232 #define MAX_VERBOSITY ((int)(sizeof debug_verbosity / sizeof debug_verbosity[0]) - 1)
233
234 static const char *info_verbosity[1+MAX_VERBOSITY] = {
235         /*0*/ "NONREG",
236         /*1*/ "COPY,DEL,FLIST,MISC,NAME,STATS,SYMSAFE",
237         /*2*/ "BACKUP,MISC2,MOUNT,NAME2,REMOVE,SKIP",
238 };
239
240 #define MAX_OUT_LEVEL 4 /* The largest N allowed for any flagN word. */
241
242 short info_levels[COUNT_INFO], debug_levels[COUNT_DEBUG];
243
244 #define DEFAULT_PRIORITY 0      /* Default/implied/--verbose set values. */
245 #define HELP_PRIORITY 1         /* The help output uses this level. */
246 #define USER_PRIORITY 2         /* User-specified via --info or --debug */
247 #define LIMIT_PRIORITY 3        /* Overriding priority when limiting values. */
248
249 #define W_CLI (1<<0)    /* client side */
250 #define W_SRV (1<<1)    /* server side */
251 #define W_SND (1<<2)    /* sending side */
252 #define W_REC (1<<3)    /* receiving side */
253
254 struct output_struct {
255         char *name;     /* The name of the info/debug flag. */
256         char *help;     /* The description of the info/debug flag. */
257         uchar namelen;  /* The length of the name string. */
258         uchar flag;     /* The flag's value, for consistency check. */
259         uchar where;    /* Bits indicating where the flag is used. */
260         uchar priority; /* See *_PRIORITY defines. */
261 };
262
263 #define INFO_WORD(flag, where, help) { #flag, help, sizeof #flag - 1, INFO_##flag, where, 0 }
264
265 static struct output_struct info_words[COUNT_INFO+1] = {
266         INFO_WORD(BACKUP, W_REC, "Mention files backed up"),
267         INFO_WORD(COPY, W_REC, "Mention files copied locally on the receiving side"),
268         INFO_WORD(DEL, W_REC, "Mention deletions on the receiving side"),
269         INFO_WORD(FLIST, W_CLI, "Mention file-list receiving/sending (levels 1-2)"),
270         INFO_WORD(MISC, W_SND|W_REC, "Mention miscellaneous information (levels 1-2)"),
271         INFO_WORD(MOUNT, W_SND|W_REC, "Mention mounts that were found or skipped"),
272         INFO_WORD(NAME, W_SND|W_REC, "Mention 1) updated file/dir names, 2) unchanged names"),
273         INFO_WORD(NONREG, W_REC, "Mention skipped non-regular files (default 1, 0 disables)"),
274         INFO_WORD(PROGRESS, W_CLI, "Mention 1) per-file progress or 2) total transfer progress"),
275         INFO_WORD(REMOVE, W_SND, "Mention files removed on the sending side"),
276         INFO_WORD(SKIP, W_REC, "Mention files skipped due to transfer overrides (levels 1-2)"),
277         INFO_WORD(STATS, W_CLI|W_SRV, "Mention statistics at end of run (levels 1-3)"),
278         INFO_WORD(SYMSAFE, W_SND|W_REC, "Mention symlinks that are unsafe"),
279         { NULL, "--info", 0, 0, 0, 0 }
280 };
281
282 #define DEBUG_WORD(flag, where, help) { #flag, help, sizeof #flag - 1, DEBUG_##flag, where, 0 }
283
284 static struct output_struct debug_words[COUNT_DEBUG+1] = {
285         DEBUG_WORD(ACL, W_SND|W_REC, "Debug extra ACL info"),
286         DEBUG_WORD(BACKUP, W_REC, "Debug backup actions (levels 1-2)"),
287         DEBUG_WORD(BIND, W_CLI, "Debug socket bind actions"),
288         DEBUG_WORD(CHDIR, W_CLI|W_SRV, "Debug when the current directory changes"),
289         DEBUG_WORD(CONNECT, W_CLI, "Debug connection events (levels 1-2)"),
290         DEBUG_WORD(CMD, W_CLI, "Debug commands+options that are issued (levels 1-2)"),
291         DEBUG_WORD(DEL, W_REC, "Debug delete actions (levels 1-3)"),
292         DEBUG_WORD(DELTASUM, W_SND|W_REC, "Debug delta-transfer checksumming (levels 1-4)"),
293         DEBUG_WORD(DUP, W_REC, "Debug weeding of duplicate names"),
294         DEBUG_WORD(EXIT, W_CLI|W_SRV, "Debug exit events (levels 1-3)"),
295         DEBUG_WORD(FILTER, W_SND|W_REC, "Debug filter actions (levels 1-2)"),
296         DEBUG_WORD(FLIST, W_SND|W_REC, "Debug file-list operations (levels 1-4)"),
297         DEBUG_WORD(FUZZY, W_REC, "Debug fuzzy scoring (levels 1-2)"),
298         DEBUG_WORD(GENR, W_REC, "Debug generator functions"),
299         DEBUG_WORD(HASH, W_SND|W_REC, "Debug hashtable code"),
300         DEBUG_WORD(HLINK, W_SND|W_REC, "Debug hard-link actions (levels 1-3)"),
301         DEBUG_WORD(ICONV, W_CLI|W_SRV, "Debug iconv character conversions (levels 1-2)"),
302         DEBUG_WORD(IO, W_CLI|W_SRV, "Debug I/O routines (levels 1-4)"),
303         DEBUG_WORD(NSTR, W_CLI|W_SRV, "Debug negotiation strings"),
304         DEBUG_WORD(OWN, W_REC, "Debug ownership changes in users & groups (levels 1-2)"),
305         DEBUG_WORD(PROTO, W_CLI|W_SRV, "Debug protocol information"),
306         DEBUG_WORD(RECV, W_REC, "Debug receiver functions"),
307         DEBUG_WORD(SEND, W_SND, "Debug sender functions"),
308         DEBUG_WORD(TIME, W_REC, "Debug setting of modified times (levels 1-2)"),
309         { NULL, "--debug", 0, 0, 0, 0 }
310 };
311
312 static int verbose = 0;
313 static int do_stats = 0;
314 static int do_progress = 0;
315 static int daemon_opt;   /* sets am_daemon after option error-reporting */
316 static int F_option_cnt = 0;
317 static int modify_window_set;
318 static int itemize_changes = 0;
319 static int refused_delete, refused_archive_part, refused_compress;
320 static int refused_partial, refused_progress, refused_delete_before;
321 static int refused_delete_during;
322 static int refused_inplace, refused_no_iconv;
323 static BOOL usermap_via_chown, groupmap_via_chown;
324 static char *outbuf_mode;
325 static char *bwlimit_arg, *max_size_arg, *min_size_arg;
326 static char tmp_partialdir[] = ".~tmp~";
327
328 /** Local address to bind.  As a character string because it's
329  * interpreted by the IPv6 layer: should be a numeric IP4 or IP6
330  * address, or a hostname. **/
331 char *bind_address;
332
333 static void output_item_help(struct output_struct *words);
334
335 /* This constructs a string that represents all the options set for either
336  * the --info or --debug setting, skipping any implied options (by -v, etc.).
337  * This is used both when conveying the user's options to the server, and
338  * when the help output wants to tell the user what options are implied. */
339 static char *make_output_option(struct output_struct *words, short *levels, uchar where)
340 {
341         char *str = words == info_words ? "--info=" : "--debug=";
342         int j, counts[MAX_OUT_LEVEL+1], pos, skipped = 0, len = 0, max = 0, lev = 0;
343         int word_count = words == info_words ? COUNT_INFO : COUNT_DEBUG;
344         char *buf;
345
346         memset(counts, 0, sizeof counts);
347
348         for (j = 0; words[j].name; j++) {
349                 if (words[j].flag != j) {
350                         rprintf(FERROR, "rsync: internal error on %s%s: %d != %d\n",
351                                 words == info_words ? "INFO_" : "DEBUG_",
352                                 words[j].name, words[j].flag, j);
353                         exit_cleanup(RERR_UNSUPPORTED);
354                 }
355                 if (!(words[j].where & where))
356                         continue;
357                 if (words[j].priority == DEFAULT_PRIORITY) {
358                         /* Implied items don't need to be mentioned. */
359                         skipped++;
360                         continue;
361                 }
362                 len += len ? 1 : strlen(str);
363                 len += strlen(words[j].name);
364                 len += levels[j] == 1 ? 0 : 1;
365
366                 if (words[j].priority == HELP_PRIORITY)
367                         continue; /* no abbreviating for help */
368
369                 assert(levels[j] <= MAX_OUT_LEVEL);
370                 if (++counts[levels[j]] > max) {
371                         /* Determine which level has the most items. */
372                         lev = levels[j];
373                         max = counts[lev];
374                 }
375         }
376
377         /* Sanity check the COUNT_* define against the length of the table. */
378         if (j != word_count) {
379                 rprintf(FERROR, "rsync: internal error: %s is wrong! (%d != %d)\n",
380                         words == info_words ? "COUNT_INFO" : "COUNT_DEBUG",
381                         j, word_count);
382                 exit_cleanup(RERR_UNSUPPORTED);
383         }
384
385         if (!len)
386                 return NULL;
387
388         len++;
389         buf = new_array(char, len);
390         pos = 0;
391
392         if (skipped || max < 5)
393                 lev = -1;
394         else {
395                 if (lev == 0)
396                         pos += snprintf(buf, len, "%sNONE", str);
397                 else if (lev == 1)
398                         pos += snprintf(buf, len, "%sALL", str);
399                 else
400                         pos += snprintf(buf, len, "%sALL%d", str, lev);
401         }
402
403         for (j = 0; words[j].name && pos < len; j++) {
404                 if (words[j].priority == DEFAULT_PRIORITY || levels[j] == lev || !(words[j].where & where))
405                         continue;
406                 if (pos)
407                         buf[pos++] = ',';
408                 else
409                         pos += strlcpy(buf+pos, str, len-pos);
410                 if (pos < len)
411                         pos += strlcpy(buf+pos, words[j].name, len-pos);
412                 /* Level 1 is implied by the name alone. */
413                 if (levels[j] != 1 && pos < len)
414                         buf[pos++] = '0' + levels[j];
415         }
416
417         buf[pos] = '\0';
418
419         return buf;
420 }
421
422 static void parse_output_words(struct output_struct *words, short *levels, const char *str, uchar priority)
423 {
424         const char *s;
425         int j, len, lev;
426
427         for ( ; str; str = s) {
428                 if ((s = strchr(str, ',')) != NULL)
429                         len = s++ - str;
430                 else
431                         len = strlen(str);
432                 if (!len)
433                         continue;
434                 if (!isDigit(str)) {
435                         while (len && isDigit(str+len-1))
436                                 len--;
437                 }
438                 lev = isDigit(str+len) ? atoi(str+len) : 1;
439                 if (lev > MAX_OUT_LEVEL)
440                         lev = MAX_OUT_LEVEL;
441                 if (len == 4 && strncasecmp(str, "help", 4) == 0) {
442                         output_item_help(words);
443                         exit_cleanup(0);
444                 }
445                 if (len == 4 && strncasecmp(str, "none", 4) == 0)
446                         len = lev = 0;
447                 else if (len == 3 && strncasecmp(str, "all", 3) == 0)
448                         len = 0;
449                 for (j = 0; words[j].name; j++) {
450                         if (!len
451                          || (len == words[j].namelen && strncasecmp(str, words[j].name, len) == 0)) {
452                                 if (priority >= words[j].priority) {
453                                         words[j].priority = priority;
454                                         levels[j] = lev;
455                                 }
456                                 if (len)
457                                         break;
458                         }
459                 }
460                 if (len && !words[j].name && !am_server) {
461                         rprintf(FERROR, "Unknown %s item: \"%.*s\"\n",
462                                 words[j].help, len, str);
463                         exit_cleanup(RERR_SYNTAX);
464                 }
465         }
466 }
467
468 /* Tell the user what all the info or debug flags mean. */
469 static void output_item_help(struct output_struct *words)
470 {
471         short *levels = words == info_words ? info_levels : debug_levels;
472         const char **verbosity = words == info_words ? info_verbosity : debug_verbosity;
473         char buf[128], *opt, *fmt = "%-10s %s\n";
474         int j;
475
476         reset_output_levels();
477
478         rprintf(FINFO, "Use OPT or OPT1 for level 1 output, OPT2 for level 2, etc.; OPT0 silences.\n");
479         rprintf(FINFO, "\n");
480         for (j = 0; words[j].name; j++)
481                 rprintf(FINFO, fmt, words[j].name, words[j].help);
482         rprintf(FINFO, "\n");
483
484         snprintf(buf, sizeof buf, "Set all %s options (e.g. all%d)",
485                  words[j].help, MAX_OUT_LEVEL);
486         rprintf(FINFO, fmt, "ALL", buf);
487
488         snprintf(buf, sizeof buf, "Silence all %s options (same as all0)",
489                  words[j].help);
490         rprintf(FINFO, fmt, "NONE", buf);
491
492         rprintf(FINFO, fmt, "HELP", "Output this help message");
493         rprintf(FINFO, "\n");
494         rprintf(FINFO, "Options added at each level of verbosity:\n");
495
496         for (j = 0; j <= MAX_VERBOSITY; j++) {
497                 parse_output_words(words, levels, verbosity[j], HELP_PRIORITY);
498                 opt = make_output_option(words, levels, W_CLI|W_SRV|W_SND|W_REC);
499                 if (opt) {
500                         rprintf(FINFO, "%d) %s\n", j, strchr(opt, '=')+1);
501                         free(opt);
502                 }
503                 reset_output_levels();
504         }
505 }
506
507 /* The --verbose option now sets info+debug flags. */
508 static void set_output_verbosity(int level, uchar priority)
509 {
510         int j;
511
512         if (level > MAX_VERBOSITY)
513                 level = MAX_VERBOSITY;
514
515         for (j = 0; j <= level; j++) {
516                 parse_output_words(info_words, info_levels, info_verbosity[j], priority);
517                 parse_output_words(debug_words, debug_levels, debug_verbosity[j], priority);
518         }
519 }
520
521 /* Limit the info+debug flag levels given a verbose-option level limit. */
522 void limit_output_verbosity(int level)
523 {
524         short info_limits[COUNT_INFO], debug_limits[COUNT_DEBUG];
525         int j;
526
527         if (level > MAX_VERBOSITY)
528                 return;
529
530         memset(info_limits, 0, sizeof info_limits);
531         memset(debug_limits, 0, sizeof debug_limits);
532
533         /* Compute the level limits in the above arrays. */
534         for (j = 0; j <= level; j++) {
535                 parse_output_words(info_words, info_limits, info_verbosity[j], LIMIT_PRIORITY);
536                 parse_output_words(debug_words, debug_limits, debug_verbosity[j], LIMIT_PRIORITY);
537         }
538
539         for (j = 0; j < COUNT_INFO; j++) {
540                 if (info_levels[j] > info_limits[j])
541                         info_levels[j] = info_limits[j];
542         }
543
544         for (j = 0; j < COUNT_DEBUG; j++) {
545                 if (debug_levels[j] > debug_limits[j])
546                         debug_levels[j] = debug_limits[j];
547         }
548 }
549
550 void reset_output_levels(void)
551 {
552         int j;
553
554         memset(info_levels, 0, sizeof info_levels);
555         memset(debug_levels, 0, sizeof debug_levels);
556
557         for (j = 0; j < COUNT_INFO; j++)
558                 info_words[j].priority = DEFAULT_PRIORITY;
559
560         for (j = 0; j < COUNT_DEBUG; j++)
561                 debug_words[j].priority = DEFAULT_PRIORITY;
562 }
563
564 void negate_output_levels(void)
565 {
566         int j;
567
568         for (j = 0; j < COUNT_INFO; j++)
569                 info_levels[j] *= -1;
570
571         for (j = 0; j < COUNT_DEBUG; j++)
572                 debug_levels[j] *= -1;
573 }
574
575 enum {OPT_SERVER = 1000, OPT_DAEMON, OPT_SENDER, OPT_EXCLUDE, OPT_EXCLUDE_FROM,
576       OPT_FILTER, OPT_COMPARE_DEST, OPT_COPY_DEST, OPT_LINK_DEST, OPT_HELP,
577       OPT_INCLUDE, OPT_INCLUDE_FROM, OPT_MODIFY_WINDOW, OPT_MIN_SIZE, OPT_CHMOD,
578       OPT_READ_BATCH, OPT_WRITE_BATCH, OPT_ONLY_WRITE_BATCH, OPT_MAX_SIZE,
579       OPT_NO_D, OPT_APPEND, OPT_NO_ICONV, OPT_INFO, OPT_DEBUG, OPT_BLOCK_SIZE,
580       OPT_USERMAP, OPT_GROUPMAP, OPT_CHOWN, OPT_BWLIMIT, OPT_STDERR,
581       OPT_OLD_COMPRESS, OPT_NEW_COMPRESS, OPT_NO_COMPRESS, OPT_OLD_ARGS,
582       OPT_STOP_AFTER, OPT_STOP_AT,
583       OPT_REFUSED_BASE = 9000};
584
585 static struct poptOption long_options[] = {
586   /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
587   {"help",             0,  POPT_ARG_NONE,   0, OPT_HELP, 0, 0 },
588   {"version",         'V', POPT_ARG_NONE,   0, 'V', 0, 0},
589   {"verbose",         'v', POPT_ARG_NONE,   0, 'v', 0, 0 },
590   {"no-verbose",       0,  POPT_ARG_VAL,    &verbose, 0, 0, 0 },
591   {"no-v",             0,  POPT_ARG_VAL,    &verbose, 0, 0, 0 },
592   {"info",             0,  POPT_ARG_STRING, 0, OPT_INFO, 0, 0 },
593   {"debug",            0,  POPT_ARG_STRING, 0, OPT_DEBUG, 0, 0 },
594   {"stderr",           0,  POPT_ARG_STRING, 0, OPT_STDERR, 0, 0 },
595   {"msgs2stderr",      0,  POPT_ARG_VAL,    &msgs2stderr, 1, 0, 0 },
596   {"no-msgs2stderr",   0,  POPT_ARG_VAL,    &msgs2stderr, 0, 0, 0 },
597   {"quiet",           'q', POPT_ARG_NONE,   0, 'q', 0, 0 },
598   {"motd",             0,  POPT_ARG_VAL,    &output_motd, 1, 0, 0 },
599   {"no-motd",          0,  POPT_ARG_VAL,    &output_motd, 0, 0, 0 },
600   {"stats",            0,  POPT_ARG_NONE,   &do_stats, 0, 0, 0 },
601   {"human-readable",  'h', POPT_ARG_NONE,   0, 'h', 0, 0},
602   {"no-human-readable",0,  POPT_ARG_VAL,    &human_readable, 0, 0, 0},
603   {"no-h",             0,  POPT_ARG_VAL,    &human_readable, 0, 0, 0},
604   {"dry-run",         'n', POPT_ARG_NONE,   &dry_run, 0, 0, 0 },
605   {"archive",         'a', POPT_ARG_NONE,   0, 'a', 0, 0 },
606   {"recursive",       'r', POPT_ARG_VAL,    &recurse, 2, 0, 0 },
607   {"no-recursive",     0,  POPT_ARG_VAL,    &recurse, 0, 0, 0 },
608   {"no-r",             0,  POPT_ARG_VAL,    &recurse, 0, 0, 0 },
609   {"inc-recursive",    0,  POPT_ARG_VAL,    &allow_inc_recurse, 1, 0, 0 },
610   {"no-inc-recursive", 0,  POPT_ARG_VAL,    &allow_inc_recurse, 0, 0, 0 },
611   {"i-r",              0,  POPT_ARG_VAL,    &allow_inc_recurse, 1, 0, 0 },
612   {"no-i-r",           0,  POPT_ARG_VAL,    &allow_inc_recurse, 0, 0, 0 },
613   {"dirs",            'd', POPT_ARG_VAL,    &xfer_dirs, 2, 0, 0 },
614   {"no-dirs",          0,  POPT_ARG_VAL,    &xfer_dirs, 0, 0, 0 },
615   {"no-d",             0,  POPT_ARG_VAL,    &xfer_dirs, 0, 0, 0 },
616   {"old-dirs",         0,  POPT_ARG_VAL,    &xfer_dirs, 4, 0, 0 },
617   {"old-d",            0,  POPT_ARG_VAL,    &xfer_dirs, 4, 0, 0 },
618   {"perms",           'p', POPT_ARG_VAL,    &preserve_perms, 1, 0, 0 },
619   {"no-perms",         0,  POPT_ARG_VAL,    &preserve_perms, 0, 0, 0 },
620   {"no-p",             0,  POPT_ARG_VAL,    &preserve_perms, 0, 0, 0 },
621   {"executability",   'E', POPT_ARG_NONE,   &preserve_executability, 0, 0, 0 },
622   {"acls",            'A', POPT_ARG_NONE,   0, 'A', 0, 0 },
623   {"no-acls",          0,  POPT_ARG_VAL,    &preserve_acls, 0, 0, 0 },
624   {"no-A",             0,  POPT_ARG_VAL,    &preserve_acls, 0, 0, 0 },
625   {"xattrs",          'X', POPT_ARG_NONE,   0, 'X', 0, 0 },
626   {"no-xattrs",        0,  POPT_ARG_VAL,    &preserve_xattrs, 0, 0, 0 },
627   {"no-X",             0,  POPT_ARG_VAL,    &preserve_xattrs, 0, 0, 0 },
628   {"times",           't', POPT_ARG_VAL,    &preserve_mtimes, 1, 0, 0 },
629   {"no-times",         0,  POPT_ARG_VAL,    &preserve_mtimes, 0, 0, 0 },
630   {"no-t",             0,  POPT_ARG_VAL,    &preserve_mtimes, 0, 0, 0 },
631   {"atimes",          'U', POPT_ARG_NONE,   0, 'U', 0, 0 },
632   {"no-atimes",        0,  POPT_ARG_VAL,    &preserve_atimes, 0, 0, 0 },
633   {"no-U",             0,  POPT_ARG_VAL,    &preserve_atimes, 0, 0, 0 },
634   {"open-noatime",     0,  POPT_ARG_VAL,    &open_noatime, 1, 0, 0 },
635   {"no-open-noatime",  0,  POPT_ARG_VAL,    &open_noatime, 0, 0, 0 },
636   {"crtimes",         'N', POPT_ARG_VAL,    &preserve_crtimes, 1, 0, 0 },
637   {"no-crtimes",       0,  POPT_ARG_VAL,    &preserve_crtimes, 0, 0, 0 },
638   {"no-N",             0,  POPT_ARG_VAL,    &preserve_crtimes, 0, 0, 0 },
639   {"omit-dir-times",  'O', POPT_ARG_VAL,    &omit_dir_times, 1, 0, 0 },
640   {"no-omit-dir-times",0,  POPT_ARG_VAL,    &omit_dir_times, 0, 0, 0 },
641   {"no-O",             0,  POPT_ARG_VAL,    &omit_dir_times, 0, 0, 0 },
642   {"omit-link-times", 'J', POPT_ARG_VAL,    &omit_link_times, 1, 0, 0 },
643   {"no-omit-link-times",0, POPT_ARG_VAL,    &omit_link_times, 0, 0, 0 },
644   {"no-J",             0,  POPT_ARG_VAL,    &omit_link_times, 0, 0, 0 },
645   {"modify-window",   '@', POPT_ARG_INT,    &modify_window, OPT_MODIFY_WINDOW, 0, 0 },
646   {"super",            0,  POPT_ARG_VAL,    &am_root, 2, 0, 0 },
647   {"no-super",         0,  POPT_ARG_VAL,    &am_root, 0, 0, 0 },
648   {"fake-super",       0,  POPT_ARG_VAL,    &am_root, -1, 0, 0 },
649   {"owner",           'o', POPT_ARG_VAL,    &preserve_uid, 1, 0, 0 },
650   {"no-owner",         0,  POPT_ARG_VAL,    &preserve_uid, 0, 0, 0 },
651   {"no-o",             0,  POPT_ARG_VAL,    &preserve_uid, 0, 0, 0 },
652   {"group",           'g', POPT_ARG_VAL,    &preserve_gid, 1, 0, 0 },
653   {"no-group",         0,  POPT_ARG_VAL,    &preserve_gid, 0, 0, 0 },
654   {"no-g",             0,  POPT_ARG_VAL,    &preserve_gid, 0, 0, 0 },
655   {0,                 'D', POPT_ARG_NONE,   0, 'D', 0, 0 },
656   {"no-D",             0,  POPT_ARG_NONE,   0, OPT_NO_D, 0, 0 },
657   {"devices",          0,  POPT_ARG_VAL,    &preserve_devices, 1, 0, 0 },
658   {"no-devices",       0,  POPT_ARG_VAL,    &preserve_devices, 0, 0, 0 },
659   {"write-devices",    0,  POPT_ARG_VAL,    &write_devices, 1, 0, 0 },
660   {"no-write-devices", 0,  POPT_ARG_VAL,    &write_devices, 0, 0, 0 },
661   {"specials",         0,  POPT_ARG_VAL,    &preserve_specials, 1, 0, 0 },
662   {"no-specials",      0,  POPT_ARG_VAL,    &preserve_specials, 0, 0, 0 },
663   {"links",           'l', POPT_ARG_VAL,    &preserve_links, 1, 0, 0 },
664   {"no-links",         0,  POPT_ARG_VAL,    &preserve_links, 0, 0, 0 },
665   {"no-l",             0,  POPT_ARG_VAL,    &preserve_links, 0, 0, 0 },
666   {"copy-links",      'L', POPT_ARG_NONE,   &copy_links, 0, 0, 0 },
667   {"copy-unsafe-links",0,  POPT_ARG_NONE,   &copy_unsafe_links, 0, 0, 0 },
668   {"safe-links",       0,  POPT_ARG_NONE,   &safe_symlinks, 0, 0, 0 },
669   {"munge-links",      0,  POPT_ARG_VAL,    &munge_symlinks, 1, 0, 0 },
670   {"no-munge-links",   0,  POPT_ARG_VAL,    &munge_symlinks, 0, 0, 0 },
671   {"copy-dirlinks",   'k', POPT_ARG_NONE,   &copy_dirlinks, 0, 0, 0 },
672   {"keep-dirlinks",   'K', POPT_ARG_NONE,   &keep_dirlinks, 0, 0, 0 },
673   {"hard-links",      'H', POPT_ARG_NONE,   0, 'H', 0, 0 },
674   {"no-hard-links",    0,  POPT_ARG_VAL,    &preserve_hard_links, 0, 0, 0 },
675   {"no-H",             0,  POPT_ARG_VAL,    &preserve_hard_links, 0, 0, 0 },
676   {"relative",        'R', POPT_ARG_VAL,    &relative_paths, 1, 0, 0 },
677   {"no-relative",      0,  POPT_ARG_VAL,    &relative_paths, 0, 0, 0 },
678   {"no-R",             0,  POPT_ARG_VAL,    &relative_paths, 0, 0, 0 },
679   {"implied-dirs",     0,  POPT_ARG_VAL,    &implied_dirs, 1, 0, 0 },
680   {"no-implied-dirs",  0,  POPT_ARG_VAL,    &implied_dirs, 0, 0, 0 },
681   {"i-d",              0,  POPT_ARG_VAL,    &implied_dirs, 1, 0, 0 },
682   {"no-i-d",           0,  POPT_ARG_VAL,    &implied_dirs, 0, 0, 0 },
683   {"chmod",            0,  POPT_ARG_STRING, 0, OPT_CHMOD, 0, 0 },
684   {"ignore-times",    'I', POPT_ARG_NONE,   &ignore_times, 0, 0, 0 },
685   {"size-only",        0,  POPT_ARG_NONE,   &size_only, 0, 0, 0 },
686   {"one-file-system", 'x', POPT_ARG_NONE,   0, 'x', 0, 0 },
687   {"no-one-file-system",0, POPT_ARG_VAL,    &one_file_system, 0, 0, 0 },
688   {"no-x",             0,  POPT_ARG_VAL,    &one_file_system, 0, 0, 0 },
689   {"update",          'u', POPT_ARG_NONE,   &update_only, 0, 0, 0 },
690   {"existing",         0,  POPT_ARG_NONE,   &ignore_non_existing, 0, 0, 0 },
691   {"ignore-non-existing",0,POPT_ARG_NONE,   &ignore_non_existing, 0, 0, 0 },
692   {"ignore-existing",  0,  POPT_ARG_NONE,   &ignore_existing, 0, 0, 0 },
693   {"max-size",         0,  POPT_ARG_STRING, &max_size_arg, OPT_MAX_SIZE, 0, 0 },
694   {"min-size",         0,  POPT_ARG_STRING, &min_size_arg, OPT_MIN_SIZE, 0, 0 },
695   {"max-alloc",        0,  POPT_ARG_STRING, &max_alloc_arg, 0, 0, 0 },
696   {"sparse",          'S', POPT_ARG_VAL,    &sparse_files, 1, 0, 0 },
697   {"no-sparse",        0,  POPT_ARG_VAL,    &sparse_files, 0, 0, 0 },
698   {"no-S",             0,  POPT_ARG_VAL,    &sparse_files, 0, 0, 0 },
699   {"preallocate",      0,  POPT_ARG_NONE,   &preallocate_files, 0, 0, 0},
700   {"inplace",          0,  POPT_ARG_VAL,    &inplace, 1, 0, 0 },
701   {"no-inplace",       0,  POPT_ARG_VAL,    &inplace, 0, 0, 0 },
702   {"append",           0,  POPT_ARG_NONE,   0, OPT_APPEND, 0, 0 },
703   {"append-verify",    0,  POPT_ARG_VAL,    &append_mode, 2, 0, 0 },
704   {"no-append",        0,  POPT_ARG_VAL,    &append_mode, 0, 0, 0 },
705   {"del",              0,  POPT_ARG_NONE,   &delete_during, 0, 0, 0 },
706   {"delete",           0,  POPT_ARG_NONE,   &delete_mode, 0, 0, 0 },
707   {"delete-before",    0,  POPT_ARG_NONE,   &delete_before, 0, 0, 0 },
708   {"delete-during",    0,  POPT_ARG_VAL,    &delete_during, 1, 0, 0 },
709   {"delete-delay",     0,  POPT_ARG_VAL,    &delete_during, 2, 0, 0 },
710   {"delete-after",     0,  POPT_ARG_NONE,   &delete_after, 0, 0, 0 },
711   {"delete-excluded",  0,  POPT_ARG_NONE,   &delete_excluded, 0, 0, 0 },
712   {"delete-missing-args",0,POPT_BIT_SET,    &missing_args, 2, 0, 0 },
713   {"ignore-missing-args",0,POPT_BIT_SET,    &missing_args, 1, 0, 0 },
714   {"remove-sent-files",0,  POPT_ARG_VAL,    &remove_source_files, 2, 0, 0 }, /* deprecated */
715   {"remove-source-files",0,POPT_ARG_VAL,    &remove_source_files, 1, 0, 0 },
716   {"force",            0,  POPT_ARG_VAL,    &force_delete, 1, 0, 0 },
717   {"no-force",         0,  POPT_ARG_VAL,    &force_delete, 0, 0, 0 },
718   {"ignore-errors",    0,  POPT_ARG_VAL,    &ignore_errors, 1, 0, 0 },
719   {"no-ignore-errors", 0,  POPT_ARG_VAL,    &ignore_errors, 0, 0, 0 },
720   {"max-delete",       0,  POPT_ARG_INT,    &max_delete, 0, 0, 0 },
721   {0,                 'F', POPT_ARG_NONE,   0, 'F', 0, 0 },
722   {"filter",          'f', POPT_ARG_STRING, 0, OPT_FILTER, 0, 0 },
723   {"exclude",          0,  POPT_ARG_STRING, 0, OPT_EXCLUDE, 0, 0 },
724   {"include",          0,  POPT_ARG_STRING, 0, OPT_INCLUDE, 0, 0 },
725   {"exclude-from",     0,  POPT_ARG_STRING, 0, OPT_EXCLUDE_FROM, 0, 0 },
726   {"include-from",     0,  POPT_ARG_STRING, 0, OPT_INCLUDE_FROM, 0, 0 },
727   {"cvs-exclude",     'C', POPT_ARG_NONE,   &cvs_exclude, 0, 0, 0 },
728   {"whole-file",      'W', POPT_ARG_VAL,    &whole_file, 1, 0, 0 },
729   {"no-whole-file",    0,  POPT_ARG_VAL,    &whole_file, 0, 0, 0 },
730   {"no-W",             0,  POPT_ARG_VAL,    &whole_file, 0, 0, 0 },
731   {"checksum",        'c', POPT_ARG_VAL,    &always_checksum, 1, 0, 0 },
732   {"no-checksum",      0,  POPT_ARG_VAL,    &always_checksum, 0, 0, 0 },
733   {"no-c",             0,  POPT_ARG_VAL,    &always_checksum, 0, 0, 0 },
734   {"checksum-choice",  0,  POPT_ARG_STRING, &checksum_choice, 0, 0, 0 },
735   {"cc",               0,  POPT_ARG_STRING, &checksum_choice, 0, 0, 0 },
736   {"block-size",      'B', POPT_ARG_STRING, 0, OPT_BLOCK_SIZE, 0, 0 },
737   {"compare-dest",     0,  POPT_ARG_STRING, 0, OPT_COMPARE_DEST, 0, 0 },
738   {"copy-dest",        0,  POPT_ARG_STRING, 0, OPT_COPY_DEST, 0, 0 },
739   {"link-dest",        0,  POPT_ARG_STRING, 0, OPT_LINK_DEST, 0, 0 },
740   {"fuzzy",           'y', POPT_ARG_NONE,   0, 'y', 0, 0 },
741   {"no-fuzzy",         0,  POPT_ARG_VAL,    &fuzzy_basis, 0, 0, 0 },
742   {"no-y",             0,  POPT_ARG_VAL,    &fuzzy_basis, 0, 0, 0 },
743   {"compress",        'z', POPT_ARG_NONE,   0, 'z', 0, 0 },
744   {"old-compress",     0,  POPT_ARG_NONE,   0, OPT_OLD_COMPRESS, 0, 0 },
745   {"new-compress",     0,  POPT_ARG_NONE,   0, OPT_NEW_COMPRESS, 0, 0 },
746   {"no-compress",      0,  POPT_ARG_NONE,   0, OPT_NO_COMPRESS, 0, 0 },
747   {"no-z",             0,  POPT_ARG_NONE,   0, OPT_NO_COMPRESS, 0, 0 },
748   {"compress-choice",  0,  POPT_ARG_STRING, &compress_choice, 0, 0, 0 },
749   {"zc",               0,  POPT_ARG_STRING, &compress_choice, 0, 0, 0 },
750   {"skip-compress",    0,  POPT_ARG_STRING, &skip_compress, 0, 0, 0 },
751   {"compress-level",   0,  POPT_ARG_INT,    &do_compression_level, 0, 0, 0 },
752   {"zl",               0,  POPT_ARG_INT,    &do_compression_level, 0, 0, 0 },
753   {0,                 'P', POPT_ARG_NONE,   0, 'P', 0, 0 },
754   {"progress",         0,  POPT_ARG_VAL,    &do_progress, 1, 0, 0 },
755   {"no-progress",      0,  POPT_ARG_VAL,    &do_progress, 0, 0, 0 },
756   {"partial",          0,  POPT_ARG_VAL,    &keep_partial, 1, 0, 0 },
757   {"no-partial",       0,  POPT_ARG_VAL,    &keep_partial, 0, 0, 0 },
758   {"partial-dir",      0,  POPT_ARG_STRING, &partial_dir, 0, 0, 0 },
759   {"delay-updates",    0,  POPT_ARG_VAL,    &delay_updates, 1, 0, 0 },
760   {"no-delay-updates", 0,  POPT_ARG_VAL,    &delay_updates, 0, 0, 0 },
761   {"prune-empty-dirs",'m', POPT_ARG_VAL,    &prune_empty_dirs, 1, 0, 0 },
762   {"no-prune-empty-dirs",0,POPT_ARG_VAL,    &prune_empty_dirs, 0, 0, 0 },
763   {"no-m",             0,  POPT_ARG_VAL,    &prune_empty_dirs, 0, 0, 0 },
764   {"log-file",         0,  POPT_ARG_STRING, &logfile_name, 0, 0, 0 },
765   {"log-file-format",  0,  POPT_ARG_STRING, &logfile_format, 0, 0, 0 },
766   {"out-format",       0,  POPT_ARG_STRING, &stdout_format, 0, 0, 0 },
767   {"log-format",       0,  POPT_ARG_STRING, &stdout_format, 0, 0, 0 }, /* DEPRECATED */
768   {"itemize-changes", 'i', POPT_ARG_NONE,   0, 'i', 0, 0 },
769   {"no-itemize-changes",0, POPT_ARG_VAL,    &itemize_changes, 0, 0, 0 },
770   {"no-i",             0,  POPT_ARG_VAL,    &itemize_changes, 0, 0, 0 },
771   {"bwlimit",          0,  POPT_ARG_STRING, &bwlimit_arg, OPT_BWLIMIT, 0, 0 },
772   {"no-bwlimit",       0,  POPT_ARG_VAL,    &bwlimit, 0, 0, 0 },
773   {"backup",          'b', POPT_ARG_VAL,    &make_backups, 1, 0, 0 },
774   {"no-backup",        0,  POPT_ARG_VAL,    &make_backups, 0, 0, 0 },
775   {"backup-dir",       0,  POPT_ARG_STRING, &backup_dir, 0, 0, 0 },
776   {"suffix",           0,  POPT_ARG_STRING, &backup_suffix, 0, 0, 0 },
777   {"list-only",        0,  POPT_ARG_VAL,    &list_only, 2, 0, 0 },
778   {"read-batch",       0,  POPT_ARG_STRING, &batch_name, OPT_READ_BATCH, 0, 0 },
779   {"write-batch",      0,  POPT_ARG_STRING, &batch_name, OPT_WRITE_BATCH, 0, 0 },
780   {"only-write-batch", 0,  POPT_ARG_STRING, &batch_name, OPT_ONLY_WRITE_BATCH, 0, 0 },
781   {"files-from",       0,  POPT_ARG_STRING, &files_from, 0, 0, 0 },
782   {"from0",           '0', POPT_ARG_VAL,    &eol_nulls, 1, 0, 0},
783   {"no-from0",         0,  POPT_ARG_VAL,    &eol_nulls, 0, 0, 0},
784   {"old-args",         0,  POPT_ARG_NONE,   0, OPT_OLD_ARGS, 0, 0},
785   {"no-old-args",      0,  POPT_ARG_VAL,    &old_style_args, 0, 0, 0},
786   {"protect-args",    's', POPT_ARG_VAL,    &protect_args, 1, 0, 0},
787   {"no-protect-args",  0,  POPT_ARG_VAL,    &protect_args, 0, 0, 0},
788   {"no-s",             0,  POPT_ARG_VAL,    &protect_args, 0, 0, 0},
789   {"numeric-ids",      0,  POPT_ARG_VAL,    &numeric_ids, 1, 0, 0 },
790   {"no-numeric-ids",   0,  POPT_ARG_VAL,    &numeric_ids, 0, 0, 0 },
791   {"usermap",          0,  POPT_ARG_STRING, 0, OPT_USERMAP, 0, 0 },
792   {"groupmap",         0,  POPT_ARG_STRING, 0, OPT_GROUPMAP, 0, 0 },
793   {"chown",            0,  POPT_ARG_STRING, 0, OPT_CHOWN, 0, 0 },
794   {"timeout",          0,  POPT_ARG_INT,    &io_timeout, 0, 0, 0 },
795   {"no-timeout",       0,  POPT_ARG_VAL,    &io_timeout, 0, 0, 0 },
796   {"contimeout",       0,  POPT_ARG_INT,    &connect_timeout, 0, 0, 0 },
797   {"no-contimeout",    0,  POPT_ARG_VAL,    &connect_timeout, 0, 0, 0 },
798   {"fsync",            0,  POPT_ARG_NONE,   &do_fsync, 0, 0, 0 },
799   {"stop-after",       0,  POPT_ARG_STRING, 0, OPT_STOP_AFTER, 0, 0 },
800   {"time-limit",       0,  POPT_ARG_STRING, 0, OPT_STOP_AFTER, 0, 0 }, /* earlier stop-after name */
801   {"stop-at",          0,  POPT_ARG_STRING, 0, OPT_STOP_AT, 0, 0 },
802   {"rsh",             'e', POPT_ARG_STRING, &shell_cmd, 0, 0, 0 },
803   {"rsync-path",       0,  POPT_ARG_STRING, &rsync_path, 0, 0, 0 },
804   {"temp-dir",        'T', POPT_ARG_STRING, &tmpdir, 0, 0, 0 },
805   {"iconv",            0,  POPT_ARG_STRING, &iconv_opt, 0, 0, 0 },
806   {"no-iconv",         0,  POPT_ARG_NONE,   0, OPT_NO_ICONV, 0, 0 },
807   {"ipv4",            '4', POPT_ARG_VAL,    &default_af_hint, AF_INET, 0, 0 },
808   {"ipv6",            '6', POPT_ARG_VAL,    &default_af_hint, AF_INET6, 0, 0 },
809   {"8-bit-output",    '8', POPT_ARG_VAL,    &allow_8bit_chars, 1, 0, 0 },
810   {"no-8-bit-output",  0,  POPT_ARG_VAL,    &allow_8bit_chars, 0, 0, 0 },
811   {"no-8",             0,  POPT_ARG_VAL,    &allow_8bit_chars, 0, 0, 0 },
812   {"mkpath",           0,  POPT_ARG_VAL,    &mkpath_dest_arg, 1, 0, 0 },
813   {"no-mkpath",        0,  POPT_ARG_VAL,    &mkpath_dest_arg, 0, 0, 0 },
814   {"qsort",            0,  POPT_ARG_NONE,   &use_qsort, 0, 0, 0 },
815   {"copy-as",          0,  POPT_ARG_STRING, &copy_as, 0, 0, 0 },
816   {"address",          0,  POPT_ARG_STRING, &bind_address, 0, 0, 0 },
817   {"port",             0,  POPT_ARG_INT,    &rsync_port, 0, 0, 0 },
818   {"sockopts",         0,  POPT_ARG_STRING, &sockopts, 0, 0, 0 },
819   {"password-file",    0,  POPT_ARG_STRING, &password_file, 0, 0, 0 },
820   {"early-input",      0,  POPT_ARG_STRING, &early_input_file, 0, 0, 0 },
821   {"blocking-io",      0,  POPT_ARG_VAL,    &blocking_io, 1, 0, 0 },
822   {"no-blocking-io",   0,  POPT_ARG_VAL,    &blocking_io, 0, 0, 0 },
823   {"outbuf",           0,  POPT_ARG_STRING, &outbuf_mode, 0, 0, 0 },
824   {"remote-option",   'M', POPT_ARG_STRING, 0, 'M', 0, 0 },
825   {"protocol",         0,  POPT_ARG_INT,    &protocol_version, 0, 0, 0 },
826   {"checksum-seed",    0,  POPT_ARG_INT,    &checksum_seed, 0, 0, 0 },
827   {"server",           0,  POPT_ARG_NONE,   0, OPT_SERVER, 0, 0 },
828   {"sender",           0,  POPT_ARG_NONE,   0, OPT_SENDER, 0, 0 },
829   /* All the following options switch us into daemon-mode option-parsing. */
830   {"config",           0,  POPT_ARG_STRING, 0, OPT_DAEMON, 0, 0 },
831   {"daemon",           0,  POPT_ARG_NONE,   0, OPT_DAEMON, 0, 0 },
832   {"dparam",           0,  POPT_ARG_STRING, 0, OPT_DAEMON, 0, 0 },
833   {"detach",           0,  POPT_ARG_NONE,   0, OPT_DAEMON, 0, 0 },
834   {"no-detach",        0,  POPT_ARG_NONE,   0, OPT_DAEMON, 0, 0 },
835   {0,0,0,0, 0, 0, 0}
836 };
837
838 static struct poptOption long_daemon_options[] = {
839   /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
840   {"address",          0,  POPT_ARG_STRING, &bind_address, 0, 0, 0 },
841   {"bwlimit",          0,  POPT_ARG_INT,    &daemon_bwlimit, 0, 0, 0 },
842   {"config",           0,  POPT_ARG_STRING, &config_file, 0, 0, 0 },
843   {"daemon",           0,  POPT_ARG_NONE,   &daemon_opt, 0, 0, 0 },
844   {"dparam",          'M', POPT_ARG_STRING, 0, 'M', 0, 0 },
845   {"ipv4",            '4', POPT_ARG_VAL,    &default_af_hint, AF_INET, 0, 0 },
846   {"ipv6",            '6', POPT_ARG_VAL,    &default_af_hint, AF_INET6, 0, 0 },
847   {"detach",           0,  POPT_ARG_VAL,    &no_detach, 0, 0, 0 },
848   {"no-detach",        0,  POPT_ARG_VAL,    &no_detach, 1, 0, 0 },
849   {"log-file",         0,  POPT_ARG_STRING, &logfile_name, 0, 0, 0 },
850   {"log-file-format",  0,  POPT_ARG_STRING, &logfile_format, 0, 0, 0 },
851   {"port",             0,  POPT_ARG_INT,    &rsync_port, 0, 0, 0 },
852   {"sockopts",         0,  POPT_ARG_STRING, &sockopts, 0, 0, 0 },
853   {"protocol",         0,  POPT_ARG_INT,    &protocol_version, 0, 0, 0 },
854   {"server",           0,  POPT_ARG_NONE,   &am_server, 0, 0, 0 },
855   {"temp-dir",        'T', POPT_ARG_STRING, &tmpdir, 0, 0, 0 },
856   {"verbose",         'v', POPT_ARG_NONE,   0, 'v', 0, 0 },
857   {"no-verbose",       0,  POPT_ARG_VAL,    &verbose, 0, 0, 0 },
858   {"no-v",             0,  POPT_ARG_VAL,    &verbose, 0, 0, 0 },
859   {"help",            'h', POPT_ARG_NONE,   0, 'h', 0, 0 },
860   {0,0,0,0, 0, 0, 0}
861 };
862
863
864 static char err_buf[200];
865
866
867 /**
868  * Store the option error message, if any, so that we can log the
869  * connection attempt (which requires parsing the options), and then
870  * show the error later on.
871  **/
872 void option_error(void)
873 {
874         if (!err_buf[0]) {
875                 strlcpy(err_buf, "Error parsing options: option may "
876                         "be supported on client but not on server?\n",
877                         sizeof err_buf);
878         }
879
880         rprintf(FERROR, RSYNC_NAME ": %s", err_buf);
881         io_flush(MSG_FLUSH);
882         msleep(20);
883 }
884
885
886 static void parse_one_refuse_match(int negated, const char *ref, const struct poptOption *list_end)
887 {
888         struct poptOption *op;
889         char shortName[2];
890         int is_wild = strpbrk(ref, "*?[") != NULL;
891         int found_match = 0;
892
893         shortName[1] = '\0';
894
895         if (strcmp("a", ref) == 0 || strcmp("archive", ref) == 0) {
896                 ref = "[ardlptgoD]";
897                 is_wild = 1;
898         }
899
900         for (op = long_options; op != list_end; op++) {
901                 *shortName = op->shortName;
902                 if ((op->longName && wildmatch(ref, op->longName))
903                  || (*shortName && wildmatch(ref, shortName))) {
904                         if (op->descrip[1] == '*')
905                                 op->descrip = negated ? "a*" : "r*";
906                         else if (!is_wild)
907                                 op->descrip = negated ? "a=" : "r=";
908                         found_match = 1;
909                         if (!is_wild)
910                                 break;
911                 }
912         }
913
914         if (!found_match)
915                 rprintf(FLOG, "No match for refuse-options string \"%s\"\n", ref);
916 }
917
918
919 /**
920  * Tweak the option table to disable all options that the rsyncd.conf
921  * file has told us to refuse.
922  **/
923 static void set_refuse_options(void)
924 {
925         struct poptOption *op, *list_end = NULL;
926         char *cp, *ref = lp_refuse_options(module_id);
927         int negated;
928
929         if (!ref)
930                 ref = "";
931
932         if (!am_daemon)
933                 ref = "";
934
935         /* We abuse the descrip field in poptOption to make it easy to flag which options
936          * are refused (since we don't use it otherwise).  Start by marking all options
937          * as "a"ccepted with a few options also marked as non-wild. */
938         for (op = long_options; ; op++) {
939                 const char *longName = op->longName ? op->longName : "";
940                 if (!op->longName && !op->shortName) {
941                         list_end = op;
942                         break;
943                 }
944                 if (!am_daemon
945                  || op->shortName == 'e' /* Required for compatibility flags */
946                  || op->shortName == '0' /* --from0 just modifies --files-from, so refuse that instead (or not) */
947                  || op->shortName == 's' /* --protect-args is always OK */
948                  || op->shortName == 'n' /* --dry-run is always OK */
949                  || strcmp("iconv", longName) == 0
950                  || strcmp("no-iconv", longName) == 0
951                  || strcmp("checksum-seed", longName) == 0
952                  || strcmp("write-devices", longName) == 0 /* disable wild-match (it gets refused below) */
953                  || strcmp("log-format", longName) == 0 /* aka out-format (NOT log-file-format) */
954                  || strcmp("sender", longName) == 0
955                  || strcmp("server", longName) == 0)
956                         op->descrip = "a="; /* exact-match only */
957                 else
958                         op->descrip = "a*"; /* wild-card-able */
959         }
960         assert(list_end != NULL);
961
962         if (am_daemon) { /* Refused by default, but can be accepted via a negated exact match. */
963                 parse_one_refuse_match(0, "write-devices", list_end);
964         }
965
966         while (1) {
967                 while (*ref == ' ') ref++;
968                 if (!*ref)
969                         break;
970                 if ((cp = strchr(ref, ' ')) != NULL)
971                         *cp = '\0';
972                 negated = *ref == '!';
973                 if (negated && ref[1])
974                         ref++;
975                 parse_one_refuse_match(negated, ref, list_end);
976                 if (!cp)
977                         break;
978                 *cp = ' ';
979                 ref = cp + 1;
980         }
981
982         if (am_daemon) {
983 #ifdef ICONV_OPTION
984                 if (!*lp_charset(module_id))
985                         parse_one_refuse_match(0, "iconv", list_end);
986 #endif
987                 parse_one_refuse_match(0, "log-file*", list_end);
988         }
989
990 #ifndef SUPPORT_ATIMES
991         parse_one_refuse_match(0, "atimes", list_end);
992 #endif
993 #ifndef SUPPORT_HARD_LINKS
994         parse_one_refuse_match(0, "link-dest", list_end);
995 #endif
996 #ifndef HAVE_MKTIME
997         parse_one_refuse_match(0, "stop-at", list_end);
998 #endif
999 #ifndef ICONV_OPTION
1000         parse_one_refuse_match(0, "iconv", list_end);
1001 #endif
1002 #ifndef HAVE_SETVBUF
1003         parse_one_refuse_match(0, "outbuf", list_end);
1004 #endif
1005 #ifndef SUPPORT_CRTIMES
1006         parse_one_refuse_match(0, "crtimes", list_end);
1007 #endif
1008
1009         /* Now we use the descrip values to actually mark the options for refusal. */
1010         for (op = long_options; op != list_end; op++) {
1011                 int refused = op->descrip[0] == 'r';
1012                 op->descrip = NULL;
1013                 if (!refused)
1014                         continue;
1015                 if (op->argInfo == POPT_ARG_VAL)
1016                         op->argInfo = POPT_ARG_NONE;
1017                 op->val = (op - long_options) + OPT_REFUSED_BASE;
1018                 /* The following flags are set to let us easily check an implied option later in the code. */
1019                 switch (op->shortName) {
1020                 case 'r': case 'd': case 'l': case 'p':
1021                 case 't': case 'g': case 'o': case 'D':
1022                         refused_archive_part = op->val;
1023                         break;
1024                 case 'z':
1025                         refused_compress = op->val;
1026                         break;
1027                 case '\0':
1028                         if (strcmp("delete", op->longName) == 0)
1029                                 refused_delete = op->val;
1030                         else if (strcmp("delete-before", op->longName) == 0)
1031                                 refused_delete_before = op->val;
1032                         else if (strcmp("delete-during", op->longName) == 0)
1033                                 refused_delete_during = op->val;
1034                         else if (strcmp("partial", op->longName) == 0)
1035                                 refused_partial = op->val;
1036                         else if (strcmp("progress", op->longName) == 0)
1037                                 refused_progress = op->val;
1038                         else if (strcmp("inplace", op->longName) == 0)
1039                                 refused_inplace = op->val;
1040                         else if (strcmp("no-iconv", op->longName) == 0)
1041                                 refused_no_iconv = op->val;
1042                         break;
1043                 }
1044         }
1045 }
1046
1047
1048 static int count_args(const char **argv)
1049 {
1050         int i = 0;
1051
1052         if (argv) {
1053                 while (argv[i] != NULL)
1054                         i++;
1055         }
1056
1057         return i;
1058 }
1059
1060 /* If the size_arg is an invalid string or the value is < min_value, an error
1061  * is put into err_buf & the return is -1.  Note that this parser does NOT
1062  * support negative numbers, so a min_value < 0 doesn't make any sense. */
1063 static ssize_t parse_size_arg(const char *size_arg, char def_suf, const char *opt_name,
1064                               ssize_t min_value, ssize_t max_value, BOOL unlimited_0)
1065 {
1066         int reps, mult, len;
1067         const char *arg, *err = "invalid", *min_max = NULL;
1068         ssize_t limit = -1, size = 1;
1069
1070         for (arg = size_arg; isDigit(arg); arg++) {}
1071         if (*arg == '.' || *arg == get_decimal_point()) /* backward compatibility: always allow '.' */
1072                 for (arg++; isDigit(arg); arg++) {}
1073         switch (*arg && *arg != '+' && *arg != '-' ? *arg++ : def_suf) {
1074         case 'b': case 'B':
1075                 reps = 0;
1076                 break;
1077         case 'k': case 'K':
1078                 reps = 1;
1079                 break;
1080         case 'm': case 'M':
1081                 reps = 2;
1082                 break;
1083         case 'g': case 'G':
1084                 reps = 3;
1085                 break;
1086         case 't': case 'T':
1087                 reps = 4;
1088                 break;
1089         case 'p': case 'P':
1090                 reps = 5;
1091                 break;
1092         default:
1093                 goto failure;
1094         }
1095         if (*arg == 'b' || *arg == 'B')
1096                 mult = 1000, arg++;
1097         else if (!*arg || *arg == '+' || *arg == '-')
1098                 mult = 1024;
1099         else if (strncasecmp(arg, "ib", 2) == 0)
1100                 mult = 1024, arg += 2;
1101         else
1102                 goto failure;
1103         while (reps--)
1104                 size *= mult;
1105         size *= atof(size_arg);
1106         if ((*arg == '+' || *arg == '-') && arg[1] == '1' && arg != size_arg)
1107                 size += atoi(arg), arg += 2;
1108         if (*arg)
1109                 goto failure;
1110         if (size < 0 || (max_value >= 0 && size > max_value)) {
1111                 err = "too large";
1112                 min_max = "max";
1113                 limit = max_value;
1114                 goto failure;
1115         }
1116         if (size < min_value && (!unlimited_0 || size != 0)) {
1117                 err = "too small";
1118                 min_max = "min";
1119                 limit = min_value;
1120                 goto failure;
1121         }
1122         return size;
1123
1124 failure:
1125         len = snprintf(err_buf, sizeof err_buf - 1, "--%s=%s is %s", opt_name, size_arg, err);
1126         if (min_max && limit >= 0 && len < (int)sizeof err_buf - 10) {
1127                 len += snprintf(err_buf + len, sizeof err_buf - len - 1, " (%s: %s%s)",
1128                         min_max, do_big_num(limit, 3, NULL),
1129                         unlimited_0 && min_max[1] == 'i' ? " or 0 for unlimited" : "");
1130         }
1131         err_buf[len] = '\n';
1132         err_buf[len+1] = '\0';
1133         return -1;
1134 }
1135
1136 #ifdef HAVE_MKTIME
1137 /* Allow the user to specify a time in the format yyyy-mm-ddThh:mm while
1138  * also allowing abbreviated data.  For instance, if the time is omitted,
1139  * it defaults to midnight.  If the date is omitted, it defaults to the
1140  * next possible date in the future with the specified time.  Even the
1141  * year or year-month can be omitted, again defaulting to the next date
1142  * in the future that matches the specified information.  A 2-digit year
1143  * is also OK, as is using '/' instead of '-'. */
1144 static time_t parse_time(const char *arg)
1145 {
1146         const char *cp;
1147         time_t val, now = time(NULL);
1148         struct tm t, *today = localtime(&now);
1149         int in_date, old_mday, n;
1150
1151         memset(&t, 0, sizeof t);
1152         t.tm_year = t.tm_mon = t.tm_mday = -1;
1153         t.tm_hour = t.tm_min = t.tm_isdst = -1;
1154         cp = arg;
1155         if (*cp == 'T' || *cp == 't' || *cp == ':') {
1156                 in_date = *cp == ':' ? 0 : -1;
1157                 cp++;
1158         } else
1159                 in_date = 1;
1160         for ( ; ; cp++) {
1161                 if (!isDigit(cp))
1162                         return (time_t)-1;
1163                 n = 0;
1164                 do {
1165                         n = n * 10 + *cp++ - '0';
1166                 } while (isDigit(cp));
1167                 if (*cp == ':')
1168                         in_date = 0;
1169                 if (in_date > 0) {
1170                         if (t.tm_year != -1)
1171                                 return (time_t)-1;
1172                         t.tm_year = t.tm_mon;
1173                         t.tm_mon = t.tm_mday;
1174                         t.tm_mday = n;
1175                         if (!*cp)
1176                                 break;
1177                         if (*cp == 'T' || *cp == 't') {
1178                                 if (!cp[1])
1179                                         break;
1180                                 in_date = -1;
1181                         } else if (*cp != '-' && *cp != '/')
1182                                 return (time_t)-1;
1183                         continue;
1184                 }
1185                 if (t.tm_hour != -1)
1186                         return (time_t)-1;
1187                 t.tm_hour = t.tm_min;
1188                 t.tm_min = n;
1189                 if (!*cp) {
1190                         if (in_date < 0)
1191                                 return (time_t)-1;
1192                         break;
1193                 }
1194                 if (*cp != ':')
1195                         return (time_t)-1;
1196                 in_date = 0;
1197         }
1198
1199         in_date = 0;
1200         if (t.tm_year < 0) {
1201                 t.tm_year = today->tm_year;
1202                 in_date = 1;
1203         } else if (t.tm_year < 100) {
1204                 while (t.tm_year < today->tm_year)
1205                         t.tm_year += 100;
1206         } else
1207                 t.tm_year -= 1900;
1208         if (t.tm_mon < 0) {
1209                 t.tm_mon = today->tm_mon;
1210                 in_date = 2;
1211         } else
1212                 t.tm_mon--;
1213         if (t.tm_mday < 0) {
1214                 t.tm_mday = today->tm_mday;
1215                 in_date = 3;
1216         }
1217
1218         n = 0;
1219         if (t.tm_min < 0) {
1220                 t.tm_hour = t.tm_min = 0;
1221         } else if (t.tm_hour < 0) {
1222                 if (in_date != 3)
1223                         return (time_t)-1;
1224                 in_date = 0;
1225                 t.tm_hour = today->tm_hour;
1226                 n = 60*60;
1227         }
1228
1229         /* Note that mktime() might change a too-large tm_mday into the start of
1230          * the following month which we need to undo in the following code! */
1231         old_mday = t.tm_mday;
1232         if (t.tm_hour > 23 || t.tm_min > 59
1233             || t.tm_mon < 0 || t.tm_mon >= 12
1234             || t.tm_mday < 1 || t.tm_mday > 31
1235             || (val = mktime(&t)) == (time_t)-1)
1236                 return (time_t)-1;
1237
1238         while (in_date && (val <= now || t.tm_mday < old_mday)) {
1239                 switch (in_date) {
1240                 case 3:
1241                         old_mday = ++t.tm_mday;
1242                         break;
1243                 case 2:
1244                         if (t.tm_mday < old_mday)
1245                                 t.tm_mday = old_mday; /* The month already got bumped forward */
1246                         else if (++t.tm_mon == 12) {
1247                                 t.tm_mon = 0;
1248                                 t.tm_year++;
1249                         }
1250                         break;
1251                 case 1:
1252                         if (t.tm_mday < old_mday) {
1253                                 /* mon==1 mday==29 got bumped to mon==2 */
1254                                 if (t.tm_mon != 2 || old_mday != 29)
1255                                         return (time_t)-1;
1256                                 t.tm_mon = 1;
1257                                 t.tm_mday = 29;
1258                         }
1259                         t.tm_year++;
1260                         break;
1261                 }
1262                 if ((val = mktime(&t)) == (time_t)-1) {
1263                         /* This code shouldn't be needed, as mktime() should auto-round to the next month. */
1264                         if (in_date != 3 || t.tm_mday <= 28)
1265                                 return (time_t)-1;
1266                         t.tm_mday = old_mday = 1;
1267                         in_date = 2;
1268                 }
1269         }
1270         if (n) {
1271                 while (val <= now)
1272                         val += n;
1273         }
1274         return val;
1275 }
1276 #endif
1277
1278 static void create_refuse_error(int which)
1279 {
1280         const char *msg;
1281         if (am_daemon)
1282                 msg = "The server is configured to refuse";
1283         else if (am_server)
1284                 msg = "The server does not support";
1285         else
1286                 msg = "This rsync does not support";
1287
1288         /* The "which" value is the index + OPT_REFUSED_BASE. */
1289         struct poptOption *op = &long_options[which - OPT_REFUSED_BASE];
1290         int n = snprintf(err_buf, sizeof err_buf, "%s --%s\n", msg, op->longName) - 1;
1291         if (op->shortName)
1292                 snprintf(err_buf + n, sizeof err_buf - n, " (-%c)\n", op->shortName);
1293 }
1294
1295 /* This is used to make sure that --daemon & --server cannot be aliased to
1296  * something else. These options have always disabled popt aliases for the
1297  * parsing of a daemon or server command-line, but we have to make sure that
1298  * these options cannot vanish so that the alias disabling can take effect. */
1299 static void popt_unalias(poptContext con, const char *opt)
1300 {
1301         struct poptAlias unalias;
1302
1303         memset(&unalias, 0, sizeof unalias);
1304
1305         unalias.longName = opt + 2; /* point past the leading "--" */
1306         unalias.argc = 1;
1307         unalias.argv = new_array0(const char*, 2);
1308         unalias.argv[0] = strdup(opt);
1309
1310         poptAddAlias(con, unalias, 0);
1311 }
1312
1313 char *alt_dest_opt(int type)
1314 {
1315         if (!type)
1316                 type = alt_dest_type;
1317
1318         switch (type) {
1319         case COMPARE_DEST:
1320                 return "--compare-dest";
1321         case COPY_DEST:
1322                 return "--copy-dest";
1323         case LINK_DEST:
1324                 return "--link-dest";
1325         default:
1326                 NOISY_DEATH("Unknown alt_dest_opt type");
1327         }
1328 }
1329
1330 /**
1331  * Process command line arguments.  Called on both local and remote.
1332  *
1333  * @retval 1 if all options are OK; with globals set to appropriate
1334  * values
1335  *
1336  * @retval 0 on error, with err_buf containing an explanation
1337  **/
1338 int parse_arguments(int *argc_p, const char ***argv_p)
1339 {
1340         static poptContext pc;
1341         const char *arg, **argv = *argv_p;
1342         int argc = *argc_p;
1343         int opt, want_dest_type;
1344         int orig_protect_args = protect_args;
1345
1346         if (argc == 0) {
1347                 strlcpy(err_buf, "argc is zero!\n", sizeof err_buf);
1348                 return 0;
1349         }
1350
1351         set_refuse_options();
1352
1353 #ifdef ICONV_OPTION
1354         if (!am_daemon && protect_args <= 0 && (arg = getenv("RSYNC_ICONV")) != NULL && *arg)
1355                 iconv_opt = strdup(arg);
1356 #endif
1357
1358         /* TODO: Call poptReadDefaultConfig; handle errors. */
1359
1360         /* The context leaks in case of an error, but if there's a
1361          * problem we always exit anyhow. */
1362         if (pc)
1363                 poptFreeContext(pc);
1364         pc = poptGetContext(RSYNC_NAME, argc, argv, long_options, 0);
1365         if (!am_server) {
1366                 poptReadDefaultConfig(pc, 0);
1367                 popt_unalias(pc, "--daemon");
1368                 popt_unalias(pc, "--server");
1369         }
1370
1371         while ((opt = poptGetNextOpt(pc)) != -1) {
1372                 /* most options are handled automatically by popt;
1373                  * only special cases are returned and listed here. */
1374
1375                 switch (opt) {
1376                 case 'V':
1377                         version_opt_cnt++;
1378                         break;
1379
1380                 case OPT_SERVER:
1381                         if (!am_server) {
1382                                 /* Disable popt aliases on the server side and
1383                                  * then start parsing the options again. */
1384                                 poptFreeContext(pc);
1385                                 pc = poptGetContext(RSYNC_NAME, argc, argv, long_options, 0);
1386                                 am_server = 1;
1387                         }
1388 #ifdef ICONV_OPTION
1389                         iconv_opt = NULL;
1390 #endif
1391                         break;
1392
1393                 case OPT_SENDER:
1394                         if (!am_server) {
1395                                 usage(FERROR);
1396                                 exit_cleanup(RERR_SYNTAX);
1397                         }
1398                         am_sender = 1;
1399                         break;
1400
1401                 case OPT_DAEMON:
1402                         if (am_daemon) {
1403                                 strlcpy(err_buf,
1404                                         "Attempt to hack rsync thwarted!\n",
1405                                         sizeof err_buf);
1406                                 return 0;
1407                         }
1408 #ifdef ICONV_OPTION
1409                         iconv_opt = NULL;
1410 #endif
1411                         protect_args = 0;
1412                         poptFreeContext(pc);
1413                         pc = poptGetContext(RSYNC_NAME, argc, argv, long_daemon_options, 0);
1414                         while ((opt = poptGetNextOpt(pc)) != -1) {
1415                                 char **cpp;
1416                                 switch (opt) {
1417                                 case 'h':
1418                                         daemon_usage(FINFO);
1419                                         exit_cleanup(0);
1420
1421                                 case 'M':
1422                                         arg = poptGetOptArg(pc);
1423                                         if (!strchr(arg, '=')) {
1424                                                 rprintf(FERROR,
1425                                                         "--dparam value is missing an '=': %s\n",
1426                                                         arg);
1427                                                 goto daemon_error;
1428                                         }
1429                                         cpp = EXPAND_ITEM_LIST(&dparam_list, char *, 4);
1430                                         *cpp = strdup(arg);
1431                                         break;
1432
1433                                 case 'v':
1434                                         verbose++;
1435                                         break;
1436
1437                                 default:
1438                                         rprintf(FERROR,
1439                                                 "rsync: %s: %s (in daemon mode)\n",
1440                                                 poptBadOption(pc, POPT_BADOPTION_NOALIAS),
1441                                                 poptStrerror(opt));
1442                                         goto daemon_error;
1443                                 }
1444                         }
1445
1446                         if (dparam_list.count && !set_dparams(1))
1447                                 exit_cleanup(RERR_SYNTAX);
1448
1449                         if (tmpdir && strlen(tmpdir) >= MAXPATHLEN - 10) {
1450                                 snprintf(err_buf, sizeof err_buf,
1451                                          "the --temp-dir path is WAY too long.\n");
1452                                 return 0;
1453                         }
1454
1455                         if (!daemon_opt) {
1456                                 rprintf(FERROR, "Daemon option(s) used without --daemon.\n");
1457                             daemon_error:
1458                                 rprintf(FERROR, "(Type \"rsync --daemon --help\" for assistance with daemon mode.)\n");
1459                                 exit_cleanup(RERR_SYNTAX);
1460                         }
1461
1462                         *argv_p = argv = poptGetArgs(pc);
1463                         *argc_p = argc = count_args(argv);
1464                         am_starting_up = 0;
1465                         daemon_opt = 0;
1466                         am_daemon = 1;
1467                         return 1;
1468
1469                 case OPT_MODIFY_WINDOW:
1470                         /* The value has already been set by popt, but
1471                          * we need to remember that we're using a
1472                          * non-default setting. */
1473                         modify_window_set = 1;
1474                         break;
1475
1476                 case OPT_FILTER:
1477                         parse_filter_str(&filter_list, poptGetOptArg(pc),
1478                                         rule_template(0), 0);
1479                         break;
1480
1481                 case OPT_EXCLUDE:
1482                         parse_filter_str(&filter_list, poptGetOptArg(pc),
1483                                         rule_template(0), XFLG_OLD_PREFIXES);
1484                         break;
1485
1486                 case OPT_INCLUDE:
1487                         parse_filter_str(&filter_list, poptGetOptArg(pc),
1488                                         rule_template(FILTRULE_INCLUDE), XFLG_OLD_PREFIXES);
1489                         break;
1490
1491                 case OPT_EXCLUDE_FROM:
1492                 case OPT_INCLUDE_FROM:
1493                         arg = poptGetOptArg(pc);
1494                         if (sanitize_paths)
1495                                 arg = sanitize_path(NULL, arg, NULL, 0, SP_DEFAULT);
1496                         if (daemon_filter_list.head) {
1497                                 int rej;
1498                                 char *cp = strdup(arg);
1499                                 if (!*cp)
1500                                         rej = 1;
1501                                 else {
1502                                         char *dir = cp + (*cp == '/' ? module_dirlen : 0);
1503                                         clean_fname(dir, CFN_COLLAPSE_DOT_DOT_DIRS);
1504                                         rej = check_filter(&daemon_filter_list, FLOG, dir, 0) < 0;
1505                                 }
1506                                 free(cp);
1507                                 if (rej)
1508                                         goto options_rejected;
1509                         }
1510                         parse_filter_file(&filter_list, arg,
1511                                 rule_template(opt == OPT_INCLUDE_FROM ? FILTRULE_INCLUDE : 0),
1512                                 XFLG_FATAL_ERRORS | XFLG_OLD_PREFIXES);
1513                         break;
1514
1515                 case 'a':
1516                         if (refused_archive_part) {
1517                                 create_refuse_error(refused_archive_part);
1518                                 return 0;
1519                         }
1520                         if (!recurse) /* preserve recurse == 2 */
1521                                 recurse = 1;
1522 #ifdef SUPPORT_LINKS
1523                         preserve_links = 1;
1524 #endif
1525                         preserve_perms = 1;
1526                         preserve_mtimes = 1;
1527                         preserve_gid = 1;
1528                         preserve_uid = 1;
1529                         preserve_devices = 1;
1530                         preserve_specials = 1;
1531                         break;
1532
1533                 case 'D':
1534                         preserve_devices = preserve_specials = 1;
1535                         break;
1536
1537                 case OPT_NO_D:
1538                         preserve_devices = preserve_specials = 0;
1539                         break;
1540
1541                 case 'h':
1542                         human_readable++;
1543                         break;
1544
1545                 case 'H':
1546                         preserve_hard_links++;
1547                         break;
1548
1549                 case 'i':
1550                         itemize_changes++;
1551                         break;
1552
1553                 case 'U':
1554                         if (++preserve_atimes > 1)
1555                                 open_noatime = 1;
1556                         break;
1557
1558                 case 'v':
1559                         verbose++;
1560                         break;
1561
1562                 case 'y':
1563                         fuzzy_basis++;
1564                         break;
1565
1566                 case 'q':
1567                         quiet++;
1568                         break;
1569
1570                 case 'x':
1571                         one_file_system++;
1572                         break;
1573
1574                 case 'F':
1575                         switch (++F_option_cnt) {
1576                         case 1:
1577                                 parse_filter_str(&filter_list,": /.rsync-filter",rule_template(0),0);
1578                                 break;
1579                         case 2:
1580                                 parse_filter_str(&filter_list,"- .rsync-filter",rule_template(0),0);
1581                                 break;
1582                         }
1583                         break;
1584
1585                 case 'P':
1586                         if (refused_partial || refused_progress) {
1587                                 create_refuse_error(refused_partial ? refused_partial : refused_progress);
1588                                 return 0;
1589                         }
1590                         do_progress = 1;
1591                         keep_partial = 1;
1592                         break;
1593
1594                 case 'z':
1595                         do_compression++;
1596                         break;
1597
1598                 case OPT_OLD_COMPRESS:
1599                         compress_choice = "zlib";
1600                         break;
1601
1602                 case OPT_NEW_COMPRESS:
1603                         compress_choice = "zlibx";
1604                         break;
1605
1606                 case OPT_NO_COMPRESS:
1607                         do_compression = 0;
1608                         compress_choice = NULL;
1609                         break;
1610
1611                 case OPT_OLD_ARGS:
1612                         if (old_style_args <= 0)
1613                                 old_style_args = 1;
1614                         else
1615                                 old_style_args++;
1616                         break;
1617
1618                 case 'M':
1619                         arg = poptGetOptArg(pc);
1620                         if (*arg != '-') {
1621                                 snprintf(err_buf, sizeof err_buf,
1622                                         "Remote option must start with a dash: %s\n", arg);
1623                                 return 0;
1624                         }
1625                         if (remote_option_cnt+2 >= remote_option_alloc) {
1626                                 remote_option_alloc += 16;
1627                                 remote_options = realloc_array(remote_options,
1628                                                         const char *, remote_option_alloc);
1629                                 if (!remote_option_cnt)
1630                                         remote_options[0] = "ARG0";
1631                         }
1632                         remote_options[++remote_option_cnt] = arg;
1633                         remote_options[remote_option_cnt+1] = NULL;
1634                         break;
1635
1636                 case OPT_WRITE_BATCH:
1637                         /* batch_name is already set */
1638                         write_batch = 1;
1639                         break;
1640
1641                 case OPT_ONLY_WRITE_BATCH:
1642                         /* batch_name is already set */
1643                         write_batch = -1;
1644                         break;
1645
1646                 case OPT_READ_BATCH:
1647                         /* batch_name is already set */
1648                         read_batch = 1;
1649                         break;
1650
1651                 case OPT_NO_ICONV:
1652 #ifdef ICONV_OPTION
1653                         iconv_opt = NULL;
1654 #endif
1655                         break;
1656
1657                 case OPT_BLOCK_SIZE: {
1658                         /* We may not know the real protocol_version at this point if this is the client
1659                          * option parsing, but we still want to check it so that the client can specify
1660                          * a --protocol=29 option with a larger block size. */
1661                         int max_blength = protocol_version < 30 ? OLD_MAX_BLOCK_SIZE : MAX_BLOCK_SIZE;
1662                         ssize_t size;
1663                         arg = poptGetOptArg(pc);
1664                         if ((size = parse_size_arg(arg, 'b', "block-size", 0, max_blength, False)) < 0)
1665                                 return 0;
1666                         block_size = (int32)size;
1667                         break;
1668                 }
1669
1670                 case OPT_MAX_SIZE:
1671                         if ((max_size = parse_size_arg(max_size_arg, 'b', "max-size", 0, -1, False)) < 0)
1672                                 return 0;
1673                         max_size_arg = strdup(do_big_num(max_size, 0, NULL));
1674                         break;
1675
1676                 case OPT_MIN_SIZE:
1677                         if ((min_size = parse_size_arg(min_size_arg, 'b', "min-size", 0, -1, False)) < 0)
1678                                 return 0;
1679                         min_size_arg = strdup(do_big_num(min_size, 0, NULL));
1680                         break;
1681
1682                 case OPT_BWLIMIT: {
1683                         ssize_t size = parse_size_arg(bwlimit_arg, 'K', "bwlimit", 512, -1, True);
1684                         if (size < 0)
1685                                 return 0;
1686                         bwlimit_arg = strdup(do_big_num(size, 0, NULL));
1687                         bwlimit = (size + 512) / 1024;
1688                         break;
1689                 }
1690
1691                 case OPT_APPEND:
1692                         if (am_server)
1693                                 append_mode++;
1694                         else
1695                                 append_mode = 1;
1696                         break;
1697
1698                 case OPT_LINK_DEST:
1699                         want_dest_type = LINK_DEST;
1700                         goto set_dest_dir;
1701
1702                 case OPT_COPY_DEST:
1703                         want_dest_type = COPY_DEST;
1704                         goto set_dest_dir;
1705
1706                 case OPT_COMPARE_DEST:
1707                         want_dest_type = COMPARE_DEST;
1708
1709                 set_dest_dir:
1710                         if (alt_dest_type && alt_dest_type != want_dest_type) {
1711                                 snprintf(err_buf, sizeof err_buf,
1712                                         "ERROR: the %s option conflicts with the %s option\n",
1713                                         alt_dest_opt(want_dest_type), alt_dest_opt(0));
1714                                 return 0;
1715                         }
1716                         alt_dest_type = want_dest_type;
1717
1718                         if (basis_dir_cnt >= MAX_BASIS_DIRS) {
1719                                 snprintf(err_buf, sizeof err_buf,
1720                                         "ERROR: at most %d %s args may be specified\n",
1721                                         MAX_BASIS_DIRS, alt_dest_opt(0));
1722                                 return 0;
1723                         }
1724                         /* We defer sanitizing this arg until we know what
1725                          * our destination directory is going to be. */
1726                         basis_dir[basis_dir_cnt++] = (char *)poptGetOptArg(pc);
1727                         break;
1728
1729                 case OPT_CHMOD:
1730                         arg = poptGetOptArg(pc);
1731                         if (!parse_chmod(arg, &chmod_modes)) {
1732                                 snprintf(err_buf, sizeof err_buf,
1733                                         "Invalid argument passed to --chmod (%s)\n",
1734                                         arg);
1735                                 return 0;
1736                         }
1737                         break;
1738
1739                 case OPT_INFO:
1740                         arg = poptGetOptArg(pc);
1741                         parse_output_words(info_words, info_levels, arg, USER_PRIORITY);
1742                         break;
1743
1744                 case OPT_DEBUG:
1745                         arg = poptGetOptArg(pc);
1746                         parse_output_words(debug_words, debug_levels, arg, USER_PRIORITY);
1747                         break;
1748
1749                 case OPT_USERMAP:
1750                         if (usermap) {
1751                                 if (usermap_via_chown) {
1752                                         snprintf(err_buf, sizeof err_buf,
1753                                                 "--usermap conflicts with prior --chown.\n");
1754                                         return 0;
1755                                 }
1756                                 snprintf(err_buf, sizeof err_buf,
1757                                         "You can only specify --usermap once.\n");
1758                                 return 0;
1759                         }
1760                         usermap = (char *)poptGetOptArg(pc);
1761                         usermap_via_chown = False;
1762                         preserve_uid = 1;
1763                         break;
1764
1765                 case OPT_GROUPMAP:
1766                         if (groupmap) {
1767                                 if (groupmap_via_chown) {
1768                                         snprintf(err_buf, sizeof err_buf,
1769                                                 "--groupmap conflicts with prior --chown.\n");
1770                                         return 0;
1771                                 }
1772                                 snprintf(err_buf, sizeof err_buf,
1773                                         "You can only specify --groupmap once.\n");
1774                                 return 0;
1775                         }
1776                         groupmap = (char *)poptGetOptArg(pc);
1777                         groupmap_via_chown = False;
1778                         preserve_gid = 1;
1779                         break;
1780
1781                 case OPT_CHOWN: {
1782                         const char *chown = poptGetOptArg(pc);
1783                         int len;
1784                         if ((arg = strchr(chown, ':')) != NULL)
1785                                 len = arg++ - chown;
1786                         else
1787                                 len = strlen(chown);
1788                         if (len) {
1789                                 if (usermap) {
1790                                         if (!usermap_via_chown) {
1791                                                 snprintf(err_buf, sizeof err_buf,
1792                                                         "--chown conflicts with prior --usermap.\n");
1793                                                 return 0;
1794                                         }
1795                                         snprintf(err_buf, sizeof err_buf,
1796                                                 "You can only specify a user-affecting --chown once.\n");
1797                                         return 0;
1798                                 }
1799                                 if (asprintf(&usermap, "*:%.*s", len, chown) < 0)
1800                                         out_of_memory("parse_arguments");
1801                                 usermap_via_chown = True;
1802                                 preserve_uid = 1;
1803                         }
1804                         if (arg && *arg) {
1805                                 if (groupmap) {
1806                                         if (!groupmap_via_chown) {
1807                                                 snprintf(err_buf, sizeof err_buf,
1808                                                         "--chown conflicts with prior --groupmap.\n");
1809                                                 return 0;
1810                                         }
1811                                         snprintf(err_buf, sizeof err_buf,
1812                                                 "You can only specify a group-affecting --chown once.\n");
1813                                         return 0;
1814                                 }
1815                                 if (asprintf(&groupmap, "*:%s", arg) < 0)
1816                                         out_of_memory("parse_arguments");
1817                                 groupmap_via_chown = True;
1818                                 preserve_gid = 1;
1819                         }
1820                         break;
1821                 }
1822
1823                 case OPT_HELP:
1824                         usage(FINFO);
1825                         exit_cleanup(0);
1826
1827                 case 'A':
1828 #ifdef SUPPORT_ACLS
1829                         preserve_acls = 1;
1830                         preserve_perms = 1;
1831                         break;
1832 #else
1833                         /* FIXME: this should probably be ignored with a
1834                          * warning and then countermeasures taken to
1835                          * restrict group and other access in the presence
1836                          * of any more restrictive ACLs, but this is safe
1837                          * for now */
1838                         snprintf(err_buf,sizeof(err_buf),
1839                                  "ACLs are not supported on this %s\n",
1840                                  am_server ? "server" : "client");
1841                         return 0;
1842 #endif
1843
1844                 case 'X':
1845 #ifdef SUPPORT_XATTRS
1846                         preserve_xattrs++;
1847                         break;
1848 #else
1849                         snprintf(err_buf,sizeof(err_buf),
1850                                  "extended attributes are not supported on this %s\n",
1851                                  am_server ? "server" : "client");
1852                         return 0;
1853 #endif
1854
1855                 case OPT_STOP_AFTER: {
1856                         long val;
1857                         arg = poptGetOptArg(pc);
1858                         stop_at_utime = time(NULL);
1859                         if ((val = atol(arg) * 60) <= 0 || LONG_MAX - val < stop_at_utime || (long)(time_t)val != val) {
1860                                 snprintf(err_buf, sizeof err_buf, "invalid --stop-after value: %s\n", arg);
1861                                 return 0;
1862                         }
1863                         stop_at_utime += val;
1864                         break;
1865                 }
1866
1867 #ifdef HAVE_MKTIME
1868                 case OPT_STOP_AT:
1869                         arg = poptGetOptArg(pc);
1870                         if ((stop_at_utime = parse_time(arg)) == (time_t)-1) {
1871                                 snprintf(err_buf, sizeof err_buf, "invalid --stop-at format: %s\n", arg);
1872                                 return 0;
1873                         }
1874                         if (stop_at_utime <= time(NULL)) {
1875                                 snprintf(err_buf, sizeof err_buf, "--stop-at time is not in the future: %s\n", arg);
1876                                 return 0;
1877                         }
1878                         break;
1879 #endif
1880
1881                 case OPT_STDERR: {
1882                         int len;
1883                         arg = poptGetOptArg(pc);
1884                         len = strlen(arg);
1885                         if (len && strncmp("errors", arg, len) == 0)
1886                                 msgs2stderr = 2;
1887                         else if (len && strncmp("all", arg, len) == 0)
1888                                 msgs2stderr = 1;
1889                         else if (len && strncmp("client", arg, len) == 0)
1890                                 msgs2stderr = 0;
1891                         else {
1892                                 snprintf(err_buf, sizeof err_buf,
1893                                         "--stderr mode \"%s\" is not one of errors, all, or client\n", arg);
1894                                 return 0;
1895                         }
1896                         saw_stderr_opt = 1;
1897                         break;
1898                 }
1899
1900                 default:
1901                         /* A large opt value means that set_refuse_options()
1902                          * turned this option off. */
1903                         if (opt >= OPT_REFUSED_BASE) {
1904                                 create_refuse_error(opt);
1905                                 return 0;
1906                         }
1907                         snprintf(err_buf, sizeof err_buf, "%s%s: %s\n",
1908                                  am_server ? "on remote machine: " : "",
1909                                  poptBadOption(pc, POPT_BADOPTION_NOALIAS),
1910                                  poptStrerror(opt));
1911                         return 0;
1912                 }
1913         }
1914
1915         if (msgs2stderr != 2)
1916                 saw_stderr_opt = 1;
1917
1918         if (version_opt_cnt) {
1919                 print_rsync_version(FINFO);
1920                 exit_cleanup(0);
1921         }
1922
1923         if (!max_alloc_arg) {
1924                 max_alloc_arg = getenv("RSYNC_MAX_ALLOC");
1925                 if (max_alloc_arg && !*max_alloc_arg)
1926                         max_alloc_arg = NULL;
1927         }
1928         if (max_alloc_arg) {
1929                 ssize_t size = parse_size_arg(max_alloc_arg, 'B', "max-alloc", 1024*1024, -1, True);
1930                 if (size < 0)
1931                         return 0;
1932                 max_alloc = size;
1933         }
1934
1935         if (old_style_args < 0) {
1936                 if (!am_server && (arg = getenv("RSYNC_OLD_ARGS")) != NULL && *arg)
1937                         old_style_args = atoi(arg);
1938                 else
1939                         old_style_args = 0;
1940         }
1941
1942         if (protect_args < 0) {
1943                 if (am_server)
1944                         protect_args = 0;
1945                 else if ((arg = getenv("RSYNC_PROTECT_ARGS")) != NULL && *arg)
1946                         protect_args = atoi(arg) ? 1 : 0;
1947                 else {
1948 #ifdef RSYNC_USE_PROTECTED_ARGS
1949                         protect_args = 1;
1950 #else
1951                         protect_args = 0;
1952 #endif
1953                 }
1954         }
1955
1956         if (checksum_choice && strcasecmp(checksum_choice, "auto") != 0 && strcasecmp(checksum_choice, "auto,auto") != 0) {
1957                 /* Call this early to verify the args and figure out if we need to force
1958                  * --whole-file. Note that the parse function will get called again later,
1959                  * just in case an "auto" choice needs to know the protocol_version. */
1960                 parse_checksum_choice(0);
1961         } else
1962                 checksum_choice = NULL;
1963
1964         if (human_readable > 1 && argc == 2 && !am_server) {
1965                 /* Allow the old meaning of 'h' (--help) on its own. */
1966                 usage(FINFO);
1967                 exit_cleanup(0);
1968         }
1969
1970         if (!compress_choice && do_compression > 1)
1971                 compress_choice = "zlibx";
1972         if (compress_choice && strcasecmp(compress_choice, "auto") != 0)
1973                 parse_compress_choice(0); /* Twiddles do_compression and can possibly NULL-out compress_choice. */
1974         else
1975                 compress_choice = NULL;
1976
1977         if (do_compression || do_compression_level != CLVL_NOT_SPECIFIED) {
1978                 if (!do_compression)
1979                         do_compression = CPRES_AUTO;
1980                 if (do_compression && refused_compress) {
1981                         create_refuse_error(refused_compress);
1982                         return 0;
1983                 }
1984         }
1985
1986 #ifdef HAVE_SETVBUF
1987         if (outbuf_mode && !am_server) {
1988                 int mode = *(uchar *)outbuf_mode;
1989                 if (islower(mode))
1990                         mode = toupper(mode);
1991                 fflush(stdout); /* Just in case... */
1992                 switch (mode) {
1993                 case 'N': /* None */
1994                 case 'U': /* Unbuffered */
1995                         mode = _IONBF;
1996                         break;
1997                 case 'L': /* Line */
1998                         mode = _IOLBF;
1999                         break;
2000                 case 'B': /* Block */
2001                 case 'F': /* Full */
2002                         mode = _IOFBF;
2003                         break;
2004                 default:
2005                         snprintf(err_buf, sizeof err_buf,
2006                                 "Invalid --outbuf setting -- specify N, L, or B.\n");
2007                         return 0;
2008                 }
2009                 setvbuf(stdout, (char *)NULL, mode, 0);
2010         }
2011
2012         if (msgs2stderr == 1) { /* Are all messages going to stderr? */
2013                 /* Make stderr line buffered for better sharing of the stream. */
2014                 fflush(stderr); /* Just in case... */
2015                 setvbuf(stderr, (char *)NULL, _IOLBF, 0);
2016         }
2017 #endif
2018
2019         set_output_verbosity(verbose, DEFAULT_PRIORITY);
2020
2021         if (do_stats) {
2022                 parse_output_words(info_words, info_levels,
2023                         verbose > 1 ? "stats3" : "stats2", DEFAULT_PRIORITY);
2024         }
2025
2026 #ifdef ICONV_OPTION
2027         if (iconv_opt && protect_args != 2) {
2028                 if (!am_server && strcmp(iconv_opt, "-") == 0)
2029                         iconv_opt = NULL;
2030                 else
2031                         need_unsorted_flist = 1;
2032         }
2033         if (refused_no_iconv && !iconv_opt) {
2034                 create_refuse_error(refused_no_iconv);
2035                 return 0;
2036         }
2037 #endif
2038
2039         if (fuzzy_basis > 1)
2040                 fuzzy_basis = basis_dir_cnt + 1;
2041
2042         /* Don't let the client reset protect_args if it was already processed */
2043         if (orig_protect_args == 2 && am_server)
2044                 protect_args = orig_protect_args;
2045
2046         if (protect_args == 1 && am_server)
2047                 return 1;
2048
2049         *argv_p = argv = poptGetArgs(pc);
2050         *argc_p = argc = count_args(argv);
2051
2052 #ifndef SUPPORT_LINKS
2053         if (preserve_links && !am_sender) {
2054                 snprintf(err_buf, sizeof err_buf,
2055                          "symlinks are not supported on this %s\n",
2056                          am_server ? "server" : "client");
2057                 return 0;
2058         }
2059 #endif
2060
2061 #ifndef SUPPORT_HARD_LINKS
2062         if (preserve_hard_links) {
2063                 snprintf(err_buf, sizeof err_buf,
2064                          "hard links are not supported on this %s\n",
2065                          am_server ? "server" : "client");
2066                 return 0;
2067         }
2068 #endif
2069
2070 #ifdef SUPPORT_XATTRS
2071         if (am_root < 0 && preserve_xattrs > 1) {
2072                 snprintf(err_buf, sizeof err_buf,
2073                          "--fake-super conflicts with -XX\n");
2074                 return 0;
2075         }
2076 #else
2077         if (am_root < 0) {
2078                 snprintf(err_buf, sizeof err_buf,
2079                          "--fake-super requires an rsync with extended attributes enabled\n");
2080                 return 0;
2081         }
2082 #endif
2083
2084         if (write_batch && read_batch) {
2085                 snprintf(err_buf, sizeof err_buf,
2086                         "--write-batch and --read-batch can not be used together\n");
2087                 return 0;
2088         }
2089         if (write_batch > 0 || read_batch) {
2090                 if (am_server) {
2091                         rprintf(FINFO,
2092                                 "ignoring --%s-batch option sent to server\n",
2093                                 write_batch ? "write" : "read");
2094                         /* We don't actually exit_cleanup(), so that we can
2095                          * still service older version clients that still send
2096                          * batch args to server. */
2097                         read_batch = write_batch = 0;
2098                         batch_name = NULL;
2099                 } else if (dry_run)
2100                         write_batch = 0;
2101         } else if (write_batch < 0 && dry_run)
2102                 write_batch = 0;
2103         if (read_batch && files_from) {
2104                 snprintf(err_buf, sizeof err_buf,
2105                         "--read-batch cannot be used with --files-from\n");
2106                 return 0;
2107         }
2108         if (read_batch && remove_source_files) {
2109                 snprintf(err_buf, sizeof err_buf,
2110                         "--read-batch cannot be used with --remove-%s-files\n",
2111                         remove_source_files == 1 ? "source" : "sent");
2112                 return 0;
2113         }
2114         if (batch_name && strlen(batch_name) > MAX_BATCH_NAME_LEN) {
2115                 snprintf(err_buf, sizeof err_buf,
2116                         "the batch-file name must be %d characters or less.\n",
2117                         MAX_BATCH_NAME_LEN);
2118                 return 0;
2119         }
2120
2121         if (tmpdir && strlen(tmpdir) >= MAXPATHLEN - 10) {
2122                 snprintf(err_buf, sizeof err_buf,
2123                          "the --temp-dir path is WAY too long.\n");
2124                 return 0;
2125         }
2126
2127         if (max_delete < 0 && max_delete != INT_MIN) {
2128                 /* Negative numbers are treated as "no deletions". */
2129                 max_delete = 0;
2130         }
2131
2132         if (files_from) {
2133                 if (recurse == 1) /* preserve recurse == 2 */
2134                         recurse = 0;
2135                 if (xfer_dirs < 0)
2136                         xfer_dirs = 1;
2137         }
2138
2139         if (argc < 2 && !read_batch && !am_server)
2140                 list_only |= 1;
2141
2142         if (xfer_dirs >= 4) {
2143                 parse_filter_str(&filter_list, "- /*/*", rule_template(0), 0);
2144                 recurse = xfer_dirs = 1;
2145         } else if (recurse)
2146                 xfer_dirs = 1;
2147         else if (xfer_dirs < 0)
2148                 xfer_dirs = list_only ? 1 : 0;
2149
2150         if (relative_paths < 0)
2151                 relative_paths = files_from? 1 : 0;
2152         if (!relative_paths)
2153                 implied_dirs = 0;
2154
2155         if (delete_before + !!delete_during + delete_after > 1) {
2156                 snprintf(err_buf, sizeof err_buf,
2157                         "You may not combine multiple --delete-WHEN options.\n");
2158                 return 0;
2159         }
2160         if (delete_before || delete_during || delete_after)
2161                 delete_mode = 1;
2162         else if (delete_mode || delete_excluded) {
2163                 /* Only choose now between before & during if one is refused. */
2164                 if (refused_delete_before) {
2165                         if (!refused_delete_during)
2166                                 delete_during = 1;
2167                         else {
2168                                 create_refuse_error(refused_delete_before);
2169                                 return 0;
2170                         }
2171                 } else if (refused_delete_during)
2172                         delete_before = 1;
2173                 delete_mode = 1;
2174         }
2175         if (!xfer_dirs && delete_mode) {
2176                 snprintf(err_buf, sizeof err_buf,
2177                         "--delete does not work without --recursive (-r) or --dirs (-d).\n");
2178                 return 0;
2179         }
2180
2181         if (missing_args == 3) /* simplify if both options were specified */
2182                 missing_args = 2;
2183         if (refused_delete && (delete_mode || missing_args == 2)) {
2184                 create_refuse_error(refused_delete);
2185                 return 0;
2186         }
2187
2188         if (remove_source_files) {
2189                 /* We only want to infer this refusal of --remove-source-files
2190                  * via the refusal of "delete", not any of the "delete-FOO"
2191                  * options. */
2192                 if (refused_delete && am_sender) {
2193                         create_refuse_error(refused_delete);
2194                         return 0;
2195                 }
2196                 need_messages_from_generator = 1;
2197         }
2198
2199         if (munge_symlinks && !am_daemon) {
2200                 STRUCT_STAT st;
2201                 char prefix[SYMLINK_PREFIX_LEN]; /* NOT +1 ! */
2202                 strlcpy(prefix, SYMLINK_PREFIX, sizeof prefix); /* trim the trailing slash */
2203                 if (do_stat(prefix, &st) == 0 && S_ISDIR(st.st_mode)) {
2204                         rprintf(FERROR, "Symlink munging is unsafe when a %s directory exists.\n",
2205                                 prefix);
2206                         exit_cleanup(RERR_UNSUPPORTED);
2207                 }
2208         }
2209
2210         if (sanitize_paths) {
2211                 int i;
2212                 for (i = argc; i-- > 0; )
2213                         argv[i] = sanitize_path(NULL, argv[i], "", 0, SP_KEEP_DOT_DIRS);
2214                 if (tmpdir)
2215                         tmpdir = sanitize_path(NULL, tmpdir, NULL, 0, SP_DEFAULT);
2216                 if (backup_dir)
2217                         backup_dir = sanitize_path(NULL, backup_dir, NULL, 0, SP_DEFAULT);
2218         }
2219         if (daemon_filter_list.head && !am_sender) {
2220                 filter_rule_list *elp = &daemon_filter_list;
2221                 if (tmpdir) {
2222                         char *dir;
2223                         if (!*tmpdir)
2224                                 goto options_rejected;
2225                         dir = tmpdir + (*tmpdir == '/' ? module_dirlen : 0);
2226                         clean_fname(dir, CFN_COLLAPSE_DOT_DOT_DIRS);
2227                         if (check_filter(elp, FLOG, dir, 1) < 0)
2228                                 goto options_rejected;
2229                 }
2230                 if (backup_dir) {
2231                         char *dir;
2232                         if (!*backup_dir)
2233                                 goto options_rejected;
2234                         dir = backup_dir + (*backup_dir == '/' ? module_dirlen : 0);
2235                         clean_fname(dir, CFN_COLLAPSE_DOT_DOT_DIRS);
2236                         if (check_filter(elp, FLOG, dir, 1) < 0)
2237                                 goto options_rejected;
2238                 }
2239         }
2240
2241         if (!backup_suffix)
2242                 backup_suffix = backup_dir ? "" : BACKUP_SUFFIX;
2243         backup_suffix_len = strlen(backup_suffix);
2244         if (strchr(backup_suffix, '/') != NULL) {
2245                 snprintf(err_buf, sizeof err_buf,
2246                         "--suffix cannot contain slashes: %s\n",
2247                         backup_suffix);
2248                 return 0;
2249         }
2250         if (backup_dir) {
2251                 size_t len;
2252                 make_backups = 1; /* --backup-dir implies --backup */
2253                 while (*backup_dir == '.' && backup_dir[1] == '/')
2254                         backup_dir += 2;
2255                 if (*backup_dir == '.' && backup_dir[1] == '\0')
2256                         backup_dir++;
2257                 len = strlcpy(backup_dir_buf, backup_dir, sizeof backup_dir_buf);
2258                 if (len > sizeof backup_dir_buf - 128) {
2259                         snprintf(err_buf, sizeof err_buf,
2260                                 "the --backup-dir path is WAY too long.\n");
2261                         return 0;
2262                 }
2263                 backup_dir_len = (int)len;
2264                 if (!backup_dir_len) {
2265                         backup_dir_len = -1;
2266                         backup_dir = NULL;
2267                 } else if (backup_dir_buf[backup_dir_len - 1] != '/') {
2268                         backup_dir_buf[backup_dir_len++] = '/';
2269                         backup_dir_buf[backup_dir_len] = '\0';
2270                 }
2271                 backup_dir_remainder = sizeof backup_dir_buf - backup_dir_len;
2272         }
2273         if (backup_dir) {
2274                 /* No need for a suffix or a protect rule. */
2275         } else if (!backup_suffix_len && (!am_server || !am_sender)) {
2276                 snprintf(err_buf, sizeof err_buf,
2277                         "--suffix cannot be empty %s\n", backup_dir_len < 0
2278                         ? "when --backup-dir is the same as the dest dir"
2279                         : "without a --backup-dir");
2280                 return 0;
2281         } else if (make_backups && delete_mode && !delete_excluded && !am_server) {
2282                 snprintf(backup_dir_buf, sizeof backup_dir_buf,
2283                         "P *%s", backup_suffix);
2284                 parse_filter_str(&filter_list, backup_dir_buf, rule_template(0), 0);
2285         }
2286
2287         if (make_backups && !backup_dir)
2288                 omit_dir_times = -1; /* Implied, so avoid -O to sender. */
2289
2290         if (stdout_format) {
2291                 if (am_server && log_format_has(stdout_format, 'I'))
2292                         stdout_format_has_i = 2;
2293                 else if (log_format_has(stdout_format, 'i'))
2294                         stdout_format_has_i = itemize_changes | 1;
2295                 if (!log_format_has(stdout_format, 'b')
2296                  && !log_format_has(stdout_format, 'c')
2297                  && !log_format_has(stdout_format, 'C'))
2298                         log_before_transfer = !am_server;
2299         } else if (itemize_changes) {
2300                 stdout_format = "%i %n%L";
2301                 stdout_format_has_i = itemize_changes;
2302                 log_before_transfer = !am_server;
2303         }
2304
2305         if (do_progress && !am_server) {
2306                 if (!log_before_transfer && INFO_EQ(NAME, 0))
2307                         parse_output_words(info_words, info_levels, "name", DEFAULT_PRIORITY);
2308                 parse_output_words(info_words, info_levels, "flist2,progress", DEFAULT_PRIORITY);
2309         }
2310
2311         if (dry_run)
2312                 do_xfers = 0;
2313
2314         set_io_timeout(io_timeout);
2315
2316         if (INFO_GTE(NAME, 1) && !stdout_format) {
2317                 stdout_format = "%n%L";
2318                 log_before_transfer = !am_server;
2319         }
2320         if (stdout_format_has_i || log_format_has(stdout_format, 'o'))
2321                 stdout_format_has_o_or_i = 1;
2322
2323         if (logfile_name && !am_daemon) {
2324                 if (!logfile_format) {
2325                         logfile_format = "%i %n%L";
2326                         logfile_format_has_i = logfile_format_has_o_or_i = 1;
2327                 } else {
2328                         if (log_format_has(logfile_format, 'i'))
2329                                 logfile_format_has_i = 1;
2330                         if (logfile_format_has_i || log_format_has(logfile_format, 'o'))
2331                                 logfile_format_has_o_or_i = 1;
2332                 }
2333                 log_init(0);
2334         } else if (!am_daemon)
2335                 logfile_format = NULL;
2336
2337         if (daemon_bwlimit && (!bwlimit || bwlimit > daemon_bwlimit))
2338                 bwlimit = daemon_bwlimit;
2339         if (bwlimit) {
2340                 bwlimit_writemax = (size_t)bwlimit * 128;
2341                 if (bwlimit_writemax < 512)
2342                         bwlimit_writemax = 512;
2343         }
2344
2345         if (append_mode) {
2346                 if (whole_file > 0) {
2347                         snprintf(err_buf, sizeof err_buf,
2348                                  "--append cannot be used with --whole-file\n");
2349                         return 0;
2350                 }
2351                 if (refused_inplace) {
2352                         create_refuse_error(refused_inplace);
2353                         return 0;
2354                 }
2355                 inplace = 1;
2356         }
2357
2358         if (write_devices) {
2359                 if (refused_inplace) {
2360                         create_refuse_error(refused_inplace);
2361                         return 0;
2362                 }
2363                 inplace = 1;
2364         }
2365
2366         if (delay_updates && !partial_dir)
2367                 partial_dir = tmp_partialdir;
2368
2369         if (inplace) {
2370 #ifdef HAVE_FTRUNCATE
2371                 if (partial_dir) {
2372                         snprintf(err_buf, sizeof err_buf,
2373                                  "--%s cannot be used with --%s\n",
2374                                  append_mode ? "append" : "inplace",
2375                                  delay_updates ? "delay-updates" : "partial-dir");
2376                         return 0;
2377                 }
2378                 /* --inplace implies --partial for refusal purposes, but we
2379                  * clear the keep_partial flag for internal logic purposes. */
2380                 if (refused_partial) {
2381                         create_refuse_error(refused_partial);
2382                         return 0;
2383                 }
2384                 keep_partial = 0;
2385 #else
2386                 snprintf(err_buf, sizeof err_buf,
2387                          "--%s is not supported on this %s\n",
2388                          append_mode ? "append" : "inplace",
2389                          am_server ? "server" : "client");
2390                 return 0;
2391 #endif
2392         } else {
2393                 if (keep_partial && !partial_dir && !am_server) {
2394                         if ((arg = getenv("RSYNC_PARTIAL_DIR")) != NULL && *arg)
2395                                 partial_dir = strdup(arg);
2396                 }
2397                 if (partial_dir) {
2398                         if (*partial_dir)
2399                                 clean_fname(partial_dir, CFN_COLLAPSE_DOT_DOT_DIRS);
2400                         if (!*partial_dir || strcmp(partial_dir, ".") == 0)
2401                                 partial_dir = NULL;
2402                         if (!partial_dir && refused_partial) {
2403                                 create_refuse_error(refused_partial);
2404                                 return 0;
2405                         }
2406                         keep_partial = 1;
2407                 }
2408         }
2409
2410         if (files_from) {
2411                 char *h, *p;
2412                 int q;
2413                 if (argc > 2 || (!am_daemon && !am_server && argc == 1)) {
2414                         usage(FERROR);
2415                         exit_cleanup(RERR_SYNTAX);
2416                 }
2417                 if (strcmp(files_from, "-") == 0) {
2418                         filesfrom_fd = 0;
2419                         if (am_server)
2420                                 filesfrom_host = ""; /* reading from socket */
2421                 } else if ((p = check_for_hostspec(files_from, &h, &q)) != 0) {
2422                         if (am_server) {
2423                                 snprintf(err_buf, sizeof err_buf,
2424                                         "The --files-from sent to the server cannot specify a host.\n");
2425                                 return 0;
2426                         }
2427                         files_from = p;
2428                         filesfrom_host = h;
2429                         if (strcmp(files_from, "-") == 0) {
2430                                 snprintf(err_buf, sizeof err_buf,
2431                                         "Invalid --files-from remote filename\n");
2432                                 return 0;
2433                         }
2434                 } else {
2435                         if (sanitize_paths)
2436                                 files_from = sanitize_path(NULL, files_from, NULL, 0, SP_DEFAULT);
2437                         if (daemon_filter_list.head) {
2438                                 char *dir;
2439                                 if (!*files_from)
2440                                         goto options_rejected;
2441                                 dir = files_from + (*files_from == '/' ? module_dirlen : 0);
2442                                 clean_fname(dir, CFN_COLLAPSE_DOT_DOT_DIRS);
2443                                 if (check_filter(&daemon_filter_list, FLOG, dir, 0) < 0)
2444                                         goto options_rejected;
2445                         }
2446                         filesfrom_fd = open(files_from, O_RDONLY|O_BINARY);
2447                         if (filesfrom_fd < 0) {
2448                                 snprintf(err_buf, sizeof err_buf,
2449                                         "failed to open files-from file %s: %s\n",
2450                                         files_from, strerror(errno));
2451                                 return 0;
2452                         }
2453                 }
2454         }
2455
2456         am_starting_up = 0;
2457
2458         return 1;
2459
2460   options_rejected:
2461         snprintf(err_buf, sizeof err_buf,
2462                 "Your options have been rejected by the server.\n");
2463         return 0;
2464 }
2465
2466
2467 static char SPLIT_ARG_WHEN_OLD[1];
2468
2469 /**
2470  * Do backslash quoting of any weird chars in "arg", append the resulting
2471  * string to the end of the "opt" (which gets a "=" appended if it is not
2472  * an empty or NULL string), and return the (perhaps malloced) result.
2473  * If opt is NULL, arg is considered a filename arg that allows wildcards.
2474  * If it is "" or any other value, it is considered an option.
2475  **/
2476 char *safe_arg(const char *opt, const char *arg)
2477 {
2478 #define SHELL_CHARS "!#$&;|<>(){}\"' \t\\"
2479 #define WILD_CHARS  "*?[]" /* We don't allow remote brace expansion */
2480         BOOL is_filename_arg = !opt;
2481         char *escapes = is_filename_arg ? SHELL_CHARS : WILD_CHARS SHELL_CHARS;
2482         BOOL escape_leading_dash = is_filename_arg && *arg == '-';
2483         int len1 = opt && *opt ? strlen(opt) + 1 : 0;
2484         int len2 = strlen(arg);
2485         int extras = escape_leading_dash ? 2 : 0;
2486         char *ret;
2487         if (!protect_args && old_style_args < 2 && (!old_style_args || (!is_filename_arg && opt != SPLIT_ARG_WHEN_OLD))) {
2488                 const char *f;
2489                 for (f = arg; *f; f++) {
2490                         if (strchr(escapes, *f))
2491                                 extras++;
2492                 }
2493         }
2494         if (!len1 && !extras)
2495                 return (char*)arg;
2496         ret = new_array(char, len1 + len2 + extras + 1);
2497         if (len1) {
2498                 memcpy(ret, opt, len1-1);
2499                 ret[len1-1] = '=';
2500         }
2501         if (escape_leading_dash) {
2502                 ret[len1++] = '.';
2503                 ret[len1++] = '/';
2504                 extras -= 2;
2505         }
2506         if (!extras)
2507                 memcpy(ret + len1, arg, len2);
2508         else {
2509                 const char *f = arg;
2510                 char *t = ret + len1;
2511                 while (*f) {
2512                         if (strchr(escapes, *f))
2513                                 *t++ = '\\';
2514                         *t++ = *f++;
2515                 }
2516         }
2517         ret[len1+len2+extras] = '\0';
2518         return ret;
2519 }
2520
2521
2522 /**
2523  * Construct a filtered list of options to pass through from the
2524  * client to the server.
2525  *
2526  * This involves setting options that will tell the server how to
2527  * behave, and also filtering out options that are processed only
2528  * locally.
2529  **/
2530 void server_options(char **args, int *argc_p)
2531 {
2532         static char argstr[64];
2533         int ac = *argc_p;
2534         uchar where;
2535         char *arg;
2536         int i, x;
2537
2538         /* This should always remain first on the server's command-line. */
2539         args[ac++] = "--server";
2540
2541         if (!am_sender)
2542                 args[ac++] = "--sender";
2543
2544         x = 1;
2545         argstr[0] = '-';
2546
2547         if (protect_args)
2548                 argstr[x++] = 's';
2549
2550         for (i = 0; i < verbose; i++)
2551                 argstr[x++] = 'v';
2552
2553         if (quiet && msgs2stderr)
2554                 argstr[x++] = 'q';
2555         if (make_backups)
2556                 argstr[x++] = 'b';
2557         if (update_only)
2558                 argstr[x++] = 'u';
2559         if (!do_xfers) /* Note: NOT "dry_run"! */
2560                 argstr[x++] = 'n';
2561         if (preserve_links)
2562                 argstr[x++] = 'l';
2563         if ((xfer_dirs >= 2 && xfer_dirs < 4)
2564          || (xfer_dirs && !recurse && (list_only || (delete_mode && am_sender))))
2565                 argstr[x++] = 'd';
2566         if (am_sender) {
2567                 if (keep_dirlinks)
2568                         argstr[x++] = 'K';
2569                 if (prune_empty_dirs)
2570                         argstr[x++] = 'm';
2571                 if (omit_dir_times > 0)
2572                         argstr[x++] = 'O';
2573                 if (omit_link_times)
2574                         argstr[x++] = 'J';
2575                 if (fuzzy_basis) {
2576                         argstr[x++] = 'y';
2577                         if (fuzzy_basis > 1)
2578                                 argstr[x++] = 'y';
2579                 }
2580         } else {
2581                 if (copy_links)
2582                         argstr[x++] = 'L';
2583                 if (copy_dirlinks)
2584                         argstr[x++] = 'k';
2585         }
2586
2587         if (whole_file > 0)
2588                 argstr[x++] = 'W';
2589         /* We don't need to send --no-whole-file, because it's the
2590          * default for remote transfers, and in any case old versions
2591          * of rsync will not understand it. */
2592
2593         if (preserve_hard_links) {
2594                 argstr[x++] = 'H';
2595                 if (preserve_hard_links > 1)
2596                         argstr[x++] = 'H';
2597         }
2598         if (preserve_uid)
2599                 argstr[x++] = 'o';
2600         if (preserve_gid)
2601                 argstr[x++] = 'g';
2602         if (preserve_devices) /* ignore preserve_specials here */
2603                 argstr[x++] = 'D';
2604         if (preserve_mtimes)
2605                 argstr[x++] = 't';
2606         if (preserve_atimes) {
2607                 argstr[x++] = 'U';
2608                 if (preserve_atimes > 1)
2609                         argstr[x++] = 'U';
2610         }
2611 #ifdef SUPPORT_CRTIMES
2612         if (preserve_crtimes)
2613                 argstr[x++] = 'N';
2614 #endif
2615         if (preserve_perms)
2616                 argstr[x++] = 'p';
2617         else if (preserve_executability && am_sender)
2618                 argstr[x++] = 'E';
2619 #ifdef SUPPORT_ACLS
2620         if (preserve_acls)
2621                 argstr[x++] = 'A';
2622 #endif
2623 #ifdef SUPPORT_XATTRS
2624         if (preserve_xattrs) {
2625                 argstr[x++] = 'X';
2626                 if (preserve_xattrs > 1)
2627                         argstr[x++] = 'X';
2628         }
2629 #endif
2630         if (recurse)
2631                 argstr[x++] = 'r';
2632         if (always_checksum)
2633                 argstr[x++] = 'c';
2634         if (cvs_exclude)
2635                 argstr[x++] = 'C';
2636         if (ignore_times)
2637                 argstr[x++] = 'I';
2638         if (relative_paths)
2639                 argstr[x++] = 'R';
2640         if (one_file_system) {
2641                 argstr[x++] = 'x';
2642                 if (one_file_system > 1)
2643                         argstr[x++] = 'x';
2644         }
2645         if (sparse_files)
2646                 argstr[x++] = 'S';
2647         if (do_compression == CPRES_ZLIB)
2648                 argstr[x++] = 'z';
2649
2650         set_allow_inc_recurse();
2651
2652         /* This '\0'-terminates argstr and makes sure it didn't overflow. */
2653         x += maybe_add_e_option(argstr + x, (int)sizeof argstr - x);
2654
2655         if (x > 1)
2656                 args[ac++] = argstr;
2657
2658 #ifdef ICONV_OPTION
2659         if (iconv_opt) {
2660                 char *set = strchr(iconv_opt, ',');
2661                 if (set)
2662                         set++;
2663                 else
2664                         set = iconv_opt;
2665                 args[ac++] = safe_arg("--iconv", set);
2666         }
2667 #endif
2668
2669         if (protect_args && !local_server) /* unprotected args stop here */
2670                 args[ac++] = NULL;
2671
2672         if (list_only > 1)
2673                 args[ac++] = "--list-only";
2674
2675         /* This makes sure that the remote rsync can handle deleting with -d
2676          * sans -r because the --no-r option was added at the same time. */
2677         if (xfer_dirs && !recurse && delete_mode && am_sender)
2678                 args[ac++] = "--no-r";
2679
2680         if (do_compression && do_compression_level != CLVL_NOT_SPECIFIED) {
2681                 if (asprintf(&arg, "--compress-level=%d", do_compression_level) < 0)
2682                         goto oom;
2683                 args[ac++] = arg;
2684         }
2685
2686         if (preserve_devices) {
2687                 /* Note: sending "--devices" would not be backward-compatible. */
2688                 if (!preserve_specials)
2689                         args[ac++] = "--no-specials"; /* -D is already set. */
2690         } else if (preserve_specials)
2691                 args[ac++] = "--specials";
2692
2693         /* The server side doesn't use our log-format, but in certain
2694          * circumstances they need to know a little about the option. */
2695         if (stdout_format && am_sender) {
2696                 /* Use --log-format, not --out-format, for compatibility. */
2697                 if (stdout_format_has_i > 1)
2698                         args[ac++] = "--log-format=%i%I";
2699                 else if (stdout_format_has_i)
2700                         args[ac++] = "--log-format=%i";
2701                 else if (stdout_format_has_o_or_i)
2702                         args[ac++] = "--log-format=%o";
2703                 else if (!verbose)
2704                         args[ac++] = "--log-format=X";
2705         }
2706
2707         if (msgs2stderr == 1)
2708                 args[ac++] = "--msgs2stderr";
2709         else if (msgs2stderr == 0)
2710                 args[ac++] = "--no-msgs2stderr";
2711
2712         if (block_size) {
2713                 if (asprintf(&arg, "-B%u", (int)block_size) < 0)
2714                         goto oom;
2715                 args[ac++] = arg;
2716         }
2717
2718         if (io_timeout) {
2719                 if (asprintf(&arg, "--timeout=%d", io_timeout) < 0)
2720                         goto oom;
2721                 args[ac++] = arg;
2722         }
2723
2724         if (bwlimit) {
2725                 if (asprintf(&arg, "--bwlimit=%d", bwlimit) < 0)
2726                         goto oom;
2727                 args[ac++] = arg;
2728         }
2729
2730         if (backup_dir) {
2731                 /* This split idiom allows for ~/path expansion via the shell. */
2732                 args[ac++] = "--backup-dir";
2733                 args[ac++] = safe_arg("", backup_dir);
2734         }
2735
2736         /* Only send --suffix if it specifies a non-default value. */
2737         if (strcmp(backup_suffix, backup_dir ? "" : BACKUP_SUFFIX) != 0)
2738                 args[ac++] = safe_arg("--suffix", backup_suffix);
2739
2740         if (checksum_choice)
2741                 args[ac++] = safe_arg("--checksum-choice", checksum_choice);
2742
2743         if (do_compression == CPRES_ZLIBX)
2744                 args[ac++] = "--new-compress";
2745         else if (compress_choice && do_compression == CPRES_ZLIB)
2746                 args[ac++] = "--old-compress";
2747         else if (compress_choice)
2748                 args[ac++] = safe_arg("--compress-choice", compress_choice);
2749
2750         if (am_sender) {
2751                 if (max_delete > 0) {
2752                         if (asprintf(&arg, "--max-delete=%d", max_delete) < 0)
2753                                 goto oom;
2754                         args[ac++] = arg;
2755                 } else if (max_delete == 0)
2756                         args[ac++] = "--max-delete=-1";
2757                 if (min_size >= 0)
2758                         args[ac++] = safe_arg("--min-size", min_size_arg);
2759                 if (max_size >= 0)
2760                         args[ac++] = safe_arg("--max-size", max_size_arg);
2761                 if (delete_before)
2762                         args[ac++] = "--delete-before";
2763                 else if (delete_during == 2)
2764                         args[ac++] = "--delete-delay";
2765                 else if (delete_during)
2766                         args[ac++] = "--delete-during";
2767                 else if (delete_after)
2768                         args[ac++] = "--delete-after";
2769                 else if (delete_mode && !delete_excluded)
2770                         args[ac++] = "--delete";
2771                 if (delete_excluded)
2772                         args[ac++] = "--delete-excluded";
2773                 if (force_delete)
2774                         args[ac++] = "--force";
2775                 if (write_batch < 0)
2776                         args[ac++] = "--only-write-batch=X";
2777                 if (am_root > 1)
2778                         args[ac++] = "--super";
2779                 if (size_only)
2780                         args[ac++] = "--size-only";
2781                 if (do_stats)
2782                         args[ac++] = "--stats";
2783         } else {
2784                 if (skip_compress)
2785                         args[ac++] = safe_arg("--skip-compress", skip_compress);
2786         }
2787
2788         if (max_alloc_arg && max_alloc != DEFAULT_MAX_ALLOC)
2789                 args[ac++] = safe_arg("--max-alloc", max_alloc_arg);
2790
2791         /* --delete-missing-args needs the cooperation of both sides, but
2792          * the sender can handle --ignore-missing-args by itself. */
2793         if (missing_args == 2)
2794                 args[ac++] = "--delete-missing-args";
2795         else if (missing_args == 1 && !am_sender)
2796                 args[ac++] = "--ignore-missing-args";
2797
2798         if (modify_window_set && am_sender) {
2799                 char *fmt = modify_window < 0 ? "-@%d" : "--modify-window=%d";
2800                 if (asprintf(&arg, fmt, modify_window) < 0)
2801                         goto oom;
2802                 args[ac++] = arg;
2803         }
2804
2805         if (checksum_seed) {
2806                 if (asprintf(&arg, "--checksum-seed=%d", checksum_seed) < 0)
2807                         goto oom;
2808                 args[ac++] = arg;
2809         }
2810
2811         if (partial_dir && am_sender) {
2812                 if (partial_dir != tmp_partialdir) {
2813                         args[ac++] = "--partial-dir";
2814                         args[ac++] = safe_arg("", partial_dir);
2815                 }
2816                 if (delay_updates)
2817                         args[ac++] = "--delay-updates";
2818         } else if (keep_partial && am_sender)
2819                 args[ac++] = "--partial";
2820
2821         if (ignore_errors)
2822                 args[ac++] = "--ignore-errors";
2823
2824         if (copy_unsafe_links)
2825                 args[ac++] = "--copy-unsafe-links";
2826
2827         if (safe_symlinks)
2828                 args[ac++] = "--safe-links";
2829
2830         if (numeric_ids)
2831                 args[ac++] = "--numeric-ids";
2832
2833         if (use_qsort)
2834                 args[ac++] = "--use-qsort";
2835
2836         if (am_sender) {
2837                 if (usermap)
2838                         args[ac++] = safe_arg("--usermap", usermap);
2839
2840                 if (groupmap)
2841                         args[ac++] = safe_arg("--groupmap", groupmap);
2842
2843                 if (ignore_existing)
2844                         args[ac++] = "--ignore-existing";
2845
2846                 /* Backward compatibility: send --existing, not --ignore-non-existing. */
2847                 if (ignore_non_existing)
2848                         args[ac++] = "--existing";
2849
2850                 if (tmpdir) {
2851                         args[ac++] = "--temp-dir";
2852                         args[ac++] = safe_arg("", tmpdir);
2853                 }
2854
2855                 if (do_fsync)
2856                         args[ac++] = "--fsync";
2857
2858                 if (basis_dir[0]) {
2859                         /* the server only needs this option if it is not the sender,
2860                          *   and it may be an older version that doesn't know this
2861                          *   option, so don't send it if client is the sender.
2862                          */
2863                         for (i = 0; i < basis_dir_cnt; i++) {
2864                                 args[ac++] = alt_dest_opt(0);
2865                                 args[ac++] = safe_arg("", basis_dir[i]);
2866                         }
2867                 }
2868         }
2869
2870         /* What flags do we need to send to the other side? */
2871         where = (am_server ? W_CLI : W_SRV) | (am_sender ? W_REC : W_SND);
2872         arg = make_output_option(info_words, info_levels, where);
2873         if (arg)
2874                 args[ac++] = arg;
2875
2876         if (append_mode) {
2877                 if (append_mode > 1)
2878                         args[ac++] = "--append";
2879                 args[ac++] = "--append";
2880         } else if (inplace) {
2881                 args[ac++] = "--inplace";
2882                 /* Work around a bug in older rsync versions (on the remote side) for --inplace --sparse */
2883                 if (sparse_files && !whole_file && am_sender)
2884                         args[ac++] = "--no-W";
2885         }
2886
2887         if (files_from && (!am_sender || filesfrom_host)) {
2888                 if (filesfrom_host) {
2889                         args[ac++] = "--files-from";
2890                         args[ac++] = safe_arg("", files_from);
2891                         if (eol_nulls)
2892                                 args[ac++] = "--from0";
2893                 } else {
2894                         args[ac++] = "--files-from=-";
2895                         args[ac++] = "--from0";
2896                 }
2897                 if (!relative_paths)
2898                         args[ac++] = "--no-relative";
2899         }
2900         /* It's OK that this checks the upper-bound of the protocol_version. */
2901         if (relative_paths && !implied_dirs && (!am_sender || protocol_version >= 30))
2902                 args[ac++] = "--no-implied-dirs";
2903
2904         if (write_devices && am_sender)
2905                 args[ac++] = "--write-devices";
2906
2907         if (remove_source_files == 1)
2908                 args[ac++] = "--remove-source-files";
2909         else if (remove_source_files)
2910                 args[ac++] = "--remove-sent-files";
2911
2912         if (preallocate_files && am_sender)
2913                 args[ac++] = "--preallocate";
2914
2915         if (open_noatime && preserve_atimes <= 1)
2916                 args[ac++] = "--open-noatime";
2917
2918         if (mkpath_dest_arg && am_sender)
2919                 args[ac++] = "--mkpath";
2920
2921         if (ac > MAX_SERVER_ARGS) { /* Not possible... */
2922                 rprintf(FERROR, "argc overflow in server_options().\n");
2923                 exit_cleanup(RERR_MALLOC);
2924         }
2925
2926         if (remote_option_cnt) {
2927                 int j;
2928                 if (ac + remote_option_cnt > MAX_SERVER_ARGS) {
2929                         rprintf(FERROR, "too many remote options specified.\n");
2930                         exit_cleanup(RERR_SYNTAX);
2931                 }
2932                 for (j = 1; j <= remote_option_cnt; j++)
2933                         args[ac++] = safe_arg(SPLIT_ARG_WHEN_OLD, remote_options[j]);
2934         }
2935
2936         *argc_p = ac;
2937         return;
2938
2939     oom:
2940         out_of_memory("server_options");
2941 }
2942
2943 int maybe_add_e_option(char *buf, int buf_len)
2944 {
2945         int x = 0;
2946
2947         /* We don't really know the actual protocol_version at this point,
2948          * but checking the pre-negotiated value allows the user to use a
2949          * --protocol=29 override to avoid the use of this -eFLAGS opt. */
2950         if (protocol_version >= 30 && buf_len > 0) {
2951                 /* We make use of the -e option to let the server know about
2952                  * any pre-release protocol version && some behavior flags. */
2953                 buf[x++] = 'e';
2954
2955 #if SUBPROTOCOL_VERSION != 0
2956                 if (protocol_version == PROTOCOL_VERSION)
2957                         x += snprintf(buf + x, buf_len - x, "%d.%d", PROTOCOL_VERSION, SUBPROTOCOL_VERSION);
2958                 else
2959 #endif
2960                         buf[x++] = '.';
2961                 if (allow_inc_recurse)
2962                         buf[x++] = 'i';
2963 #ifdef CAN_SET_SYMLINK_TIMES
2964                 buf[x++] = 'L'; /* symlink time-setting support */
2965 #endif
2966 #ifdef ICONV_OPTION
2967                 buf[x++] = 's'; /* symlink iconv translation support */
2968 #endif
2969                 buf[x++] = 'f'; /* flist I/O-error safety support */
2970                 buf[x++] = 'x'; /* xattr hardlink optimization not desired */
2971                 buf[x++] = 'C'; /* support checksum seed order fix */
2972                 buf[x++] = 'I'; /* support inplace_partial behavior */
2973                 buf[x++] = 'v'; /* use varint for flist & compat flags; negotiate checksum */
2974                 buf[x++] = 'u'; /* include name of uid 0 & gid 0 in the id map */
2975
2976                 /* NOTE: Avoid using 'V' -- it was represented with the high bit of a write_byte() that became a write_varint(). */
2977         }
2978
2979         if (x >= buf_len) { /* Not possible... */
2980                 rprintf(FERROR, "overflow in add_e_flags().\n");
2981                 exit_cleanup(RERR_MALLOC);
2982         }
2983
2984         buf[x] = '\0';
2985
2986         return x;
2987 }
2988
2989 /* If str points to a valid hostspec, return allocated memory containing the
2990  * [USER@]HOST part of the string, and set the path_start_ptr to the part of
2991  * the string after the host part.  Otherwise, return NULL.  If port_ptr is
2992  * non-NULL, we must be parsing an rsync:// URL hostname, and we will set
2993  * *port_ptr if a port number is found.  Note that IPv6 IPs will have their
2994  * (required for parsing) [ and ] chars elided from the returned string. */
2995 static char *parse_hostspec(char *str, char **path_start_ptr, int *port_ptr)
2996 {
2997         char *s, *host_start = str;
2998         int hostlen = 0, userlen = 0;
2999         char *ret;
3000
3001         for (s = str; ; s++) {
3002                 if (!*s) {
3003                         /* It is only OK if we run out of string with rsync:// */
3004                         if (!port_ptr)
3005                                 return NULL;
3006                         if (!hostlen)
3007                                 hostlen = s - host_start;
3008                         break;
3009                 }
3010                 if (*s == ':' || *s == '/') {
3011                         if (!hostlen)
3012                                 hostlen = s - host_start;
3013                         if (*s++ == '/') {
3014                                 if (!port_ptr)
3015                                         return NULL;
3016                         } else if (port_ptr) {
3017                                 *port_ptr = atoi(s);
3018                                 while (isDigit(s)) s++;
3019                                 if (*s && *s++ != '/')
3020                                         return NULL;
3021                         }
3022                         break;
3023                 }
3024                 if (*s == '@') {
3025                         userlen = s - str + 1;
3026                         host_start = s + 1;
3027                 } else if (*s == '[') {
3028                         if (s != host_start++)
3029                                 return NULL;
3030                         while (*s && *s != ']' && *s != '/') s++; /*SHARED ITERATOR*/
3031                         hostlen = s - host_start;
3032                         if (*s != ']' || (s[1] && s[1] != '/' && s[1] != ':') || !hostlen)
3033                                 return NULL;
3034                 }
3035         }
3036
3037         *path_start_ptr = s;
3038         ret = new_array(char, userlen + hostlen + 1);
3039         if (userlen)
3040                 strlcpy(ret, str, userlen + 1);
3041         strlcpy(ret + userlen, host_start, hostlen + 1);
3042         return ret;
3043 }
3044
3045 /* Look for a HOST specification of the form "HOST:PATH", "HOST::PATH", or
3046  * "rsync://HOST:PORT/PATH".  If found, *host_ptr will be set to some allocated
3047  * memory with the HOST.  If a daemon-accessing spec was specified, the value
3048  * of *port_ptr will contain a non-0 port number, otherwise it will be set to
3049  * 0.  The return value is a pointer to the PATH.  Note that the HOST spec can
3050  * be an IPv6 literal address enclosed in '[' and ']' (such as "[::1]" or
3051  * "[::ffff:127.0.0.1]") which is returned without the '[' and ']'. */
3052 char *check_for_hostspec(char *s, char **host_ptr, int *port_ptr)
3053 {
3054         char *path;
3055
3056         if (port_ptr && strncasecmp(URL_PREFIX, s, strlen(URL_PREFIX)) == 0) {
3057                 *host_ptr = parse_hostspec(s + strlen(URL_PREFIX), &path, port_ptr);
3058                 if (*host_ptr) {
3059                         if (!*port_ptr)
3060                                 *port_ptr = -1; /* -1 indicates they want the default */
3061                         return path;
3062                 }
3063         }
3064
3065         *host_ptr = parse_hostspec(s, &path, NULL);
3066         if (!*host_ptr)
3067                 return NULL;
3068
3069         if (*path == ':') {
3070                 if (port_ptr && !*port_ptr)
3071                         *port_ptr = -1;
3072                 return path + 1;
3073         }
3074         if (port_ptr)
3075                 *port_ptr = 0;
3076
3077         return path;
3078 }