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