File:  [ELWIX - Embedded LightWeight unIX -] / embedaddon / rsync / io.c
Revision 1.1.1.2 (vendor branch): download - view: text, annotated - select for diffs - revision graph
Mon Oct 14 07:51:14 2013 UTC (10 years, 8 months ago) by misho
Branches: rsync, MAIN
CVS tags: RSYNC3_1_0, HEAD
v 3.1.0

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

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