More tweaks for Actions.
[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 HAVE_SYS_TIME_H
370 #include <sys/time.h>
371 #endif
372 #include <time.h>
373
374 #ifdef HAVE_FCNTL_H
375 #include <fcntl.h>
376 #else
377 #ifdef HAVE_SYS_FCNTL_H
378 #include <sys/fcntl.h>
379 #endif
380 #endif
381
382 #ifdef HAVE_SYS_IOCTL_H
383 #include <sys/ioctl.h>
384 #endif
385
386 #ifdef HAVE_SYS_FILIO_H
387 #include <sys/filio.h>
388 #endif
389
390 #include <signal.h>
391 #ifdef HAVE_SYS_WAIT_H
392 #include <sys/wait.h>
393 #endif
394 #ifdef HAVE_CTYPE_H
395 #include <ctype.h>
396 #endif
397 #ifdef HAVE_GRP_H
398 #include <grp.h>
399 #endif
400 #include <errno.h>
401
402 #ifdef HAVE_UTIME_H
403 #include <utime.h>
404 #endif
405
406 #if defined HAVE_UTIMENSAT || defined HAVE_LUTIMES || defined HAVE_SETATTRLIST
407 #define CAN_SET_SYMLINK_TIMES 1
408 #endif
409
410 #if defined HAVE_LCHOWN || defined CHOWN_MODIFIES_SYMLINK
411 #define CAN_CHOWN_SYMLINK 1
412 #endif
413
414 #if defined HAVE_LCHMOD || defined HAVE_SETATTRLIST
415 #define CAN_CHMOD_SYMLINK 1
416 #endif
417
418 #if defined HAVE_UTIMENSAT || defined HAVE_SETATTRLIST
419 #define CAN_SET_NSEC 1
420 #endif
421
422 #ifdef CAN_SET_NSEC
423 #ifdef HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
424 #define ST_MTIME_NSEC st_mtim.tv_nsec
425 #define ST_ATIME_NSEC st_atim.tv_nsec
426 #elif defined(HAVE_STRUCT_STAT_ST_MTIMENSEC)
427 #define ST_MTIME_NSEC st_mtimensec
428 #define ST_ATIME_NSEC st_atimensec
429 #elif defined(HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC)
430 #define ST_MTIME_NSEC st_mtimespec.tv_nsec
431 #define ST_ATIME_NSEC st_atimespec.tv_nsec
432 #endif
433 #endif
434
435 #ifdef HAVE_SYS_SELECT_H
436 #include <sys/select.h>
437 #endif
438
439 #ifdef HAVE_SYS_MODE_H
440 /* apparently AIX needs this for S_ISLNK */
441 #ifndef S_ISLNK
442 #include <sys/mode.h>
443 #endif
444 #endif
445
446 /* these are needed for the uid/gid mapping code */
447 #include <pwd.h>
448 #include <grp.h>
449
450 #include <stdarg.h>
451 #include <netinet/in.h>
452 #include <arpa/inet.h>
453 #ifdef HAVE_NETDB_H
454 #include <netdb.h>
455 #endif
456 #include <syslog.h>
457 #ifdef HAVE_SYS_FILE_H
458 #include <sys/file.h>
459 #endif
460
461 #ifdef HAVE_DIRENT_H
462 # include <dirent.h>
463 #else
464 # define dirent direct
465 # ifdef HAVE_SYS_NDIR_H
466 #  include <sys/ndir.h>
467 # endif
468 # ifdef HAVE_SYS_DIR_H
469 #  include <sys/dir.h>
470 # endif
471 # ifdef HAVE_NDIR_H
472 #  include <ndir.h>
473 # endif
474 #endif
475
476 #ifdef MAJOR_IN_MKDEV
477 #include <sys/mkdev.h>
478 # if !defined makedev && (defined mkdev || defined _WIN32 || defined __WIN32__)
479 #  define makedev mkdev
480 # endif
481 #elif defined MAJOR_IN_SYSMACROS
482 #include <sys/sysmacros.h>
483 #endif
484
485 #ifdef MAKEDEV_TAKES_3_ARGS
486 #define MAKEDEV(devmajor,devminor) makedev(0,devmajor,devminor)
487 #else
488 #ifndef __TANDEM
489 #define MAKEDEV(devmajor,devminor) makedev(devmajor,devminor)
490 #else
491 # define major DEV_TO_MAJOR
492 # define minor DEV_TO_MINOR
493 # define MAKEDEV MAJORMINOR_TO_DEV
494 #endif
495 #endif
496
497 #ifdef __TANDEM
498 # include <floss.h(floss_read,floss_write,floss_fork,floss_execvp)>
499 # include <floss.h(floss_getpwuid,floss_select,floss_seteuid)>
500 # define S_IEXEC S_IXUSR
501 # define ROOT_UID 65535
502 #else
503 # define ROOT_UID 0
504 #endif
505
506 #ifdef HAVE_COMPAT_H
507 #include <compat.h>
508 #endif
509
510 #ifdef HAVE_LIMITS_H
511 # include <limits.h>
512 #endif
513
514 #if defined USE_ICONV_OPEN && defined HAVE_ICONV_H
515 #include <iconv.h>
516 #ifndef ICONV_CONST
517 #define ICONV_CONST
518 #endif
519 #else
520 #ifdef ICONV_CONST
521 #undef ICONV_CONST
522 #endif
523 #ifdef ICONV_OPTION
524 #undef ICONV_OPTION
525 #endif
526 #ifdef iconv_t
527 #undef iconv_t
528 #endif
529 #define iconv_t int
530 #endif
531
532 #include <assert.h>
533
534 #include "lib/pool_alloc.h"
535
536 #ifndef HAVE_ID_T
537 typedef unsigned int id_t;
538 #endif
539 #ifndef HAVE_PID_T
540 typedef int pid_t;
541 #endif
542 #ifndef HAVE_MODE_T
543 typedef unsigned int mode_t;
544 #endif
545 #ifndef HAVE_OFF_T
546 typedef long off_t;
547 #undef SIZEOF_OFF_T
548 #define SIZEOF_OFF_T SIZEOF_LONG
549 #endif
550 #ifndef HAVE_SIZE_T
551 typedef unsigned int size_t;
552 #endif
553
554 #define BOOL int
555
556 #ifndef uchar
557 #define uchar unsigned char
558 #endif
559
560 #ifdef SIGNED_CHAR_OK
561 #define schar signed char
562 #else
563 #define schar char
564 #endif
565
566 #ifndef int16
567 #if SIZEOF_INT16_T == 2
568 # define int16 int16_t
569 #else
570 # define int16 short
571 #endif
572 #endif
573
574 #ifndef uint16
575 #if SIZEOF_UINT16_T == 2
576 # define uint16 uint16_t
577 #else
578 # define uint16 unsigned int16
579 #endif
580 #endif
581
582 #if !defined __APPLE__ || defined HAVE_GETATTRLIST
583 #define SUPPORT_ATIMES 1
584 #endif
585
586 #if defined HAVE_GETATTRLIST || defined __CYGWIN__
587 #define SUPPORT_CRTIMES 1
588 #endif
589
590 /* Find a variable that is either exactly 32-bits or longer.
591  * If some code depends on 32-bit truncation, it will need to
592  * take special action in a "#if SIZEOF_INT32 > 4" section. */
593 #ifndef int32
594 #if SIZEOF_INT32_T == 4
595 # define int32 int32_t
596 # define SIZEOF_INT32 4
597 #elif SIZEOF_INT == 4
598 # define int32 int
599 # define SIZEOF_INT32 4
600 #elif SIZEOF_LONG == 4
601 # define int32 long
602 # define SIZEOF_INT32 4
603 #elif SIZEOF_SHORT == 4
604 # define int32 short
605 # define SIZEOF_INT32 4
606 #elif SIZEOF_INT > 4
607 # define int32 int
608 # define SIZEOF_INT32 SIZEOF_INT
609 #elif SIZEOF_LONG > 4
610 # define int32 long
611 # define SIZEOF_INT32 SIZEOF_LONG
612 #else
613 # error Could not find a 32-bit integer variable
614 #endif
615 #else
616 # define SIZEOF_INT32 4
617 #endif
618
619 #ifndef uint32
620 #if SIZEOF_UINT32_T == 4
621 # define uint32 uint32_t
622 #else
623 # define uint32 unsigned int32
624 #endif
625 #endif
626
627 #if SIZEOF_OFF_T == 8 || !SIZEOF_OFF64_T || !defined HAVE_STRUCT_STAT64
628 #define OFF_T off_t
629 #define STRUCT_STAT struct stat
630 #define SIZEOF_CAPITAL_OFF_T SIZEOF_OFF_T
631 #else
632 #define OFF_T off64_t
633 #define STRUCT_STAT struct stat64
634 #define USE_STAT64_FUNCS 1
635 #define SIZEOF_CAPITAL_OFF_T SIZEOF_OFF64_T
636 #endif
637
638 /* CAVEAT: on some systems, int64 will really be a 32-bit integer IFF
639  * that's the maximum size the file system can handle and there is no
640  * 64-bit type available.  The rsync source must therefore take steps
641  * to ensure that any code that really requires a 64-bit integer has
642  * it (e.g. the checksum code uses two 32-bit integers for its 64-bit
643  * counter). */
644 #if SIZEOF_INT64_T == 8
645 # define int64 int64_t
646 # define SIZEOF_INT64 8
647 #elif SIZEOF_LONG == 8
648 # define int64 long
649 # define SIZEOF_INT64 8
650 #elif SIZEOF_INT == 8
651 # define int64 int
652 # define SIZEOF_INT64 8
653 #elif SIZEOF_LONG_LONG == 8
654 # define int64 long long
655 # define SIZEOF_INT64 8
656 #elif SIZEOF_OFF64_T == 8
657 # define int64 off64_t
658 # define SIZEOF_INT64 8
659 #elif SIZEOF_OFF_T == 8
660 # define int64 off_t
661 # define SIZEOF_INT64 8
662 #elif SIZEOF_INT > 8
663 # define int64 int
664 # define SIZEOF_INT64 SIZEOF_INT
665 #elif SIZEOF_LONG > 8
666 # define int64 long
667 # define SIZEOF_INT64 SIZEOF_LONG
668 #elif SIZEOF_LONG_LONG > 8
669 # define int64 long long
670 # define SIZEOF_INT64 SIZEOF_LONG_LONG
671 #else
672 /* As long as it gets... */
673 # define int64 off_t
674 # define SIZEOF_INT64 SIZEOF_OFF_T
675 #endif
676
677 #define HT_KEY32 0
678 #define HT_KEY64 1
679
680 struct hashtable {
681         void *nodes;
682         int32 size, entries;
683         uint32 node_size;
684         short key64;
685 };
686
687 struct ht_int32_node {
688         void *data;
689         int32 key;
690 };
691
692 struct ht_int64_node {
693         void *data;
694         int64 key;
695 };
696
697 #define HT_NODE(tbl, bkts, i) ((void*)((char*)(bkts) + (i)*(tbl)->node_size))
698 #define HT_KEY(node, k64) ((k64)? ((struct ht_int64_node*)(node))->key \
699                          : (int64)((struct ht_int32_node*)(node))->key)
700
701 #ifndef MIN
702 #define MIN(a,b) ((a)<(b)?(a):(b))
703 #endif
704
705 #ifndef MAX
706 #define MAX(a,b) ((a)>(b)?(a):(b))
707 #endif
708
709 #ifndef MAXHOSTNAMELEN
710 #define MAXHOSTNAMELEN 256
711 #endif
712
713 #define SUM_LENGTH 16
714 #define SHORT_SUM_LENGTH 2
715 #define BLOCKSUM_BIAS 10
716
717 #ifndef MAXPATHLEN
718 #define MAXPATHLEN 1024
719 #endif
720
721 /* We want a roomy line buffer that can hold more than MAXPATHLEN,
722  * and significantly more than an overly short MAXPATHLEN. */
723 #if MAXPATHLEN < 4096
724 #define BIGPATHBUFLEN (4096+1024)
725 #else
726 #define BIGPATHBUFLEN (MAXPATHLEN+1024)
727 #endif
728
729 #ifndef NAME_MAX
730 #define NAME_MAX 255
731 #endif
732
733 #ifndef SIZE_MAX
734 #define SIZE_MAX ((size_t)-1)
735 #endif
736
737 #ifndef INADDR_NONE
738 #define INADDR_NONE 0xffffffff
739 #endif
740
741 #ifndef IN_LOOPBACKNET
742 #define IN_LOOPBACKNET 127
743 #endif
744
745 #if HAVE_UNIXWARE_ACLS|HAVE_SOLARIS_ACLS|HAVE_HPUX_ACLS
746 #define ACLS_NEED_MASK 1
747 #endif
748
749 #if defined HAVE_FALLOCATE || HAVE_SYS_FALLOCATE
750 #ifdef HAVE_LINUX_FALLOC_H
751 #include <linux/falloc.h>
752 #endif
753 #ifdef FALLOC_FL_KEEP_SIZE
754 #define SUPPORT_PREALLOCATION 1
755 #elif defined HAVE_FTRUNCATE
756 #define SUPPORT_PREALLOCATION 1
757 #define PREALLOCATE_NEEDS_TRUNCATE 1
758 #endif
759 #else /* !fallocate */
760 #if defined HAVE_EFFICIENT_POSIX_FALLOCATE && defined HAVE_FTRUNCATE
761 #define SUPPORT_PREALLOCATION 1
762 #define PREALLOCATE_NEEDS_TRUNCATE 1
763 #endif
764 #endif
765
766 #if SIZEOF_CHARP == 4
767 # define PTRS_ARE_32 1
768 # define PTR_EXTRA_CNT 1
769 #elif SIZEOF_CHARP == 8
770 # define PTRS_ARE_64 1
771 # define PTR_EXTRA_CNT EXTRA64_CNT
772 #else
773 # error Character pointers are not 4 or 8 bytes.
774 #endif
775
776 #if defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L
777 #define USE_FLEXIBLE_ARRAY 1
778 #define SIZE_T_FMT_MOD "z" /* printf supports %zd */
779 #define SIZE_T_FMT_CAST size_t
780 #else
781 #define SIZE_T_FMT_MOD "l" /* printf supports %ld */
782 #define SIZE_T_FMT_CAST long
783 #endif
784
785 union file_extras {
786         int32 num;
787         uint32 unum;
788 #ifdef PTRS_ARE_32
789         const char* ptr;
790 #endif
791 };
792
793 union file_extras64 {
794         int64 num;
795 #ifdef PTRS_ARE_64
796         const char* ptr;
797 #endif
798 };
799
800 struct file_struct {
801         const char *dirname;    /* The dir info inside the transfer */
802         time_t modtime;         /* When the item was last modified */
803         uint32 len32;           /* Lowest 32 bits of the file's length */
804         uint16 mode;            /* The item's type and permissions */
805         uint16 flags;           /* The FLAG_* bits for this item */
806 #ifdef USE_FLEXIBLE_ARRAY
807         const char basename[];  /* The basename (AKA filename) follows */
808 #else
809         const char basename[1]; /* A kluge that should work like a flexible array */
810 #endif
811 };
812
813 extern int file_extra_cnt;
814 extern int inc_recurse;
815 extern int atimes_ndx;
816 extern int crtimes_ndx;
817 extern int pathname_ndx;
818 extern int depth_ndx;
819 extern int uid_ndx;
820 extern int gid_ndx;
821 extern int acls_ndx;
822 extern int xattrs_ndx;
823 extern int file_sum_extra_cnt;
824
825 #ifdef USE_FLEXIBLE_ARRAY
826 #define FILE_STRUCT_LEN (sizeof (struct file_struct))
827 #else
828 #define FILE_STRUCT_LEN (offsetof(struct file_struct, basename))
829 #endif
830 #define EXTRA_LEN (sizeof (union file_extras))
831 #define DEV_EXTRA_CNT 2
832 #define DIRNODE_EXTRA_CNT 3
833 #define EXTRA64_CNT ((sizeof (union file_extras64) + EXTRA_LEN - 1) / EXTRA_LEN)
834 #define SUM_EXTRA_CNT file_sum_extra_cnt
835
836 #define REQ_EXTRA(f,ndx) ((union file_extras*)(f) - (ndx))
837 #define OPT_EXTRA(f,bump) ((union file_extras*)(f) - file_extra_cnt - 1 - (bump))
838
839 /* These are guaranteed to be allocated first in the array so that they
840  * are aligned for direct int64-pointer access. */
841 #define REQ_EXTRA64(f,ndx) ((union file_extras64*)REQ_EXTRA(f,ndx))
842
843 #define NSEC_BUMP(f) ((f)->flags & FLAG_MOD_NSEC ? 1 : 0)
844 #define LEN64_BUMP(f) ((f)->flags & FLAG_LENGTH64 ? 1 : 0)
845 #define START_BUMP(f) (NSEC_BUMP(f) + LEN64_BUMP(f))
846 #define HLINK_BUMP(f) ((f)->flags & (FLAG_HLINKED|FLAG_HLINK_DONE) ? inc_recurse+1 : 0)
847 #define ACL_BUMP(f) (acls_ndx ? 1 : 0)
848
849 /* The length applies to all items. */
850 #if SIZEOF_INT64 < 8
851 #define F_LENGTH(f) ((int64)(f)->len32)
852 #else
853 #define F_HIGH_LEN(f) (OPT_EXTRA(f, NSEC_BUMP(f))->unum)
854 #define F_LENGTH(f) ((int64)(f)->len32 + ((f)->flags & FLAG_LENGTH64 ? (int64)F_HIGH_LEN(f) << 32 : 0))
855 #endif
856
857 #define F_MOD_NSEC(f) OPT_EXTRA(f, 0)->unum
858 #define F_MOD_NSEC_or_0(f) ((f)->flags & FLAG_MOD_NSEC ? F_MOD_NSEC(f) : 0)
859
860 /* If there is a symlink string, it is always right after the basename */
861 #define F_SYMLINK(f) ((f)->basename + strlen((f)->basename) + 1)
862
863 /* The sending side always has this available: */
864 #ifdef PTRS_ARE_32
865 #define F_PATHNAME(f) REQ_EXTRA(f, pathname_ndx)->ptr
866 #else
867 #define F_PATHNAME(f) REQ_EXTRA64(f, pathname_ndx)->ptr
868 #endif
869
870 /* The receiving side always has this available: */
871 #define F_DEPTH(f) REQ_EXTRA(f, depth_ndx)->num
872
873 /* When the associated option is on, all entries will have these present: */
874 #define F_OWNER(f) REQ_EXTRA(f, uid_ndx)->unum
875 #define F_GROUP(f) REQ_EXTRA(f, gid_ndx)->unum
876 #define F_ACL(f) REQ_EXTRA(f, acls_ndx)->num
877 #define F_XATTR(f) REQ_EXTRA(f, xattrs_ndx)->num
878 #define F_NDX(f) REQ_EXTRA(f, unsort_ndx)->num
879 #define F_ATIME(f) REQ_EXTRA64(f, atimes_ndx)->num
880 #define F_CRTIME(f) REQ_EXTRA64(f, crtimes_ndx)->num
881
882 /* These items are per-entry optional: */
883 #define F_HL_GNUM(f) OPT_EXTRA(f, START_BUMP(f))->num /* non-dirs */
884 #define F_HL_PREV(f) OPT_EXTRA(f, START_BUMP(f)+inc_recurse)->num /* non-dirs */
885 #define F_DIR_NODE_P(f) (&OPT_EXTRA(f, START_BUMP(f) \
886                                 + DIRNODE_EXTRA_CNT - 1)->num) /* sender dirs */
887 #define F_DIR_RELNAMES_P(f) (&OPT_EXTRA(f, START_BUMP(f) + DIRNODE_EXTRA_CNT \
888                                 + PTR_EXTRA_CNT - 1)->num) /* sender dirs */
889 #define F_DIR_DEFACL(f) OPT_EXTRA(f, START_BUMP(f))->unum /* receiver dirs */
890 #define F_DIR_DEV_P(f) (&OPT_EXTRA(f, START_BUMP(f) + ACL_BUMP(f) \
891                                 + DEV_EXTRA_CNT - 1)->unum) /* receiver dirs */
892
893 /* This optional item might follow an F_HL_*() item. */
894 #define F_RDEV_P(f) (&OPT_EXTRA(f, START_BUMP(f) + HLINK_BUMP(f) + DEV_EXTRA_CNT - 1)->unum)
895
896 /* The sum is only present on regular files. */
897 #define F_SUM(f) ((char*)OPT_EXTRA(f, START_BUMP(f) + HLINK_BUMP(f) \
898                                     + SUM_EXTRA_CNT - 1))
899
900 /* Some utility defines: */
901 #define F_IS_ACTIVE(f) (f)->basename[0]
902 #define F_IS_HLINKED(f) ((f)->flags & FLAG_HLINKED)
903
904 #define F_HLINK_NOT_FIRST(f) BITS_SETnUNSET((f)->flags, FLAG_HLINKED, FLAG_HLINK_FIRST)
905 #define F_HLINK_NOT_LAST(f) BITS_SETnUNSET((f)->flags, FLAG_HLINKED, FLAG_HLINK_LAST)
906
907 /* These access the F_DIR_DEV_P() and F_RDEV_P() values: */
908 #define DEV_MAJOR(a) (a)[0]
909 #define DEV_MINOR(a) (a)[1]
910
911 /* These access the F_DIRS_NODE_P() values: */
912 #define DIR_PARENT(a) (a)[0]
913 #define DIR_FIRST_CHILD(a) (a)[1]
914 #define DIR_NEXT_SIBLING(a) (a)[2]
915
916 #define IS_MISSING_FILE(statbuf) ((statbuf).st_mode == 0)
917
918 /*
919  * Start the flist array at FLIST_START entries and grow it
920  * by doubling until FLIST_LINEAR then grow by FLIST_LINEAR
921  */
922 #define FLIST_START             (32)
923 #define FLIST_START_LARGE       (32 * 1024)
924 #define FLIST_LINEAR            (FLIST_START_LARGE * 512)
925
926 /*
927  * Extent size for allocation pools: A minimum size of 128KB
928  * is needed to mmap them so that freeing will release the
929  * space to the OS.
930  *
931  * Larger sizes reduce leftover fragments and speed free calls
932  * (when they happen). Smaller sizes increase the chance of
933  * freed allocations freeing whole extents.
934  */
935 #define NORMAL_EXTENT   (256 * 1024)
936 #define SMALL_EXTENT    (128 * 1024)
937
938 #define FLIST_TEMP      (1<<1)
939
940 struct file_list {
941         struct file_list *next, *prev;
942         struct file_struct **files, **sorted;
943         alloc_pool_t file_pool;
944         void *pool_boundary;
945         int used, malloced;
946         int low, high;  /* 0-relative index values excluding empties */
947         int ndx_start;  /* the start offset for inc_recurse mode */
948         int flist_num;  /* 1-relative file_list number or 0 */
949         int parent_ndx; /* dir_flist index of parent directory */
950         int in_progress, to_redo;
951 };
952
953 #define SUMFLG_SAME_OFFSET      (1<<0)
954
955 struct sum_buf {
956         OFF_T offset;           /**< offset in file of this chunk */
957         int32 len;              /**< length of chunk of file */
958         uint32 sum1;            /**< simple checksum */
959         int32 chain;            /**< next hash-table collision */
960         short flags;            /**< flag bits */
961         char sum2[SUM_LENGTH];  /**< checksum  */
962 };
963
964 struct sum_struct {
965         OFF_T flength;          /**< total file length */
966         struct sum_buf *sums;   /**< points to info for each chunk */
967         int32 count;            /**< how many chunks */
968         int32 blength;          /**< block_length */
969         int32 remainder;        /**< flength % block_length */
970         int s2length;           /**< sum2_length */
971 };
972
973 struct map_struct {
974         OFF_T file_size;        /* File size (from stat)                */
975         OFF_T p_offset;         /* Window start                         */
976         OFF_T p_fd_offset;      /* offset of cursor in fd ala lseek     */
977         char *p;                /* Window pointer                       */
978         int32 p_size;           /* Largest window size we allocated     */
979         int32 p_len;            /* Latest (rounded) window size         */
980         int32 def_window_size;  /* Default window size                  */
981         int fd;                 /* File Descriptor                      */
982         int status;             /* first errno from read errors         */
983 };
984
985 #define NAME_IS_FILE            (0)    /* filter name as a file */
986 #define NAME_IS_DIR             (1<<0) /* filter name as a dir */
987 #define NAME_IS_XATTR           (1<<2) /* filter name as an xattr */
988
989 #define FILTRULE_WILD           (1<<0) /* pattern has '*', '[', and/or '?' */
990 #define FILTRULE_WILD2          (1<<1) /* pattern has '**' */
991 #define FILTRULE_WILD2_PREFIX   (1<<2) /* pattern starts with "**" */
992 #define FILTRULE_WILD3_SUFFIX   (1<<3) /* pattern ends with "***" */
993 #define FILTRULE_ABS_PATH       (1<<4) /* path-match on absolute path */
994 #define FILTRULE_INCLUDE        (1<<5) /* this is an include, not an exclude */
995 #define FILTRULE_DIRECTORY      (1<<6) /* this matches only directories */
996 #define FILTRULE_WORD_SPLIT     (1<<7) /* split rules on whitespace */
997 #define FILTRULE_NO_INHERIT     (1<<8) /* don't inherit these rules */
998 #define FILTRULE_NO_PREFIXES    (1<<9) /* parse no prefixes from patterns */
999 #define FILTRULE_MERGE_FILE     (1<<10)/* specifies a file to merge */
1000 #define FILTRULE_PERDIR_MERGE   (1<<11)/* merge-file is searched per-dir */
1001 #define FILTRULE_EXCLUDE_SELF   (1<<12)/* merge-file name should be excluded */
1002 #define FILTRULE_FINISH_SETUP   (1<<13)/* per-dir merge file needs setup */
1003 #define FILTRULE_NEGATE         (1<<14)/* rule matches when pattern does not */
1004 #define FILTRULE_CVS_IGNORE     (1<<15)/* rule was -C or :C */
1005 #define FILTRULE_SENDER_SIDE    (1<<16)/* rule applies to the sending side */
1006 #define FILTRULE_RECEIVER_SIDE  (1<<17)/* rule applies to the receiving side */
1007 #define FILTRULE_CLEAR_LIST     (1<<18)/* this item is the "!" token */
1008 #define FILTRULE_PERISHABLE     (1<<19)/* perishable if parent dir goes away */
1009 #define FILTRULE_XATTR          (1<<20)/* rule only applies to xattr names */
1010
1011 #define FILTRULES_SIDES (FILTRULE_SENDER_SIDE | FILTRULE_RECEIVER_SIDE)
1012
1013 typedef struct filter_struct {
1014         struct filter_struct *next;
1015         char *pattern;
1016         uint32 rflags;
1017         union {
1018                 int slash_cnt;
1019                 struct filter_list_struct *mergelist;
1020         } u;
1021         uchar elide;
1022 } filter_rule;
1023
1024 typedef struct filter_list_struct {
1025         filter_rule *head;
1026         filter_rule *tail;
1027         char *debug_type;
1028 } filter_rule_list;
1029
1030 struct stats {
1031         int64 total_size;
1032         int64 total_transferred_size;
1033         int64 total_written;
1034         int64 total_read;
1035         int64 literal_data;
1036         int64 matched_data;
1037         int64 flist_buildtime;
1038         int64 flist_xfertime;
1039         int64 flist_size;
1040         int num_files, num_dirs, num_symlinks, num_devices, num_specials;
1041         int created_files, created_dirs, created_symlinks, created_devices, created_specials;
1042         int deleted_files, deleted_dirs, deleted_symlinks, deleted_devices, deleted_specials;
1043         int xferred_files;
1044 };
1045
1046 struct chmod_mode_struct;
1047
1048 struct flist_ndx_item {
1049         struct flist_ndx_item *next;
1050         int ndx;
1051 };
1052
1053 typedef struct {
1054         struct flist_ndx_item *head, *tail;
1055 } flist_ndx_list;
1056
1057 #define EMPTY_ITEM_LIST {NULL, 0, 0}
1058
1059 typedef struct {
1060         void *items;
1061         size_t count;
1062         size_t malloced;
1063 } item_list;
1064
1065 #define EXPAND_ITEM_LIST(lp, type, incr) \
1066         (type*)expand_item_list(lp, sizeof (type), #type, incr)
1067
1068 #define EMPTY_XBUF {NULL, 0, 0, 0}
1069
1070 typedef struct {
1071         char *buf;
1072         size_t pos;  /* pos = read pos in the buf */
1073         size_t len;  /* len = chars following pos */
1074         size_t size; /* size = total space in buf */
1075 } xbuf;
1076
1077 #define INIT_XBUF(xb, str, ln, sz) (xb).buf = (str), (xb).len = (ln), (xb).size = (sz), (xb).pos = 0
1078 #define INIT_XBUF_STRLEN(xb, str) (xb).buf = (str), (xb).len = strlen((xb).buf), (xb).size = (size_t)-1, (xb).pos = 0
1079 /* This one is used to make an output xbuf based on a char[] buffer: */
1080 #define INIT_CONST_XBUF(xb, bf) (xb).buf = (bf), (xb).size = sizeof (bf), (xb).len = (xb).pos = 0
1081
1082 #define ICB_EXPAND_OUT (1<<0)
1083 #define ICB_INCLUDE_BAD (1<<1)
1084 #define ICB_INCLUDE_INCOMPLETE (1<<2)
1085 #define ICB_CIRCULAR_OUT (1<<3)
1086 #define ICB_INIT (1<<4)
1087
1088 #define IOBUF_KEEP_BUFS 0
1089 #define IOBUF_FREE_BUFS 1
1090
1091 #define MPLX_SWITCHING IOBUF_KEEP_BUFS
1092 #define MPLX_ALL_DONE IOBUF_FREE_BUFS
1093 #define MPLX_TO_BUFFERED 2
1094
1095 #define RL_EOL_NULLS (1<<0)
1096 #define RL_DUMP_COMMENTS (1<<1)
1097 #define RL_CONVERT (1<<2)
1098
1099 typedef struct {
1100         char name_type;
1101 #ifdef USE_FLEXIBLE_ARRAY
1102         char fname[]; /* has variable size */
1103 #else
1104         char fname[1]; /* A kluge that should work like a flexible array */
1105 #endif
1106 } relnamecache;
1107
1108 #ifdef USE_FLEXIBLE_ARRAY
1109 #define RELNAMECACHE_LEN (sizeof (relnamecache))
1110 #else
1111 #define RELNAMECACHE_LEN (offsetof(relnamecache, fname))
1112 #endif
1113
1114 #include "byteorder.h"
1115 #include "lib/mdigest.h"
1116 #include "lib/wildmatch.h"
1117 #include "lib/permstring.h"
1118 #include "lib/addrinfo.h"
1119
1120 #ifndef __GNUC__
1121 #define __attribute__(x)
1122 #else
1123 # if __GNUC__ <= 2
1124 # define NORETURN
1125 # endif
1126 #endif
1127
1128 #define UNUSED(x) x __attribute__((__unused__))
1129 #ifndef NORETURN
1130 #define NORETURN __attribute__((__noreturn__))
1131 #endif
1132
1133 typedef struct {
1134     STRUCT_STAT st;
1135     time_t crtime;
1136 #ifdef SUPPORT_ACLS
1137     struct rsync_acl *acc_acl; /* access ACL */
1138     struct rsync_acl *def_acl; /* default ACL */
1139 #endif
1140 #ifdef SUPPORT_XATTRS
1141     item_list *xattr;
1142 #endif
1143 } stat_x;
1144
1145 #define ACL_READY(sx) ((sx).acc_acl != NULL)
1146 #define XATTR_READY(sx) ((sx).xattr != NULL)
1147
1148 #define CLVL_NOT_SPECIFIED INT_MIN
1149
1150 #define CPRES_AUTO (-1)
1151 #define CPRES_NONE 0
1152 #define CPRES_ZLIB 1
1153 #define CPRES_ZLIBX 2
1154 #define CPRES_LZ4 3
1155 #define CPRES_ZSTD 4
1156
1157 #define NSTR_CHECKSUM 0
1158 #define NSTR_COMPRESS 1
1159
1160 struct name_num_item {
1161         int num, flags;
1162         const char *name;
1163         struct name_num_item *main_nni;
1164 };
1165
1166 struct name_num_obj {
1167         const char *type;
1168         struct name_num_item *negotiated_nni;
1169         uchar *saw;
1170         int saw_len;
1171         struct name_num_item *list;
1172 };
1173
1174 #ifdef EXTERNAL_ZLIB
1175 #define read_buf read_buf_
1176 #endif
1177
1178 #ifndef __cplusplus
1179 #include "proto.h"
1180 #endif
1181
1182 #ifndef SUPPORT_XATTRS
1183 #define x_stat(fn,fst,xst) do_stat(fn,fst)
1184 #define x_lstat(fn,fst,xst) do_lstat(fn,fst)
1185 #define x_fstat(fd,fst,xst) do_fstat(fd,fst)
1186 #endif
1187
1188 /* We have replacement versions of these if they're missing. */
1189 #ifndef HAVE_ASPRINTF
1190 int asprintf(char **ptr, const char *format, ...);
1191 #endif
1192
1193 #ifndef HAVE_VASPRINTF
1194 int vasprintf(char **ptr, const char *format, va_list ap);
1195 #endif
1196
1197 #if !defined HAVE_VSNPRINTF || !defined HAVE_C99_VSNPRINTF
1198 #define vsnprintf rsync_vsnprintf
1199 int vsnprintf(char *str, size_t count, const char *fmt, va_list args);
1200 #endif
1201
1202 #if !defined HAVE_SNPRINTF || !defined HAVE_C99_VSNPRINTF
1203 #define snprintf rsync_snprintf
1204 int snprintf(char *str, size_t count, const char *fmt,...);
1205 #endif
1206
1207 #ifndef HAVE_STRERROR
1208 extern char *sys_errlist[];
1209 #define strerror(i) sys_errlist[i]
1210 #endif
1211
1212 #ifndef HAVE_STRCHR
1213 # define strchr                 index
1214 # define strrchr                rindex
1215 #endif
1216
1217 #ifndef HAVE_ERRNO_DECL
1218 extern int errno;
1219 #endif
1220
1221 #ifdef HAVE_READLINK
1222 #define SUPPORT_LINKS 1
1223 #if !defined NO_SYMLINK_XATTRS && !defined NO_SYMLINK_USER_XATTRS
1224 #define do_readlink(path, buf, bufsiz) readlink(path, buf, bufsiz)
1225 #endif
1226 #endif
1227 #ifdef HAVE_LINK
1228 #define SUPPORT_HARD_LINKS 1
1229 #endif
1230
1231 #ifdef HAVE_SIGACTION
1232 #define SIGACTION(n,h) sigact.sa_handler=(h), sigaction((n),&sigact,NULL)
1233 #define signal(n,h) we_need_to_call_SIGACTION_not_signal(n,h)
1234 #else
1235 #define SIGACTION(n,h) signal(n,h)
1236 #endif
1237
1238 #ifndef EWOULDBLOCK
1239 #define EWOULDBLOCK EAGAIN
1240 #endif
1241
1242 #ifndef STDIN_FILENO
1243 #define STDIN_FILENO 0
1244 #endif
1245
1246 #ifndef STDOUT_FILENO
1247 #define STDOUT_FILENO 1
1248 #endif
1249
1250 #ifndef STDERR_FILENO
1251 #define STDERR_FILENO 2
1252 #endif
1253
1254 #ifndef S_IRUSR
1255 #define S_IRUSR 0400
1256 #endif
1257
1258 #ifndef S_IWUSR
1259 #define S_IWUSR 0200
1260 #endif
1261
1262 #ifndef ACCESSPERMS
1263 #define ACCESSPERMS 0777
1264 #endif
1265
1266 #ifndef S_ISVTX
1267 #define S_ISVTX 0
1268 #endif
1269
1270 #define CHMOD_BITS (S_ISUID | S_ISGID | S_ISVTX | ACCESSPERMS)
1271
1272 #ifndef _S_IFMT
1273 #define _S_IFMT        0170000
1274 #endif
1275
1276 #ifndef _S_IFLNK
1277 #define _S_IFLNK  0120000
1278 #endif
1279
1280 #ifndef S_ISLNK
1281 #define S_ISLNK(mode) (((mode) & (_S_IFMT)) == (_S_IFLNK))
1282 #endif
1283
1284 #ifndef S_ISBLK
1285 #define S_ISBLK(mode) (((mode) & (_S_IFMT)) == (_S_IFBLK))
1286 #endif
1287
1288 #ifndef S_ISCHR
1289 #define S_ISCHR(mode) (((mode) & (_S_IFMT)) == (_S_IFCHR))
1290 #endif
1291
1292 #ifndef S_ISSOCK
1293 #ifdef _S_IFSOCK
1294 #define S_ISSOCK(mode) (((mode) & (_S_IFMT)) == (_S_IFSOCK))
1295 #else
1296 #define S_ISSOCK(mode) (0)
1297 #endif
1298 #endif
1299
1300 #ifndef S_ISFIFO
1301 #ifdef _S_IFIFO
1302 #define S_ISFIFO(mode) (((mode) & (_S_IFMT)) == (_S_IFIFO))
1303 #else
1304 #define S_ISFIFO(mode) (0)
1305 #endif
1306 #endif
1307
1308 #ifndef S_ISDIR
1309 #define S_ISDIR(mode) (((mode) & (_S_IFMT)) == (_S_IFDIR))
1310 #endif
1311
1312 #ifndef S_ISREG
1313 #define S_ISREG(mode) (((mode) & (_S_IFMT)) == (_S_IFREG))
1314 #endif
1315
1316 /* work out what fcntl flag to use for non-blocking */
1317 #ifdef O_NONBLOCK
1318 # define NONBLOCK_FLAG O_NONBLOCK
1319 #elif defined SYSV
1320 # define NONBLOCK_FLAG O_NDELAY
1321 #else
1322 # define NONBLOCK_FLAG FNDELAY
1323 #endif
1324
1325 #ifndef INADDR_LOOPBACK
1326 #define INADDR_LOOPBACK 0x7f000001
1327 #endif
1328
1329 #ifndef INADDR_NONE
1330 #define INADDR_NONE 0xffffffff
1331 #endif
1332
1333 #define IS_SPECIAL(mode) (S_ISSOCK(mode) || S_ISFIFO(mode))
1334 #define IS_DEVICE(mode) (S_ISCHR(mode) || S_ISBLK(mode))
1335
1336 /* Initial mask on permissions given to temporary files.  Mask off setuid
1337      bits and group access because of potential race-condition security
1338      holes, and mask other access because mode 707 is bizarre */
1339 #define INITACCESSPERMS 0700
1340
1341 /* handler for null strings in printf format */
1342 #define NS(s) ((s)?(s):"<NULL>")
1343
1344 extern char *do_calloc;
1345
1346 /* Convenient wrappers for malloc and realloc.  Use them. */
1347 #define new(type) ((type*)my_alloc(NULL, sizeof (type), 1, __FILE__, __LINE__))
1348 #define new0(type) ((type*)my_alloc(do_calloc, sizeof (type), 1, __FILE__, __LINE__))
1349 #define realloc_buf(ptr, num) my_alloc((ptr), (num), 1, __FILE__, __LINE__)
1350
1351 #define new_array(type, num) ((type*)my_alloc(NULL, (num), sizeof (type), __FILE__, __LINE__))
1352 #define new_array0(type, num) ((type*)my_alloc(do_calloc, (num), sizeof (type), __FILE__, __LINE__))
1353 #define realloc_array(ptr, type, num) ((type*)my_alloc((ptr), (num), sizeof (type), __FILE__, __LINE__))
1354
1355 #undef strdup
1356 #define strdup(s) my_strdup(s, __FILE__, __LINE__)
1357
1358 #define out_of_memory(msg) _out_of_memory(msg, __FILE__, __LINE__)
1359 #define overflow_exit(msg) _overflow_exit(msg, __FILE__, __LINE__)
1360
1361 /* use magic gcc attributes to catch format errors */
1362  void rprintf(enum logcode , const char *, ...)
1363      __attribute__((format (printf, 2, 3)))
1364 ;
1365
1366 /* This is just like rprintf, but it also tries to print some
1367  * representation of the error code.  Normally errcode = errno. */
1368 void rsyserr(enum logcode, int, const char *, ...)
1369      __attribute__((format (printf, 3, 4)))
1370      ;
1371
1372 /* Make sure that the O_BINARY flag is defined. */
1373 #ifndef O_BINARY
1374 #define O_BINARY 0
1375 #endif
1376
1377 #ifndef HAVE_STRLCPY
1378 size_t strlcpy(char *d, const char *s, size_t bufsize);
1379 #endif
1380
1381 #ifndef HAVE_STRLCAT
1382 size_t strlcat(char *d, const char *s, size_t bufsize);
1383 #endif
1384
1385 #ifndef WEXITSTATUS
1386 #define WEXITSTATUS(stat)       ((int)(((stat)>>8)&0xFF))
1387 #endif
1388 #ifndef WIFEXITED
1389 #define WIFEXITED(stat)         ((int)((stat)&0xFF) == 0)
1390 #endif
1391
1392 #define exit_cleanup(code) _exit_cleanup(code, __FILE__, __LINE__)
1393
1394 #ifdef HAVE_GETEUID
1395 #define MY_UID() geteuid()
1396 #else
1397 #define MY_UID() getuid()
1398 #endif
1399
1400 #ifdef HAVE_GETEGID
1401 #define MY_GID() getegid()
1402 #else
1403 #define MY_GID() getgid()
1404 #endif
1405
1406 #ifdef FORCE_FD_ZERO_MEMSET
1407 #undef FD_ZERO
1408 #define FD_ZERO(fdsetp) memset(fdsetp, 0, sizeof (fd_set))
1409 #endif
1410
1411 extern short info_levels[], debug_levels[];
1412
1413 #define INFO_GTE(flag, lvl) (info_levels[INFO_##flag] >= (lvl))
1414 #define INFO_EQ(flag, lvl) (info_levels[INFO_##flag] == (lvl))
1415 #define DEBUG_GTE(flag, lvl) (debug_levels[DEBUG_##flag] >= (lvl))
1416 #define DEBUG_EQ(flag, lvl) (debug_levels[DEBUG_##flag] == (lvl))
1417
1418 #define INFO_BACKUP 0
1419 #define INFO_COPY (INFO_BACKUP+1)
1420 #define INFO_DEL (INFO_COPY+1)
1421 #define INFO_FLIST (INFO_DEL+1)
1422 #define INFO_MISC (INFO_FLIST+1)
1423 #define INFO_MOUNT (INFO_MISC+1)
1424 #define INFO_NAME (INFO_MOUNT+1)
1425 #define INFO_NONREG (INFO_NAME+1)
1426 #define INFO_PROGRESS (INFO_NONREG+1)
1427 #define INFO_REMOVE (INFO_PROGRESS+1)
1428 #define INFO_SKIP (INFO_REMOVE+1)
1429 #define INFO_STATS (INFO_SKIP+1)
1430 #define INFO_SYMSAFE (INFO_STATS+1)
1431
1432 #define COUNT_INFO (INFO_SYMSAFE+1)
1433
1434 #define DEBUG_ACL 0
1435 #define DEBUG_BACKUP (DEBUG_ACL+1)
1436 #define DEBUG_BIND (DEBUG_BACKUP+1)
1437 #define DEBUG_CHDIR (DEBUG_BIND+1)
1438 #define DEBUG_CONNECT (DEBUG_CHDIR+1)
1439 #define DEBUG_CMD (DEBUG_CONNECT+1)
1440 #define DEBUG_DEL (DEBUG_CMD+1)
1441 #define DEBUG_DELTASUM (DEBUG_DEL+1)
1442 #define DEBUG_DUP (DEBUG_DELTASUM+1)
1443 #define DEBUG_EXIT (DEBUG_DUP+1)
1444 #define DEBUG_FILTER (DEBUG_EXIT+1)
1445 #define DEBUG_FLIST (DEBUG_FILTER+1)
1446 #define DEBUG_FUZZY (DEBUG_FLIST+1)
1447 #define DEBUG_GENR (DEBUG_FUZZY+1)
1448 #define DEBUG_HASH (DEBUG_GENR+1)
1449 #define DEBUG_HLINK (DEBUG_HASH+1)
1450 #define DEBUG_ICONV (DEBUG_HLINK+1)
1451 #define DEBUG_IO (DEBUG_ICONV+1)
1452 #define DEBUG_NSTR (DEBUG_IO+1)
1453 #define DEBUG_OWN (DEBUG_NSTR+1)
1454 #define DEBUG_PROTO (DEBUG_OWN+1)
1455 #define DEBUG_RECV (DEBUG_PROTO+1)
1456 #define DEBUG_SEND (DEBUG_RECV+1)
1457 #define DEBUG_TIME (DEBUG_SEND+1)
1458
1459 #define COUNT_DEBUG (DEBUG_TIME+1)
1460
1461 #ifndef HAVE_INET_NTOP
1462 const char *inet_ntop(int af, const void *src, char *dst, size_t size);
1463 #endif
1464
1465 #ifndef HAVE_INET_PTON
1466 int inet_pton(int af, const char *src, void *dst);
1467 #endif
1468
1469 #ifndef HAVE_GETPASS
1470 char *getpass(const char *prompt);
1471 #endif
1472
1473 #ifdef MAINTAINER_MODE
1474 const char *get_panic_action(void);
1475 #endif
1476
1477 #define NOISY_DEATH(msg) do { \
1478     fprintf(stderr, "%s in %s at line %d\n", msg, __FILE__, __LINE__); \
1479     exit_cleanup(RERR_UNSUPPORTED); \
1480 } while (0)
1481
1482 #ifdef HAVE_MALLINFO2
1483 #define MEM_ALLOC_INFO mallinfo2
1484 #elif defined HAVE_MALLINFO
1485 #define MEM_ALLOC_INFO mallinfo
1486 #endif