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