diff --git a/NEWS.md b/NEWS.md index 9dcfe8d89..034978aa6 100644 --- a/NEWS.md +++ b/NEWS.md @@ -2,6 +2,8 @@ ## Enhancements +- Add local FIFO transfers on supported Linux builds with `--stream-source`. + Require an exact byte count and EOF before replacing a regular destination. - Accept `TCP_CONGESTION=NAME` in socket options on supported Linux builds. Distinguish unknown names, unavailable options and malformed values. - Add `--placement-log` for local receivers to record verified regular files diff --git a/README.md b/README.md index 100bc4dc8..9b34ac90d 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,10 @@ options. To get a complete list of supported options type: See the [manpage][0] for more detailed information. +On supported Linux builds, `--stream-source --stream-size=SIZE` copies one +local named pipe into a regular file. The writer must produce exactly `SIZE` +bytes and close the pipe before rsync can publish the file. + For local transfers to an existing directory, `--compare-dest-per-dir` and `--copy-dest-per-dir` can use files in that tree as bases for missing regular files. The [option reference](rsync.1.md#options) describes their limits. diff --git a/configure.ac b/configure.ac index 5e0da4e1a..a8456b018 100644 --- a/configure.ac +++ b/configure.ac @@ -1043,6 +1043,12 @@ dnl io.c and socket.c include unconditionally, so the HEADER has to dnl be required too: a system that exposes poll() through some other header dnl would otherwise pass configure and then fail to compile. AC_CHECK_FUNCS([poll], , [AC_MSG_ERROR([rsync requires poll(); please report the platform to the rsync developers])]) +case $host_os in + linux*) + AC_CHECK_HEADERS([linux/magic.h sys/vfs.h]) + AC_CHECK_FUNCS([clock_gettime fstatfs]) + ;; +esac if test x"$ac_cv_header_poll_h" != x"yes"; then AC_MSG_ERROR([rsync requires ; please report the platform to the rsync developers]) fi diff --git a/fileio.c b/fileio.c index b8db29b85..be2946abd 100644 --- a/fileio.c +++ b/fileio.c @@ -21,6 +21,9 @@ #include "rsync.h" #include "inums.h" +#ifdef SUPPORT_STREAM_SOURCE +#include +#endif #ifndef ENODATA #define ENODATA EAGAIN @@ -334,6 +337,107 @@ struct map_struct *map_file(int fd, OFF_T len, int32 read_size, int32 blk_size) } +#ifdef SUPPORT_STREAM_SOURCE +static int64 stream_millis(void) +{ + struct timespec now; + + if (clock_gettime(CLOCK_MONOTONIC, &now) < 0) { + rsyserr(FERROR, errno, "cannot read monotonic clock for FIFO input"); + exit_cleanup(RERR_FILEIO); + } + return (int64)now.tv_sec * 1000 + now.tv_nsec / 1000000; +} + +static int32 read_stream(struct map_struct *map, char *buf, int32 len) +{ + int64 deadline = stream_millis() + map->stream_timeout * 1000; + struct pollfd pfd = { map->fd, POLLIN, 0 }; + + /* Linux suppresses POLLHUP on this nonblocking FIFO reader until a + * writer has opened it. Do not interpret a bare read of zero as EOF. */ + for (;;) { + int64 remaining = deadline - stream_millis(); + int ready; + ssize_t n; + + if (remaining <= 0 || (ready = poll(&pfd, 1, (int)remaining)) == 0) { + rprintf(FERROR, "FIFO input timed out after %d seconds waiting for data or EOF\n", + map->stream_timeout); + exit_cleanup(RERR_TIMEOUT); + } + if (ready < 0) { + if (errno == EINTR) + continue; + rsyserr(FERROR, errno, "cannot poll FIFO input"); + exit_cleanup(RERR_FILEIO); + } + if (pfd.revents & (POLLERR | POLLNVAL) || !(pfd.revents & (POLLIN | POLLHUP))) { + rprintf(FERROR, "unexpected FIFO poll events %#x\n", (unsigned int)pfd.revents); + exit_cleanup(RERR_FILEIO); + } + n = read(map->fd, buf, len); + if (n >= 0) + return (int32)n; + if (errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK) { + rsyserr(FERROR, errno, "cannot read FIFO input"); + exit_cleanup(RERR_FILEIO); + } + } +} + +void check_stream_eof(struct map_struct *map) +{ + char extra; + + if (map->p_fd_offset != map->file_size) { + rprintf(FERROR, "FIFO transfer did not read the declared stream size\n"); + exit_cleanup(RERR_FILEIO); + } + if (read_stream(map, &extra, 1) != 0) { + rprintf(FERROR, "FIFO input exceeds --stream-size (%s bytes)\n", big_num(map->file_size)); + exit_cleanup(RERR_FILEIO); + } +} + +static char *map_stream_ptr(struct map_struct *map, OFF_T offset, int32 len) +{ + /* The matcher may look ahead beyond unsent literals. Keep those bytes + * until it has sent and checksummed them rather than seeking backwards. */ + const int32 max_window = 4 * MAX_BLOCK_SIZE + 3 * CHUNK_SIZE + ALIGN_BOUNDARY; + OFF_T start = map->stream_keep - ALIGNED_OVERSHOOT(map->stream_keep); + int32 window, kept; + + if (start < map->p_offset || start > map->p_fd_offset || offset < start + || len > map->file_size - offset || offset - start > max_window - len) { + rprintf(FERROR, "FIFO read exceeds the forward input window\n"); + exit_cleanup(RERR_FILEIO); + } + window = MAX(map->def_window_size, ALIGNED_LENGTH((int32)(offset - start) + len)); + window = (int32)MIN((OFF_T)window, map->file_size - start); + if (window > map->p_size) { + map->p = realloc_array(map->p, char, window); + map->p_size = window; + } + kept = (int32)(map->p_fd_offset - start); + if (kept) + memmove(map->p, map->p + (start - map->p_offset), kept); + while (kept < window) { + int32 n = read_stream(map, map->p + kept, window - kept); + if (!n) { + rprintf(FERROR, "FIFO input ended before --stream-size at %s of %s bytes\n", + big_num(map->p_fd_offset), big_num(map->file_size)); + exit_cleanup(RERR_FILEIO); + } + map->p_fd_offset += n; + kept += n; + } + map->p_offset = start; + map->p_len = window; + return map->p + (offset - start); +} +#endif + /* slide the read window in the file */ char *map_ptr(struct map_struct *map, OFF_T offset, int32 len) { @@ -352,6 +456,11 @@ char *map_ptr(struct map_struct *map, OFF_T offset, int32 len) if (offset >= map->p_offset && offset+len <= map->p_offset+map->p_len) return map->p + (offset - map->p_offset); +#ifdef SUPPORT_STREAM_SOURCE + if (map->stream_timeout) + return map_stream_ptr(map, offset, len); +#endif + /* nope, we are going to have to do a read. Work out our desired window */ align_fudge = (int32)ALIGNED_OVERSHOOT(offset); window_start = offset - align_fudge; diff --git a/flist.c b/flist.c index 08fe90505..5e2449f41 100644 --- a/flist.c +++ b/flist.c @@ -51,6 +51,8 @@ extern char *files_from; extern char *skip_dir_marker; extern int one_file_system; extern int copy_devices; +extern int stream_source; +extern OFF_T stream_size; extern int copy_dirlinks; extern int preserve_uid; extern int preserve_gid; @@ -1697,7 +1699,12 @@ struct file_struct *make_file(const char *fname, struct file_list *flist, if (sanitize_paths) sanitize_path(thisname, thisname, "", 0, SP_DEFAULT); - if (stp && (S_ISDIR(stp->st_mode) || IS_MISSING_FILE(*stp))) { + if (stream_source && am_sender && stp && S_ISFIFO(stp->st_mode)) { + /* The sender pinned this FIFO before advertising its exact byte count. */ + st = *stp; + st.st_mode = S_IFREG | (st.st_mode & ACCESSPERMS); + st.st_size = stream_size; + } else if (stp && (S_ISDIR(stp->st_mode) || IS_MISSING_FILE(*stp))) { /* This is needed to handle a "symlink/." with a --relative * dir, or a request to delete a specific file. */ st = *stp; @@ -2998,6 +3005,11 @@ struct file_list *send_file_list(int f, int argc, char *argv[]) if (fn != fbuf) memmove(fbuf, fn, len + 1); +#ifdef SUPPORT_STREAM_SOURCE + if (stream_source) + pin_stream_source(fbuf, &st); + else +#endif if (scan_link_stat(fbuf, &st, copy_dirlinks || name_type != NORMAL_NAME) != 0 || (name_type != DOTDIR_NAME && is_excluded(fbuf, S_ISDIR(st.st_mode) != 0, SERVER_FILTERS)) || (relative_paths && path_is_daemon_excluded(fbuf, 1))) { @@ -3079,6 +3091,11 @@ struct file_list *send_file_list(int f, int argc, char *argv[]) send_file_name(f, flist, fbuf, &st, flags, NO_FILTERS); } + if (stream_source && flist->used != 1) { + rprintf(FERROR, "--stream-source requires one readable FIFO source\n"); + exit_cleanup(RERR_FILESELECT); + } + if (reenable_multiplex >= 0) io_start_multiplex_in(reenable_multiplex); diff --git a/generator.c b/generator.c index 6c5282af3..a6d4a8b8c 100644 --- a/generator.c +++ b/generator.c @@ -92,6 +92,7 @@ extern int alt_dest_type; extern int per_dir_basis; extern int per_dir_basis_root_fd; extern int whole_file; +extern int stream_source; extern int list_only; extern int read_batch; extern int write_batch; @@ -2538,6 +2539,11 @@ static void recv_generator(char *fname, struct file_struct *file, int ndx, fnamecmp_type = FNAMECMP_FNAME; if (statret == 0 && !(stype == FT_REG || (write_devices && stype == FT_DEVICE))) { + if (stream_source) { + rprintf(FERROR, "--stream-source will not replace a non-regular destination: %s\n", + full_fname(fname)); + exit_cleanup(RERR_FILEIO); + } if (delete_item(fname, sx.st.st_mode, del_opts | DEL_FOR_FILE) != 0) goto cleanup; statret = -1; @@ -2628,6 +2634,8 @@ static void recv_generator(char *fname, struct file_struct *file, int ndx, goto notify_others; rsyserr(FERROR_XFER, stat_errno, "recv_generator: failed to stat %s", full_fname(fname)); + if (stream_source) + exit_cleanup(RERR_FILEIO); goto cleanup; } @@ -2706,6 +2714,15 @@ static void recv_generator(char *fname, struct file_struct *file, int ndx, } /* open the file */ +#ifdef SUPPORT_STREAM_SOURCE + if (stream_source) { + fd = open_stream_basis(fnamecmp, &sx.st); + if (fd < 0) { + rsyserr(FERROR, errno, "cannot open regular FIFO transfer basis %s", full_fname(fnamecmp)); + exit_cleanup(RERR_FILEIO); + } + } else +#endif if (fd < 0 && (fd = do_open_checklinks(fnamecmp)) < 0) { rsyserr(FERROR, errno, "failed to open %s, continuing", full_fname(fnamecmp)); diff --git a/main.c b/main.c index f110a6308..a48f6eb34 100644 --- a/main.c +++ b/main.c @@ -76,6 +76,8 @@ extern unsigned int curr_dir_len; extern int module_id; extern int rsync_port; extern int whole_file; +extern int stream_source; +extern struct name_num_item *xfer_sum_nni; extern int read_batch; extern int write_batch; extern int batch_fd; @@ -831,6 +833,11 @@ static char *get_local_name(struct file_list *flist, char *dest_path) * of a single non-directory or the user has requested one via a * destination path ending in a slash, create one and use mode 1. */ if (file_total > 1 || trailing_slash) { + if (stream_source) { + rprintf(FERROR, "--stream-source requires an existing destination directory: %s\n", + full_fname(dest_path)); + exit_cleanup(RERR_FILESELECT); + } if (trailing_slash) *cp = '\0'; /* Lop off the final slash (if any). */ @@ -1401,6 +1408,10 @@ int client_run(int f_in, int f_out, pid_t pid, int argc, char *argv[]) io_set_sock_fds(f_in, f_out); setup_protocol(f_out,f_in); + if (stream_source && xfer_sum_nni->num == CSUM_NONE) { + rprintf(FERROR, "--stream-source requires a transfer checksum\n"); + exit_cleanup(RERR_SYNTAX); + } /* We set our stderr file handle to blocking because ssh might have * set it to non-blocking. This can be particularly troublesome if @@ -1521,6 +1532,11 @@ static int start_client(int argc, char *argv[]) int ret; pid_t pid; + if (stream_source && (!argv[0][0] || !argv[1][0])) { + rprintf(FERROR, "--stream-source requires non-empty source and destination arguments\n"); + exit_cleanup(RERR_SYNTAX); + } + if (!read_batch) { /* for read_batch, NO source is specified */ char *path = check_for_hostspec(argv[0], &shell_machine, &rsync_port); if (path) { /* source is remote */ @@ -1595,6 +1611,11 @@ static int start_client(int argc, char *argv[]) rsync_port = 0; } + if (stream_source && (!local_server || !am_sender)) { + rprintf(FERROR, "--stream-source requires a local source and destination\n"); + exit_cleanup(RERR_SYNTAX); + } + if (placement_log && am_sender && !local_server) { rprintf(FERROR, "--placement-log requires a local receiver\n"); exit_cleanup(RERR_SYNTAX); diff --git a/match.c b/match.c index 6f17b354e..1f2ebe580 100644 --- a/match.c +++ b/match.c @@ -129,6 +129,13 @@ static void matched(int f, struct sum_struct *s, struct map_struct *buf, OFF_T o { int32 n = (int32)(offset - last_match); /* max value: block_size (int32) */ int32 j; + int32 token = i; +#ifdef SUPPORT_STREAM_SOURCE + BOOL streaming = buf && buf->stream_timeout; + + if (streaming && i == -1) + token = -2; +#endif if (DEBUG_GTE(DELTASUM, 2) && i >= 0) { rprintf(FINFO, @@ -137,7 +144,7 @@ static void matched(int f, struct sum_struct *s, struct map_struct *buf, OFF_T o (long)s->sums[i].len, (long)n); } - send_token(f, i, buf, last_match, n, i < 0 ? 0 : s->sums[i].len); + send_token(f, token, buf, last_match, n, i < 0 ? 0 : s->sums[i].len); data_transfer += n; if (i >= 0) { @@ -155,6 +162,18 @@ static void matched(int f, struct sum_struct *s, struct map_struct *buf, OFF_T o else last_match = offset; +#ifdef SUPPORT_STREAM_SOURCE + if (streaming) { + /* hash_search may inspect the byte at the end of the last match. */ + buf->stream_keep = last_match ? last_match - 1 : 0; + if (i == -1) { + check_stream_eof(buf); + send_token(f, -1, buf, offset, 0, 0); + } else if (last_match == buf->file_size) + return; /* Completion is reported only after checking FIFO EOF. */ + } +#endif + if (buf && INFO_GTE(PROGRESS, 1)) show_progress(last_match, buf->file_size); } diff --git a/options.c b/options.c index 4f26fc99b..579b604d0 100644 --- a/options.c +++ b/options.c @@ -120,6 +120,11 @@ int old_style_args = -1; int human_readable = 1; int recurse = 0; int mkpath_dest_arg = 0; +int stream_source = 0; +OFF_T stream_size = 0; +int stream_timeout = 30; +static int stream_timeout_given = 0; +static char *stream_size_arg = NULL; int allow_inc_recurse = 1; int xfer_dirs = -1; int am_daemon = 0; @@ -618,7 +623,7 @@ enum {OPT_SERVER = 1000, OPT_DAEMON, OPT_SENDER, OPT_EXCLUDE, OPT_EXCLUDE_FROM, OPT_USERMAP, OPT_GROUPMAP, OPT_CHOWN, OPT_BWLIMIT, OPT_STDERR, OPT_OLD_COMPRESS, OPT_NEW_COMPRESS, OPT_NO_COMPRESS, OPT_OLD_ARGS, OPT_STOP_AFTER, OPT_STOP_AT, OPT_NICE, OPT_NO_NICE, OPT_CHMOD_DEST, - OPT_PLACEMENT_LOG, + OPT_PLACEMENT_LOG, OPT_STREAM_TIMEOUT, OPT_REFUSED_BASE = 9000}; static struct poptOption long_options[] = { @@ -742,6 +747,9 @@ static struct poptOption long_options[] = { {"max-size", 0, POPT_ARG_STRING, &max_size_arg, OPT_MAX_SIZE, 0, 0 }, {"min-size", 0, POPT_ARG_STRING, &min_size_arg, OPT_MIN_SIZE, 0, 0 }, {"max-alloc", 0, POPT_ARG_STRING, &max_alloc_arg, 0, 0, 0 }, + {"stream-source", 0, POPT_ARG_NONE, &stream_source, 0, 0, 0 }, + {"stream-size", 0, POPT_ARG_STRING, &stream_size_arg, 0, 0, 0 }, + {"stream-timeout", 0, POPT_ARG_INT, &stream_timeout, OPT_STREAM_TIMEOUT, 0, 0 }, {"sparse", 'S', POPT_ARG_VAL, &sparse_files, 1, 0, 0 }, {"no-sparse", 0, POPT_ARG_VAL, &sparse_files, 0, 0, 0 }, {"no-S", 0, POPT_ARG_VAL, &sparse_files, 0, 0, 0 }, @@ -1540,6 +1548,57 @@ char *alt_dest_opt(int type) } } +static BOOL check_stream_options(int argc) +{ + const char *err; + + if (!stream_source) { + if (!stream_size_arg && !stream_timeout_given) + return True; + err = "--stream-size and --stream-timeout require --stream-source"; + } else if (am_server || am_daemon || argc != 2) { + err = "--stream-source requires one local source and one local destination"; +#ifndef SUPPORT_STREAM_SOURCE + } else { + err = "--stream-source is not supported on this platform"; +#else + } else if (!stream_size_arg) { + err = "--stream-source requires --stream-size"; + } else if (stream_timeout <= 0 || stream_timeout > INT_MAX / 1000) { + err = "--stream-source requires a positive --stream-timeout within the supported range"; + } else if (protocol_version < 31) { + err = "--stream-source requires protocol 31 or newer"; + } else if (inplace || append_mode || keep_partial || partial_dir || delay_updates + || tmpdir || write_devices || make_backups || backup_dir || mkpath_dest_arg) { + err = "--stream-source requires a same-directory temporary file without partials or backups"; + } else if (delete_mode || delete_before || delete_during || delete_after || delete_excluded || force_delete + || remove_source_files || missing_args || read_batch || write_batch) { + err = "--stream-source cannot be combined with deletions, missing-arg handling or batch mode"; + } else if (dry_run || list_only || always_checksum || size_only || time_only || update_only || update_links + || ignore_existing || ignore_non_existing || ignore_non_existing_dirs + || min_size >= 0 || max_size >= 0 || filter_list.head || cvs_exclude || prune_empty_dirs + || skip_dir_marker || xfer_dirs >= 4) { + err = "--stream-source cannot be combined with transfer selection, listing or dry-run options"; + } else if (relative_paths > 0 || files_from || basis_dir[0] || fuzzy_basis + || remote_option_cnt || copy_as || copy_links || copy_dirlinks || copy_unsafe_links + || copy_devices || insecure_links || confine_root || open_noatime + || am_root < 0 || preserve_acls || preserve_xattrs || chmod_modes + || io_timeout || stop_at_utime) { + err = "--stream-source does not support alternate paths, extended metadata or other timeout options"; + } else { + /* Leave room for the matcher to advance beyond the last byte. */ + stream_size = parse_size_arg(stream_size_arg, 'b', "stream-size", 0, + SIZE_ARG_MAX - MAX_MAP_SIZE, False); + if (stream_size < 0) + return False; + ignore_times = 1; + return True; +#endif + } + snprintf(err_buf, sizeof err_buf, "%s.\n", err); + return False; +} + /* Only leading parent components can refer to directories absent in a dry run. */ static int valid_per_dir_basis(const char *path) { @@ -2156,6 +2215,10 @@ int parse_arguments(int *argc_p, const char ***argv_p) break; } + case OPT_STREAM_TIMEOUT: + stream_timeout_given = 1; + break; + #ifdef HAVE_MKTIME case OPT_STOP_AT: arg = poptGetOptArg(pc); @@ -2365,6 +2428,8 @@ int parse_arguments(int *argc_p, const char ***argv_p) /* Only the remote server will read a second argument vector. */ if (protect_args == 1 && am_server && !local_server) { + if (!check_stream_options(0)) + goto cleanup; poptFreeContext(pc); return 1; } @@ -2376,6 +2441,8 @@ int parse_arguments(int *argc_p, const char ***argv_p) * make a copy of the array and then do an immediate cleanup. */ argv = poptGetArgs(pc); argc = count_args(argv); + if (!check_stream_options(argc)) + goto cleanup; if (!argc) { *argv_p = empty_argv; *argc_p = 0; diff --git a/receiver.c b/receiver.c index 606d26f03..f6b295b29 100644 --- a/receiver.c +++ b/receiver.c @@ -57,6 +57,7 @@ extern int preallocate_files; extern int keep_partial; extern int checksum_seed; extern int whole_file; +extern int stream_source; extern int inplace; extern int inplace_partial; extern int allowed_lull; @@ -666,6 +667,11 @@ static int receive_data(int f_in, char *fname_r, int fd_r, OFF_T size_r, offset += len; } + if (stream_source && fd != -1 && offset != total_size) { + rprintf(FERROR, "FIFO output length differs from the declared stream size\n"); + exit_cleanup(RERR_FILEIO); + } + if (fd != -1 && offset > 0) { if (sparse_files > 0) { if (sparse_end(fd, offset, updating_basis_or_equiv) != 0) @@ -874,6 +880,7 @@ int recv_files(int f_in, int f_out, char *local_name, int placement_fd) while (1) { const char *basedir = NULL; int per_dir_basis_ndx = -1; + BOOL basis_has_stat = False; cleanup_disable(); @@ -1113,6 +1120,17 @@ int recv_files(int f_in, int f_out, char *local_name, int placement_fd) * planted one avoids both an escape and a basis-content info-leak. * Otherwise use secure_basis_open, which also tolerates an operator- * trusted absolute fnamecmp (e.g. an absolute --partial-dir basis). */ +#ifdef SUPPORT_STREAM_SOURCE + if (stream_source) { + fd1 = open_stream_basis(fnamecmp, &st); + if (fd1 >= 0) + basis_has_stat = True; + else if (errno != ENOENT) { + rsyserr(FERROR, errno, "cannot open regular FIFO transfer destination %s", full_fname(fnamecmp)); + exit_cleanup(RERR_FILEIO); + } + } else +#endif if (per_dir_basis_ndx >= 0) { fd1 = open_per_dir_basis(per_dir_basis_root_fd, basis_dir[per_dir_basis_ndx], fname, fnamecmpbuf, &st); @@ -1127,6 +1145,7 @@ int recv_files(int f_in, int f_out, char *local_name, int placement_fd) continue; } fnamecmp = fnamecmpbuf; + basis_has_stat = True; } else { int bdfd; BOOL backup_basis = fnamecmp_type == FNAMECMP_BACKUP && inplace && make_backups > 0; @@ -1218,7 +1237,7 @@ int recv_files(int f_in, int f_out, char *local_name, int placement_fd) if (fd1 == -1) { st.st_mode = 0; st.st_size = 0; - } else if (per_dir_basis_ndx < 0 && do_fstat(fd1,&st) != 0) { + } else if (!basis_has_stat && do_fstat(fd1, &st) != 0) { rsyserr(FERROR_XFER, errno, "fstat %s failed", full_fname(fnamecmp)); discard_receive_data(f_in, file); @@ -1267,6 +1286,8 @@ int recv_files(int f_in, int f_out, char *local_name, int placement_fd) #endif file->mode = dest_mode(file->mode, st.st_mode, dflt_perms, exists); } + if (stream_source) + file->mode &= ~(S_ISUID | S_ISGID | S_ISVTX); /* We now check to see if we are writing the file "inplace" */ if (inplace || one_inplace) { @@ -1312,6 +1333,8 @@ int recv_files(int f_in, int f_out, char *local_name, int placement_fd) } if (fd2 == -1) { + if (stream_source) + exit_cleanup(RERR_FILEIO); discard_receive_data(f_in, file); if (fd1 != -1) close(fd1); @@ -1341,6 +1364,11 @@ int recv_files(int f_in, int f_out, char *local_name, int placement_fd) /* recv file data */ recv_ok = receive_data(f_in, fnamecmp, fd1, st.st_size, fname, fd2, file, inplace || one_inplace); + if (stream_source && recv_ok <= 0) { + rprintf(FERROR, "FIFO transfer of %s failed verification and cannot be retried\n", + full_fname(fname)); + exit_cleanup(RERR_FILEIO); + } if (write_to_device) { file->mode = write_devices_saved_mode; @@ -1353,11 +1381,24 @@ int recv_files(int f_in, int f_out, char *local_name, int placement_fd) if (fd1 != -1) close(fd1); + if (stream_source) { + STRUCT_STAT output; + if (do_fstat(fd2, &output) < 0) { + rsyserr(FERROR, errno, "cannot inspect temporary FIFO output %s", full_fname(fnametmp)); + exit_cleanup(RERR_FILEIO); + } + if (output.st_size != F_LENGTH(file)) { + rprintf(FERROR, "Temporary FIFO output differs from the declared stream size\n"); + exit_cleanup(RERR_FILEIO); + } + } if (close(fd2) < 0) { rsyserr(FERROR, errno, "close failed on %s", full_fname(fnametmp)); exit_cleanup(RERR_FILEIO); } + if (stream_source) + cleanup_set(fnametmp, NULL, file, -1, -1); if ((recv_ok && (!delay_updates || !partialptr)) || inplace) { if (partialptr == fname) diff --git a/rsync.1.md b/rsync.1.md index 5dde3e6c8..87ebfd719 100644 --- a/rsync.1.md +++ b/rsync.1.md @@ -580,6 +580,9 @@ has its own detailed description later in this manpage. --devices preserve device files (super-user only) --copy-devices copy device contents as a regular file --write-devices write to devices as files (implies --inplace) +--stream-source copy a local FIFO as a regular file on Linux +--stream-size=SIZE exact byte count expected from the FIFO +--stream-timeout=SECONDS maximum wait for FIFO data or EOF --specials preserve special files --drop-D receiver refuses to create devices/specials -D same as --devices --specials @@ -1931,6 +1934,53 @@ sign) if you want the local shell to expand it. This option is refused by default by an rsync daemon. +0. `--stream-source` + + Read one explicit local named pipe (FIFO) into a regular file. This option + requires a supported Linux build with access to `/proc/self/fd` and uses + protocol 31 or newer between the local processes. Remote transfers and + symbolic links to the FIFO are not supported. + + The sender reads the FIFO once using a bounded memory window. It does not + spool input to disk. [`--no-whole-file`](#opt) enables delta matching + against a readable regular destination file. A matching size and timestamp + never skip the transfer. Use one producer and no other readers for the + FIFO. Producers must close the writing end to signal EOF. + + The destination file must be absent or regular. If its argument names a + directory, the directory must already exist. Rsync receives into a + temporary file in the destination directory and renames it into place + only after exact input length, EOF, transfer checksum verification and + successful application of requested file attributes. + Extra data, premature EOF and FIFO timeouts leave any existing destination + file in place. A verification failure is not retried. Rsync does not check + the producer's exit status. + + In-place and append updates, partial retention, delayed updates, an + alternate temporary directory, backups, deletions and batch transfers + are not supported. This mode refuses disabling the transfer checksum with + [`--checksum-choice=none`](#opt). It also refuses active filters, options that skip + transfers, dry runs, listing, alternate basis paths, relative layouts, + source lists, remote options, identity changes, ACLs and extended + attributes. Set-user-ID, set-group-ID and sticky bits are not copied. + +0. `--stream-size=SIZE` + + Require exactly `SIZE` bytes from the FIFO when using + [`--stream-source`](#opt). This option is mandatory in that mode. It + accepts the units described in [`--max-size`](#opt). A size of 0 still + requires a writer to open the FIFO and close it without writing data. + Rsync attempts to read one byte past this length to detect excess input. + +0. `--stream-timeout=SECONDS` + + Bound each wait for data or EOF from the FIFO when using + [`--stream-source`](#opt). This includes waiting for the first writer + and waiting for EOF after the declared byte count. The value must be an + integer from 1 to 2147483. The default is 30 seconds. This option does not bound + the total duration of the local copy and cannot be combined with + [`--timeout`](#opt), [`--stop-after`](#opt) or [`--stop-at`](#opt). + 0. `--times`, `-t` This tells rsync to set the modification times of the destination files diff --git a/rsync.c b/rsync.c index c900ed5ea..043e124bc 100644 --- a/rsync.c +++ b/rsync.c @@ -50,6 +50,8 @@ extern int got_kill_signal; extern int called_from_signal_handler; extern int inc_recurse; extern int inplace; +extern int stream_source; +extern int got_xfer_error; extern int flist_eof; extern int file_old_total; extern int keep_dirlinks; @@ -931,7 +933,7 @@ int finish_transfer(const char *fname, const char *fnametmp, BOOL backup_basis = False; const char *temp_copy_name = partialptr && *partialptr != '/' ? partialptr : NULL; - if (dest_chmod_modes) + if (dest_chmod_modes || stream_source) attr_flags |= ATTRS_REQUIRE_SUCCESS; if (inplace) { @@ -963,6 +965,8 @@ int finish_transfer(const char *fname, const char *fnametmp, operator_path_resolve = 0; if (backup_basis && !end_backup_access()) return 0; + if (stream_source && (ret < 0 || got_xfer_error)) + exit_cleanup(RERR_FILEIO); if (ret < 0) { rsyserr(FERROR_XFER, errno, "cannot prepare backup attributes for %s", full_fname(fname)); do_unlink_at(fnametmp); @@ -972,6 +976,14 @@ int finish_transfer(const char *fname, const char *fnametmp, /* move tmp file over real file */ if (DEBUG_GTE(RECV, 1)) rprintf(FINFO, "renaming %s to %s\n", fnametmp, fname); + if (stream_source) { + /* Leave the unplaced temporary file with the receiver's cleanup. */ + if (do_rename_at(fnametmp, fname) == 0) + return 1; + rsyserr(FERROR, errno, "cannot rename temporary FIFO output %s to %s", + full_fname(fnametmp), fname); + exit_cleanup(RERR_FILEIO); + } /* A copy fallback would publish before the requested mode was applied. */ ret = dest_chmod_modes ? do_rename_at(fnametmp, fname) : robust_rename(fnametmp, fname, temp_copy_name, file->mode, file); diff --git a/rsync.h b/rsync.h index f1cf0ed76..5eeb60384 100644 --- a/rsync.h +++ b/rsync.h @@ -428,6 +428,13 @@ enum delret { #undef O_DIRECTORY #endif +#if defined __linux__ && !defined __ANDROID__ && !defined RSYNC_TEST_NO_AT_FDCWD \ + && defined O_PATH && defined O_DIRECTORY && defined O_NOFOLLOW && O_CLOEXEC \ + && defined HAVE_CLOCK_GETTIME && defined CLOCK_MONOTONIC && defined HAVE_FSTATFS \ + && defined HAVE_SYS_VFS_H && defined HAVE_LINUX_MAGIC_H +#define SUPPORT_STREAM_SOURCE +#endif + #ifdef HAVE_SYS_IOCTL_H #include #endif @@ -1043,6 +1050,10 @@ struct map_struct { int32 def_window_size; /* Default window size */ int fd; /* File Descriptor */ int status; /* first errno from read errors */ +#ifdef SUPPORT_STREAM_SOURCE + OFF_T stream_keep; /* First byte the matcher may revisit */ + int stream_timeout; /* Non-zero only on the FIFO input map */ +#endif }; #define sum2_at(s, i) ((s)->sum2_array + ((size_t)(i) * xfer_sum_len)) diff --git a/sender.c b/sender.c index 3c2fe8fd5..1a440ebcf 100644 --- a/sender.c +++ b/sender.c @@ -42,6 +42,9 @@ extern int insecure_links; extern int io_error; extern int flist_eof; extern int whole_file; +extern int stream_source; +extern int stream_timeout; +extern OFF_T stream_size; extern int allowed_lull; extern int copy_devices; extern int preserve_xattrs; @@ -495,6 +498,46 @@ static void write_ndx_and_attrs(int f_out, int ndx, int iflags, #endif } +#ifdef SUPPORT_STREAM_SOURCE +static int stream_source_pin = -1; +static STRUCT_STAT stream_source_stat; + +void pin_stream_source(const char *fname, STRUCT_STAT *st) +{ + assert(stream_source_pin < 0); + stream_source_pin = do_open_nofollow(fname, O_PATH | O_CLOEXEC); + if (stream_source_pin < 0 || do_fstat(stream_source_pin, st) < 0) { + rsyserr(FERROR, errno, "cannot inspect FIFO source %s", full_fname(fname)); + exit_cleanup(RERR_FILEIO); + } + if (!S_ISFIFO(st->st_mode)) { + rprintf(FERROR, "--stream-source requires a FIFO: %s\n", full_fname(fname)); + exit_cleanup(RERR_FILEIO); + } + stream_source_stat = *st; +} + +static int open_stream_source(const char *fname, STRUCT_STAT *st) +{ + int fd; + + if (stream_source_pin < 0) { + rprintf(FERROR, "Cannot read a FIFO source more than once\n"); + exit_cleanup(RERR_FILEIO); + } + *st = stream_source_stat; + fd = reopen_stream_file(stream_source_pin, st, O_NONBLOCK); + if (fd < 0) { + rsyserr(FERROR, errno, "cannot open pinned FIFO source %s", full_fname(fname)); + exit_cleanup(RERR_FILEIO); + } + close(stream_source_pin); + stream_source_pin = -1; + st->st_size = stream_size; + return fd; +} +#endif + void send_files(int f_in, int f_out) { int fd = -1; @@ -522,6 +565,8 @@ void send_files(int f_in, int f_out) progress_init(); while (1) { + BOOL opened_stream = False; + if (inc_recurse) { send_extra_file_list(f_out, MIN_FILECNT_LOOKAHEAD); extra_flist_sending_enabled = !flist_eof; @@ -658,6 +703,12 @@ void send_files(int f_in, int f_out) exit_cleanup(RERR_PROTOCOL); } +#ifdef SUPPORT_STREAM_SOURCE + if (stream_source) { + fd = open_stream_source(fname, &st); + opened_stream = True; + } else +#endif if (symlink_optout_allowed()) { /* Module opted out of symlink confinement ("insecure links = * yes", admin-only) -- or a non-daemon --insecure-links: legacy @@ -720,7 +771,7 @@ void send_files(int f_in, int f_out) } /* A file may have become a directory after the file-list scan. * The direct sender-root open shares this post-open type check. */ - if (fd >= 0 && do_fstat(fd, &st) != 0) { + if (!opened_stream && fd >= 0 && do_fstat(fd, &st) != 0) { io_error |= IOERR_GENERAL; rsyserr(FERROR_XFER, errno, "fstat failed"); free_sums(s); @@ -769,9 +820,13 @@ void send_files(int f_in, int f_out) continue; } - if (st.st_size) { + if (st.st_size || opened_stream) { int32 read_size = MAX(s->blength * 3, MAX_MAP_SIZE); mbuf = map_file(fd, st.st_size, read_size, s->blength); +#ifdef SUPPORT_STREAM_SOURCE + if (opened_stream) + mbuf->stream_timeout = stream_timeout; +#endif } else mbuf = NULL; diff --git a/syscall.c b/syscall.c index 5d2e84f28..901213d31 100644 --- a/syscall.c +++ b/syscall.c @@ -58,6 +58,10 @@ #ifdef __linux__ #include /* SYS_fchmodat2 / SYS_fallocate raw-syscall wrappers */ #endif +#ifdef SUPPORT_STREAM_SOURCE +#include +#include +#endif #include "ifuncs.h" @@ -3290,6 +3294,74 @@ int do_open_nofollow(const char *pathname, int flags) return fd; } +#ifdef SUPPORT_STREAM_SOURCE +static BOOL same_stream_inode(const STRUCT_STAT *a, const STRUCT_STAT *b) +{ + return a->st_dev == b->st_dev && a->st_ino == b->st_ino + && (a->st_mode & S_IFMT) == (b->st_mode & S_IFMT); +} + +/* Reopen the checked inode rather than resolving its name a second time. */ +int reopen_stream_file(int pin, STRUCT_STAT *st, int flags) +{ + char entry[32]; + STRUCT_STAT opened; + struct statfs fs; + int dfd, fd = -1, saved_errno; + + dfd = open("/proc/self/fd", O_PATH | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC); + if (dfd < 0) + return -1; + if (fstatfs(dfd, &fs) < 0) + goto done; + if (fs.f_type != PROC_SUPER_MAGIC) { + errno = ENOTSUP; + goto done; + } + snprintf(entry, sizeof entry, "%d", pin); + if (fstatat(dfd, entry, &opened, 0) < 0) + goto done; + if (!same_stream_inode(st, &opened)) { + errno = ESTALE; + goto done; + } + fd = openat(dfd, entry, O_RDONLY | O_CLOEXEC | flags); + if (fd >= 0) { + int err = do_fstat(fd, &opened) < 0 ? errno : !same_stream_inode(st, &opened) ? ESTALE : 0; + if (err) { + close(fd); + fd = -1; + errno = err; + } else + *st = opened; + } + done: + saved_errno = errno; + close(dfd); + errno = saved_errno; + return fd; +} + +int open_stream_basis(const char *path, STRUCT_STAT *st) +{ + int pin = do_open_nofollow(path, O_PATH | O_CLOEXEC); + int fd = -1, saved_errno; + + if (pin < 0) + return -1; + if (do_fstat(pin, st) == 0) { + if (S_ISREG(st->st_mode)) + fd = reopen_stream_file(pin, st, 0); + else + errno = EINVAL; + } + saved_errno = errno; + close(pin); + errno = saved_errno; + return fd; +} +#endif + /* open a file relative to a base directory. The basedir can be NULL, in which case the current working directory is used. The relpath diff --git a/testsuite/tests/transfer/stream-source.py b/testsuite/tests/transfer/stream-source.py new file mode 100644 index 000000000..a551932f5 --- /dev/null +++ b/testsuite/tests/transfer/stream-source.py @@ -0,0 +1,248 @@ +#!/usr/bin/env python3 + +import json +import os +import random +import subprocess +import sys +import time + +from harness import TestContext, requires, run +from harness.results import test_fail +from harness.rsync import forced_protocol, rsync_argv + + +WRITER = ''' +import shutil +import sys + +with open(sys.argv[1], 'wb') as fifo, open(sys.argv[2], 'rb') as payload: + shutil.copyfileobj(payload, fifo) + fifo.flush() + print('written', flush=True) + if sys.argv[3] == 'hold': + sys.stdin.buffer.read(1) +''' + + +def invoke(*args): + return subprocess.run(rsync_argv(*args), stdin=subprocess.DEVNULL, capture_output=True, text=True, + env={**os.environ, 'LC_ALL': 'C'}, timeout=20) + + +def expect(result, code, message=''): + if result.returncode != code or message not in result.stderr: + test_fail(f'{result.args}: expected exit {code} and {message!r}, got {result.returncode}: ' + f'{result.stdout}{result.stderr}') + + +def transfer(source, target, size, data=None, *, hold=False, options=()): + writer = None + if data is not None: + payload = source.parent / 'payload' + payload.write_bytes(data) + writer = subprocess.Popen( + [sys.executable, '-c', WRITER, str(source), str(payload), 'hold' if hold else 'close'], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + ) + try: + result = invoke('--stream-source', f'--stream-size={size}', + f'--stream-timeout={1 if hold or data is None else 5}', + *options, str(source), str(target)) + if writer and result.returncode == 0 and not hold: + try: + writer.wait(timeout=5) + except subprocess.TimeoutExpired: + test_fail('rsync returned success without letting the FIFO writer finish') + finally: + if writer: + if writer.poll() is None: + writer.kill() + output, error = writer.communicate(timeout=5) + if writer and (hold or result.returncode == 0): + if output != 'written\n' or (not hold and writer.returncode != 0): + test_fail(f'writer did not complete the fixture: {output}{error}') + return result + + +def assert_preserved(target, before, label, contents=b'previous destination\n'): + after = target.stat() + if (target.read_bytes() != contents + or (after.st_ino, after.st_mode, after.st_mtime_ns) + != (before.st_ino, before.st_mode, before.st_mtime_ns) + or {p.name for p in target.parent.iterdir()} != {'out'}): + test_fail(f'{label}: rejected data altered the destination or left a temporary file') + + +def check_interrupted_copy(source, target, options): + target.write_bytes(b'previous destination\n') + before = target.stat() + payload = source.parent / 'payload' + random_source = random.Random(185) + payload.write_bytes(bytes(random_source.getrandbits(8) for _ in range(1048576))) + with subprocess.Popen([sys.executable, '-c', WRITER, str(source), str(payload), 'hold'], + stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, + stderr=subprocess.PIPE) as writer: + try: + args = rsync_argv('--stream-source', '--stream-size=1MiB', '--stream-timeout=8', + *options, str(source), str(target)) + with subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) as rsync: + try: + deadline = time.monotonic() + 6 + while not any(path.stat().st_size > 0 for path in target.parent.glob('.out.*')): + if rsync.poll() is not None or time.monotonic() >= deadline: + test_fail('receiver did not stage bytes before the writer closed the FIFO') + time.sleep(0.02) + if target.read_bytes() != b'previous destination\n' or writer.poll() is not None: + test_fail('destination changed before EOF') + rsync.terminate() + out, err = rsync.communicate(timeout=6) + expect(subprocess.CompletedProcess(args, rsync.returncode, out, err), 20) + finally: + if rsync.poll() is None: + rsync.kill() + finally: + if writer.poll() is None: + writer.kill() + writer.communicate(timeout=5) + assert_preserved(target, before, 'interrupted copy') + + +def check_transfers(source, target, compressor): + options = (f'--compress-choice={compressor}', '--debug=NSTR') + directory = target.parent + regular = source.parent / 'regular' + regular.write_bytes(b'data') + target.write_bytes(b'previous destination\n') + result = invoke('--whole-file', *options, str(regular), str(target)) + expect(result, 0) + if target.read_bytes() != b'data' or (compressor != 'none' + and f'compress: {compressor} (level' not in result.stdout): + test_fail(f'{compressor}: ordinary file did not use the selected codec: {result.stdout}') + + for size in (4, 0, 1, 32767, 32768, 32769, 262144, 262145): + data = (b'123456789\n' * (size // 10 + 1))[:size] + # Same length and mtime must not allow a quick-check skip. + target.write_bytes(b'x' * size) + now = source.stat().st_mtime_ns + os.utime(target, ns=(now, now)) + result = transfer(source, target, size, data, options=('--whole-file', '--stats', *options)) + expect(result, 0) + if target.read_bytes() != data or {p.name for p in directory.iterdir()} != {'out'}: + test_fail(f'{size} byte FIFO did not produce exactly the requested file') + if f'Total file size: {size:,} bytes' not in result.stdout: + test_fail(f'{size} byte FIFO was reported with an incorrect size: {result.stdout}') + + # Both the reused blocks and unmatched literals cross sender window boundaries. + random_source = random.Random(168) + old = bytes(random_source.getrandbits(8) for _ in range(1048576)) + data = (b'new' * 100000 + old[262144:786432] + b'end' * 120000) + delta_options = ('--no-whole-file', '--block-size=131072', '--stats', *options) + regular.write_bytes(data) + target.write_bytes(old) + result = invoke(*delta_options, str(regular), str(target)) + expect(result, 0) + if target.read_bytes() != data or 'Matched data: 524,288 bytes' not in result.stdout: + test_fail(f'ordinary delta did not reuse the expected blocks: {result.stdout}') + + target.write_bytes(old) + result = transfer(source, target, len(data), data, options=delta_options) + expect(result, 0) + if target.read_bytes() != data or 'Matched data: 524,288 bytes' not in result.stdout: + test_fail(f'FIFO delta did not reuse the expected blocks: {result.stdout}') + + for name, size, payload, hold, code, message in ( + ('absent writer', 0, None, False, 30, 'timed out'), + ('short', 300000, b'x' * 270000, False, 11, 'ended before'), + ('long', 300000, b'x' * 300001, False, 11, 'exceeds'), + ('idle after data', 300000, b'x' * 270000, True, 30, 'timed out'), + ('idle instead of EOF', 300000, b'x' * 300000, True, 30, 'timed out'), + ('overrun at zero', 0, b'x', False, 11, 'exceeds'), + ): + target.write_bytes(b'previous destination\n') + target.chmod(0o640) + before = target.stat() + result = transfer(source, target, size, payload, hold=hold, options=options) + expect(result, code, message) + assert_preserved(target, before, name) + + check_interrupted_copy(source, target, options) + + +@requires(transports={'pipe'}, mutates={'filesystem', 'process'}, tags={'transfer', 'regression'}) +def test(context: TestContext): + source = context.scratch / 'source' + directory = context.scratch / 'destination' + directory.mkdir() + target = directory / 'out' + flags = ('--stream-source', '--stream-size=0', '--stream-timeout=1') + + protocol = forced_protocol() + if sys.platform != 'linux' or hasattr(sys, 'getandroidapilevel'): + expect(invoke(*flags, str(source), str(target)), 1, 'not supported on this platform') + return + if protocol and protocol < 31: + expect(invoke(*flags, str(source), str(target)), 1, 'requires protocol 31 or newer') + return + + os.mkfifo(source, 0o600) + version = invoke('-VV') + expect(version, 0) + compressors = ['none', *[name for name in json.loads(version.stdout).get('compress_list', []) + if name != 'none']] + for compressor in compressors: + print(f'Checking {compressor} stream transfers', flush=True) + check_transfers(source, target, compressor) + + placement = context.scratch / 'stream.placements' + expect(transfer(source, target, 3, b'abc', options=(f'--placement-log={placement}',)), 0) + if target.read_bytes() != b'abc' or placement.read_bytes() != b'out\0': + test_fail('successful stream did not record one placement') + before = target.stat() + refused = context.scratch / 'refused.placements' + expect(transfer(source, target, 2, b'xyz', options=(f'--placement-log={refused}',)), 11, 'exceeds') + assert_preserved(target, before, 'overrun with placement log', contents=b'abc') + if refused.read_bytes(): + test_fail('unsuccessful stream was recorded') + + for option in ('--inplace', '--partial', '-P', '--partial-dir=partial', '--append-verify', + '--delay-updates', '--write-devices', '--backup', f'--backup-dir={context.scratch}', + f'--temp-dir={context.scratch}', '--remove-source-files', '--delete-missing-args', + '--ignore-existing', '--size-only', '--checksum', '--dry-run', '--list-only', + f'--copy-dest={context.scratch}', f'--write-batch={context.scratch / "batch"}', + '--read-batch=absent', '--copy-as=nobody', '-M--inplace', '--exclude=*', + '--checksum-choice=none', '--timeout=1', '--old-dirs', '--force', '--update-links', + '--skip-dir-with=.skip'): + expect(invoke(*flags, option, str(source), str(target)), 1, '--stream-source') + + for args in (('--stream-source',), ('--stream-size=0',), ('--stream-timeout=1',), + (*flags, '--stream-size=-1'), (*flags, '--stream-size=99999999999999999999'), + (*flags, '--stream-timeout=0'), (*flags, '--stream-timeout=-1'), + (*flags, '--stream-timeout=2147484')): + expect(invoke(*args, str(source), str(target)), 1) + expect(invoke(*flags, str(source)), 1, '--stream-source') + expect(invoke(*flags, str(source), ''), 1, '--stream-source') + expect(invoke(*flags, str(source), str(source), str(target)), 1, '--stream-source') + expect(invoke(*flags, '-e', 'false', str(source), 'remote:target'), 1, '--stream-source') + expect(invoke(*flags, '-e', 'false', 'remote:source', str(target)), 1, '--stream-source') + expect(invoke('--server', *flags, '.', str(target)), 1, '--stream-source') + expect(invoke('--server', '--secluded-args', *flags, '.', str(target)), 1, '--stream-source') + + regular = source.parent / 'regular' + regular.write_bytes(b'ordinary input\n') + expect(invoke(*flags, str(regular), str(target)), 11, 'FIFO') + link = source.parent / 'link' + link.symlink_to(source.name) + expect(invoke(*flags, str(link), str(target)), 11, 'FIFO') + if not source.is_fifo(): + test_fail('FIFO source was removed or replaced') + + target.unlink() + os.mkfifo(target, 0o600) + result = transfer(source, target, 0) + if result.returncode == 0 or 'destination' not in result.stderr or not target.is_fifo(): + test_fail(f'non-regular destination was not refused and preserved: {result.stderr}') + + +if __name__ == '__main__': + run(test) diff --git a/token.c b/token.c index ea09cee53..6be6c4da4 100644 --- a/token.c +++ b/token.c @@ -928,7 +928,7 @@ static int32 recv_zstd_token(int f, char **data) static void send_compressed_token(int f, int32 token, struct map_struct *buf, OFF_T offset, int32 nb) { - static int init_done, flush_pending; + static int init_done; int size = MAX(LZ4_compressBound(CHUNK_SIZE), MAX_DATA_COUNT+2); int32 n, r; @@ -939,7 +939,6 @@ send_compressed_token(int f, int32 token, struct map_struct *buf, OFF_T offset, } last_run_end = 0; run_start = token; - flush_pending = 0; } else if (last_token == -2) { run_start = token; } else if (nb != 0 || token != last_token + 1 || token >= run_start + 65536) { @@ -962,7 +961,8 @@ send_compressed_token(int f, int32 token, struct map_struct *buf, OFF_T offset, last_token = token; - if (nb != 0 || flush_pending) { + /* Each LZ4 block is complete; there is no pending data to flush. */ + if (nb != 0) { int available_in, available_out = 0; const char *next_in; @@ -991,7 +991,6 @@ send_compressed_token(int f, int32 token, struct map_struct *buf, OFF_T offset, offset += available_in; } } while (nb != 0); - flush_pending = token == -2; } if (token == -1) { /* end of file - clean up */