Debian Codegraph @

io.c

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