File:  [ELWIX - Embedded LightWeight unIX -] / embedaddon / rsync / io.c
Revision 1.1.1.4 (vendor branch): download - view: text, annotated - select for diffs - revision graph
Wed Mar 17 00:32:36 2021 UTC (3 years, 3 months ago) by misho
Branches: rsync, MAIN
CVS tags: v3_2_3, HEAD
rsync 3.2.3

    1: /*
    2:  * Socket and pipe I/O utilities used in rsync.
    3:  *
    4:  * Copyright (C) 1996-2001 Andrew Tridgell
    5:  * Copyright (C) 1996 Paul Mackerras
    6:  * Copyright (C) 2001, 2002 Martin Pool <mbp@samba.org>
    7:  * Copyright (C) 2003-2020 Wayne Davison
    8:  *
    9:  * This program is free software; you can redistribute it and/or modify
   10:  * it under the terms of the GNU General Public License as published by
   11:  * the Free Software Foundation; either version 3 of the License, or
   12:  * (at your option) any later version.
   13:  *
   14:  * This program is distributed in the hope that it will be useful,
   15:  * but WITHOUT ANY WARRANTY; without even the implied warranty of
   16:  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   17:  * GNU General Public License for more details.
   18:  *
   19:  * You should have received a copy of the GNU General Public License along
   20:  * with this program; if not, visit the http://fsf.org website.
   21:  */
   22: 
   23: /* Rsync provides its own multiplexing system, which is used to send
   24:  * stderr and stdout over a single socket.
   25:  *
   26:  * For historical reasons this is off during the start of the
   27:  * connection, but it's switched on quite early using
   28:  * io_start_multiplex_out() and io_start_multiplex_in(). */
   29: 
   30: #include "rsync.h"
   31: #include "ifuncs.h"
   32: #include "inums.h"
   33: 
   34: /** If no timeout is specified then use a 60 second select timeout */
   35: #define SELECT_TIMEOUT 60
   36: 
   37: extern int bwlimit;
   38: extern size_t bwlimit_writemax;
   39: extern int io_timeout;
   40: extern int am_server;
   41: extern int am_sender;
   42: extern int am_receiver;
   43: extern int am_generator;
   44: extern int local_server;
   45: extern int msgs2stderr;
   46: extern int inc_recurse;
   47: extern int same_db;
   48: extern int io_error;
   49: extern int batch_fd;
   50: extern int eol_nulls;
   51: extern int flist_eof;
   52: extern int file_total;
   53: extern int file_old_total;
   54: extern int list_only;
   55: extern int read_batch;
   56: extern int compat_flags;
   57: extern int protect_args;
   58: extern int checksum_seed;
   59: extern int checksum_files;
   60: extern int daemon_connection;
   61: extern int protocol_version;
   62: extern int remove_source_files;
   63: extern int preserve_hard_links;
   64: extern BOOL extra_flist_sending_enabled;
   65: extern BOOL flush_ok_after_signal;
   66: extern struct stats stats;
   67: extern time_t stop_at_utime;
   68: extern struct file_list *cur_flist;
   69: #ifdef ICONV_OPTION
   70: extern int filesfrom_convert;
   71: extern iconv_t ic_send, ic_recv;
   72: #endif
   73: 
   74: int csum_length = SHORT_SUM_LENGTH; /* initial value */
   75: int allowed_lull = 0;
   76: int msgdone_cnt = 0;
   77: int forward_flist_data = 0;
   78: BOOL flist_receiving_enabled = False;
   79: 
   80: /* Ignore an EOF error if non-zero. See whine_about_eof(). */
   81: int kluge_around_eof = 0;
   82: int got_kill_signal = -1; /* is set to 0 only after multiplexed I/O starts */
   83: 
   84: int sock_f_in = -1;
   85: int sock_f_out = -1;
   86: 
   87: int64 total_data_read = 0;
   88: int64 total_data_written = 0;
   89: 
   90: static struct {
   91: 	xbuf in, out, msg;
   92: 	int in_fd;
   93: 	int out_fd; /* Both "out" and "msg" go to this fd. */
   94: 	int in_multiplexed;
   95: 	unsigned out_empty_len;
   96: 	size_t raw_data_header_pos;      /* in the out xbuf */
   97: 	size_t raw_flushing_ends_before; /* in the out xbuf */
   98: 	size_t raw_input_ends_before;    /* in the in xbuf */
   99: } iobuf = { .in_fd = -1, .out_fd = -1 };
  100: 
  101: static time_t last_io_in;
  102: static time_t last_io_out;
  103: 
  104: static int write_batch_monitor_in = -1;
  105: static int write_batch_monitor_out = -1;
  106: 
  107: static int ff_forward_fd = -1;
  108: static int ff_reenable_multiplex = -1;
  109: static char ff_lastchar = '\0';
  110: static xbuf ff_xb = EMPTY_XBUF;
  111: #ifdef ICONV_OPTION
  112: static xbuf iconv_buf = EMPTY_XBUF;
  113: #endif
  114: static int select_timeout = SELECT_TIMEOUT;
  115: static int active_filecnt = 0;
  116: static OFF_T active_bytecnt = 0;
  117: static int first_message = 1;
  118: 
  119: static char int_byte_extra[64] = {
  120: 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* (00 - 3F)/4 */
  121: 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* (40 - 7F)/4 */
  122: 	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* (80 - BF)/4 */
  123: 	2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 6, /* (C0 - FF)/4 */
  124: };
  125: 
  126: /* Our I/O buffers are sized with no bits on in the lowest byte of the "size"
  127:  * (indeed, our rounding of sizes in 1024-byte units assures more than this).
  128:  * This allows the code that is storing bytes near the physical end of a
  129:  * circular buffer to temporarily reduce the buffer's size (in order to make
  130:  * some storing idioms easier), while also making it simple to restore the
  131:  * buffer's actual size when the buffer's "pos" wraps around to the start (we
  132:  * just round the buffer's size up again). */
  133: 
  134: #define IOBUF_WAS_REDUCED(siz) ((siz) & 0xFF)
  135: #define IOBUF_RESTORE_SIZE(siz) (((siz) | 0xFF) + 1)
  136: 
  137: #define IN_MULTIPLEXED (iobuf.in_multiplexed != 0)
  138: #define IN_MULTIPLEXED_AND_READY (iobuf.in_multiplexed > 0)
  139: #define OUT_MULTIPLEXED (iobuf.out_empty_len != 0)
  140: 
  141: #define PIO_NEED_INPUT (1<<0) /* The *_NEED_* flags are mutually exclusive. */
  142: #define PIO_NEED_OUTROOM (1<<1)
  143: #define PIO_NEED_MSGROOM (1<<2)
  144: 
  145: #define PIO_CONSUME_INPUT (1<<4) /* Must becombined with PIO_NEED_INPUT. */
  146: 
  147: #define PIO_INPUT_AND_CONSUME (PIO_NEED_INPUT | PIO_CONSUME_INPUT)
  148: #define PIO_NEED_FLAGS (PIO_NEED_INPUT | PIO_NEED_OUTROOM | PIO_NEED_MSGROOM)
  149: 
  150: #define REMOTE_OPTION_ERROR "rsync: on remote machine: -"
  151: #define REMOTE_OPTION_ERROR2 ": unknown option"
  152: 
  153: #define FILESFROM_BUFLEN 2048
  154: 
  155: enum festatus { FES_SUCCESS, FES_REDO, FES_NO_SEND };
  156: 
  157: static flist_ndx_list redo_list, hlink_list;
  158: 
  159: static void read_a_msg(void);
  160: static void drain_multiplex_messages(void);
  161: static void sleep_for_bwlimit(int bytes_written);
  162: 
  163: static void check_timeout(BOOL allow_keepalive, int keepalive_flags)
  164: {
  165: 	time_t t, chk;
  166: 
  167: 	/* On the receiving side, the generator is now the one that decides
  168: 	 * when a timeout has occurred.  When it is sifting through a lot of
  169: 	 * files looking for work, it will be sending keep-alive messages to
  170: 	 * the sender, and even though the receiver won't be sending/receiving
  171: 	 * anything (not even keep-alive messages), the successful writes to
  172: 	 * the sender will keep things going.  If the receiver is actively
  173: 	 * receiving data, it will ensure that the generator knows that it is
  174: 	 * not idle by sending the generator keep-alive messages (since the
  175: 	 * generator might be blocked trying to send checksums, it needs to
  176: 	 * know that the receiver is active).  Thus, as long as one or the
  177: 	 * other is successfully doing work, the generator will not timeout. */
  178: 	if (!io_timeout)
  179: 		return;
  180: 
  181: 	t = time(NULL);
  182: 
  183: 	if (allow_keepalive) {
  184: 		/* This may put data into iobuf.msg w/o flushing. */
  185: 		maybe_send_keepalive(t, keepalive_flags);
  186: 	}
  187: 
  188: 	if (!last_io_in)
  189: 		last_io_in = t;
  190: 
  191: 	if (am_receiver)
  192: 		return;
  193: 
  194: 	chk = MAX(last_io_out, last_io_in);
  195: 	if (t - chk >= io_timeout) {
  196: 		if (am_server)
  197: 			msgs2stderr = 1;
  198: 		rprintf(FERROR, "[%s] io timeout after %d seconds -- exiting\n",
  199: 			who_am_i(), (int)(t-chk));
  200: 		exit_cleanup(RERR_TIMEOUT);
  201: 	}
  202: }
  203: 
  204: /* It's almost always an error to get an EOF when we're trying to read from the
  205:  * network, because the protocol is (for the most part) self-terminating.
  206:  *
  207:  * There is one case for the receiver when it is at the end of the transfer
  208:  * (hanging around reading any keep-alive packets that might come its way): if
  209:  * the sender dies before the generator's kill-signal comes through, we can end
  210:  * up here needing to loop until the kill-signal arrives.  In this situation,
  211:  * kluge_around_eof will be < 0.
  212:  *
  213:  * There is another case for older protocol versions (< 24) where the module
  214:  * listing was not terminated, so we must ignore an EOF error in that case and
  215:  * exit.  In this situation, kluge_around_eof will be > 0. */
  216: static NORETURN void whine_about_eof(BOOL allow_kluge)
  217: {
  218: 	if (kluge_around_eof && allow_kluge) {
  219: 		int i;
  220: 		if (kluge_around_eof > 0)
  221: 			exit_cleanup(0);
  222: 		/* If we're still here after 10 seconds, exit with an error. */
  223: 		for (i = 10*1000/20; i--; )
  224: 			msleep(20);
  225: 	}
  226: 
  227: 	rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
  228: 		"(%s bytes received so far) [%s]\n",
  229: 		big_num(stats.total_read), who_am_i());
  230: 
  231: 	exit_cleanup(RERR_STREAMIO);
  232: }
  233: 
  234: /* Do a safe read, handling any needed looping and error handling.
  235:  * Returns the count of the bytes read, which will only be different
  236:  * from "len" if we encountered an EOF.  This routine is not used on
  237:  * the socket except very early in the transfer. */
  238: static size_t safe_read(int fd, char *buf, size_t len)
  239: {
  240: 	size_t got = 0;
  241: 
  242: 	assert(fd != iobuf.in_fd);
  243: 
  244: 	while (1) {
  245: 		struct timeval tv;
  246: 		fd_set r_fds, e_fds;
  247: 		int cnt;
  248: 
  249: 		FD_ZERO(&r_fds);
  250: 		FD_SET(fd, &r_fds);
  251: 		FD_ZERO(&e_fds);
  252: 		FD_SET(fd, &e_fds);
  253: 		tv.tv_sec = select_timeout;
  254: 		tv.tv_usec = 0;
  255: 
  256: 		cnt = select(fd+1, &r_fds, NULL, &e_fds, &tv);
  257: 		if (cnt <= 0) {
  258: 			if (cnt < 0 && errno == EBADF) {
  259: 				rsyserr(FERROR, errno, "safe_read select failed");
  260: 				exit_cleanup(RERR_FILEIO);
  261: 			}
  262: 			check_timeout(1, MSK_ALLOW_FLUSH);
  263: 			continue;
  264: 		}
  265: 
  266: 		/*if (FD_ISSET(fd, &e_fds))
  267: 			rprintf(FINFO, "select exception on fd %d\n", fd); */
  268: 
  269: 		if (FD_ISSET(fd, &r_fds)) {
  270: 			int n = read(fd, buf + got, len - got);
  271: 			if (DEBUG_GTE(IO, 2))
  272: 				rprintf(FINFO, "[%s] safe_read(%d)=%ld\n", who_am_i(), fd, (long)n);
  273: 			if (n == 0)
  274: 				break;
  275: 			if (n < 0) {
  276: 				if (errno == EINTR)
  277: 					continue;
  278: 				rsyserr(FERROR, errno, "safe_read failed to read %ld bytes", (long)len);
  279: 				exit_cleanup(RERR_STREAMIO);
  280: 			}
  281: 			if ((got += (size_t)n) == len)
  282: 				break;
  283: 		}
  284: 	}
  285: 
  286: 	return got;
  287: }
  288: 
  289: static const char *what_fd_is(int fd)
  290: {
  291: 	static char buf[20];
  292: 
  293: 	if (fd == sock_f_out)
  294: 		return "socket";
  295: 	else if (fd == iobuf.out_fd)
  296: 		return "message fd";
  297: 	else if (fd == batch_fd)
  298: 		return "batch file";
  299: 	else {
  300: 		snprintf(buf, sizeof buf, "fd %d", fd);
  301: 		return buf;
  302: 	}
  303: }
  304: 
  305: /* Do a safe write, handling any needed looping and error handling.
  306:  * Returns only if everything was successfully written.  This routine
  307:  * is not used on the socket except very early in the transfer. */
  308: static void safe_write(int fd, const char *buf, size_t len)
  309: {
  310: 	int n;
  311: 
  312: 	assert(fd != iobuf.out_fd);
  313: 
  314: 	n = write(fd, buf, len);
  315: 	if ((size_t)n == len)
  316: 		return;
  317: 	if (n < 0) {
  318: 		if (errno != EINTR && errno != EWOULDBLOCK && errno != EAGAIN) {
  319: 		  write_failed:
  320: 			rsyserr(FERROR, errno,
  321: 				"safe_write failed to write %ld bytes to %s",
  322: 				(long)len, what_fd_is(fd));
  323: 			exit_cleanup(RERR_STREAMIO);
  324: 		}
  325: 	} else {
  326: 		buf += n;
  327: 		len -= n;
  328: 	}
  329: 
  330: 	while (len) {
  331: 		struct timeval tv;
  332: 		fd_set w_fds;
  333: 		int cnt;
  334: 
  335: 		FD_ZERO(&w_fds);
  336: 		FD_SET(fd, &w_fds);
  337: 		tv.tv_sec = select_timeout;
  338: 		tv.tv_usec = 0;
  339: 
  340: 		cnt = select(fd + 1, NULL, &w_fds, NULL, &tv);
  341: 		if (cnt <= 0) {
  342: 			if (cnt < 0 && errno == EBADF) {
  343: 				rsyserr(FERROR, errno, "safe_write select failed on %s", what_fd_is(fd));
  344: 				exit_cleanup(RERR_FILEIO);
  345: 			}
  346: 			if (io_timeout)
  347: 				maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH);
  348: 			continue;
  349: 		}
  350: 
  351: 		if (FD_ISSET(fd, &w_fds)) {
  352: 			n = write(fd, buf, len);
  353: 			if (n < 0) {
  354: 				if (errno == EINTR)
  355: 					continue;
  356: 				goto write_failed;
  357: 			}
  358: 			buf += n;
  359: 			len -= n;
  360: 		}
  361: 	}
  362: }
  363: 
  364: /* This is only called when files-from data is known to be available.  We read
  365:  * a chunk of data and put it into the output buffer. */
  366: static void forward_filesfrom_data(void)
  367: {
  368: 	int len;
  369: 
  370: 	len = read(ff_forward_fd, ff_xb.buf + ff_xb.len, ff_xb.size - ff_xb.len);
  371: 	if (len <= 0) {
  372: 		if (len == 0 || errno != EINTR) {
  373: 			/* Send end-of-file marker */
  374: 			ff_forward_fd = -1;
  375: 			write_buf(iobuf.out_fd, "\0\0", ff_lastchar ? 2 : 1);
  376: 			free_xbuf(&ff_xb);
  377: 			if (ff_reenable_multiplex >= 0)
  378: 				io_start_multiplex_out(ff_reenable_multiplex);
  379: 		}
  380: 		return;
  381: 	}
  382: 
  383: 	if (DEBUG_GTE(IO, 2))
  384: 		rprintf(FINFO, "[%s] files-from read=%ld\n", who_am_i(), (long)len);
  385: 
  386: #ifdef ICONV_OPTION
  387: 	len += ff_xb.len;
  388: #endif
  389: 
  390: 	if (!eol_nulls) {
  391: 		char *s = ff_xb.buf + len;
  392: 		/* Transform CR and/or LF into '\0' */
  393: 		while (s-- > ff_xb.buf) {
  394: 			if (*s == '\n' || *s == '\r')
  395: 				*s = '\0';
  396: 		}
  397: 	}
  398: 
  399: 	if (ff_lastchar)
  400: 		ff_xb.pos = 0;
  401: 	else {
  402: 		char *s = ff_xb.buf;
  403: 		/* Last buf ended with a '\0', so don't let this buf start with one. */
  404: 		while (len && *s == '\0')
  405: 			s++, len--;
  406: 		ff_xb.pos = s - ff_xb.buf;
  407: 	}
  408: 
  409: #ifdef ICONV_OPTION
  410: 	if (filesfrom_convert && len) {
  411: 		char *sob = ff_xb.buf + ff_xb.pos, *s = sob;
  412: 		char *eob = sob + len;
  413: 		int flags = ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE | ICB_CIRCULAR_OUT;
  414: 		if (ff_lastchar == '\0')
  415: 			flags |= ICB_INIT;
  416: 		/* Convert/send each null-terminated string separately, skipping empties. */
  417: 		while (s != eob) {
  418: 			if (*s++ == '\0') {
  419: 				ff_xb.len = s - sob - 1;
  420: 				if (iconvbufs(ic_send, &ff_xb, &iobuf.out, flags) < 0)
  421: 					exit_cleanup(RERR_PROTOCOL); /* impossible? */
  422: 				write_buf(iobuf.out_fd, s-1, 1); /* Send the '\0'. */
  423: 				while (s != eob && *s == '\0')
  424: 					s++;
  425: 				sob = s;
  426: 				ff_xb.pos = sob - ff_xb.buf;
  427: 				flags |= ICB_INIT;
  428: 			}
  429: 		}
  430: 
  431: 		if ((ff_xb.len = s - sob) == 0)
  432: 			ff_lastchar = '\0';
  433: 		else {
  434: 			/* Handle a partial string specially, saving any incomplete chars. */
  435: 			flags &= ~ICB_INCLUDE_INCOMPLETE;
  436: 			if (iconvbufs(ic_send, &ff_xb, &iobuf.out, flags) < 0) {
  437: 				if (errno == E2BIG)
  438: 					exit_cleanup(RERR_PROTOCOL); /* impossible? */
  439: 				if (ff_xb.pos)
  440: 					memmove(ff_xb.buf, ff_xb.buf + ff_xb.pos, ff_xb.len);
  441: 			}
  442: 			ff_lastchar = 'x'; /* Anything non-zero. */
  443: 		}
  444: 	} else
  445: #endif
  446: 
  447: 	if (len) {
  448: 		char *f = ff_xb.buf + ff_xb.pos;
  449: 		char *t = ff_xb.buf;
  450: 		char *eob = f + len;
  451: 		/* Eliminate any multi-'\0' runs. */
  452: 		while (f != eob) {
  453: 			if (!(*t++ = *f++)) {
  454: 				while (f != eob && *f == '\0')
  455: 					f++;
  456: 			}
  457: 		}
  458: 		ff_lastchar = f[-1];
  459: 		if ((len = t - ff_xb.buf) != 0) {
  460: 			/* This will not circle back to perform_io() because we only get
  461: 			 * called when there is plenty of room in the output buffer. */
  462: 			write_buf(iobuf.out_fd, ff_xb.buf, len);
  463: 		}
  464: 	}
  465: }
  466: 
  467: void reduce_iobuf_size(xbuf *out, size_t new_size)
  468: {
  469: 	if (new_size < out->size) {
  470: 		/* Avoid weird buffer interactions by only outputting this to stderr. */
  471: 		if (msgs2stderr == 1 && DEBUG_GTE(IO, 4)) {
  472: 			const char *name = out == &iobuf.out ? "iobuf.out"
  473: 					 : out == &iobuf.msg ? "iobuf.msg"
  474: 					 : NULL;
  475: 			if (name) {
  476: 				rprintf(FINFO, "[%s] reduced size of %s (-%d)\n",
  477: 					who_am_i(), name, (int)(out->size - new_size));
  478: 			}
  479: 		}
  480: 		out->size = new_size;
  481: 	}
  482: }
  483: 
  484: void restore_iobuf_size(xbuf *out)
  485: {
  486: 	if (IOBUF_WAS_REDUCED(out->size)) {
  487: 		size_t new_size = IOBUF_RESTORE_SIZE(out->size);
  488: 		/* Avoid weird buffer interactions by only outputting this to stderr. */
  489: 		if (msgs2stderr == 1 && DEBUG_GTE(IO, 4)) {
  490: 			const char *name = out == &iobuf.out ? "iobuf.out"
  491: 					 : out == &iobuf.msg ? "iobuf.msg"
  492: 					 : NULL;
  493: 			if (name) {
  494: 				rprintf(FINFO, "[%s] restored size of %s (+%d)\n",
  495: 					who_am_i(), name, (int)(new_size - out->size));
  496: 			}
  497: 		}
  498: 		out->size = new_size;
  499: 	}
  500: }
  501: 
  502: static void handle_kill_signal(BOOL flush_ok)
  503: {
  504: 	got_kill_signal = -1;
  505: 	flush_ok_after_signal = flush_ok;
  506: 	exit_cleanup(RERR_SIGNAL);
  507: }
  508: 
  509: /* Perform buffered input and/or output until specified conditions are met.
  510:  * When given a "needed" read or write request, this returns without doing any
  511:  * I/O if the needed input bytes or write space is already available.  Once I/O
  512:  * is needed, this will try to do whatever reading and/or writing is currently
  513:  * possible, up to the maximum buffer allowances, no matter if this is a read
  514:  * or write request.  However, the I/O stops as soon as the required input
  515:  * bytes or output space is available.  If this is not a read request, the
  516:  * routine may also do some advantageous reading of messages from a multiplexed
  517:  * input source (which ensures that we don't jam up with everyone in their
  518:  * "need to write" code and nobody reading the accumulated data that would make
  519:  * writing possible).
  520:  *
  521:  * The iobuf.in, .out and .msg buffers are all circular.  Callers need to be
  522:  * aware that some data copies will need to be split when the bytes wrap around
  523:  * from the end to the start.  In order to help make writing into the output
  524:  * buffers easier for some operations (such as the use of SIVAL() into the
  525:  * buffer) a buffer may be temporarily shortened by a small amount, but the
  526:  * original size will be automatically restored when the .pos wraps to the
  527:  * start.  See also the 3 raw_* iobuf vars that are used in the handling of
  528:  * MSG_DATA bytes as they are read-from/written-into the buffers.
  529:  *
  530:  * When writing, we flush data in the following priority order:
  531:  *
  532:  * 1. Finish writing any in-progress MSG_DATA sequence from iobuf.out.
  533:  *
  534:  * 2. Write out all the messages from the message buf (if iobuf.msg is active).
  535:  *    Yes, this means that a PIO_NEED_OUTROOM call will completely flush any
  536:  *    messages before getting to the iobuf.out flushing (except for rule 1).
  537:  *
  538:  * 3. Write out the raw data from iobuf.out, possibly filling in the multiplexed
  539:  *    MSG_DATA header that was pre-allocated (when output is multiplexed).
  540:  *
  541:  * TODO:  items for possible future work:
  542:  *
  543:  *    - Make this routine able to read the generator-to-receiver batch flow?
  544:  *
  545:  * Unlike the old routines that this replaces, it is OK to read ahead as far as
  546:  * we can because the read_a_msg() routine now reads its bytes out of the input
  547:  * buffer.  In the old days, only raw data was in the input buffer, and any
  548:  * unused raw data in the buf would prevent the reading of socket data. */
  549: static char *perform_io(size_t needed, int flags)
  550: {
  551: 	fd_set r_fds, e_fds, w_fds;
  552: 	struct timeval tv;
  553: 	int cnt, max_fd;
  554: 	size_t empty_buf_len = 0;
  555: 	xbuf *out;
  556: 	char *data;
  557: 
  558: 	if (iobuf.in.len == 0 && iobuf.in.pos != 0) {
  559: 		if (iobuf.raw_input_ends_before)
  560: 			iobuf.raw_input_ends_before -= iobuf.in.pos;
  561: 		iobuf.in.pos = 0;
  562: 	}
  563: 
  564: 	switch (flags & PIO_NEED_FLAGS) {
  565: 	case PIO_NEED_INPUT:
  566: 		/* We never resize the circular input buffer. */
  567: 		if (iobuf.in.size < needed) {
  568: 			rprintf(FERROR, "need to read %ld bytes, iobuf.in.buf is only %ld bytes.\n",
  569: 				(long)needed, (long)iobuf.in.size);
  570: 			exit_cleanup(RERR_PROTOCOL);
  571: 		}
  572: 
  573: 		if (msgs2stderr == 1 && DEBUG_GTE(IO, 3)) {
  574: 			rprintf(FINFO, "[%s] perform_io(%ld, %sinput)\n",
  575: 				who_am_i(), (long)needed, flags & PIO_CONSUME_INPUT ? "consume&" : "");
  576: 		}
  577: 		break;
  578: 
  579: 	case PIO_NEED_OUTROOM:
  580: 		/* We never resize the circular output buffer. */
  581: 		if (iobuf.out.size - iobuf.out_empty_len < needed) {
  582: 			fprintf(stderr, "need to write %ld bytes, iobuf.out.buf is only %ld bytes.\n",
  583: 				(long)needed, (long)(iobuf.out.size - iobuf.out_empty_len));
  584: 			exit_cleanup(RERR_PROTOCOL);
  585: 		}
  586: 
  587: 		if (msgs2stderr == 1 && DEBUG_GTE(IO, 3)) {
  588: 			rprintf(FINFO, "[%s] perform_io(%ld, outroom) needs to flush %ld\n",
  589: 				who_am_i(), (long)needed,
  590: 				iobuf.out.len + needed > iobuf.out.size
  591: 				? (long)(iobuf.out.len + needed - iobuf.out.size) : 0L);
  592: 		}
  593: 		break;
  594: 
  595: 	case PIO_NEED_MSGROOM:
  596: 		/* We never resize the circular message buffer. */
  597: 		if (iobuf.msg.size < needed) {
  598: 			fprintf(stderr, "need to write %ld bytes, iobuf.msg.buf is only %ld bytes.\n",
  599: 				(long)needed, (long)iobuf.msg.size);
  600: 			exit_cleanup(RERR_PROTOCOL);
  601: 		}
  602: 
  603: 		if (msgs2stderr == 1 && DEBUG_GTE(IO, 3)) {
  604: 			rprintf(FINFO, "[%s] perform_io(%ld, msgroom) needs to flush %ld\n",
  605: 				who_am_i(), (long)needed,
  606: 				iobuf.msg.len + needed > iobuf.msg.size
  607: 				? (long)(iobuf.msg.len + needed - iobuf.msg.size) : 0L);
  608: 		}
  609: 		break;
  610: 
  611: 	case 0:
  612: 		if (msgs2stderr == 1 && DEBUG_GTE(IO, 3))
  613: 			rprintf(FINFO, "[%s] perform_io(%ld, %d)\n", who_am_i(), (long)needed, flags);
  614: 		break;
  615: 
  616: 	default:
  617: 		exit_cleanup(RERR_UNSUPPORTED);
  618: 	}
  619: 
  620: 	while (1) {
  621: 		switch (flags & PIO_NEED_FLAGS) {
  622: 		case PIO_NEED_INPUT:
  623: 			if (iobuf.in.len >= needed)
  624: 				goto double_break;
  625: 			break;
  626: 		case PIO_NEED_OUTROOM:
  627: 			/* Note that iobuf.out_empty_len doesn't factor into this check
  628: 			 * because iobuf.out.len already holds any needed header len. */
  629: 			if (iobuf.out.len + needed <= iobuf.out.size)
  630: 				goto double_break;
  631: 			break;
  632: 		case PIO_NEED_MSGROOM:
  633: 			if (iobuf.msg.len + needed <= iobuf.msg.size)
  634: 				goto double_break;
  635: 			break;
  636: 		}
  637: 
  638: 		max_fd = -1;
  639: 
  640: 		FD_ZERO(&r_fds);
  641: 		FD_ZERO(&e_fds);
  642: 		if (iobuf.in_fd >= 0 && iobuf.in.size - iobuf.in.len) {
  643: 			if (!read_batch || batch_fd >= 0) {
  644: 				FD_SET(iobuf.in_fd, &r_fds);
  645: 				FD_SET(iobuf.in_fd, &e_fds);
  646: 			}
  647: 			if (iobuf.in_fd > max_fd)
  648: 				max_fd = iobuf.in_fd;
  649: 		}
  650: 
  651: 		/* Only do more filesfrom processing if there is enough room in the out buffer. */
  652: 		if (ff_forward_fd >= 0 && iobuf.out.size - iobuf.out.len > FILESFROM_BUFLEN*2) {
  653: 			FD_SET(ff_forward_fd, &r_fds);
  654: 			if (ff_forward_fd > max_fd)
  655: 				max_fd = ff_forward_fd;
  656: 		}
  657: 
  658: 		FD_ZERO(&w_fds);
  659: 		if (iobuf.out_fd >= 0) {
  660: 			if (iobuf.raw_flushing_ends_before
  661: 			 || (!iobuf.msg.len && iobuf.out.len > iobuf.out_empty_len && !(flags & PIO_NEED_MSGROOM))) {
  662: 				if (OUT_MULTIPLEXED && !iobuf.raw_flushing_ends_before) {
  663: 					/* The iobuf.raw_flushing_ends_before value can point off the end
  664: 					 * of the iobuf.out buffer for a while, for easier subtracting. */
  665: 					iobuf.raw_flushing_ends_before = iobuf.out.pos + iobuf.out.len;
  666: 
  667: 					SIVAL(iobuf.out.buf + iobuf.raw_data_header_pos, 0,
  668: 					      ((MPLEX_BASE + (int)MSG_DATA)<<24) + iobuf.out.len - 4);
  669: 
  670: 					if (msgs2stderr == 1 && DEBUG_GTE(IO, 1)) {
  671: 						rprintf(FINFO, "[%s] send_msg(%d, %ld)\n",
  672: 							who_am_i(), (int)MSG_DATA, (long)iobuf.out.len - 4);
  673: 					}
  674: 
  675: 					/* reserve room for the next MSG_DATA header */
  676: 					iobuf.raw_data_header_pos = iobuf.raw_flushing_ends_before;
  677: 					if (iobuf.raw_data_header_pos >= iobuf.out.size)
  678: 						iobuf.raw_data_header_pos -= iobuf.out.size;
  679: 					else if (iobuf.raw_data_header_pos + 4 > iobuf.out.size) {
  680: 						/* The 4-byte header won't fit at the end of the buffer,
  681: 						 * so we'll temporarily reduce the output buffer's size
  682: 						 * and put the header at the start of the buffer. */
  683: 						reduce_iobuf_size(&iobuf.out, iobuf.raw_data_header_pos);
  684: 						iobuf.raw_data_header_pos = 0;
  685: 					}
  686: 					/* Yes, it is possible for this to make len > size for a while. */
  687: 					iobuf.out.len += 4;
  688: 				}
  689: 
  690: 				empty_buf_len = iobuf.out_empty_len;
  691: 				out = &iobuf.out;
  692: 			} else if (iobuf.msg.len) {
  693: 				empty_buf_len = 0;
  694: 				out = &iobuf.msg;
  695: 			} else
  696: 				out = NULL;
  697: 			if (out) {
  698: 				FD_SET(iobuf.out_fd, &w_fds);
  699: 				if (iobuf.out_fd > max_fd)
  700: 					max_fd = iobuf.out_fd;
  701: 			}
  702: 		} else
  703: 			out = NULL;
  704: 
  705: 		if (max_fd < 0) {
  706: 			switch (flags & PIO_NEED_FLAGS) {
  707: 			case PIO_NEED_INPUT:
  708: 				iobuf.in.len = 0;
  709: 				if (kluge_around_eof == 2)
  710: 					exit_cleanup(0);
  711: 				if (iobuf.in_fd == -2)
  712: 					whine_about_eof(True);
  713: 				rprintf(FERROR, "error in perform_io: no fd for input.\n");
  714: 				exit_cleanup(RERR_PROTOCOL);
  715: 			case PIO_NEED_OUTROOM:
  716: 			case PIO_NEED_MSGROOM:
  717: 				msgs2stderr = 1;
  718: 				drain_multiplex_messages();
  719: 				if (iobuf.out_fd == -2)
  720: 					whine_about_eof(True);
  721: 				rprintf(FERROR, "error in perform_io: no fd for output.\n");
  722: 				exit_cleanup(RERR_PROTOCOL);
  723: 			default:
  724: 				/* No stated needs, so I guess this is OK. */
  725: 				break;
  726: 			}
  727: 			break;
  728: 		}
  729: 
  730: 		if (got_kill_signal > 0)
  731: 			handle_kill_signal(True);
  732: 
  733: 		if (extra_flist_sending_enabled) {
  734: 			if (file_total - file_old_total < MAX_FILECNT_LOOKAHEAD && IN_MULTIPLEXED_AND_READY)
  735: 				tv.tv_sec = 0;
  736: 			else {
  737: 				extra_flist_sending_enabled = False;
  738: 				tv.tv_sec = select_timeout;
  739: 			}
  740: 		} else
  741: 			tv.tv_sec = select_timeout;
  742: 		tv.tv_usec = 0;
  743: 
  744: 		cnt = select(max_fd + 1, &r_fds, &w_fds, &e_fds, &tv);
  745: 
  746: 		if (cnt <= 0) {
  747: 			if (cnt < 0 && errno == EBADF) {
  748: 				msgs2stderr = 1;
  749: 				exit_cleanup(RERR_SOCKETIO);
  750: 			}
  751: 			if (extra_flist_sending_enabled) {
  752: 				extra_flist_sending_enabled = False;
  753: 				send_extra_file_list(sock_f_out, -1);
  754: 				extra_flist_sending_enabled = !flist_eof;
  755: 			} else
  756: 				check_timeout((flags & PIO_NEED_INPUT) != 0, 0);
  757: 			FD_ZERO(&r_fds); /* Just in case... */
  758: 			FD_ZERO(&w_fds);
  759: 		}
  760: 
  761: 		if (iobuf.in_fd >= 0 && FD_ISSET(iobuf.in_fd, &r_fds)) {
  762: 			size_t len, pos = iobuf.in.pos + iobuf.in.len;
  763: 			int n;
  764: 			if (pos >= iobuf.in.size) {
  765: 				pos -= iobuf.in.size;
  766: 				len = iobuf.in.size - iobuf.in.len;
  767: 			} else
  768: 				len = iobuf.in.size - pos;
  769: 			if ((n = read(iobuf.in_fd, iobuf.in.buf + pos, len)) <= 0) {
  770: 				if (n == 0) {
  771: 					/* Signal that input has become invalid. */
  772: 					if (!read_batch || batch_fd < 0 || am_generator)
  773: 						iobuf.in_fd = -2;
  774: 					batch_fd = -1;
  775: 					continue;
  776: 				}
  777: 				if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
  778: 					n = 0;
  779: 				else {
  780: 					/* Don't write errors on a dead socket. */
  781: 					if (iobuf.in_fd == sock_f_in) {
  782: 						if (am_sender)
  783: 							msgs2stderr = 1;
  784: 						rsyserr(FERROR_SOCKET, errno, "read error");
  785: 					} else
  786: 						rsyserr(FERROR, errno, "read error");
  787: 					exit_cleanup(RERR_SOCKETIO);
  788: 				}
  789: 			}
  790: 			if (msgs2stderr == 1 && DEBUG_GTE(IO, 2))
  791: 				rprintf(FINFO, "[%s] recv=%ld\n", who_am_i(), (long)n);
  792: 
  793: 			if (io_timeout || stop_at_utime) {
  794: 				last_io_in = time(NULL);
  795: 				if (stop_at_utime && last_io_in >= stop_at_utime) {
  796: 					rprintf(FERROR, "stopping at requested limit\n");
  797: 					exit_cleanup(RERR_TIMEOUT);
  798: 				}
  799: 				if (io_timeout && flags & PIO_NEED_INPUT)
  800: 					maybe_send_keepalive(last_io_in, 0);
  801: 			}
  802: 			stats.total_read += n;
  803: 
  804: 			iobuf.in.len += n;
  805: 		}
  806: 
  807: 		if (out && FD_ISSET(iobuf.out_fd, &w_fds)) {
  808: 			size_t len = iobuf.raw_flushing_ends_before ? iobuf.raw_flushing_ends_before - out->pos : out->len;
  809: 			int n;
  810: 
  811: 			if (bwlimit_writemax && len > bwlimit_writemax)
  812: 				len = bwlimit_writemax;
  813: 
  814: 			if (out->pos + len > out->size)
  815: 				len = out->size - out->pos;
  816: 			if ((n = write(iobuf.out_fd, out->buf + out->pos, len)) <= 0) {
  817: 				if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
  818: 					n = 0;
  819: 				else {
  820: 					/* Don't write errors on a dead socket. */
  821: 					msgs2stderr = 1;
  822: 					iobuf.out_fd = -2;
  823: 					iobuf.out.len = iobuf.msg.len = iobuf.raw_flushing_ends_before = 0;
  824: 					rsyserr(FERROR_SOCKET, errno, "write error");
  825: 					drain_multiplex_messages();
  826: 					exit_cleanup(RERR_SOCKETIO);
  827: 				}
  828: 			}
  829: 			if (msgs2stderr == 1 && DEBUG_GTE(IO, 2)) {
  830: 				rprintf(FINFO, "[%s] %s sent=%ld\n",
  831: 					who_am_i(), out == &iobuf.out ? "out" : "msg", (long)n);
  832: 			}
  833: 
  834: 			if (io_timeout)
  835: 				last_io_out = time(NULL);
  836: 			stats.total_written += n;
  837: 
  838: 			if (bwlimit_writemax)
  839: 				sleep_for_bwlimit(n);
  840: 
  841: 			if ((out->pos += n) == out->size) {
  842: 				if (iobuf.raw_flushing_ends_before)
  843: 					iobuf.raw_flushing_ends_before -= out->size;
  844: 				out->pos = 0;
  845: 				restore_iobuf_size(out);
  846: 			} else if (out->pos == iobuf.raw_flushing_ends_before)
  847: 				iobuf.raw_flushing_ends_before = 0;
  848: 			if ((out->len -= n) == empty_buf_len) {
  849: 				out->pos = 0;
  850: 				restore_iobuf_size(out);
  851: 				if (empty_buf_len)
  852: 					iobuf.raw_data_header_pos = 0;
  853: 			}
  854: 		}
  855: 
  856: 		if (got_kill_signal > 0)
  857: 			handle_kill_signal(True);
  858: 
  859: 		/* We need to help prevent deadlock by doing what reading
  860: 		 * we can whenever we are here trying to write. */
  861: 		if (IN_MULTIPLEXED_AND_READY && !(flags & PIO_NEED_INPUT)) {
  862: 			while (!iobuf.raw_input_ends_before && iobuf.in.len > 512)
  863: 				read_a_msg();
  864: 			if (flist_receiving_enabled && iobuf.in.len > 512)
  865: 				wait_for_receiver(); /* generator only */
  866: 		}
  867: 
  868: 		if (ff_forward_fd >= 0 && FD_ISSET(ff_forward_fd, &r_fds)) {
  869: 			/* This can potentially flush all output and enable
  870: 			 * multiplexed output, so keep this last in the loop
  871: 			 * and be sure to not cache anything that would break
  872: 			 * such a change. */
  873: 			forward_filesfrom_data();
  874: 		}
  875: 	}
  876:   double_break:
  877: 
  878: 	if (got_kill_signal > 0)
  879: 		handle_kill_signal(True);
  880: 
  881: 	data = iobuf.in.buf + iobuf.in.pos;
  882: 
  883: 	if (flags & PIO_CONSUME_INPUT) {
  884: 		iobuf.in.len -= needed;
  885: 		iobuf.in.pos += needed;
  886: 		if (iobuf.in.pos == iobuf.raw_input_ends_before)
  887: 			iobuf.raw_input_ends_before = 0;
  888: 		if (iobuf.in.pos >= iobuf.in.size) {
  889: 			iobuf.in.pos -= iobuf.in.size;
  890: 			if (iobuf.raw_input_ends_before)
  891: 				iobuf.raw_input_ends_before -= iobuf.in.size;
  892: 		}
  893: 	}
  894: 
  895: 	return data;
  896: }
  897: 
  898: static void raw_read_buf(char *buf, size_t len)
  899: {
  900: 	size_t pos = iobuf.in.pos;
  901: 	char *data = perform_io(len, PIO_INPUT_AND_CONSUME);
  902: 	if (iobuf.in.pos <= pos && len) {
  903: 		size_t siz = len - iobuf.in.pos;
  904: 		memcpy(buf, data, siz);
  905: 		memcpy(buf + siz, iobuf.in.buf, iobuf.in.pos);
  906: 	} else
  907: 		memcpy(buf, data, len);
  908: }
  909: 
  910: static int32 raw_read_int(void)
  911: {
  912: 	char *data, buf[4];
  913: 	if (iobuf.in.size - iobuf.in.pos >= 4)
  914: 		data = perform_io(4, PIO_INPUT_AND_CONSUME);
  915: 	else
  916: 		raw_read_buf(data = buf, 4);
  917: 	return IVAL(data, 0);
  918: }
  919: 
  920: void noop_io_until_death(void)
  921: {
  922: 	char buf[1024];
  923: 
  924: 	if (!iobuf.in.buf || !iobuf.out.buf || iobuf.in_fd < 0 || iobuf.out_fd < 0 || kluge_around_eof)
  925: 		return;
  926: 
  927: 	/* If we're talking to a daemon over a socket, don't short-circuit this logic */
  928: 	if (msgs2stderr && daemon_connection >= 0)
  929: 		return;
  930: 
  931: 	kluge_around_eof = 2;
  932: 	/* Setting an I/O timeout ensures that if something inexplicably weird
  933: 	 * happens, we won't hang around forever. */
  934: 	if (!io_timeout)
  935: 		set_io_timeout(60);
  936: 
  937: 	while (1)
  938: 		read_buf(iobuf.in_fd, buf, sizeof buf);
  939: }
  940: 
  941: /* Buffer a message for the multiplexed output stream.  Is not used for (normal) MSG_DATA. */
  942: int send_msg(enum msgcode code, const char *buf, size_t len, int convert)
  943: {
  944: 	char *hdr;
  945: 	size_t needed, pos;
  946: 	BOOL want_debug = DEBUG_GTE(IO, 1) && convert >= 0 && (msgs2stderr == 1 || code != MSG_INFO);
  947: 
  948: 	if (!OUT_MULTIPLEXED)
  949: 		return 0;
  950: 
  951: 	if (want_debug)
  952: 		rprintf(FINFO, "[%s] send_msg(%d, %ld)\n", who_am_i(), (int)code, (long)len);
  953: 
  954: 	/* When checking for enough free space for this message, we need to
  955: 	 * make sure that there is space for the 4-byte header, plus we'll
  956: 	 * assume that we may waste up to 3 bytes (if the header doesn't fit
  957: 	 * at the physical end of the buffer). */
  958: #ifdef ICONV_OPTION
  959: 	if (convert > 0 && ic_send == (iconv_t)-1)
  960: 		convert = 0;
  961: 	if (convert > 0) {
  962: 		/* Ensuring double-size room leaves space for maximal conversion expansion. */
  963: 		needed = len*2 + 4 + 3;
  964: 	} else
  965: #endif
  966: 		needed = len + 4 + 3;
  967: 	if (iobuf.msg.len + needed > iobuf.msg.size) {
  968: 		if (!am_receiver)
  969: 			perform_io(needed, PIO_NEED_MSGROOM);
  970: 		else { /* We allow the receiver to increase their iobuf.msg size to avoid a deadlock. */
  971: 			size_t old_size = iobuf.msg.size;
  972: 			restore_iobuf_size(&iobuf.msg);
  973: 			realloc_xbuf(&iobuf.msg, iobuf.msg.size * 2);
  974: 			if (iobuf.msg.pos + iobuf.msg.len > old_size)
  975: 				memcpy(iobuf.msg.buf + old_size, iobuf.msg.buf, iobuf.msg.pos + iobuf.msg.len - old_size);
  976: 		}
  977: 	}
  978: 
  979: 	pos = iobuf.msg.pos + iobuf.msg.len; /* Must be set after any flushing. */
  980: 	if (pos >= iobuf.msg.size)
  981: 		pos -= iobuf.msg.size;
  982: 	else if (pos + 4 > iobuf.msg.size) {
  983: 		/* The 4-byte header won't fit at the end of the buffer,
  984: 		 * so we'll temporarily reduce the message buffer's size
  985: 		 * and put the header at the start of the buffer. */
  986: 		reduce_iobuf_size(&iobuf.msg, pos);
  987: 		pos = 0;
  988: 	}
  989: 	hdr = iobuf.msg.buf + pos;
  990: 
  991: 	iobuf.msg.len += 4; /* Allocate room for the coming header bytes. */
  992: 
  993: #ifdef ICONV_OPTION
  994: 	if (convert > 0) {
  995: 		xbuf inbuf;
  996: 
  997: 		INIT_XBUF(inbuf, (char*)buf, len, (size_t)-1);
  998: 
  999: 		len = iobuf.msg.len;
 1000: 		iconvbufs(ic_send, &inbuf, &iobuf.msg,
 1001: 			  ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE | ICB_CIRCULAR_OUT | ICB_INIT);
 1002: 		if (inbuf.len > 0) {
 1003: 			rprintf(FERROR, "overflowed iobuf.msg buffer in send_msg");
 1004: 			exit_cleanup(RERR_UNSUPPORTED);
 1005: 		}
 1006: 		len = iobuf.msg.len - len;
 1007: 	} else
 1008: #endif
 1009: 	{
 1010: 		size_t siz;
 1011: 
 1012: 		if ((pos += 4) == iobuf.msg.size)
 1013: 			pos = 0;
 1014: 
 1015: 		/* Handle a split copy if we wrap around the end of the circular buffer. */
 1016: 		if (pos >= iobuf.msg.pos && (siz = iobuf.msg.size - pos) < len) {
 1017: 			memcpy(iobuf.msg.buf + pos, buf, siz);
 1018: 			memcpy(iobuf.msg.buf, buf + siz, len - siz);
 1019: 		} else
 1020: 			memcpy(iobuf.msg.buf + pos, buf, len);
 1021: 
 1022: 		iobuf.msg.len += len;
 1023: 	}
 1024: 
 1025: 	SIVAL(hdr, 0, ((MPLEX_BASE + (int)code)<<24) + len);
 1026: 
 1027: 	if (want_debug && convert > 0)
 1028: 		rprintf(FINFO, "[%s] converted msg len=%ld\n", who_am_i(), (long)len);
 1029: 
 1030: 	return 1;
 1031: }
 1032: 
 1033: void send_msg_int(enum msgcode code, int num)
 1034: {
 1035: 	char numbuf[4];
 1036: 
 1037: 	if (DEBUG_GTE(IO, 1))
 1038: 		rprintf(FINFO, "[%s] send_msg_int(%d, %d)\n", who_am_i(), (int)code, num);
 1039: 
 1040: 	SIVAL(numbuf, 0, num);
 1041: 	send_msg(code, numbuf, 4, -1);
 1042: }
 1043: 
 1044: static void got_flist_entry_status(enum festatus status, int ndx)
 1045: {
 1046: 	struct file_list *flist = flist_for_ndx(ndx, "got_flist_entry_status");
 1047: 
 1048: 	if (remove_source_files) {
 1049: 		active_filecnt--;
 1050: 		active_bytecnt -= F_LENGTH(flist->files[ndx - flist->ndx_start]);
 1051: 	}
 1052: 
 1053: 	if (inc_recurse)
 1054: 		flist->in_progress--;
 1055: 
 1056: 	switch (status) {
 1057: 	case FES_SUCCESS:
 1058: 		if (remove_source_files)
 1059: 			send_msg_int(MSG_SUCCESS, ndx);
 1060: 		/* FALL THROUGH */
 1061: 	case FES_NO_SEND:
 1062: #ifdef SUPPORT_HARD_LINKS
 1063: 		if (preserve_hard_links) {
 1064: 			struct file_struct *file = flist->files[ndx - flist->ndx_start];
 1065: 			if (F_IS_HLINKED(file)) {
 1066: 				if (status == FES_NO_SEND)
 1067: 					flist_ndx_push(&hlink_list, -2); /* indicates a failure follows */
 1068: 				flist_ndx_push(&hlink_list, ndx);
 1069: 				if (inc_recurse)
 1070: 					flist->in_progress++;
 1071: 			}
 1072: 		} else if (checksum_files & CSF_UPDATE) {
 1073: 			struct file_struct *file = flist->files[ndx - flist->ndx_start];
 1074: 			set_cached_checksum(flist, file);
 1075: 		}
 1076: #endif
 1077: 		break;
 1078: 	case FES_REDO:
 1079: 		if (read_batch) {
 1080: 			if (inc_recurse)
 1081: 				flist->in_progress++;
 1082: 			break;
 1083: 		}
 1084: 		if (inc_recurse)
 1085: 			flist->to_redo++;
 1086: 		flist_ndx_push(&redo_list, ndx);
 1087: 		break;
 1088: 	}
 1089: }
 1090: 
 1091: /* Note the fds used for the main socket (which might really be a pipe
 1092:  * for a local transfer, but we can ignore that). */
 1093: void io_set_sock_fds(int f_in, int f_out)
 1094: {
 1095: 	sock_f_in = f_in;
 1096: 	sock_f_out = f_out;
 1097: }
 1098: 
 1099: void set_io_timeout(int secs)
 1100: {
 1101: 	io_timeout = secs;
 1102: 	allowed_lull = (io_timeout + 1) / 2;
 1103: 
 1104: 	if (!io_timeout || allowed_lull > SELECT_TIMEOUT)
 1105: 		select_timeout = SELECT_TIMEOUT;
 1106: 	else
 1107: 		select_timeout = allowed_lull;
 1108: 
 1109: 	if (read_batch)
 1110: 		allowed_lull = 0;
 1111: }
 1112: 
 1113: static void check_for_d_option_error(const char *msg)
 1114: {
 1115: 	static char rsync263_opts[] = "BCDHIKLPRSTWabceghlnopqrtuvxz";
 1116: 	char *colon;
 1117: 	int saw_d = 0;
 1118: 
 1119: 	if (*msg != 'r'
 1120: 	 || strncmp(msg, REMOTE_OPTION_ERROR, sizeof REMOTE_OPTION_ERROR - 1) != 0)
 1121: 		return;
 1122: 
 1123: 	msg += sizeof REMOTE_OPTION_ERROR - 1;
 1124: 	if (*msg == '-' || (colon = strchr(msg, ':')) == NULL
 1125: 	 || strncmp(colon, REMOTE_OPTION_ERROR2, sizeof REMOTE_OPTION_ERROR2 - 1) != 0)
 1126: 		return;
 1127: 
 1128: 	for ( ; *msg != ':'; msg++) {
 1129: 		if (*msg == 'd')
 1130: 			saw_d = 1;
 1131: 		else if (*msg == 'e')
 1132: 			break;
 1133: 		else if (strchr(rsync263_opts, *msg) == NULL)
 1134: 			return;
 1135: 	}
 1136: 
 1137: 	if (saw_d) {
 1138: 		rprintf(FWARNING, "*** Try using \"--old-d\" if remote rsync is <= 2.6.3 ***\n");
 1139: 	}
 1140: }
 1141: 
 1142: /* This is used by the generator to limit how many file transfers can
 1143:  * be active at once when --remove-source-files is specified.  Without
 1144:  * this, sender-side deletions were mostly happening at the end. */
 1145: void increment_active_files(int ndx, int itemizing, enum logcode code)
 1146: {
 1147: 	while (1) {
 1148: 		/* TODO: tune these limits? */
 1149: 		int limit = active_bytecnt >= 128*1024 ? 10 : 50;
 1150: 		if (active_filecnt < limit)
 1151: 			break;
 1152: 		check_for_finished_files(itemizing, code, 0);
 1153: 		if (active_filecnt < limit)
 1154: 			break;
 1155: 		wait_for_receiver();
 1156: 	}
 1157: 
 1158: 	active_filecnt++;
 1159: 	active_bytecnt += F_LENGTH(cur_flist->files[ndx - cur_flist->ndx_start]);
 1160: }
 1161: 
 1162: int get_redo_num(void)
 1163: {
 1164: 	return flist_ndx_pop(&redo_list);
 1165: }
 1166: 
 1167: int get_hlink_num(void)
 1168: {
 1169: 	return flist_ndx_pop(&hlink_list);
 1170: }
 1171: 
 1172: /* When we're the receiver and we have a local --files-from list of names
 1173:  * that needs to be sent over the socket to the sender, we have to do two
 1174:  * things at the same time: send the sender a list of what files we're
 1175:  * processing and read the incoming file+info list from the sender.  We do
 1176:  * this by making recv_file_list() call forward_filesfrom_data(), which
 1177:  * will ensure that we forward data to the sender until we get some data
 1178:  * for recv_file_list() to use. */
 1179: void start_filesfrom_forwarding(int fd)
 1180: {
 1181: 	if (protocol_version < 31 && OUT_MULTIPLEXED) {
 1182: 		/* Older protocols send the files-from data w/o packaging
 1183: 		 * it in multiplexed I/O packets, so temporarily switch
 1184: 		 * to buffered I/O to match this behavior. */
 1185: 		iobuf.msg.pos = iobuf.msg.len = 0; /* Be extra sure no messages go out. */
 1186: 		ff_reenable_multiplex = io_end_multiplex_out(MPLX_TO_BUFFERED);
 1187: 	}
 1188: 	ff_forward_fd = fd;
 1189: 
 1190: 	alloc_xbuf(&ff_xb, FILESFROM_BUFLEN);
 1191: }
 1192: 
 1193: /* Read a line into the "buf" buffer. */
 1194: int read_line(int fd, char *buf, size_t bufsiz, int flags)
 1195: {
 1196: 	char ch, *s, *eob;
 1197: 
 1198: #ifdef ICONV_OPTION
 1199: 	if (flags & RL_CONVERT && iconv_buf.size < bufsiz)
 1200: 		realloc_xbuf(&iconv_buf, ROUND_UP_1024(bufsiz) + 1024);
 1201: #endif
 1202: 
 1203:   start:
 1204: #ifdef ICONV_OPTION
 1205: 	s = flags & RL_CONVERT ? iconv_buf.buf : buf;
 1206: #else
 1207: 	s = buf;
 1208: #endif
 1209: 	eob = s + bufsiz - 1;
 1210: 	while (1) {
 1211: 		/* We avoid read_byte() for files because files can return an EOF. */
 1212: 		if (fd == iobuf.in_fd)
 1213: 			ch = read_byte(fd);
 1214: 		else if (safe_read(fd, &ch, 1) == 0)
 1215: 			break;
 1216: 		if (flags & RL_EOL_NULLS ? ch == '\0' : (ch == '\r' || ch == '\n')) {
 1217: 			/* Skip empty lines if dumping comments. */
 1218: 			if (flags & RL_DUMP_COMMENTS && s == buf)
 1219: 				continue;
 1220: 			break;
 1221: 		}
 1222: 		if (s < eob)
 1223: 			*s++ = ch;
 1224: 	}
 1225: 	*s = '\0';
 1226: 
 1227: 	if (flags & RL_DUMP_COMMENTS && (*buf == '#' || *buf == ';'))
 1228: 		goto start;
 1229: 
 1230: #ifdef ICONV_OPTION
 1231: 	if (flags & RL_CONVERT) {
 1232: 		xbuf outbuf;
 1233: 		INIT_XBUF(outbuf, buf, 0, bufsiz);
 1234: 		iconv_buf.pos = 0;
 1235: 		iconv_buf.len = s - iconv_buf.buf;
 1236: 		iconvbufs(ic_recv, &iconv_buf, &outbuf,
 1237: 			  ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE | ICB_INIT);
 1238: 		outbuf.buf[outbuf.len] = '\0';
 1239: 		return outbuf.len;
 1240: 	}
 1241: #endif
 1242: 
 1243: 	return s - buf;
 1244: }
 1245: 
 1246: void read_args(int f_in, char *mod_name, char *buf, size_t bufsiz, int rl_nulls,
 1247: 	       char ***argv_p, int *argc_p, char **request_p)
 1248: {
 1249: 	int maxargs = MAX_ARGS;
 1250: 	int dot_pos = 0, argc = 0, request_len = 0;
 1251: 	char **argv, *p;
 1252: 	int rl_flags = (rl_nulls ? RL_EOL_NULLS : 0);
 1253: 
 1254: #ifdef ICONV_OPTION
 1255: 	rl_flags |= (protect_args && ic_recv != (iconv_t)-1 ? RL_CONVERT : 0);
 1256: #endif
 1257: 
 1258: 	argv = new_array(char *, maxargs);
 1259: 	if (mod_name && !protect_args)
 1260: 		argv[argc++] = "rsyncd";
 1261: 
 1262: 	if (request_p)
 1263: 		*request_p = NULL;
 1264: 
 1265: 	while (1) {
 1266: 		if (read_line(f_in, buf, bufsiz, rl_flags) == 0)
 1267: 			break;
 1268: 
 1269: 		if (argc == maxargs-1) {
 1270: 			maxargs += MAX_ARGS;
 1271: 			argv = realloc_array(argv, char *, maxargs);
 1272: 		}
 1273: 
 1274: 		if (dot_pos) {
 1275: 			if (request_p && request_len < 1024) {
 1276: 				int len = strlen(buf);
 1277: 				if (request_len)
 1278: 					request_p[0][request_len++] = ' ';
 1279: 				*request_p = realloc_array(*request_p, char, request_len + len + 1);
 1280: 				memcpy(*request_p + request_len, buf, len + 1);
 1281: 				request_len += len;
 1282: 			}
 1283: 			if (mod_name)
 1284: 				glob_expand_module(mod_name, buf, &argv, &argc, &maxargs);
 1285: 			else
 1286: 				glob_expand(buf, &argv, &argc, &maxargs);
 1287: 		} else {
 1288: 			p = strdup(buf);
 1289: 			argv[argc++] = p;
 1290: 			if (*p == '.' && p[1] == '\0')
 1291: 				dot_pos = argc;
 1292: 		}
 1293: 	}
 1294: 	argv[argc] = NULL;
 1295: 
 1296: 	glob_expand(NULL, NULL, NULL, NULL);
 1297: 
 1298: 	*argc_p = argc;
 1299: 	*argv_p = argv;
 1300: }
 1301: 
 1302: BOOL io_start_buffering_out(int f_out)
 1303: {
 1304: 	if (msgs2stderr == 1 && DEBUG_GTE(IO, 2))
 1305: 		rprintf(FINFO, "[%s] io_start_buffering_out(%d)\n", who_am_i(), f_out);
 1306: 
 1307: 	if (iobuf.out.buf) {
 1308: 		if (iobuf.out_fd == -1)
 1309: 			iobuf.out_fd = f_out;
 1310: 		else
 1311: 			assert(f_out == iobuf.out_fd);
 1312: 		return False;
 1313: 	}
 1314: 
 1315: 	alloc_xbuf(&iobuf.out, ROUND_UP_1024(IO_BUFFER_SIZE * 2));
 1316: 	iobuf.out_fd = f_out;
 1317: 
 1318: 	return True;
 1319: }
 1320: 
 1321: BOOL io_start_buffering_in(int f_in)
 1322: {
 1323: 	if (msgs2stderr == 1 && DEBUG_GTE(IO, 2))
 1324: 		rprintf(FINFO, "[%s] io_start_buffering_in(%d)\n", who_am_i(), f_in);
 1325: 
 1326: 	if (iobuf.in.buf) {
 1327: 		if (iobuf.in_fd == -1)
 1328: 			iobuf.in_fd = f_in;
 1329: 		else
 1330: 			assert(f_in == iobuf.in_fd);
 1331: 		return False;
 1332: 	}
 1333: 
 1334: 	alloc_xbuf(&iobuf.in, ROUND_UP_1024(IO_BUFFER_SIZE));
 1335: 	iobuf.in_fd = f_in;
 1336: 
 1337: 	return True;
 1338: }
 1339: 
 1340: void io_end_buffering_in(BOOL free_buffers)
 1341: {
 1342: 	if (msgs2stderr == 1 && DEBUG_GTE(IO, 2)) {
 1343: 		rprintf(FINFO, "[%s] io_end_buffering_in(IOBUF_%s_BUFS)\n",
 1344: 			who_am_i(), free_buffers ? "FREE" : "KEEP");
 1345: 	}
 1346: 
 1347: 	if (free_buffers)
 1348: 		free_xbuf(&iobuf.in);
 1349: 	else
 1350: 		iobuf.in.pos = iobuf.in.len = 0;
 1351: 
 1352: 	iobuf.in_fd = -1;
 1353: }
 1354: 
 1355: void io_end_buffering_out(BOOL free_buffers)
 1356: {
 1357: 	if (msgs2stderr == 1 && DEBUG_GTE(IO, 2)) {
 1358: 		rprintf(FINFO, "[%s] io_end_buffering_out(IOBUF_%s_BUFS)\n",
 1359: 			who_am_i(), free_buffers ? "FREE" : "KEEP");
 1360: 	}
 1361: 
 1362: 	io_flush(FULL_FLUSH);
 1363: 
 1364: 	if (free_buffers) {
 1365: 		free_xbuf(&iobuf.out);
 1366: 		free_xbuf(&iobuf.msg);
 1367: 	}
 1368: 
 1369: 	iobuf.out_fd = -1;
 1370: }
 1371: 
 1372: void maybe_flush_socket(int important)
 1373: {
 1374: 	if (flist_eof && iobuf.out.buf && iobuf.out.len > iobuf.out_empty_len
 1375: 	 && (important || time(NULL) - last_io_out >= 5))
 1376: 		io_flush(NORMAL_FLUSH);
 1377: }
 1378: 
 1379: /* Older rsync versions used to send either a MSG_NOOP (protocol 30) or a
 1380:  * raw-data-based keep-alive (protocol 29), both of which implied forwarding of
 1381:  * the message through the sender.  Since the new timeout method does not need
 1382:  * any forwarding, we just send an empty MSG_DATA message, which works with all
 1383:  * rsync versions.  This avoids any message forwarding, and leaves the raw-data
 1384:  * stream alone (since we can never be quite sure if that stream is in the
 1385:  * right state for a keep-alive message). */
 1386: void maybe_send_keepalive(time_t now, int flags)
 1387: {
 1388: 	if (flags & MSK_ACTIVE_RECEIVER)
 1389: 		last_io_in = now; /* Fudge things when we're working hard on the files. */
 1390: 
 1391: 	/* Early in the transfer (before the receiver forks) the receiving side doesn't
 1392: 	 * care if it hasn't sent data in a while as long as it is receiving data (in
 1393: 	 * fact, a pre-3.1.0 rsync would die if we tried to send it a keep alive during
 1394: 	 * this time).  So, if we're an early-receiving proc, just return and let the
 1395: 	 * incoming data determine if we timeout. */
 1396: 	if (!am_sender && !am_receiver && !am_generator)
 1397: 		return;
 1398: 
 1399: 	if (now - last_io_out >= allowed_lull) {
 1400: 		/* The receiver is special:  it only sends keep-alive messages if it is
 1401: 		 * actively receiving data.  Otherwise, it lets the generator timeout. */
 1402: 		if (am_receiver && now - last_io_in >= io_timeout)
 1403: 			return;
 1404: 
 1405: 		if (!iobuf.msg.len && iobuf.out.len == iobuf.out_empty_len)
 1406: 			send_msg(MSG_DATA, "", 0, 0);
 1407: 		if (!(flags & MSK_ALLOW_FLUSH)) {
 1408: 			/* Let the caller worry about writing out the data. */
 1409: 		} else if (iobuf.msg.len)
 1410: 			perform_io(iobuf.msg.size - iobuf.msg.len + 1, PIO_NEED_MSGROOM);
 1411: 		else if (iobuf.out.len > iobuf.out_empty_len)
 1412: 			io_flush(NORMAL_FLUSH);
 1413: 	}
 1414: }
 1415: 
 1416: void start_flist_forward(int ndx)
 1417: {
 1418: 	write_int(iobuf.out_fd, ndx);
 1419: 	forward_flist_data = 1;
 1420: }
 1421: 
 1422: void stop_flist_forward(void)
 1423: {
 1424: 	forward_flist_data = 0;
 1425: }
 1426: 
 1427: /* Read a message from a multiplexed source. */
 1428: static void read_a_msg(void)
 1429: {
 1430: 	char data[BIGPATHBUFLEN];
 1431: 	int tag, val;
 1432: 	size_t msg_bytes;
 1433: 
 1434: 	/* This ensures that perform_io() does not try to do any message reading
 1435: 	 * until we've read all of the data for this message.  We should also
 1436: 	 * try to avoid calling things that will cause data to be written via
 1437: 	 * perform_io() prior to this being reset to 1. */
 1438: 	iobuf.in_multiplexed = -1;
 1439: 
 1440: 	tag = raw_read_int();
 1441: 
 1442: 	msg_bytes = tag & 0xFFFFFF;
 1443: 	tag = (tag >> 24) - MPLEX_BASE;
 1444: 
 1445: 	if (msgs2stderr == 1 && DEBUG_GTE(IO, 1))
 1446: 		rprintf(FINFO, "[%s] got msg=%d, len=%ld\n", who_am_i(), (int)tag, (long)msg_bytes);
 1447: 
 1448: 	switch (tag) {
 1449: 	case MSG_DATA:
 1450: 		assert(iobuf.raw_input_ends_before == 0);
 1451: 		/* Though this does not yet read the data, we do mark where in
 1452: 		 * the buffer the msg data will end once it is read.  It is
 1453: 		 * possible that this points off the end of the buffer, in
 1454: 		 * which case the gradual reading of the input stream will
 1455: 		 * cause this value to wrap around and eventually become real. */
 1456: 		if (msg_bytes)
 1457: 			iobuf.raw_input_ends_before = iobuf.in.pos + msg_bytes;
 1458: 		iobuf.in_multiplexed = 1;
 1459: 		break;
 1460: 	case MSG_STATS:
 1461: 		if (msg_bytes != sizeof stats.total_read || !am_generator)
 1462: 			goto invalid_msg;
 1463: 		raw_read_buf((char*)&stats.total_read, sizeof stats.total_read);
 1464: 		iobuf.in_multiplexed = 1;
 1465: 		break;
 1466: 	case MSG_REDO:
 1467: 		if (msg_bytes != 4 || !am_generator)
 1468: 			goto invalid_msg;
 1469: 		val = raw_read_int();
 1470: 		iobuf.in_multiplexed = 1;
 1471: 		got_flist_entry_status(FES_REDO, val);
 1472: 		break;
 1473: 	case MSG_IO_ERROR:
 1474: 		if (msg_bytes != 4)
 1475: 			goto invalid_msg;
 1476: 		val = raw_read_int();
 1477: 		iobuf.in_multiplexed = 1;
 1478: 		io_error |= val;
 1479: 		if (am_receiver)
 1480: 			send_msg_int(MSG_IO_ERROR, val);
 1481: 		break;
 1482: 	case MSG_IO_TIMEOUT:
 1483: 		if (msg_bytes != 4 || am_server || am_generator)
 1484: 			goto invalid_msg;
 1485: 		val = raw_read_int();
 1486: 		iobuf.in_multiplexed = 1;
 1487: 		if (!io_timeout || io_timeout > val) {
 1488: 			if (INFO_GTE(MISC, 2))
 1489: 				rprintf(FINFO, "Setting --timeout=%d to match server\n", val);
 1490: 			set_io_timeout(val);
 1491: 		}
 1492: 		break;
 1493: 	case MSG_NOOP:
 1494: 		/* Support protocol-30 keep-alive method. */
 1495: 		if (msg_bytes != 0)
 1496: 			goto invalid_msg;
 1497: 		iobuf.in_multiplexed = 1;
 1498: 		if (am_sender)
 1499: 			maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH);
 1500: 		break;
 1501: 	case MSG_CHECKSUM:
 1502: 		/* This receives some checksum info that we want to make a note of
 1503: 		 * (which allows a single process to do all the writing to the db). */
 1504: 		if (msg_bytes != MSG_CHECKSUM_LEN)
 1505: 			goto overflow;
 1506: 		raw_read_buf(data, MSG_CHECKSUM_LEN);
 1507: 		if (am_generator && same_db) {
 1508: 			iobuf.in_multiplexed = 1;
 1509: 			send_msg(MSG_CHECKSUM, data, MSG_CHECKSUM_LEN, 0);
 1510: 		} if (am_receiver || (am_sender && !local_server))
 1511: 			goto unexpected;
 1512: 		else {
 1513: 			/* The received data is a set of numbers followed by the checksum. */
 1514: 			STRUCT_STAT st;
 1515: 			st.st_dev = IVAL64(data, 0);
 1516: 			st.st_ino = IVAL64(data, 8);
 1517: 			st.st_size = IVAL64(data, 16);
 1518: 			st.st_mtime = IVAL64(data, 24);
 1519: 			st.st_ctime = IVAL64(data, 32);
 1520: #if MSG_CHECKSUM_LONGS != 5
 1521: #error Fix the parsing of checksum long values
 1522: #endif
 1523: 			iobuf.in_multiplexed = 1;
 1524: 			db_set_checksum(IVAL(data, MSG_CHECKSUM_LONGS*8), &st, data + MSG_CHECKSUM_LONGS*8 + 4);
 1525: 		}
 1526: 		break;
 1527: 	case MSG_DELETED:
 1528: 		if (msg_bytes >= sizeof data)
 1529: 			goto overflow;
 1530: 		if (am_generator) {
 1531: 			raw_read_buf(data, msg_bytes);
 1532: 			iobuf.in_multiplexed = 1;
 1533: 			send_msg(MSG_DELETED, data, msg_bytes, 1);
 1534: 			break;
 1535: 		}
 1536: #ifdef ICONV_OPTION
 1537: 		if (ic_recv != (iconv_t)-1) {
 1538: 			xbuf outbuf, inbuf;
 1539: 			char ibuf[512];
 1540: 			int add_null = 0;
 1541: 			int flags = ICB_INCLUDE_BAD | ICB_INIT;
 1542: 
 1543: 			INIT_CONST_XBUF(outbuf, data);
 1544: 			INIT_XBUF(inbuf, ibuf, 0, (size_t)-1);
 1545: 
 1546: 			while (msg_bytes) {
 1547: 				size_t len = msg_bytes > sizeof ibuf - inbuf.len ? sizeof ibuf - inbuf.len : msg_bytes;
 1548: 				raw_read_buf(ibuf + inbuf.len, len);
 1549: 				inbuf.pos = 0;
 1550: 				inbuf.len += len;
 1551: 				if (!(msg_bytes -= len) && !ibuf[inbuf.len-1])
 1552: 					inbuf.len--, add_null = 1;
 1553: 				if (iconvbufs(ic_send, &inbuf, &outbuf, flags) < 0) {
 1554: 					if (errno == E2BIG)
 1555: 						goto overflow;
 1556: 					/* Buffer ended with an incomplete char, so move the
 1557: 					 * bytes to the start of the buffer and continue. */
 1558: 					memmove(ibuf, ibuf + inbuf.pos, inbuf.len);
 1559: 				}
 1560: 				flags &= ~ICB_INIT;
 1561: 			}
 1562: 			if (add_null) {
 1563: 				if (outbuf.len == outbuf.size)
 1564: 					goto overflow;
 1565: 				outbuf.buf[outbuf.len++] = '\0';
 1566: 			}
 1567: 			msg_bytes = outbuf.len;
 1568: 		} else
 1569: #endif
 1570: 			raw_read_buf(data, msg_bytes);
 1571: 		iobuf.in_multiplexed = 1;
 1572: 		/* A directory name was sent with the trailing null */
 1573: 		if (msg_bytes > 0 && !data[msg_bytes-1])
 1574: 			log_delete(data, S_IFDIR);
 1575: 		else {
 1576: 			data[msg_bytes] = '\0';
 1577: 			log_delete(data, S_IFREG);
 1578: 		}
 1579: 		break;
 1580: 	case MSG_SUCCESS:
 1581: 		if (msg_bytes != 4) {
 1582: 		  invalid_msg:
 1583: 			rprintf(FERROR, "invalid multi-message %d:%lu [%s%s]\n",
 1584: 				tag, (unsigned long)msg_bytes, who_am_i(),
 1585: 				inc_recurse ? "/inc" : "");
 1586: 			exit_cleanup(RERR_STREAMIO);
 1587: 		}
 1588: 		val = raw_read_int();
 1589: 		iobuf.in_multiplexed = 1;
 1590: 		if (am_generator)
 1591: 			got_flist_entry_status(FES_SUCCESS, val);
 1592: 		else
 1593: 			successful_send(val);
 1594: 		break;
 1595: 	case MSG_NO_SEND:
 1596: 		if (msg_bytes != 4)
 1597: 			goto invalid_msg;
 1598: 		val = raw_read_int();
 1599: 		iobuf.in_multiplexed = 1;
 1600: 		if (am_generator)
 1601: 			got_flist_entry_status(FES_NO_SEND, val);
 1602: 		else
 1603: 			send_msg_int(MSG_NO_SEND, val);
 1604: 		break;
 1605: 	case MSG_ERROR_SOCKET:
 1606: 	case MSG_ERROR_UTF8:
 1607: 	case MSG_CLIENT:
 1608: 	case MSG_LOG:
 1609: 		if (!am_generator)
 1610: 			goto invalid_msg;
 1611: 		if (tag == MSG_ERROR_SOCKET)
 1612: 			msgs2stderr = 1;
 1613: 		/* FALL THROUGH */
 1614: 	case MSG_INFO:
 1615: 	case MSG_ERROR:
 1616: 	case MSG_ERROR_XFER:
 1617: 	case MSG_WARNING:
 1618: 		if (msg_bytes >= sizeof data) {
 1619: 		    overflow:
 1620: 			rprintf(FERROR,
 1621: 				"multiplexing overflow %d:%lu [%s%s]\n",
 1622: 				tag, (unsigned long)msg_bytes, who_am_i(),
 1623: 				inc_recurse ? "/inc" : "");
 1624: 			exit_cleanup(RERR_STREAMIO);
 1625: 		}
 1626: 		raw_read_buf(data, msg_bytes);
 1627: 		/* We don't set in_multiplexed value back to 1 before writing this message
 1628: 		 * because the write might loop back and read yet another message, over and
 1629: 		 * over again, while waiting for room to put the message in the msg buffer. */
 1630: 		rwrite((enum logcode)tag, data, msg_bytes, !am_generator);
 1631: 		iobuf.in_multiplexed = 1;
 1632: 		if (first_message) {
 1633: 			if (list_only && !am_sender && tag == 1 && msg_bytes < sizeof data) {
 1634: 				data[msg_bytes] = '\0';
 1635: 				check_for_d_option_error(data);
 1636: 			}
 1637: 			first_message = 0;
 1638: 		}
 1639: 		break;
 1640: 	case MSG_ERROR_EXIT:
 1641: 		if (msg_bytes == 4)
 1642: 			val = raw_read_int();
 1643: 		else if (msg_bytes == 0)
 1644: 			val = 0;
 1645: 		else
 1646: 			goto invalid_msg;
 1647: 		iobuf.in_multiplexed = 1;
 1648: 		if (DEBUG_GTE(EXIT, 3))
 1649: 			rprintf(FINFO, "[%s] got MSG_ERROR_EXIT with %ld bytes\n", who_am_i(), (long)msg_bytes);
 1650: 		if (msg_bytes == 0) {
 1651: 			if (!am_sender && !am_generator) {
 1652: 				if (DEBUG_GTE(EXIT, 3)) {
 1653: 					rprintf(FINFO, "[%s] sending MSG_ERROR_EXIT (len 0)\n",
 1654: 						who_am_i());
 1655: 				}
 1656: 				send_msg(MSG_ERROR_EXIT, "", 0, 0);
 1657: 				io_flush(FULL_FLUSH);
 1658: 			}
 1659: 		} else if (protocol_version >= 31) {
 1660: 			if (am_generator || am_receiver) {
 1661: 				if (DEBUG_GTE(EXIT, 3)) {
 1662: 					rprintf(FINFO, "[%s] sending MSG_ERROR_EXIT with exit_code %d\n",
 1663: 						who_am_i(), val);
 1664: 				}
 1665: 				send_msg_int(MSG_ERROR_EXIT, val);
 1666: 			} else {
 1667: 				if (DEBUG_GTE(EXIT, 3)) {
 1668: 					rprintf(FINFO, "[%s] sending MSG_ERROR_EXIT (len 0)\n",
 1669: 						who_am_i());
 1670: 				}
 1671: 				send_msg(MSG_ERROR_EXIT, "", 0, 0);
 1672: 			}
 1673: 		}
 1674: 		/* Send a negative linenum so that we don't end up
 1675: 		 * with a duplicate exit message. */
 1676: 		_exit_cleanup(val, __FILE__, 0 - __LINE__);
 1677: 	default:
 1678: 	unexpected:
 1679: 		rprintf(FERROR, "unexpected tag %d [%s%s]\n",
 1680: 			tag, who_am_i(), inc_recurse ? "/inc" : "");
 1681: 		exit_cleanup(RERR_STREAMIO);
 1682: 	}
 1683: 
 1684: 	assert(iobuf.in_multiplexed > 0);
 1685: }
 1686: 
 1687: static void drain_multiplex_messages(void)
 1688: {
 1689: 	while (IN_MULTIPLEXED_AND_READY && iobuf.in.len) {
 1690: 		if (iobuf.raw_input_ends_before) {
 1691: 			size_t raw_len = iobuf.raw_input_ends_before - iobuf.in.pos;
 1692: 			iobuf.raw_input_ends_before = 0;
 1693: 			if (raw_len >= iobuf.in.len) {
 1694: 				iobuf.in.len = 0;
 1695: 				break;
 1696: 			}
 1697: 			iobuf.in.len -= raw_len;
 1698: 			if ((iobuf.in.pos += raw_len) >= iobuf.in.size)
 1699: 				iobuf.in.pos -= iobuf.in.size;
 1700: 		}
 1701: 		read_a_msg();
 1702: 	}
 1703: }
 1704: 
 1705: void wait_for_receiver(void)
 1706: {
 1707: 	if (!iobuf.raw_input_ends_before)
 1708: 		read_a_msg();
 1709: 
 1710: 	if (iobuf.raw_input_ends_before) {
 1711: 		int ndx = read_int(iobuf.in_fd);
 1712: 		if (ndx < 0) {
 1713: 			switch (ndx) {
 1714: 			case NDX_FLIST_EOF:
 1715: 				flist_eof = 1;
 1716: 				if (DEBUG_GTE(FLIST, 3))
 1717: 					rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
 1718: 				break;
 1719: 			case NDX_DONE:
 1720: 				msgdone_cnt++;
 1721: 				break;
 1722: 			default:
 1723: 				exit_cleanup(RERR_STREAMIO);
 1724: 			}
 1725: 		} else {
 1726: 			struct file_list *flist;
 1727: 			flist_receiving_enabled = False;
 1728: 			if (DEBUG_GTE(FLIST, 2)) {
 1729: 				rprintf(FINFO, "[%s] receiving flist for dir %d\n",
 1730: 					who_am_i(), ndx);
 1731: 			}
 1732: 			flist = recv_file_list(iobuf.in_fd, ndx);
 1733: 			flist->parent_ndx = ndx;
 1734: #ifdef SUPPORT_HARD_LINKS
 1735: 			if (preserve_hard_links)
 1736: 				match_hard_links(flist);
 1737: #endif
 1738: 			flist_receiving_enabled = True;
 1739: 		}
 1740: 	}
 1741: }
 1742: 
 1743: unsigned short read_shortint(int f)
 1744: {
 1745: 	char b[2];
 1746: 	read_buf(f, b, 2);
 1747: 	return (UVAL(b, 1) << 8) + UVAL(b, 0);
 1748: }
 1749: 
 1750: int32 read_int(int f)
 1751: {
 1752: 	char b[4];
 1753: 	int32 num;
 1754: 
 1755: 	read_buf(f, b, 4);
 1756: 	num = IVAL(b, 0);
 1757: #if SIZEOF_INT32 > 4
 1758: 	if (num & (int32)0x80000000)
 1759: 		num |= ~(int32)0xffffffff;
 1760: #endif
 1761: 	return num;
 1762: }
 1763: 
 1764: int32 read_varint(int f)
 1765: {
 1766: 	union {
 1767: 		char b[5];
 1768: 		int32 x;
 1769: 	} u;
 1770: 	uchar ch;
 1771: 	int extra;
 1772: 
 1773: 	u.x = 0;
 1774: 	ch = read_byte(f);
 1775: 	extra = int_byte_extra[ch / 4];
 1776: 	if (extra) {
 1777: 		uchar bit = ((uchar)1<<(8-extra));
 1778: 		if (extra >= (int)sizeof u.b) {
 1779: 			rprintf(FERROR, "Overflow in read_varint()\n");
 1780: 			exit_cleanup(RERR_STREAMIO);
 1781: 		}
 1782: 		read_buf(f, u.b, extra);
 1783: 		u.b[extra] = ch & (bit-1);
 1784: 	} else
 1785: 		u.b[0] = ch;
 1786: #if CAREFUL_ALIGNMENT
 1787: 	u.x = IVAL(u.b,0);
 1788: #endif
 1789: #if SIZEOF_INT32 > 4
 1790: 	if (u.x & (int32)0x80000000)
 1791: 		u.x |= ~(int32)0xffffffff;
 1792: #endif
 1793: 	return u.x;
 1794: }
 1795: 
 1796: int64 read_varlong(int f, uchar min_bytes)
 1797: {
 1798: 	union {
 1799: 		char b[9];
 1800: 		int64 x;
 1801: 	} u;
 1802: 	char b2[8];
 1803: 	int extra;
 1804: 
 1805: #if SIZEOF_INT64 < 8
 1806: 	memset(u.b, 0, 8);
 1807: #else
 1808: 	u.x = 0;
 1809: #endif
 1810: 	read_buf(f, b2, min_bytes);
 1811: 	memcpy(u.b, b2+1, min_bytes-1);
 1812: 	extra = int_byte_extra[CVAL(b2, 0) / 4];
 1813: 	if (extra) {
 1814: 		uchar bit = ((uchar)1<<(8-extra));
 1815: 		if (min_bytes + extra > (int)sizeof u.b) {
 1816: 			rprintf(FERROR, "Overflow in read_varlong()\n");
 1817: 			exit_cleanup(RERR_STREAMIO);
 1818: 		}
 1819: 		read_buf(f, u.b + min_bytes - 1, extra);
 1820: 		u.b[min_bytes + extra - 1] = CVAL(b2, 0) & (bit-1);
 1821: #if SIZEOF_INT64 < 8
 1822: 		if (min_bytes + extra > 5 || u.b[4] || CVAL(u.b,3) & 0x80) {
 1823: 			rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
 1824: 			exit_cleanup(RERR_UNSUPPORTED);
 1825: 		}
 1826: #endif
 1827: 	} else
 1828: 		u.b[min_bytes + extra - 1] = CVAL(b2, 0);
 1829: #if SIZEOF_INT64 < 8
 1830: 	u.x = IVAL(u.b,0);
 1831: #elif CAREFUL_ALIGNMENT
 1832: 	u.x = IVAL64(u.b,0);
 1833: #endif
 1834: 	return u.x;
 1835: }
 1836: 
 1837: int64 read_longint(int f)
 1838: {
 1839: #if SIZEOF_INT64 >= 8
 1840: 	char b[9];
 1841: #endif
 1842: 	int32 num = read_int(f);
 1843: 
 1844: 	if (num != (int32)0xffffffff)
 1845: 		return num;
 1846: 
 1847: #if SIZEOF_INT64 < 8
 1848: 	rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
 1849: 	exit_cleanup(RERR_UNSUPPORTED);
 1850: #else
 1851: 	read_buf(f, b, 8);
 1852: 	return IVAL(b,0) | (((int64)IVAL(b,4))<<32);
 1853: #endif
 1854: }
 1855: 
 1856: void read_buf(int f, char *buf, size_t len)
 1857: {
 1858: 	if (f != iobuf.in_fd) {
 1859: 		if (safe_read(f, buf, len) != len)
 1860: 			whine_about_eof(False); /* Doesn't return. */
 1861: 		goto batch_copy;
 1862: 	}
 1863: 
 1864: 	if (!IN_MULTIPLEXED) {
 1865: 		raw_read_buf(buf, len);
 1866: 		total_data_read += len;
 1867: 		if (forward_flist_data)
 1868: 			write_buf(iobuf.out_fd, buf, len);
 1869: 	  batch_copy:
 1870: 		if (f == write_batch_monitor_in)
 1871: 			safe_write(batch_fd, buf, len);
 1872: 		return;
 1873: 	}
 1874: 
 1875: 	while (1) {
 1876: 		size_t siz;
 1877: 
 1878: 		while (!iobuf.raw_input_ends_before)
 1879: 			read_a_msg();
 1880: 
 1881: 		siz = MIN(len, iobuf.raw_input_ends_before - iobuf.in.pos);
 1882: 		if (siz >= iobuf.in.size)
 1883: 			siz = iobuf.in.size;
 1884: 		raw_read_buf(buf, siz);
 1885: 		total_data_read += siz;
 1886: 
 1887: 		if (forward_flist_data)
 1888: 			write_buf(iobuf.out_fd, buf, siz);
 1889: 
 1890: 		if (f == write_batch_monitor_in)
 1891: 			safe_write(batch_fd, buf, siz);
 1892: 
 1893: 		if ((len -= siz) == 0)
 1894: 			break;
 1895: 		buf += siz;
 1896: 	}
 1897: }
 1898: 
 1899: void read_sbuf(int f, char *buf, size_t len)
 1900: {
 1901: 	read_buf(f, buf, len);
 1902: 	buf[len] = '\0';
 1903: }
 1904: 
 1905: uchar read_byte(int f)
 1906: {
 1907: 	uchar c;
 1908: 	read_buf(f, (char*)&c, 1);
 1909: 	return c;
 1910: }
 1911: 
 1912: int read_vstring(int f, char *buf, int bufsize)
 1913: {
 1914: 	int len = read_byte(f);
 1915: 
 1916: 	if (len & 0x80)
 1917: 		len = (len & ~0x80) * 0x100 + read_byte(f);
 1918: 
 1919: 	if (len >= bufsize) {
 1920: 		rprintf(FERROR, "over-long vstring received (%d > %d)\n",
 1921: 			len, bufsize - 1);
 1922: 		return -1;
 1923: 	}
 1924: 
 1925: 	if (len)
 1926: 		read_buf(f, buf, len);
 1927: 	buf[len] = '\0';
 1928: 	return len;
 1929: }
 1930: 
 1931: /* Populate a sum_struct with values from the socket.  This is
 1932:  * called by both the sender and the receiver. */
 1933: void read_sum_head(int f, struct sum_struct *sum)
 1934: {
 1935: 	int32 max_blength = protocol_version < 30 ? OLD_MAX_BLOCK_SIZE : MAX_BLOCK_SIZE;
 1936: 	sum->count = read_int(f);
 1937: 	if (sum->count < 0) {
 1938: 		rprintf(FERROR, "Invalid checksum count %ld [%s]\n",
 1939: 			(long)sum->count, who_am_i());
 1940: 		exit_cleanup(RERR_PROTOCOL);
 1941: 	}
 1942: 	sum->blength = read_int(f);
 1943: 	if (sum->blength < 0 || sum->blength > max_blength) {
 1944: 		rprintf(FERROR, "Invalid block length %ld [%s]\n",
 1945: 			(long)sum->blength, who_am_i());
 1946: 		exit_cleanup(RERR_PROTOCOL);
 1947: 	}
 1948: 	sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
 1949: 	if (sum->s2length < 0 || sum->s2length > MAX_DIGEST_LEN) {
 1950: 		rprintf(FERROR, "Invalid checksum length %d [%s]\n",
 1951: 			sum->s2length, who_am_i());
 1952: 		exit_cleanup(RERR_PROTOCOL);
 1953: 	}
 1954: 	sum->remainder = read_int(f);
 1955: 	if (sum->remainder < 0 || sum->remainder > sum->blength) {
 1956: 		rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
 1957: 			(long)sum->remainder, who_am_i());
 1958: 		exit_cleanup(RERR_PROTOCOL);
 1959: 	}
 1960: }
 1961: 
 1962: /* Send the values from a sum_struct over the socket.  Set sum to
 1963:  * NULL if there are no checksums to send.  This is called by both
 1964:  * the generator and the sender. */
 1965: void write_sum_head(int f, struct sum_struct *sum)
 1966: {
 1967: 	static struct sum_struct null_sum;
 1968: 
 1969: 	if (sum == NULL)
 1970: 		sum = &null_sum;
 1971: 
 1972: 	write_int(f, sum->count);
 1973: 	write_int(f, sum->blength);
 1974: 	if (protocol_version >= 27)
 1975: 		write_int(f, sum->s2length);
 1976: 	write_int(f, sum->remainder);
 1977: }
 1978: 
 1979: /* Sleep after writing to limit I/O bandwidth usage.
 1980:  *
 1981:  * @todo Rather than sleeping after each write, it might be better to
 1982:  * use some kind of averaging.  The current algorithm seems to always
 1983:  * use a bit less bandwidth than specified, because it doesn't make up
 1984:  * for slow periods.  But arguably this is a feature.  In addition, we
 1985:  * ought to take the time used to write the data into account.
 1986:  *
 1987:  * During some phases of big transfers (file FOO is uptodate) this is
 1988:  * called with a small bytes_written every time.  As the kernel has to
 1989:  * round small waits up to guarantee that we actually wait at least the
 1990:  * requested number of microseconds, this can become grossly inaccurate.
 1991:  * We therefore keep track of the bytes we've written over time and only
 1992:  * sleep when the accumulated delay is at least 1 tenth of a second. */
 1993: static void sleep_for_bwlimit(int bytes_written)
 1994: {
 1995: 	static struct timeval prior_tv;
 1996: 	static long total_written = 0;
 1997: 	struct timeval tv, start_tv;
 1998: 	long elapsed_usec, sleep_usec;
 1999: 
 2000: #define ONE_SEC	1000000L /* # of microseconds in a second */
 2001: 
 2002: 	total_written += bytes_written;
 2003: 
 2004: 	gettimeofday(&start_tv, NULL);
 2005: 	if (prior_tv.tv_sec) {
 2006: 		elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
 2007: 			     + (start_tv.tv_usec - prior_tv.tv_usec);
 2008: 		total_written -= (int64)elapsed_usec * bwlimit / (ONE_SEC/1024);
 2009: 		if (total_written < 0)
 2010: 			total_written = 0;
 2011: 	}
 2012: 
 2013: 	sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
 2014: 	if (sleep_usec < ONE_SEC / 10) {
 2015: 		prior_tv = start_tv;
 2016: 		return;
 2017: 	}
 2018: 
 2019: 	tv.tv_sec  = sleep_usec / ONE_SEC;
 2020: 	tv.tv_usec = sleep_usec % ONE_SEC;
 2021: 	select(0, NULL, NULL, NULL, &tv);
 2022: 
 2023: 	gettimeofday(&prior_tv, NULL);
 2024: 	elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
 2025: 		     + (prior_tv.tv_usec - start_tv.tv_usec);
 2026: 	total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
 2027: }
 2028: 
 2029: void io_flush(int flush_type)
 2030: {
 2031: 	if (iobuf.out.len > iobuf.out_empty_len) {
 2032: 		if (flush_type == FULL_FLUSH)		/* flush everything in the output buffers */
 2033: 			perform_io(iobuf.out.size - iobuf.out_empty_len, PIO_NEED_OUTROOM);
 2034: 		else if (flush_type == NORMAL_FLUSH)	/* flush at least 1 byte */
 2035: 			perform_io(iobuf.out.size - iobuf.out.len + 1, PIO_NEED_OUTROOM);
 2036: 							/* MSG_FLUSH: flush iobuf.msg only */
 2037: 	}
 2038: 	if (iobuf.msg.len)
 2039: 		perform_io(iobuf.msg.size, PIO_NEED_MSGROOM);
 2040: }
 2041: 
 2042: void write_shortint(int f, unsigned short x)
 2043: {
 2044: 	char b[2];
 2045: 	b[0] = (char)x;
 2046: 	b[1] = (char)(x >> 8);
 2047: 	write_buf(f, b, 2);
 2048: }
 2049: 
 2050: void write_int(int f, int32 x)
 2051: {
 2052: 	char b[4];
 2053: 	SIVAL(b, 0, x);
 2054: 	write_buf(f, b, 4);
 2055: }
 2056: 
 2057: void write_varint(int f, int32 x)
 2058: {
 2059: 	char b[5];
 2060: 	uchar bit;
 2061: 	int cnt;
 2062: 
 2063: 	SIVAL(b, 1, x);
 2064: 
 2065: 	for (cnt = 4; cnt > 1 && b[cnt] == 0; cnt--) {}
 2066: 	bit = ((uchar)1<<(7-cnt+1));
 2067: 
 2068: 	if (CVAL(b, cnt) >= bit) {
 2069: 		cnt++;
 2070: 		*b = ~(bit-1);
 2071: 	} else if (cnt > 1)
 2072: 		*b = b[cnt] | ~(bit*2-1);
 2073: 	else
 2074: 		*b = b[1];
 2075: 
 2076: 	write_buf(f, b, cnt);
 2077: }
 2078: 
 2079: void write_varlong(int f, int64 x, uchar min_bytes)
 2080: {
 2081: 	char b[9];
 2082: 	uchar bit;
 2083: 	int cnt = 8;
 2084: 
 2085: #if SIZEOF_INT64 >= 8
 2086: 	SIVAL64(b, 1, x);
 2087: #else
 2088: 	SIVAL(b, 1, x);
 2089: 	if (x <= 0x7FFFFFFF && x >= 0)
 2090: 		memset(b + 5, 0, 4);
 2091: 	else {
 2092: 		rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
 2093: 		exit_cleanup(RERR_UNSUPPORTED);
 2094: 	}
 2095: #endif
 2096: 
 2097: 	while (cnt > min_bytes && b[cnt] == 0)
 2098: 		cnt--;
 2099: 	bit = ((uchar)1<<(7-cnt+min_bytes));
 2100: 	if (CVAL(b, cnt) >= bit) {
 2101: 		cnt++;
 2102: 		*b = ~(bit-1);
 2103: 	} else if (cnt > min_bytes)
 2104: 		*b = b[cnt] | ~(bit*2-1);
 2105: 	else
 2106: 		*b = b[cnt];
 2107: 
 2108: 	write_buf(f, b, cnt);
 2109: }
 2110: 
 2111: /*
 2112:  * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
 2113:  * 64-bit types on this platform.
 2114:  */
 2115: void write_longint(int f, int64 x)
 2116: {
 2117: 	char b[12], * const s = b+4;
 2118: 
 2119: 	SIVAL(s, 0, x);
 2120: 	if (x <= 0x7FFFFFFF && x >= 0) {
 2121: 		write_buf(f, s, 4);
 2122: 		return;
 2123: 	}
 2124: 
 2125: #if SIZEOF_INT64 < 8
 2126: 	rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
 2127: 	exit_cleanup(RERR_UNSUPPORTED);
 2128: #else
 2129: 	memset(b, 0xFF, 4);
 2130: 	SIVAL(s, 4, x >> 32);
 2131: 	write_buf(f, b, 12);
 2132: #endif
 2133: }
 2134: 
 2135: void write_bigbuf(int f, const char *buf, size_t len)
 2136: {
 2137: 	size_t half_max = (iobuf.out.size - iobuf.out_empty_len) / 2;
 2138: 
 2139: 	while (len > half_max + 1024) {
 2140: 		write_buf(f, buf, half_max);
 2141: 		buf += half_max;
 2142: 		len -= half_max;
 2143: 	}
 2144: 
 2145: 	write_buf(f, buf, len);
 2146: }
 2147: 
 2148: void write_buf(int f, const char *buf, size_t len)
 2149: {
 2150: 	size_t pos, siz;
 2151: 
 2152: 	if (f != iobuf.out_fd) {
 2153: 		safe_write(f, buf, len);
 2154: 		goto batch_copy;
 2155: 	}
 2156: 
 2157: 	if (iobuf.out.len + len > iobuf.out.size)
 2158: 		perform_io(len, PIO_NEED_OUTROOM);
 2159: 
 2160: 	pos = iobuf.out.pos + iobuf.out.len; /* Must be set after any flushing. */
 2161: 	if (pos >= iobuf.out.size)
 2162: 		pos -= iobuf.out.size;
 2163: 
 2164: 	/* Handle a split copy if we wrap around the end of the circular buffer. */
 2165: 	if (pos >= iobuf.out.pos && (siz = iobuf.out.size - pos) < len) {
 2166: 		memcpy(iobuf.out.buf + pos, buf, siz);
 2167: 		memcpy(iobuf.out.buf, buf + siz, len - siz);
 2168: 	} else
 2169: 		memcpy(iobuf.out.buf + pos, buf, len);
 2170: 
 2171: 	iobuf.out.len += len;
 2172: 	total_data_written += len;
 2173: 
 2174:   batch_copy:
 2175: 	if (f == write_batch_monitor_out)
 2176: 		safe_write(batch_fd, buf, len);
 2177: }
 2178: 
 2179: /* Write a string to the connection */
 2180: void write_sbuf(int f, const char *buf)
 2181: {
 2182: 	write_buf(f, buf, strlen(buf));
 2183: }
 2184: 
 2185: void write_byte(int f, uchar c)
 2186: {
 2187: 	write_buf(f, (char *)&c, 1);
 2188: }
 2189: 
 2190: void write_vstring(int f, const char *str, int len)
 2191: {
 2192: 	uchar lenbuf[3], *lb = lenbuf;
 2193: 
 2194: 	if (len > 0x7F) {
 2195: 		if (len > 0x7FFF) {
 2196: 			rprintf(FERROR,
 2197: 				"attempting to send over-long vstring (%d > %d)\n",
 2198: 				len, 0x7FFF);
 2199: 			exit_cleanup(RERR_PROTOCOL);
 2200: 		}
 2201: 		*lb++ = len / 0x100 + 0x80;
 2202: 	}
 2203: 	*lb = len;
 2204: 
 2205: 	write_buf(f, (char*)lenbuf, lb - lenbuf + 1);
 2206: 	if (len)
 2207: 		write_buf(f, str, len);
 2208: }
 2209: 
 2210: /* Send a file-list index using a byte-reduction method. */
 2211: void write_ndx(int f, int32 ndx)
 2212: {
 2213: 	static int32 prev_positive = -1, prev_negative = 1;
 2214: 	int32 diff, cnt = 0;
 2215: 	char b[6];
 2216: 
 2217: 	if (protocol_version < 30 || read_batch) {
 2218: 		write_int(f, ndx);
 2219: 		return;
 2220: 	}
 2221: 
 2222: 	/* Send NDX_DONE as a single-byte 0 with no side effects.  Send
 2223: 	 * negative nums as a positive after sending a leading 0xFF. */
 2224: 	if (ndx >= 0) {
 2225: 		diff = ndx - prev_positive;
 2226: 		prev_positive = ndx;
 2227: 	} else if (ndx == NDX_DONE) {
 2228: 		*b = 0;
 2229: 		write_buf(f, b, 1);
 2230: 		return;
 2231: 	} else {
 2232: 		b[cnt++] = (char)0xFF;
 2233: 		ndx = -ndx;
 2234: 		diff = ndx - prev_negative;
 2235: 		prev_negative = ndx;
 2236: 	}
 2237: 
 2238: 	/* A diff of 1 - 253 is sent as a one-byte diff; a diff of 254 - 32767
 2239: 	 * or 0 is sent as a 0xFE + a two-byte diff; otherwise we send 0xFE
 2240: 	 * & all 4 bytes of the (non-negative) num with the high-bit set. */
 2241: 	if (diff < 0xFE && diff > 0)
 2242: 		b[cnt++] = (char)diff;
 2243: 	else if (diff < 0 || diff > 0x7FFF) {
 2244: 		b[cnt++] = (char)0xFE;
 2245: 		b[cnt++] = (char)((ndx >> 24) | 0x80);
 2246: 		b[cnt++] = (char)ndx;
 2247: 		b[cnt++] = (char)(ndx >> 8);
 2248: 		b[cnt++] = (char)(ndx >> 16);
 2249: 	} else {
 2250: 		b[cnt++] = (char)0xFE;
 2251: 		b[cnt++] = (char)(diff >> 8);
 2252: 		b[cnt++] = (char)diff;
 2253: 	}
 2254: 	write_buf(f, b, cnt);
 2255: }
 2256: 
 2257: /* Receive a file-list index using a byte-reduction method. */
 2258: int32 read_ndx(int f)
 2259: {
 2260: 	static int32 prev_positive = -1, prev_negative = 1;
 2261: 	int32 *prev_ptr, num;
 2262: 	char b[4];
 2263: 
 2264: 	if (protocol_version < 30)
 2265: 		return read_int(f);
 2266: 
 2267: 	read_buf(f, b, 1);
 2268: 	if (CVAL(b, 0) == 0xFF) {
 2269: 		read_buf(f, b, 1);
 2270: 		prev_ptr = &prev_negative;
 2271: 	} else if (CVAL(b, 0) == 0)
 2272: 		return NDX_DONE;
 2273: 	else
 2274: 		prev_ptr = &prev_positive;
 2275: 	if (CVAL(b, 0) == 0xFE) {
 2276: 		read_buf(f, b, 2);
 2277: 		if (CVAL(b, 0) & 0x80) {
 2278: 			b[3] = CVAL(b, 0) & ~0x80;
 2279: 			b[0] = b[1];
 2280: 			read_buf(f, b+1, 2);
 2281: 			num = IVAL(b, 0);
 2282: 		} else
 2283: 			num = (UVAL(b,0)<<8) + UVAL(b,1) + *prev_ptr;
 2284: 	} else
 2285: 		num = UVAL(b, 0) + *prev_ptr;
 2286: 	*prev_ptr = num;
 2287: 	if (prev_ptr == &prev_negative)
 2288: 		num = -num;
 2289: 	return num;
 2290: }
 2291: 
 2292: /* Read a line of up to bufsiz-1 characters into buf.  Strips
 2293:  * the (required) trailing newline and all carriage returns.
 2294:  * Returns 1 for success; 0 for I/O error or truncation. */
 2295: int read_line_old(int fd, char *buf, size_t bufsiz, int eof_ok)
 2296: {
 2297: 	assert(fd != iobuf.in_fd);
 2298: 	bufsiz--; /* leave room for the null */
 2299: 	while (bufsiz > 0) {
 2300: 		if (safe_read(fd, buf, 1) == 0) {
 2301: 			if (eof_ok)
 2302: 				break;
 2303: 			return 0;
 2304: 		}
 2305: 		if (*buf == '\0')
 2306: 			return 0;
 2307: 		if (*buf == '\n')
 2308: 			break;
 2309: 		if (*buf != '\r') {
 2310: 			buf++;
 2311: 			bufsiz--;
 2312: 		}
 2313: 	}
 2314: 	*buf = '\0';
 2315: 	return bufsiz > 0;
 2316: }
 2317: 
 2318: void io_printf(int fd, const char *format, ...)
 2319: {
 2320: 	va_list ap;
 2321: 	char buf[BIGPATHBUFLEN];
 2322: 	int len;
 2323: 
 2324: 	va_start(ap, format);
 2325: 	len = vsnprintf(buf, sizeof buf, format, ap);
 2326: 	va_end(ap);
 2327: 
 2328: 	if (len < 0)
 2329: 		exit_cleanup(RERR_PROTOCOL);
 2330: 
 2331: 	if (len >= (int)sizeof buf) {
 2332: 		rprintf(FERROR, "io_printf() was too long for the buffer.\n");
 2333: 		exit_cleanup(RERR_PROTOCOL);
 2334: 	}
 2335: 
 2336: 	write_sbuf(fd, buf);
 2337: }
 2338: 
 2339: /* Setup for multiplexing a MSG_* stream with the data stream. */
 2340: void io_start_multiplex_out(int fd)
 2341: {
 2342: 	io_flush(FULL_FLUSH);
 2343: 
 2344: 	if (msgs2stderr == 1 && DEBUG_GTE(IO, 2))
 2345: 		rprintf(FINFO, "[%s] io_start_multiplex_out(%d)\n", who_am_i(), fd);
 2346: 
 2347: 	if (!iobuf.msg.buf)
 2348: 		alloc_xbuf(&iobuf.msg, ROUND_UP_1024(IO_BUFFER_SIZE));
 2349: 
 2350: 	iobuf.out_empty_len = 4; /* See also OUT_MULTIPLEXED */
 2351: 	io_start_buffering_out(fd);
 2352: 	got_kill_signal = 0;
 2353: 
 2354: 	iobuf.raw_data_header_pos = iobuf.out.pos + iobuf.out.len;
 2355: 	iobuf.out.len += 4;
 2356: }
 2357: 
 2358: /* Setup for multiplexing a MSG_* stream with the data stream. */
 2359: void io_start_multiplex_in(int fd)
 2360: {
 2361: 	if (msgs2stderr == 1 && DEBUG_GTE(IO, 2))
 2362: 		rprintf(FINFO, "[%s] io_start_multiplex_in(%d)\n", who_am_i(), fd);
 2363: 
 2364: 	iobuf.in_multiplexed = 1; /* See also IN_MULTIPLEXED */
 2365: 	io_start_buffering_in(fd);
 2366: }
 2367: 
 2368: int io_end_multiplex_in(int mode)
 2369: {
 2370: 	int ret = iobuf.in_multiplexed ? iobuf.in_fd : -1;
 2371: 
 2372: 	if (msgs2stderr == 1 && DEBUG_GTE(IO, 2))
 2373: 		rprintf(FINFO, "[%s] io_end_multiplex_in(mode=%d)\n", who_am_i(), mode);
 2374: 
 2375: 	iobuf.in_multiplexed = 0;
 2376: 	if (mode == MPLX_SWITCHING)
 2377: 		iobuf.raw_input_ends_before = 0;
 2378: 	else
 2379: 		assert(iobuf.raw_input_ends_before == 0);
 2380: 	if (mode != MPLX_TO_BUFFERED)
 2381: 		io_end_buffering_in(mode);
 2382: 
 2383: 	return ret;
 2384: }
 2385: 
 2386: int io_end_multiplex_out(int mode)
 2387: {
 2388: 	int ret = iobuf.out_empty_len ? iobuf.out_fd : -1;
 2389: 
 2390: 	if (msgs2stderr == 1 && DEBUG_GTE(IO, 2))
 2391: 		rprintf(FINFO, "[%s] io_end_multiplex_out(mode=%d)\n", who_am_i(), mode);
 2392: 
 2393: 	if (mode != MPLX_TO_BUFFERED)
 2394: 		io_end_buffering_out(mode);
 2395: 	else
 2396: 		io_flush(FULL_FLUSH);
 2397: 
 2398: 	iobuf.out.len = 0;
 2399: 	iobuf.out_empty_len = 0;
 2400: 	if (got_kill_signal > 0) /* Just in case... */
 2401: 		handle_kill_signal(False);
 2402: 	got_kill_signal = -1;
 2403: 
 2404: 	return ret;
 2405: }
 2406: 
 2407: void start_write_batch(int fd)
 2408: {
 2409: 	/* Some communication has already taken place, but we don't
 2410: 	 * enable batch writing until here so that we can write a
 2411: 	 * canonical record of the communication even though the
 2412: 	 * actual communication so far depends on whether a daemon
 2413: 	 * is involved. */
 2414: 	write_int(batch_fd, protocol_version);
 2415: 	if (protocol_version >= 30)
 2416: 		write_varint(batch_fd, compat_flags);
 2417: 	write_int(batch_fd, checksum_seed);
 2418: 
 2419: 	if (am_sender)
 2420: 		write_batch_monitor_out = fd;
 2421: 	else
 2422: 		write_batch_monitor_in = fd;
 2423: }
 2424: 
 2425: void stop_write_batch(void)
 2426: {
 2427: 	write_batch_monitor_out = -1;
 2428: 	write_batch_monitor_in = -1;
 2429: }

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>