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