Add safety check for local --remove-source-files.
[rsync.git] / rsync.h
1 /*
2  * Copyright (C) 1996, 2000 Andrew Tridgell
3  * Copyright (C) 1996 Paul Mackerras
4  * Copyright (C) 2001, 2002 Martin Pool <mbp@samba.org>
5  * Copyright (C) 2003-2022 Wayne Davison
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along
18  * with this program; if not, visit the http://fsf.org website.
19  */
20
21 #define False 0
22 #define True 1
23 #define Unset (-1) /* Our BOOL values are always an int. */
24
25 #define BLOCK_SIZE 700
26 #define RSYNC_RSH_ENV "RSYNC_RSH"
27 #define RSYNC_RSH_IO_ENV "RSYNC_RSH_IO"
28
29 #define RSYNC_NAME "rsync"
30 /* RSYNCD_SYSCONF is now set in config.h */
31 #define RSYNCD_USERCONF "rsyncd.conf"
32
33 #define DEFAULT_LOCK_FILE "/var/run/rsyncd.lock"
34 #define URL_PREFIX "rsync://"
35
36 #define SYMLINK_PREFIX "/rsyncd-munged/"  /* This MUST have a trailing slash! */
37 #define SYMLINK_PREFIX_LEN ((int)sizeof SYMLINK_PREFIX - 1)
38
39 #define BACKUP_SUFFIX "~"
40
41 /* a non-zero CHAR_OFFSET makes the rolling sum stronger, but is
42    incompatible with older versions :-( */
43 #define CHAR_OFFSET 0
44
45 /* These flags are only used during the flist transfer. */
46
47 #define XMIT_TOP_DIR (1<<0)
48 #define XMIT_SAME_MODE (1<<1)
49 #define XMIT_SAME_RDEV_pre28 (1<<2)     /* protocols 20 - 27  */
50 #define XMIT_EXTENDED_FLAGS (1<<2)      /* protocols 28 - now */
51 #define XMIT_SAME_UID (1<<3)
52 #define XMIT_SAME_GID (1<<4)
53 #define XMIT_SAME_NAME (1<<5)
54 #define XMIT_LONG_NAME (1<<6)
55 #define XMIT_SAME_TIME (1<<7)
56
57 #define XMIT_SAME_RDEV_MAJOR (1<<8)     /* protocols 28 - now (devices only) */
58 #define XMIT_NO_CONTENT_DIR (1<<8)      /* protocols 30 - now (dirs only) */
59 #define XMIT_HLINKED (1<<9)             /* protocols 28 - now (non-dirs) */
60 #define XMIT_SAME_DEV_pre30 (1<<10)     /* protocols 28 - 29  */
61 #define XMIT_USER_NAME_FOLLOWS (1<<10)  /* protocols 30 - now */
62 #define XMIT_RDEV_MINOR_8_pre30 (1<<11) /* protocols 28 - 29  */
63 #define XMIT_GROUP_NAME_FOLLOWS (1<<11) /* protocols 30 - now */
64 #define XMIT_HLINK_FIRST (1<<12)        /* protocols 30 - now (HLINKED files only) */
65 #define XMIT_IO_ERROR_ENDLIST (1<<12)   /* protocols 31*- now (w/XMIT_EXTENDED_FLAGS) (also protocol 30 w/'f' compat flag) */
66 #define XMIT_MOD_NSEC (1<<13)           /* protocols 31 - now */
67 #define XMIT_SAME_ATIME (1<<14)         /* any protocol - restricted by command-line option */
68 #define XMIT_UNUSED_15 (1<<15)          /* unused flag bit */
69
70 /* The following XMIT flags require an rsync that uses a varint for the flag values */
71
72 #define XMIT_RESERVED_16 (1<<16)        /* reserved for future fileflags use */
73 #define XMIT_CRTIME_EQ_MTIME (1<<17)    /* any protocol - restricted by command-line option */
74
75 /* These flags are used in the live flist data. */
76
77 #define FLAG_TOP_DIR (1<<0)     /* sender/receiver/generator */
78 #define FLAG_OWNED_BY_US (1<<0) /* generator: set by make_file() for aux flists only */
79 #define FLAG_FILE_SENT (1<<1)   /* sender/receiver/generator */
80 #define FLAG_DIR_CREATED (1<<1) /* generator */
81 #define FLAG_CONTENT_DIR (1<<2) /* sender/receiver/generator */
82 #define FLAG_MOUNT_DIR (1<<3)   /* sender/generator (dirs only) */
83 #define FLAG_SKIP_HLINK (1<<3)  /* receiver/generator (w/FLAG_HLINKED) */
84 #define FLAG_DUPLICATE (1<<4)   /* sender */
85 #define FLAG_MISSING_DIR (1<<4) /* generator */
86 #define FLAG_HLINKED (1<<5)     /* receiver/generator (checked on all types) */
87 #define FLAG_HLINK_FIRST (1<<6) /* receiver/generator (w/FLAG_HLINKED) */
88 #define FLAG_IMPLIED_DIR (1<<6) /* sender/receiver/generator (dirs only) */
89 #define FLAG_HLINK_LAST (1<<7)  /* receiver/generator */
90 #define FLAG_HLINK_DONE (1<<8)  /* receiver/generator (checked on all types) */
91 #define FLAG_LENGTH64 (1<<9)    /* sender/receiver/generator */
92 #define FLAG_SKIP_GROUP (1<<10) /* receiver/generator */
93 #define FLAG_TIME_FAILED (1<<11)/* generator */
94 #define FLAG_MOD_NSEC (1<<12)   /* sender/receiver/generator */
95
96 /* These flags are passed to functions but not stored. */
97
98 #define FLAG_DIVERT_DIRS (1<<16)   /* sender, but must be unique */
99 #define FLAG_PERHAPS_DIR (1<<17)   /* generator */
100
101 /* These flags are for get_dirlist(). */
102 #define GDL_IGNORE_FILTER_RULES (1<<0)
103 #define GDL_PERHAPS_DIR (1<<1)
104
105 /* Some helper macros for matching bits. */
106 #define BITS_SET(val,bits) (((val) & (bits)) == (bits))
107 #define BITS_SETnUNSET(val,onbits,offbits) (((val) & ((onbits)|(offbits))) == (onbits))
108 #define BITS_EQUAL(b1,b2,mask) (((unsigned)(b1) & (unsigned)(mask)) \
109                              == ((unsigned)(b2) & (unsigned)(mask)))
110
111 /* Update this if you make incompatible changes and ALSO update the
112  * SUBPROTOCOL_VERSION if it is not a final (official) release. */
113 #define PROTOCOL_VERSION 31
114
115 /* This is used when working on a new protocol version or for any unofficial
116  * protocol tweaks.  It should be a non-zero value for each pre-release repo
117  * change that affects the protocol. The official pre-release versions should
118  * start with 1 (after incrementing the PROTOCOL_VERSION) and go up by 1 for
119  * each new protocol change.  For unofficial changes, pick a fairly large
120  * random number that will hopefully not collide with anyone else's unofficial
121  * protocol.  It must ALWAYS be 0 when the protocol goes final (and official)
122  * and NEVER before!  When rsync negotiates a protocol match, it will only
123  * allow the newest protocol to be used if the SUBPROTOCOL_VERSION matches.
124  * All older protocol versions MUST be compatible with the final, official
125  * release of the protocol, so don't tweak the code to change the protocol
126  * behavior for an older protocol version. */
127 #define SUBPROTOCOL_VERSION 0
128
129 /* We refuse to interoperate with versions that are not in this range.
130  * Note that we assume we'll work with later versions: the onus is on
131  * people writing them to make sure that they don't send us anything
132  * we won't understand.
133  *
134  * Interoperation with old but supported protocol versions
135  * should cause a warning to be printed.  At a future date
136  * the old protocol will become the minimum and
137  * compatibility code removed.
138  *
139  * There are two possible explanations for the limit at
140  * MAX_PROTOCOL_VERSION: either to allow new major-rev versions that
141  * do not interoperate with us, and (more likely) so that we can
142  * detect an attempt to connect rsync to a non-rsync server, which is
143  * unlikely to begin by sending a byte between MIN_PROTOCL_VERSION and
144  * MAX_PROTOCOL_VERSION. */
145
146 #define MIN_PROTOCOL_VERSION 20
147 #define OLD_PROTOCOL_VERSION 25
148 #define MAX_PROTOCOL_VERSION 40
149
150 #define MIN_FILECNT_LOOKAHEAD 1000
151 #define MAX_FILECNT_LOOKAHEAD 10000
152
153 #define RSYNC_PORT 873
154
155 #define SPARSE_WRITE_SIZE (1024)
156 #define WRITE_SIZE (32*1024)
157 #define CHUNK_SIZE (32*1024)
158 #define MAX_MAP_SIZE (256*1024)
159 #define IO_BUFFER_SIZE (32*1024)
160 #define MAX_BLOCK_SIZE ((int32)1 << 17)
161
162 /* For compatibility with older rsyncs */
163 #define OLD_MAX_BLOCK_SIZE ((int32)1 << 29)
164
165 #define ROUND_UP_1024(siz) ((siz) & (1024-1) ? ((siz) | (1024-1)) + 1 : (siz))
166
167 #define IOERR_GENERAL   (1<<0) /* For backward compatibility, this must == 1 */
168 #define IOERR_VANISHED  (1<<1)
169 #define IOERR_DEL_LIMIT (1<<2)
170
171 #define MAX_ARGS 1000
172 #define MAX_BASIS_DIRS 20
173 #define MAX_SERVER_ARGS (MAX_BASIS_DIRS*2 + 100)
174
175 #define COMPARE_DEST 1
176 #define COPY_DEST 2
177 #define LINK_DEST 3
178
179 #define MPLEX_BASE 7
180
181 #define NO_FILTERS      0
182 #define SERVER_FILTERS  1
183 #define ALL_FILTERS     2
184
185 #define XFLG_FATAL_ERRORS       (1<<0)
186 #define XFLG_OLD_PREFIXES       (1<<1)
187 #define XFLG_ANCHORED2ABS       (1<<2) /* leading slash indicates absolute */
188 #define XFLG_ABS_IF_SLASH       (1<<3) /* leading or interior slash is absolute */
189 #define XFLG_DIR2WILD3          (1<<4) /* dir/ match gets trailing *** added */
190
191 #define ATTRS_REPORT            (1<<0)
192 #define ATTRS_SKIP_MTIME        (1<<1)
193 #define ATTRS_ACCURATE_TIME     (1<<2)
194 #define ATTRS_SKIP_ATIME        (1<<3)
195 #define ATTRS_SKIP_CRTIME       (1<<5)
196
197 #define MSG_FLUSH       2
198 #define FULL_FLUSH      1
199 #define NORMAL_FLUSH    0
200
201 #define PDIR_CREATE     1
202 #define PDIR_DELETE     0
203
204 /* Note: 0x00 - 0x7F are used for basis_dir[] indexes! */
205 #define FNAMECMP_BASIS_DIR_LOW  0x00 /* Must remain 0! */
206 #define FNAMECMP_BASIS_DIR_HIGH 0x7F
207 #define FNAMECMP_FNAME          0x80
208 #define FNAMECMP_PARTIAL_DIR    0x81
209 #define FNAMECMP_BACKUP         0x82
210 #define FNAMECMP_FUZZY          0x83
211
212 /* For use by the itemize_changes code */
213 #define ITEM_REPORT_ATIME (1<<0)
214 #define ITEM_REPORT_CHANGE (1<<1)
215 #define ITEM_REPORT_SIZE (1<<2)     /* regular files only */
216 #define ITEM_REPORT_TIMEFAIL (1<<2) /* symlinks only */
217 #define ITEM_REPORT_TIME (1<<3)
218 #define ITEM_REPORT_PERMS (1<<4)
219 #define ITEM_REPORT_OWNER (1<<5)
220 #define ITEM_REPORT_GROUP (1<<6)
221 #define ITEM_REPORT_ACL (1<<7)
222 #define ITEM_REPORT_XATTR (1<<8)
223 #define ITEM_REPORT_CRTIME (1<<10)
224 #define ITEM_BASIS_TYPE_FOLLOWS (1<<11)
225 #define ITEM_XNAME_FOLLOWS (1<<12)
226 #define ITEM_IS_NEW (1<<13)
227 #define ITEM_LOCAL_CHANGE (1<<14)
228 #define ITEM_TRANSFER (1<<15)
229 /* These are outside the range of the transmitted flags. */
230 #define ITEM_MISSING_DATA (1<<16)          /* used by log_formatted() */
231 #define ITEM_DELETED (1<<17)               /* used by log_formatted() */
232 #define ITEM_MATCHED (1<<18)               /* used by itemize() */
233
234 #define SIGNIFICANT_ITEM_FLAGS (~(\
235         ITEM_BASIS_TYPE_FOLLOWS | ITEM_XNAME_FOLLOWS | ITEM_LOCAL_CHANGE))
236
237 #define CFN_KEEP_DOT_DIRS (1<<0)
238 #define CFN_KEEP_TRAILING_SLASH (1<<1)
239 #define CFN_DROP_TRAILING_DOT_DIR (1<<2)
240 #define CFN_COLLAPSE_DOT_DOT_DIRS (1<<3)
241 #define CFN_REFUSE_DOT_DOT_DIRS (1<<4)
242
243 #define SP_DEFAULT 0
244 #define SP_KEEP_DOT_DIRS (1<<0)
245
246 #define CD_NORMAL 0
247 #define CD_SKIP_CHDIR 1
248
249 /* Log-message categories.  FLOG only goes to the log file, not the client;
250  * FCLIENT is the opposite. */
251 enum logcode {
252     FNONE=0, /* never sent */
253     FERROR_XFER=1, FINFO=2, /* sent over socket for any protocol */
254     FERROR=3, FWARNING=4, /* sent over socket for protocols >= 30 */
255     FERROR_SOCKET=5, FLOG=6, /* only sent via receiver -> generator pipe */
256     FERROR_UTF8=8, /* only sent via receiver -> generator pipe */
257     FCLIENT=7 /* never transmitted (e.g. server converts to FINFO) */
258 };
259
260 /* Messages types that are sent over the message channel.  The logcode
261  * values must all be present here with identical numbers. */
262 enum msgcode {
263         MSG_DATA=0,     /* raw data on the multiplexed stream */
264         MSG_ERROR_XFER=FERROR_XFER, MSG_INFO=FINFO, /* remote logging */
265         MSG_ERROR=FERROR, MSG_WARNING=FWARNING, /* protocol-30 remote logging */
266         MSG_ERROR_SOCKET=FERROR_SOCKET, /* sibling logging */
267         MSG_ERROR_UTF8=FERROR_UTF8, /* sibling logging */
268         MSG_LOG=FLOG, MSG_CLIENT=FCLIENT, /* sibling logging */
269         MSG_REDO=9,     /* reprocess indicated flist index */
270         MSG_STATS=10,   /* message has stats data for generator */
271         MSG_IO_ERROR=22,/* the sending side had an I/O error */
272         MSG_IO_TIMEOUT=33,/* tell client about a daemon's timeout value */
273         MSG_NOOP=42,    /* a do-nothing message (legacy protocol-30 only) */
274         MSG_ERROR_EXIT=86, /* synchronize an error exit (siblings and protocol >= 31) */
275         MSG_SUCCESS=100,/* successfully updated indicated flist index */
276         MSG_DELETED=101,/* successfully deleted a file on receiving side */
277         MSG_NO_SEND=102,/* sender failed to open a file we wanted */
278 };
279
280 enum filetype {
281         FT_UNSUPPORTED, FT_REG, FT_DIR, FT_SYMLINK, FT_SPECIAL, FT_DEVICE
282 };
283
284 #define NDX_DONE -1
285 #define NDX_FLIST_EOF -2
286 #define NDX_DEL_STATS -3
287 #define NDX_FLIST_OFFSET -101
288
289 /* For calling delete_item() and delete_dir_contents(). */
290 #define DEL_NO_UID_WRITE        (1<<0) /* file/dir has our uid w/o write perm */
291 #define DEL_RECURSE             (1<<1) /* if dir, delete all contents */
292 #define DEL_DIR_IS_EMPTY        (1<<2) /* internal delete_FUNCTIONS use only */
293 #define DEL_FOR_FILE            (1<<3) /* making room for a replacement file */
294 #define DEL_FOR_DIR             (1<<4) /* making room for a replacement dir */
295 #define DEL_FOR_SYMLINK         (1<<5) /* making room for a replacement symlink */
296 #define DEL_FOR_DEVICE          (1<<6) /* making room for a replacement device */
297 #define DEL_FOR_SPECIAL         (1<<7) /* making room for a replacement special */
298 #define DEL_FOR_BACKUP          (1<<8) /* the delete is for a backup operation */
299
300 #define DEL_MAKE_ROOM (DEL_FOR_FILE|DEL_FOR_DIR|DEL_FOR_SYMLINK|DEL_FOR_DEVICE|DEL_FOR_SPECIAL)
301
302 enum delret {
303         DR_SUCCESS = 0, DR_FAILURE, DR_AT_LIMIT, DR_NOT_EMPTY
304 };
305
306 /* Defines for make_path() */
307 #define MKP_DROP_NAME           (1<<0) /* drop trailing filename or trailing slash */
308 #define MKP_SKIP_SLASH          (1<<1) /* skip one or more leading slashes */
309
310 /* Defines for maybe_send_keepalive() */
311 #define MSK_ALLOW_FLUSH         (1<<0)
312 #define MSK_ACTIVE_RECEIVER     (1<<1)
313
314 #include "errcode.h"
315
316 #include "config.h"
317
318 /* The default RSYNC_RSH is always set in config.h. */
319
320 #include <stdio.h>
321 #ifdef HAVE_SYS_TYPES_H
322 # include <sys/types.h>
323 #endif
324 #ifdef HAVE_SYS_STAT_H
325 # include <sys/stat.h>
326 #endif
327 #ifdef STDC_HEADERS
328 # include <stdlib.h>
329 # include <stddef.h>
330 #else
331 # ifdef HAVE_STDLIB_H
332 #  include <stdlib.h>
333 # endif
334 #endif
335 #ifdef HAVE_STRING_H
336 # if !defined STDC_HEADERS && defined HAVE_MEMORY_H
337 #  include <memory.h>
338 # endif
339 # include <string.h>
340 #endif
341 #ifdef HAVE_BSD_STRING_H
342 # include <bsd/string.h>
343 #endif
344 #ifdef HAVE_STRINGS_H
345 # include <strings.h>
346 #endif
347 #ifdef HAVE_INTTYPES_H
348 # include <inttypes.h>
349 #endif
350 #ifdef HAVE_STDINT_H
351 # include <stdint.h>
352 #endif
353 #ifdef HAVE_UNISTD_H
354 # include <unistd.h>
355 #endif
356
357 #ifdef HAVE_SYS_PARAM_H
358 #include <sys/param.h>
359 #endif
360
361 #if defined HAVE_MALLOC_H && (defined HAVE_MALLINFO || !defined HAVE_STDLIB_H)
362 #include <malloc.h>
363 #endif
364
365 #ifdef HAVE_SYS_SOCKET_H
366 #include <sys/socket.h>
367 #endif
368
369 #ifdef TIME_WITH_SYS_TIME
370 #include <sys/time.h>
371 #include <time.h>
372 #else
373 #ifdef HAVE_SYS_TIME_H
374 #include <sys/time.h>
375 #else
376 #include <time.h>
377 #endif
378 #endif
379
380 #ifdef HAVE_FCNTL_H
381 #include <fcntl.h>
382 #else
383 #ifdef HAVE_SYS_FCNTL_H
384 #include <sys/fcntl.h>
385 #endif
386 #endif
387
388 #ifdef HAVE_SYS_IOCTL_H
389 #include <sys/ioctl.h>
390 #endif
391
392 #ifdef HAVE_SYS_FILIO_H
393 #include <sys/filio.h>
394 #endif
395
396 #include <signal.h>
397 #ifdef HAVE_SYS_WAIT_H
398 #include <sys/wait.h>
399 #endif
400 #ifdef HAVE_CTYPE_H
401 #include <ctype.h>
402 #endif
403 #ifdef HAVE_GRP_H
404 #include <grp.h>
405 #endif
406 #include <errno.h>
407
408 #ifdef HAVE_UTIME_H
409 #include <utime.h>
410 #endif
411
412 #if defined HAVE_UTIMENSAT || defined HAVE_LUTIMES || defined HAVE_SETATTRLIST
413 #define CAN_SET_SYMLINK_TIMES 1
414 #endif
415
416 #if defined HAVE_LCHOWN || defined CHOWN_MODIFIES_SYMLINK
417 #define CAN_CHOWN_SYMLINK 1
418 #endif
419
420 #if defined HAVE_LCHMOD || defined HAVE_SETATTRLIST
421 #define CAN_CHMOD_SYMLINK 1
422 #endif
423
424 #if defined HAVE_UTIMENSAT || defined HAVE_SETATTRLIST
425 #define CAN_SET_NSEC 1
426 #endif
427
428 #ifdef CAN_SET_NSEC
429 #ifdef HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
430 #define ST_MTIME_NSEC st_mtim.tv_nsec
431 #define ST_ATIME_NSEC st_atim.tv_nsec
432 #elif defined(HAVE_STRUCT_STAT_ST_MTIMENSEC)
433 #define ST_MTIME_NSEC st_mtimensec
434 #define ST_ATIME_NSEC st_atimensec
435 #elif defined(HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC)
436 #define ST_MTIME_NSEC st_mtimespec.tv_nsec
437 #define ST_ATIME_NSEC st_atimespec.tv_nsec
438 #endif
439 #endif
440
441 #ifdef HAVE_SYS_SELECT_H
442 #include <sys/select.h>
443 #endif
444
445 #ifdef HAVE_SYS_MODE_H
446 /* apparently AIX needs this for S_ISLNK */
447 #ifndef S_ISLNK
448 #include <sys/mode.h>
449 #endif
450 #endif
451
452 /* these are needed for the uid/gid mapping code */
453 #include <pwd.h>
454 #include <grp.h>
455
456 #include <stdarg.h>
457 #include <netinet/in.h>
458 #include <arpa/inet.h>
459 #ifdef HAVE_NETDB_H
460 #include <netdb.h>
461 #endif
462 #include <syslog.h>
463 #ifdef HAVE_SYS_FILE_H
464 #include <sys/file.h>
465 #endif
466
467 #ifdef HAVE_DIRENT_H
468 # include <dirent.h>
469 #else
470 # define dirent direct
471 # ifdef HAVE_SYS_NDIR_H
472 #  include <sys/ndir.h>
473 # endif
474 # ifdef HAVE_SYS_DIR_H
475 #  include <sys/dir.h>
476 # endif
477 # ifdef HAVE_NDIR_H
478 #  include <ndir.h>
479 # endif
480 #endif
481
482 #ifdef MAJOR_IN_MKDEV
483 #include <sys/mkdev.h>
484 # if !defined makedev && (defined mkdev || defined _WIN32 || defined __WIN32__)
485 #  define makedev mkdev
486 # endif
487 #elif defined MAJOR_IN_SYSMACROS
488 #include <sys/sysmacros.h>
489 #endif
490
491 #ifdef MAKEDEV_TAKES_3_ARGS
492 #define MAKEDEV(devmajor,devminor) makedev(0,devmajor,devminor)
493 #else
494 #ifndef __TANDEM
495 #define MAKEDEV(devmajor,devminor) makedev(devmajor,devminor)
496 #else
497 # define major DEV_TO_MAJOR
498 # define minor DEV_TO_MINOR
499 # define MAKEDEV MAJORMINOR_TO_DEV
500 #endif
501 #endif
502
503 #ifdef __TANDEM
504 # include <floss.h(floss_read,floss_write,floss_fork,floss_execvp)>
505 # include <floss.h(floss_getpwuid,floss_select,floss_seteuid)>
506 # define S_IEXEC S_IXUSR
507 # define ROOT_UID 65535
508 #else
509 # define ROOT_UID 0
510 #endif
511
512 #ifdef HAVE_COMPAT_H
513 #include <compat.h>
514 #endif
515
516 #ifdef HAVE_LIMITS_H
517 # include <limits.h>
518 #endif
519
520 #if defined USE_ICONV_OPEN && defined HAVE_ICONV_H
521 #include <iconv.h>
522 #ifndef ICONV_CONST
523 #define ICONV_CONST
524 #endif
525 #else
526 #ifdef ICONV_CONST
527 #undef ICONV_CONST
528 #endif
529 #ifdef ICONV_OPTION
530 #undef ICONV_OPTION
531 #endif
532 #ifdef iconv_t
533 #undef iconv_t
534 #endif
535 #define iconv_t int
536 #endif
537
538 #include <assert.h>
539
540 #include "lib/pool_alloc.h"
541
542 #ifndef HAVE_ID_T
543 typedef unsigned int id_t;
544 #endif
545 #ifndef HAVE_PID_T
546 typedef int pid_t;
547 #endif
548 #ifndef HAVE_MODE_T
549 typedef unsigned int mode_t;
550 #endif
551 #ifndef HAVE_OFF_T
552 typedef long off_t;
553 #undef SIZEOF_OFF_T
554 #define SIZEOF_OFF_T SIZEOF_LONG
555 #endif
556 #ifndef HAVE_SIZE_T
557 typedef unsigned int size_t;
558 #endif
559
560 #define BOOL int
561
562 #ifndef uchar
563 #define uchar unsigned char
564 #endif
565
566 #ifdef SIGNED_CHAR_OK
567 #define schar signed char
568 #else
569 #define schar char
570 #endif
571
572 #ifndef int16
573 #if SIZEOF_INT16_T == 2
574 # define int16 int16_t
575 #else
576 # define int16 short
577 #endif
578 #endif
579
580 #ifndef uint16
581 #if SIZEOF_UINT16_T == 2
582 # define uint16 uint16_t
583 #else
584 # define uint16 unsigned int16
585 #endif
586 #endif
587
588 #if !defined __APPLE__ || defined HAVE_GETATTRLIST
589 #define SUPPORT_ATIMES 1
590 #endif
591
592 #if defined HAVE_GETATTRLIST || defined __CYGWIN__
593 #define SUPPORT_CRTIMES 1
594 #endif
595
596 /* Find a variable that is either exactly 32-bits or longer.
597  * If some code depends on 32-bit truncation, it will need to
598  * take special action in a "#if SIZEOF_INT32 > 4" section. */
599 #ifndef int32
600 #if SIZEOF_INT32_T == 4
601 # define int32 int32_t
602 # define SIZEOF_INT32 4
603 #elif SIZEOF_INT == 4
604 # define int32 int
605 # define SIZEOF_INT32 4
606 #elif SIZEOF_LONG == 4
607 # define int32 long
608 # define SIZEOF_INT32 4
609 #elif SIZEOF_SHORT == 4
610 # define int32 short
611 # define SIZEOF_INT32 4
612 #elif SIZEOF_INT > 4
613 # define int32 int
614 # define SIZEOF_INT32 SIZEOF_INT
615 #elif SIZEOF_LONG > 4
616 # define int32 long
617 # define SIZEOF_INT32 SIZEOF_LONG
618 #else
619 # error Could not find a 32-bit integer variable
620 #endif
621 #else
622 # define SIZEOF_INT32 4
623 #endif
624
625 #ifndef uint32
626 #if SIZEOF_UINT32_T == 4
627 # define uint32 uint32_t
628 #else
629 # define uint32 unsigned int32
630 #endif
631 #endif
632
633 #if SIZEOF_OFF_T == 8 || !SIZEOF_OFF64_T || !defined HAVE_STRUCT_STAT64
634 #define OFF_T off_t
635 #define STRUCT_STAT struct stat
636 #define SIZEOF_CAPITAL_OFF_T SIZEOF_OFF_T
637 #else
638 #define OFF_T off64_t
639 #define STRUCT_STAT struct stat64
640 #define USE_STAT64_FUNCS 1
641 #define SIZEOF_CAPITAL_OFF_T SIZEOF_OFF64_T
642 #endif
643
644 /* CAVEAT: on some systems, int64 will really be a 32-bit integer IFF
645  * that's the maximum size the file system can handle and there is no
646  * 64-bit type available.  The rsync source must therefore take steps
647  * to ensure that any code that really requires a 64-bit integer has
648  * it (e.g. the checksum code uses two 32-bit integers for its 64-bit
649  * counter). */
650 #if SIZEOF_INT64_T == 8
651 # define int64 int64_t
652 # define SIZEOF_INT64 8
653 #elif SIZEOF_LONG == 8
654 # define int64 long
655 # define SIZEOF_INT64 8
656 #elif SIZEOF_INT == 8
657 # define int64 int
658 # define SIZEOF_INT64 8
659 #elif SIZEOF_LONG_LONG == 8
660 # define int64 long long
661 # define SIZEOF_INT64 8
662 #elif SIZEOF_OFF64_T == 8
663 # define int64 off64_t
664 # define SIZEOF_INT64 8
665 #elif SIZEOF_OFF_T == 8
666 # define int64 off_t
667 # define SIZEOF_INT64 8
668 #elif SIZEOF_INT > 8
669 # define int64 int
670 # define SIZEOF_INT64 SIZEOF_INT
671 #elif SIZEOF_LONG > 8
672 # define int64 long
673 # define SIZEOF_INT64 SIZEOF_LONG
674 #elif SIZEOF_LONG_LONG > 8
675 # define int64 long long
676 # define SIZEOF_INT64 SIZEOF_LONG_LONG
677 #else
678 /* As long as it gets... */
679 # define int64 off_t
680 # define SIZEOF_INT64 SIZEOF_OFF_T
681 #endif
682
683 #define HT_KEY32 0
684 #define HT_KEY64 1
685
686 struct hashtable {
687         void *nodes;
688         int32 size, entries;
689         uint32 node_size;
690         short key64;
691 };
692
693 struct ht_int32_node {
694         void *data;
695         int32 key;
696 };
697
698 struct ht_int64_node {
699         void *data;
700         int64 key;
701 };
702
703 #define HT_NODE(tbl, bkts, i) ((void*)((char*)(bkts) + (i)*(tbl)->node_size))
704 #define HT_KEY(node, k64) ((k64)? ((struct ht_int64_node*)(node))->key \
705                          : (int64)((struct ht_int32_node*)(node))->key)
706
707 #ifndef MIN
708 #define MIN(a,b) ((a)<(b)?(a):(b))
709 #endif
710
711 #ifndef MAX
712 #define MAX(a,b) ((a)>(b)?(a):(b))
713 #endif
714
715 #ifndef MAXHOSTNAMELEN
716 #define MAXHOSTNAMELEN 256
717 #endif
718
719 #define SUM_LENGTH 16
720 #define SHORT_SUM_LENGTH 2
721 #define BLOCKSUM_BIAS 10
722
723 #ifndef MAXPATHLEN
724 #define MAXPATHLEN 1024
725 #endif
726
727 /* We want a roomy line buffer that can hold more than MAXPATHLEN,
728  * and significantly more than an overly short MAXPATHLEN. */
729 #if MAXPATHLEN < 4096
730 #define BIGPATHBUFLEN (4096+1024)
731 #else
732 #define BIGPATHBUFLEN (MAXPATHLEN+1024)
733 #endif
734
735 #ifndef NAME_MAX
736 #define NAME_MAX 255
737 #endif
738
739 #ifndef SIZE_MAX
740 #define SIZE_MAX ((size_t)-1)
741 #endif
742
743 #ifndef INADDR_NONE
744 #define INADDR_NONE 0xffffffff
745 #endif
746
747 #ifndef IN_LOOPBACKNET
748 #define IN_LOOPBACKNET 127
749 #endif
750
751 #if HAVE_UNIXWARE_ACLS|HAVE_SOLARIS_ACLS|HAVE_HPUX_ACLS
752 #define ACLS_NEED_MASK 1
753 #endif
754
755 #if defined HAVE_FALLOCATE || HAVE_SYS_FALLOCATE
756 #ifdef HAVE_LINUX_FALLOC_H
757 #include <linux/falloc.h>
758 #endif
759 #ifdef FALLOC_FL_KEEP_SIZE
760 #define SUPPORT_PREALLOCATION 1
761 #elif defined HAVE_FTRUNCATE
762 #define SUPPORT_PREALLOCATION 1
763 #define PREALLOCATE_NEEDS_TRUNCATE 1
764 #endif
765 #else /* !fallocate */
766 #if defined HAVE_EFFICIENT_POSIX_FALLOCATE && defined HAVE_FTRUNCATE
767 #define SUPPORT_PREALLOCATION 1
768 #define PREALLOCATE_NEEDS_TRUNCATE 1
769 #endif
770 #endif
771
772 #if SIZEOF_CHARP == 4
773 # define PTRS_ARE_32 1
774 # define PTR_EXTRA_CNT 1
775 #elif SIZEOF_CHARP == 8
776 # define PTRS_ARE_64 1
777 # define PTR_EXTRA_CNT EXTRA64_CNT
778 #else
779 # error Character pointers are not 4 or 8 bytes.
780 #endif
781
782 #if defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L
783 #define USE_FLEXIBLE_ARRAY 1
784 #define SIZE_T_FMT_MOD "z" /* printf supports %zd */
785 #define SIZE_T_FMT_CAST size_t
786 #else
787 #define SIZE_T_FMT_MOD "l" /* printf supports %ld */
788 #define SIZE_T_FMT_CAST long
789 #endif
790
791 union file_extras {
792         int32 num;
793         uint32 unum;
794 #ifdef PTRS_ARE_32
795         const char* ptr;
796 #endif
797 };
798
799 union file_extras64 {
800         int64 num;
801 #ifdef PTRS_ARE_64
802         const char* ptr;
803 #endif
804 };
805
806 struct file_struct {
807         const char *dirname;    /* The dir info inside the transfer */
808         time_t modtime;         /* When the item was last modified */
809         uint32 len32;           /* Lowest 32 bits of the file's length */
810         uint16 mode;            /* The item's type and permissions */
811         uint16 flags;           /* The FLAG_* bits for this item */
812 #ifdef USE_FLEXIBLE_ARRAY
813         const char basename[];  /* The basename (AKA filename) follows */
814 #else
815         const char basename[1]; /* A kluge that should work like a flexible array */
816 #endif
817 };
818
819 extern int file_extra_cnt;
820 extern int inc_recurse;
821 extern int atimes_ndx;
822 extern int crtimes_ndx;
823 extern int pathname_ndx;
824 extern int depth_ndx;
825 extern int uid_ndx;
826 extern int gid_ndx;
827 extern int acls_ndx;
828 extern int xattrs_ndx;
829
830 #ifdef USE_FLEXIBLE_ARRAY
831 #define FILE_STRUCT_LEN (sizeof (struct file_struct))
832 #else
833 #define FILE_STRUCT_LEN (offsetof(struct file_struct, basename))
834 #endif
835 #define EXTRA_LEN (sizeof (union file_extras))
836 #define DEV_EXTRA_CNT 2
837 #define DIRNODE_EXTRA_CNT 3
838 #define EXTRA64_CNT ((sizeof (union file_extras64) + EXTRA_LEN - 1) / EXTRA_LEN)
839 #define SUM_EXTRA_CNT ((MAX_DIGEST_LEN + EXTRA_LEN - 1) / EXTRA_LEN)
840
841 #define REQ_EXTRA(f,ndx) ((union file_extras*)(f) - (ndx))
842 #define OPT_EXTRA(f,bump) ((union file_extras*)(f) - file_extra_cnt - 1 - (bump))
843
844 /* These are guaranteed to be allocated first in the array so that they
845  * are aligned for direct int64-pointer access. */
846 #define REQ_EXTRA64(f,ndx) ((union file_extras64*)REQ_EXTRA(f,ndx))
847
848 #define NSEC_BUMP(f) ((f)->flags & FLAG_MOD_NSEC ? 1 : 0)
849 #define LEN64_BUMP(f) ((f)->flags & FLAG_LENGTH64 ? 1 : 0)
850 #define START_BUMP(f) (NSEC_BUMP(f) + LEN64_BUMP(f))
851 #define HLINK_BUMP(f) ((f)->flags & (FLAG_HLINKED|FLAG_HLINK_DONE) ? inc_recurse+1 : 0)
852 #define ACL_BUMP(f) (acls_ndx ? 1 : 0)
853
854 /* The length applies to all items. */
855 #if SIZEOF_INT64 < 8
856 #define F_LENGTH(f) ((int64)(f)->len32)
857 #else
858 #define F_HIGH_LEN(f) (OPT_EXTRA(f, NSEC_BUMP(f))->unum)
859 #define F_LENGTH(f) ((int64)(f)->len32 + ((f)->flags & FLAG_LENGTH64 ? (int64)F_HIGH_LEN(f) << 32 : 0))
860 #endif
861
862 #define F_MOD_NSEC(f) OPT_EXTRA(f, 0)->unum
863 #define F_MOD_NSEC_or_0(f) ((f)->flags & FLAG_MOD_NSEC ? F_MOD_NSEC(f) : 0)
864
865 /* If there is a symlink string, it is always right after the basename */
866 #define F_SYMLINK(f) ((f)->basename + strlen((f)->basename) + 1)
867
868 /* The sending side always has this available: */
869 #ifdef PTRS_ARE_32
870 #define F_PATHNAME(f) REQ_EXTRA(f, pathname_ndx)->ptr
871 #else
872 #define F_PATHNAME(f) REQ_EXTRA64(f, pathname_ndx)->ptr
873 #endif
874
875 /* The receiving side always has this available: */
876 #define F_DEPTH(f) REQ_EXTRA(f, depth_ndx)->num
877
878 /* When the associated option is on, all entries will have these present: */
879 #define F_OWNER(f) REQ_EXTRA(f, uid_ndx)->unum
880 #define F_GROUP(f) REQ_EXTRA(f, gid_ndx)->unum
881 #define F_ACL(f) REQ_EXTRA(f, acls_ndx)->num
882 #define F_XATTR(f) REQ_EXTRA(f, xattrs_ndx)->num
883 #define F_NDX(f) REQ_EXTRA(f, unsort_ndx)->num
884 #define F_ATIME(f) REQ_EXTRA64(f, atimes_ndx)->num
885 #define F_CRTIME(f) REQ_EXTRA64(f, crtimes_ndx)->num
886
887 /* These items are per-entry optional: */
888 #define F_HL_GNUM(f) OPT_EXTRA(f, START_BUMP(f))->num /* non-dirs */
889 #define F_HL_PREV(f) OPT_EXTRA(f, START_BUMP(f)+inc_recurse)->num /* non-dirs */
890 #define F_DIR_NODE_P(f) (&OPT_EXTRA(f, START_BUMP(f) \
891                                 + DIRNODE_EXTRA_CNT - 1)->num) /* sender dirs */
892 #define F_DIR_RELNAMES_P(f) (&OPT_EXTRA(f, START_BUMP(f) + DIRNODE_EXTRA_CNT \
893                                 + PTR_EXTRA_CNT - 1)->num) /* sender dirs */
894 #define F_DIR_DEFACL(f) OPT_EXTRA(f, START_BUMP(f))->unum /* receiver dirs */
895 #define F_DIR_DEV_P(f) (&OPT_EXTRA(f, START_BUMP(f) + ACL_BUMP(f) \
896                                 + DEV_EXTRA_CNT - 1)->unum) /* receiver dirs */
897
898 /* This optional item might follow an F_HL_*() item. */
899 #define F_RDEV_P(f) (&OPT_EXTRA(f, START_BUMP(f) + HLINK_BUMP(f) + DEV_EXTRA_CNT - 1)->unum)
900
901 /* The sum is only present on regular files. */
902 #define F_SUM(f) ((char*)OPT_EXTRA(f, START_BUMP(f) + HLINK_BUMP(f) \
903                                     + SUM_EXTRA_CNT - 1))
904
905 /* Some utility defines: */
906 #define F_IS_ACTIVE(f) (f)->basename[0]
907 #define F_IS_HLINKED(f) ((f)->flags & FLAG_HLINKED)
908
909 #define F_HLINK_NOT_FIRST(f) BITS_SETnUNSET((f)->flags, FLAG_HLINKED, FLAG_HLINK_FIRST)
910 #define F_HLINK_NOT_LAST(f) BITS_SETnUNSET((f)->flags, FLAG_HLINKED, FLAG_HLINK_LAST)
911
912 /* These access the F_DIR_DEV_P() and F_RDEV_P() values: */
913 #define DEV_MAJOR(a) (a)[0]
914 #define DEV_MINOR(a) (a)[1]
915
916 /* These access the F_DIRS_NODE_P() values: */
917 #define DIR_PARENT(a) (a)[0]
918 #define DIR_FIRST_CHILD(a) (a)[1]
919 #define DIR_NEXT_SIBLING(a) (a)[2]
920
921 #define IS_MISSING_FILE(statbuf) ((statbuf).st_mode == 0)
922
923 /*
924  * Start the flist array at FLIST_START entries and grow it
925  * by doubling until FLIST_LINEAR then grow by FLIST_LINEAR
926  */
927 #define FLIST_START             (32)
928 #define FLIST_START_LARGE       (32 * 1024)
929 #define FLIST_LINEAR            (FLIST_START_LARGE * 512)
930
931 /*
932  * Extent size for allocation pools: A minimum size of 128KB
933  * is needed to mmap them so that freeing will release the
934  * space to the OS.
935  *
936  * Larger sizes reduce leftover fragments and speed free calls
937  * (when they happen). Smaller sizes increase the chance of
938  * freed allocations freeing whole extents.
939  */
940 #define NORMAL_EXTENT   (256 * 1024)
941 #define SMALL_EXTENT    (128 * 1024)
942
943 #define FLIST_TEMP      (1<<1)
944
945 struct file_list {
946         struct file_list *next, *prev;
947         struct file_struct **files, **sorted;
948         alloc_pool_t file_pool;
949         void *pool_boundary;
950         int used, malloced;
951         int low, high;  /* 0-relative index values excluding empties */
952         int ndx_start;  /* the start offset for inc_recurse mode */
953         int flist_num;  /* 1-relative file_list number or 0 */
954         int parent_ndx; /* dir_flist index of parent directory */
955         int in_progress, to_redo;
956 };
957
958 #define SUMFLG_SAME_OFFSET      (1<<0)
959
960 struct sum_buf {
961         OFF_T offset;           /**< offset in file of this chunk */
962         int32 len;              /**< length of chunk of file */
963         uint32 sum1;            /**< simple checksum */
964         int32 chain;            /**< next hash-table collision */
965         short flags;            /**< flag bits */
966         char sum2[SUM_LENGTH];  /**< checksum  */
967 };
968
969 struct sum_struct {
970         OFF_T flength;          /**< total file length */
971         struct sum_buf *sums;   /**< points to info for each chunk */
972         int32 count;            /**< how many chunks */
973         int32 blength;          /**< block_length */
974         int32 remainder;        /**< flength % block_length */
975         int s2length;           /**< sum2_length */
976 };
977
978 struct map_struct {
979         OFF_T file_size;        /* File size (from stat)                */
980         OFF_T p_offset;         /* Window start                         */
981         OFF_T p_fd_offset;      /* offset of cursor in fd ala lseek     */
982         char *p;                /* Window pointer                       */
983         int32 p_size;           /* Largest window size we allocated     */
984         int32 p_len;            /* Latest (rounded) window size         */
985         int32 def_window_size;  /* Default window size                  */
986         int fd;                 /* File Descriptor                      */
987         int status;             /* first errno from read errors         */
988 };
989
990 #define NAME_IS_FILE            (0)    /* filter name as a file */
991 #define NAME_IS_DIR             (1<<0) /* filter name as a dir */
992 #define NAME_IS_XATTR           (1<<2) /* filter name as an xattr */
993
994 #define FILTRULE_WILD           (1<<0) /* pattern has '*', '[', and/or '?' */
995 #define FILTRULE_WILD2          (1<<1) /* pattern has '**' */
996 #define FILTRULE_WILD2_PREFIX   (1<<2) /* pattern starts with "**" */
997 #define FILTRULE_WILD3_SUFFIX   (1<<3) /* pattern ends with "***" */
998 #define FILTRULE_ABS_PATH       (1<<4) /* path-match on absolute path */
999 #define FILTRULE_INCLUDE        (1<<5) /* this is an include, not an exclude */
1000 #define FILTRULE_DIRECTORY      (1<<6) /* this matches only directories */
1001 #define FILTRULE_WORD_SPLIT     (1<<7) /* split rules on whitespace */
1002 #define FILTRULE_NO_INHERIT     (1<<8) /* don't inherit these rules */
1003 #define FILTRULE_NO_PREFIXES    (1<<9) /* parse no prefixes from patterns */
1004 #define FILTRULE_MERGE_FILE     (1<<10)/* specifies a file to merge */
1005 #define FILTRULE_PERDIR_MERGE   (1<<11)/* merge-file is searched per-dir */
1006 #define FILTRULE_EXCLUDE_SELF   (1<<12)/* merge-file name should be excluded */
1007 #define FILTRULE_FINISH_SETUP   (1<<13)/* per-dir merge file needs setup */
1008 #define FILTRULE_NEGATE         (1<<14)/* rule matches when pattern does not */
1009 #define FILTRULE_CVS_IGNORE     (1<<15)/* rule was -C or :C */
1010 #define FILTRULE_SENDER_SIDE    (1<<16)/* rule applies to the sending side */
1011 #define FILTRULE_RECEIVER_SIDE  (1<<17)/* rule applies to the receiving side */
1012 #define FILTRULE_CLEAR_LIST     (1<<18)/* this item is the "!" token */
1013 #define FILTRULE_PERISHABLE     (1<<19)/* perishable if parent dir goes away */
1014 #define FILTRULE_XATTR          (1<<20)/* rule only applies to xattr names */
1015
1016 #define FILTRULES_SIDES (FILTRULE_SENDER_SIDE | FILTRULE_RECEIVER_SIDE)
1017
1018 typedef struct filter_struct {
1019         struct filter_struct *next;
1020         char *pattern;
1021         uint32 rflags;
1022         union {
1023                 int slash_cnt;
1024                 struct filter_list_struct *mergelist;
1025         } u;
1026 } filter_rule;
1027
1028 typedef struct filter_list_struct {
1029         filter_rule *head;
1030         filter_rule *tail;
1031         char *debug_type;
1032 } filter_rule_list;
1033
1034 struct stats {
1035         int64 total_size;
1036         int64 total_transferred_size;
1037         int64 total_written;
1038         int64 total_read;
1039         int64 literal_data;
1040         int64 matched_data;
1041         int64 flist_buildtime;
1042         int64 flist_xfertime;
1043         int64 flist_size;
1044         int num_files, num_dirs, num_symlinks, num_devices, num_specials;
1045         int created_files, created_dirs, created_symlinks, created_devices, created_specials;
1046         int deleted_files, deleted_dirs, deleted_symlinks, deleted_devices, deleted_specials;
1047         int xferred_files;
1048 };
1049
1050 struct chmod_mode_struct;
1051
1052 struct flist_ndx_item {
1053         struct flist_ndx_item *next;
1054         int ndx;
1055 };
1056
1057 typedef struct {
1058         struct flist_ndx_item *head, *tail;
1059 } flist_ndx_list;
1060
1061 #define EMPTY_ITEM_LIST {NULL, 0, 0}
1062
1063 typedef struct {
1064         void *items;
1065         size_t count;
1066         size_t malloced;
1067 } item_list;
1068
1069 #define EXPAND_ITEM_LIST(lp, type, incr) \
1070         (type*)expand_item_list(lp, sizeof (type), #type, incr)
1071
1072 #define EMPTY_XBUF {NULL, 0, 0, 0}
1073
1074 typedef struct {
1075         char *buf;
1076         size_t pos;  /* pos = read pos in the buf */
1077         size_t len;  /* len = chars following pos */
1078         size_t size; /* size = total space in buf */
1079 } xbuf;
1080
1081 #define INIT_XBUF(xb, str, ln, sz) (xb).buf = (str), (xb).len = (ln), (xb).size = (sz), (xb).pos = 0
1082 #define INIT_XBUF_STRLEN(xb, str) (xb).buf = (str), (xb).len = strlen((xb).buf), (xb).size = (size_t)-1, (xb).pos = 0
1083 /* This one is used to make an output xbuf based on a char[] buffer: */
1084 #define INIT_CONST_XBUF(xb, bf) (xb).buf = (bf), (xb).size = sizeof (bf), (xb).len = (xb).pos = 0
1085
1086 #define ICB_EXPAND_OUT (1<<0)
1087 #define ICB_INCLUDE_BAD (1<<1)
1088 #define ICB_INCLUDE_INCOMPLETE (1<<2)
1089 #define ICB_CIRCULAR_OUT (1<<3)
1090 #define ICB_INIT (1<<4)
1091
1092 #define IOBUF_KEEP_BUFS 0
1093 #define IOBUF_FREE_BUFS 1
1094
1095 #define MPLX_SWITCHING IOBUF_KEEP_BUFS
1096 #define MPLX_ALL_DONE IOBUF_FREE_BUFS
1097 #define MPLX_TO_BUFFERED 2
1098
1099 #define RL_EOL_NULLS (1<<0)
1100 #define RL_DUMP_COMMENTS (1<<1)
1101 #define RL_CONVERT (1<<2)
1102
1103 typedef struct {
1104         char name_type;
1105 #ifdef USE_FLEXIBLE_ARRAY
1106         char fname[]; /* has variable size */
1107 #else
1108         char fname[1]; /* A kluge that should work like a flexible array */
1109 #endif
1110 } relnamecache;
1111
1112 #ifdef USE_FLEXIBLE_ARRAY
1113 #define RELNAMECACHE_LEN (sizeof (relnamecache))
1114 #else
1115 #define RELNAMECACHE_LEN (offsetof(relnamecache, fname))
1116 #endif
1117
1118 #include "byteorder.h"
1119 #include "lib/mdigest.h"
1120 #include "lib/wildmatch.h"
1121 #include "lib/permstring.h"
1122 #include "lib/addrinfo.h"
1123
1124 #ifndef __GNUC__
1125 #define __attribute__(x)
1126 #else
1127 # if __GNUC__ <= 2
1128 # define NORETURN
1129 # endif
1130 #endif
1131
1132 #define UNUSED(x) x __attribute__((__unused__))
1133 #ifndef NORETURN
1134 #define NORETURN __attribute__((__noreturn__))
1135 #endif
1136
1137 typedef struct {
1138     STRUCT_STAT st;
1139     time_t crtime;
1140 #ifdef SUPPORT_ACLS
1141     struct rsync_acl *acc_acl; /* access ACL */
1142     struct rsync_acl *def_acl; /* default ACL */
1143 #endif
1144 #ifdef SUPPORT_XATTRS
1145     item_list *xattr;
1146 #endif
1147 } stat_x;
1148
1149 #define ACL_READY(sx) ((sx).acc_acl != NULL)
1150 #define XATTR_READY(sx) ((sx).xattr != NULL)
1151
1152 #define CLVL_NOT_SPECIFIED INT_MIN
1153
1154 #define CPRES_AUTO (-1)
1155 #define CPRES_NONE 0
1156 #define CPRES_ZLIB 1
1157 #define CPRES_ZLIBX 2
1158 #define CPRES_LZ4 3
1159 #define CPRES_ZSTD 4
1160
1161 #define NSTR_CHECKSUM 0
1162 #define NSTR_COMPRESS 1
1163
1164 struct name_num_item {
1165         int num;
1166         const char *name, *main_name;
1167 };
1168
1169 struct name_num_obj {
1170         const char *type;
1171         const char *negotiated_name;
1172         uchar *saw;
1173         int saw_len;
1174         int negotiated_num;
1175         struct name_num_item *list;
1176 };
1177
1178 #ifdef EXTERNAL_ZLIB
1179 #define read_buf read_buf_
1180 #endif
1181
1182 #ifndef __cplusplus
1183 #include "proto.h"
1184 #endif
1185
1186 #ifndef SUPPORT_XATTRS
1187 #define x_stat(fn,fst,xst) do_stat(fn,fst)
1188 #define x_lstat(fn,fst,xst) do_lstat(fn,fst)
1189 #define x_fstat(fd,fst,xst) do_fstat(fd,fst)
1190 #endif
1191
1192 /* We have replacement versions of these if they're missing. */
1193 #ifndef HAVE_ASPRINTF
1194 int asprintf(char **ptr, const char *format, ...);
1195 #endif
1196
1197 #ifndef HAVE_VASPRINTF
1198 int vasprintf(char **ptr, const char *format, va_list ap);
1199 #endif
1200
1201 #if !defined HAVE_VSNPRINTF || !defined HAVE_C99_VSNPRINTF
1202 #define vsnprintf rsync_vsnprintf
1203 int vsnprintf(char *str, size_t count, const char *fmt, va_list args);
1204 #endif
1205
1206 #if !defined HAVE_SNPRINTF || !defined HAVE_C99_VSNPRINTF
1207 #define snprintf rsync_snprintf
1208 int snprintf(char *str, size_t count, const char *fmt,...);
1209 #endif
1210
1211 #ifndef HAVE_STRERROR
1212 extern char *sys_errlist[];
1213 #define strerror(i) sys_errlist[i]
1214 #endif
1215
1216 #ifndef HAVE_STRCHR
1217 # define strchr                 index
1218 # define strrchr                rindex
1219 #endif
1220
1221 #ifndef HAVE_ERRNO_DECL
1222 extern int errno;
1223 #endif
1224
1225 #ifdef HAVE_READLINK
1226 #define SUPPORT_LINKS 1
1227 #if !defined NO_SYMLINK_XATTRS && !defined NO_SYMLINK_USER_XATTRS
1228 #define do_readlink(path, buf, bufsiz) readlink(path, buf, bufsiz)
1229 #endif
1230 #endif
1231 #ifdef HAVE_LINK
1232 #define SUPPORT_HARD_LINKS 1
1233 #endif
1234
1235 #ifdef HAVE_SIGACTION
1236 #define SIGACTION(n,h) sigact.sa_handler=(h), sigaction((n),&sigact,NULL)
1237 #define signal(n,h) we_need_to_call_SIGACTION_not_signal(n,h)
1238 #else
1239 #define SIGACTION(n,h) signal(n,h)
1240 #endif
1241
1242 #ifndef EWOULDBLOCK
1243 #define EWOULDBLOCK EAGAIN
1244 #endif
1245
1246 #ifndef STDIN_FILENO
1247 #define STDIN_FILENO 0
1248 #endif
1249
1250 #ifndef STDOUT_FILENO
1251 #define STDOUT_FILENO 1
1252 #endif
1253
1254 #ifndef STDERR_FILENO
1255 #define STDERR_FILENO 2
1256 #endif
1257
1258 #ifndef S_IRUSR
1259 #define S_IRUSR 0400
1260 #endif
1261
1262 #ifndef S_IWUSR
1263 #define S_IWUSR 0200
1264 #endif
1265
1266 #ifndef ACCESSPERMS
1267 #define ACCESSPERMS 0777
1268 #endif
1269
1270 #ifndef S_ISVTX
1271 #define S_ISVTX 0
1272 #endif
1273
1274 #define CHMOD_BITS (S_ISUID | S_ISGID | S_ISVTX | ACCESSPERMS)
1275
1276 #ifndef _S_IFMT
1277 #define _S_IFMT        0170000
1278 #endif
1279
1280 #ifndef _S_IFLNK
1281 #define _S_IFLNK  0120000
1282 #endif
1283
1284 #ifndef S_ISLNK
1285 #define S_ISLNK(mode) (((mode) & (_S_IFMT)) == (_S_IFLNK))
1286 #endif
1287
1288 #ifndef S_ISBLK
1289 #define S_ISBLK(mode) (((mode) & (_S_IFMT)) == (_S_IFBLK))
1290 #endif
1291
1292 #ifndef S_ISCHR
1293 #define S_ISCHR(mode) (((mode) & (_S_IFMT)) == (_S_IFCHR))
1294 #endif
1295
1296 #ifndef S_ISSOCK
1297 #ifdef _S_IFSOCK
1298 #define S_ISSOCK(mode) (((mode) & (_S_IFMT)) == (_S_IFSOCK))
1299 #else
1300 #define S_ISSOCK(mode) (0)
1301 #endif
1302 #endif
1303
1304 #ifndef S_ISFIFO
1305 #ifdef _S_IFIFO
1306 #define S_ISFIFO(mode) (((mode) & (_S_IFMT)) == (_S_IFIFO))
1307 #else
1308 #define S_ISFIFO(mode) (0)
1309 #endif
1310 #endif
1311
1312 #ifndef S_ISDIR
1313 #define S_ISDIR(mode) (((mode) & (_S_IFMT)) == (_S_IFDIR))
1314 #endif
1315
1316 #ifndef S_ISREG
1317 #define S_ISREG(mode) (((mode) & (_S_IFMT)) == (_S_IFREG))
1318 #endif
1319
1320 /* work out what fcntl flag to use for non-blocking */
1321 #ifdef O_NONBLOCK
1322 # define NONBLOCK_FLAG O_NONBLOCK
1323 #elif defined SYSV
1324 # define NONBLOCK_FLAG O_NDELAY
1325 #else
1326 # define NONBLOCK_FLAG FNDELAY
1327 #endif
1328
1329 #ifndef INADDR_LOOPBACK
1330 #define INADDR_LOOPBACK 0x7f000001
1331 #endif
1332
1333 #ifndef INADDR_NONE
1334 #define INADDR_NONE 0xffffffff
1335 #endif
1336
1337 #define IS_SPECIAL(mode) (S_ISSOCK(mode) || S_ISFIFO(mode))
1338 #define IS_DEVICE(mode) (S_ISCHR(mode) || S_ISBLK(mode))
1339
1340 /* Initial mask on permissions given to temporary files.  Mask off setuid
1341      bits and group access because of potential race-condition security
1342      holes, and mask other access because mode 707 is bizarre */
1343 #define INITACCESSPERMS 0700
1344
1345 /* handler for null strings in printf format */
1346 #define NS(s) ((s)?(s):"<NULL>")
1347
1348 extern char *do_calloc;
1349
1350 /* Convenient wrappers for malloc and realloc.  Use them. */
1351 #define new(type) ((type*)my_alloc(NULL, sizeof (type), 1, __FILE__, __LINE__))
1352 #define new0(type) ((type*)my_alloc(do_calloc, sizeof (type), 1, __FILE__, __LINE__))
1353 #define realloc_buf(ptr, num) my_alloc((ptr), (num), 1, __FILE__, __LINE__)
1354
1355 #define new_array(type, num) ((type*)my_alloc(NULL, (num), sizeof (type), __FILE__, __LINE__))
1356 #define new_array0(type, num) ((type*)my_alloc(do_calloc, (num), sizeof (type), __FILE__, __LINE__))
1357 #define realloc_array(ptr, type, num) ((type*)my_alloc((ptr), (num), sizeof (type), __FILE__, __LINE__))
1358
1359 #undef strdup
1360 #define strdup(s) my_strdup(s, __FILE__, __LINE__)
1361
1362 #define out_of_memory(msg) _out_of_memory(msg, __FILE__, __LINE__)
1363 #define overflow_exit(msg) _overflow_exit(msg, __FILE__, __LINE__)
1364
1365 /* use magic gcc attributes to catch format errors */
1366  void rprintf(enum logcode , const char *, ...)
1367      __attribute__((format (printf, 2, 3)))
1368 ;
1369
1370 /* This is just like rprintf, but it also tries to print some
1371  * representation of the error code.  Normally errcode = errno. */
1372 void rsyserr(enum logcode, int, const char *, ...)
1373      __attribute__((format (printf, 3, 4)))
1374      ;
1375
1376 /* Make sure that the O_BINARY flag is defined. */
1377 #ifndef O_BINARY
1378 #define O_BINARY 0
1379 #endif
1380
1381 #ifndef HAVE_STRLCPY
1382 size_t strlcpy(char *d, const char *s, size_t bufsize);
1383 #endif
1384
1385 #ifndef HAVE_STRLCAT
1386 size_t strlcat(char *d, const char *s, size_t bufsize);
1387 #endif
1388
1389 #ifndef WEXITSTATUS
1390 #define WEXITSTATUS(stat)       ((int)(((stat)>>8)&0xFF))
1391 #endif
1392 #ifndef WIFEXITED
1393 #define WIFEXITED(stat)         ((int)((stat)&0xFF) == 0)
1394 #endif
1395
1396 #define exit_cleanup(code) _exit_cleanup(code, __FILE__, __LINE__)
1397
1398 #ifdef HAVE_GETEUID
1399 #define MY_UID() geteuid()
1400 #else
1401 #define MY_UID() getuid()
1402 #endif
1403
1404 #ifdef HAVE_GETEGID
1405 #define MY_GID() getegid()
1406 #else
1407 #define MY_GID() getgid()
1408 #endif
1409
1410 #ifdef FORCE_FD_ZERO_MEMSET
1411 #undef FD_ZERO
1412 #define FD_ZERO(fdsetp) memset(fdsetp, 0, sizeof (fd_set))
1413 #endif
1414
1415 extern short info_levels[], debug_levels[];
1416
1417 #define INFO_GTE(flag, lvl) (info_levels[INFO_##flag] >= (lvl))
1418 #define INFO_EQ(flag, lvl) (info_levels[INFO_##flag] == (lvl))
1419 #define DEBUG_GTE(flag, lvl) (debug_levels[DEBUG_##flag] >= (lvl))
1420 #define DEBUG_EQ(flag, lvl) (debug_levels[DEBUG_##flag] == (lvl))
1421
1422 #define INFO_BACKUP 0
1423 #define INFO_COPY (INFO_BACKUP+1)
1424 #define INFO_DEL (INFO_COPY+1)
1425 #define INFO_FLIST (INFO_DEL+1)
1426 #define INFO_MISC (INFO_FLIST+1)
1427 #define INFO_MOUNT (INFO_MISC+1)
1428 #define INFO_NAME (INFO_MOUNT+1)
1429 #define INFO_NONREG (INFO_NAME+1)
1430 #define INFO_PROGRESS (INFO_NONREG+1)
1431 #define INFO_REMOVE (INFO_PROGRESS+1)
1432 #define INFO_SKIP (INFO_REMOVE+1)
1433 #define INFO_STATS (INFO_SKIP+1)
1434 #define INFO_SYMSAFE (INFO_STATS+1)
1435
1436 #define COUNT_INFO (INFO_SYMSAFE+1)
1437
1438 #define DEBUG_ACL 0
1439 #define DEBUG_BACKUP (DEBUG_ACL+1)
1440 #define DEBUG_BIND (DEBUG_BACKUP+1)
1441 #define DEBUG_CHDIR (DEBUG_BIND+1)
1442 #define DEBUG_CONNECT (DEBUG_CHDIR+1)
1443 #define DEBUG_CMD (DEBUG_CONNECT+1)
1444 #define DEBUG_DEL (DEBUG_CMD+1)
1445 #define DEBUG_DELTASUM (DEBUG_DEL+1)
1446 #define DEBUG_DUP (DEBUG_DELTASUM+1)
1447 #define DEBUG_EXIT (DEBUG_DUP+1)
1448 #define DEBUG_FILTER (DEBUG_EXIT+1)
1449 #define DEBUG_FLIST (DEBUG_FILTER+1)
1450 #define DEBUG_FUZZY (DEBUG_FLIST+1)
1451 #define DEBUG_GENR (DEBUG_FUZZY+1)
1452 #define DEBUG_HASH (DEBUG_GENR+1)
1453 #define DEBUG_HLINK (DEBUG_HASH+1)
1454 #define DEBUG_ICONV (DEBUG_HLINK+1)
1455 #define DEBUG_IO (DEBUG_ICONV+1)
1456 #define DEBUG_NSTR (DEBUG_IO+1)
1457 #define DEBUG_OWN (DEBUG_NSTR+1)
1458 #define DEBUG_PROTO (DEBUG_OWN+1)
1459 #define DEBUG_RECV (DEBUG_PROTO+1)
1460 #define DEBUG_SEND (DEBUG_RECV+1)
1461 #define DEBUG_TIME (DEBUG_SEND+1)
1462
1463 #define COUNT_DEBUG (DEBUG_TIME+1)
1464
1465 #ifndef HAVE_INET_NTOP
1466 const char *inet_ntop(int af, const void *src, char *dst, size_t size);
1467 #endif
1468
1469 #ifndef HAVE_INET_PTON
1470 int inet_pton(int af, const char *src, void *dst);
1471 #endif
1472
1473 #ifndef HAVE_GETPASS
1474 char *getpass(const char *prompt);
1475 #endif
1476
1477 #ifdef MAINTAINER_MODE
1478 const char *get_panic_action(void);
1479 #endif
1480
1481 #define NOISY_DEATH(msg) do { \
1482     fprintf(stderr, "%s in %s at line %d\n", msg, __FILE__, __LINE__); \
1483     exit_cleanup(RERR_UNSUPPORTED); \
1484 } while (0)
1485
1486 #ifdef HAVE_MALLINFO2
1487 #define MEM_ALLOC_INFO mallinfo2
1488 #elif defined HAVE_MALLINFO
1489 #define MEM_ALLOC_INFO mallinfo
1490 #endif