Set am_sender to -1 until the end of the option parsing. This
[rsync/rsync.git] / io.c
CommitLineData
7a24c346 1/* -*- c-file-style: "linux" -*-
d62bcc17
WD
2 *
3 * Copyright (C) 1996-2001 by Andrew Tridgell
880da007
MP
4 * Copyright (C) Paul Mackerras 1996
5 * Copyright (C) 2001, 2002 by Martin Pool <mbp@samba.org>
d62bcc17 6 *
880da007
MP
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
d62bcc17 11 *
880da007
MP
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
d62bcc17 16 *
880da007
MP
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
720b47f2 21
87ee2481 22/**
87ee2481
MP
23 * @file io.c
24 *
6ed6d7f5 25 * Socket and pipe I/O utilities used in rsync.
87ee2481
MP
26 *
27 * rsync provides its own multiplexing system, which is used to send
28 * stderr and stdout over a single socket. We need this because
29 * stdout normally carries the binary data stream, and stderr all our
30 * error messages.
31 *
32 * For historical reasons this is off during the start of the
33 * connection, but it's switched on quite early using
34 * io_start_multiplex_out() and io_start_multiplex_in().
35 **/
720b47f2 36
720b47f2
AT
37#include "rsync.h"
38
880da007 39/** If no timeout is specified then use a 60 second select timeout */
8cd9fd4e
AT
40#define SELECT_TIMEOUT 60
41
7a55d06e 42extern int bwlimit;
71e58630 43extern size_t bwlimit_writemax;
720b47f2 44extern int verbose;
6ba9279f 45extern int io_timeout;
d17e1dd2
WD
46extern int am_server;
47extern int am_daemon;
48extern int am_sender;
98f8c9a5 49extern int am_generator;
e626b29e 50extern int eol_nulls;
188fed95 51extern int csum_length;
b9f592fb
WD
52extern int checksum_seed;
53extern int protocol_version;
e626b29e 54extern char *remote_filesfrom_file;
a800434a 55extern struct stats stats;
720b47f2 56
a86179f4 57const char phase_unknown[] = "unknown";
e626b29e 58int select_timeout = SELECT_TIMEOUT;
b9f592fb 59int batch_fd = -1;
b0ad5429 60int batch_gen_fd = -1;
805edf9d 61
98b332ed
MP
62/**
63 * The connection might be dropped at some point; perhaps because the
64 * remote instance crashed. Just giving the offset on the stream is
65 * not very helpful. So instead we try to make io_phase_name point to
66 * something useful.
eca2adb4 67 *
6ed6d7f5 68 * For buffered/multiplexed I/O these names will be somewhat
805edf9d 69 * approximate; perhaps for ease of support we would rather make the
6ed6d7f5 70 * buffer always flush when a single application-level I/O finishes.
805edf9d 71 *
eca2adb4
MP
72 * @todo Perhaps we want some simple stack functionality, but there's
73 * no need to overdo it.
98b332ed 74 **/
805edf9d
MP
75const char *io_write_phase = phase_unknown;
76const char *io_read_phase = phase_unknown;
98b332ed 77
7a55d06e
MP
78/** Ignore EOF errors while reading a module listing if the remote
79 version is 24 or less. */
80int kludge_around_eof = False;
81
d17e1dd2
WD
82int msg_fd_in = -1;
83int msg_fd_out = -1;
7a55d06e 84
1f75bb10
WD
85static int io_multiplexing_out;
86static int io_multiplexing_in;
87static int sock_f_in = -1;
88static int sock_f_out = -1;
89static time_t last_io;
90static int no_flush;
91
b9f592fb
WD
92static int write_batch_monitor_in = -1;
93static int write_batch_monitor_out = -1;
94
56014c8c
WD
95static int io_filesfrom_f_in = -1;
96static int io_filesfrom_f_out = -1;
97static char io_filesfrom_buf[2048];
98static char *io_filesfrom_bp;
99static char io_filesfrom_lastchar;
100static int io_filesfrom_buflen;
720b47f2 101
9dd891bb 102static void read_loop(int fd, char *buf, size_t len);
ff41a59f 103
d17e1dd2
WD
104struct redo_list {
105 struct redo_list *next;
106 int num;
107};
108
109static struct redo_list *redo_list_head;
110static struct redo_list *redo_list_tail;
111
112struct msg_list {
113 struct msg_list *next;
114 char *buf;
115 int len;
116};
117
118static struct msg_list *msg_list_head;
119static struct msg_list *msg_list_tail;
120
121static void redo_list_add(int num)
122{
123 struct redo_list *rl;
124
125 if (!(rl = new(struct redo_list)))
126 exit_cleanup(RERR_MALLOC);
127 rl->next = NULL;
128 rl->num = num;
129 if (redo_list_tail)
130 redo_list_tail->next = rl;
131 else
132 redo_list_head = rl;
133 redo_list_tail = rl;
134}
135
8d9dc9f9
AT
136static void check_timeout(void)
137{
138 time_t t;
90ba34e2 139
d17e1dd2
WD
140 if (!io_timeout)
141 return;
8d9dc9f9
AT
142
143 if (!last_io) {
144 last_io = time(NULL);
145 return;
146 }
147
148 t = time(NULL);
149
1f75bb10 150 if (t - last_io >= io_timeout) {
0adb99b9 151 if (!am_server && !am_daemon) {
4ccfd96c 152 rprintf(FERROR, "io timeout after %d seconds -- exiting\n",
0adb99b9
AT
153 (int)(t-last_io));
154 }
65417579 155 exit_cleanup(RERR_TIMEOUT);
8d9dc9f9
AT
156 }
157}
158
1f75bb10
WD
159/* Note the fds used for the main socket (which might really be a pipe
160 * for a local transfer, but we can ignore that). */
161void io_set_sock_fds(int f_in, int f_out)
162{
163 sock_f_in = f_in;
164 sock_f_out = f_out;
165}
166
98f8c9a5
WD
167/* Setup the fd used to receive MSG_* messages. Only needed during the
168 * early stages of being a local sender (up through the sending of the
169 * file list) or when we're the generator (to fetch the messages from
170 * the receiver). */
d17e1dd2
WD
171void set_msg_fd_in(int fd)
172{
173 msg_fd_in = fd;
174}
175
98f8c9a5
WD
176/* Setup the fd used to send our MSG_* messages. Only needed when
177 * we're the receiver (to send our messages to the generator). */
d17e1dd2
WD
178void set_msg_fd_out(int fd)
179{
180 msg_fd_out = fd;
181 set_nonblocking(msg_fd_out);
182}
183
184/* Add a message to the pending MSG_* list. */
185static void msg_list_add(int code, char *buf, int len)
554e0a8d 186{
d17e1dd2
WD
187 struct msg_list *ml;
188
189 if (!(ml = new(struct msg_list)))
190 exit_cleanup(RERR_MALLOC);
191 ml->next = NULL;
192 if (!(ml->buf = new_array(char, len+4)))
193 exit_cleanup(RERR_MALLOC);
194 SIVAL(ml->buf, 0, ((code+MPLEX_BASE)<<24) | len);
195 memcpy(ml->buf+4, buf, len);
196 ml->len = len+4;
197 if (msg_list_tail)
198 msg_list_tail->next = ml;
199 else
200 msg_list_head = ml;
201 msg_list_tail = ml;
554e0a8d
AT
202}
203
d17e1dd2
WD
204void send_msg(enum msgcode code, char *buf, int len)
205{
206 msg_list_add(code, buf, len);
207 msg_list_push(NORMAL_FLUSH);
208}
209
98f8c9a5
WD
210/* Read a message from the MSG_* fd and handle it. This is called either
211 * during the early stages of being a local sender (up through the sending
212 * of the file list) or when we're the generator (to fetch the messages
213 * from the receiver). */
d17e1dd2 214static void read_msg_fd(void)
554e0a8d 215{
f9c6b3e7 216 char buf[2048];
06ce139f 217 size_t n;
d17e1dd2 218 int fd = msg_fd_in;
ff41a59f
AT
219 int tag, len;
220
00bdf899
WD
221 /* Temporarily disable msg_fd_in. This is needed to avoid looping back
222 * to this routine from read_timeout() and writefd_unbuffered(). */
d17e1dd2 223 msg_fd_in = -1;
554e0a8d 224
ff41a59f
AT
225 read_loop(fd, buf, 4);
226 tag = IVAL(buf, 0);
227
228 len = tag & 0xFFFFFF;
d17e1dd2 229 tag = (tag >> 24) - MPLEX_BASE;
ff41a59f 230
d17e1dd2
WD
231 switch (tag) {
232 case MSG_DONE:
98f8c9a5 233 if (len != 0 || !am_generator) {
13c7bcbb 234 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
d17e1dd2 235 exit_cleanup(RERR_STREAMIO);
13c7bcbb 236 }
d17e1dd2
WD
237 redo_list_add(-1);
238 break;
239 case MSG_REDO:
98f8c9a5 240 if (len != 4 || !am_generator) {
13c7bcbb 241 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
d17e1dd2 242 exit_cleanup(RERR_STREAMIO);
13c7bcbb 243 }
d17e1dd2
WD
244 read_loop(fd, buf, 4);
245 redo_list_add(IVAL(buf,0));
246 break;
247 case MSG_INFO:
248 case MSG_ERROR:
249 case MSG_LOG:
250 while (len) {
251 n = len;
252 if (n >= sizeof buf)
253 n = sizeof buf - 1;
254 read_loop(fd, buf, n);
255 rwrite((enum logcode)tag, buf, n);
256 len -= n;
257 }
258 break;
259 default:
13c7bcbb 260 rprintf(FERROR, "unknown message %d:%d\n", tag, len);
d17e1dd2
WD
261 exit_cleanup(RERR_STREAMIO);
262 }
263
264 msg_fd_in = fd;
265}
266
267/* Try to push messages off the list onto the wire. If we leave with more
268 * to do, return 0. On error, return -1. If everything flushed, return 1.
f9c6b3e7 269 * This is only active in the receiver. */
d17e1dd2
WD
270int msg_list_push(int flush_it_all)
271{
272 static int written = 0;
273 struct timeval tv;
274 fd_set fds;
275
276 if (msg_fd_out < 0)
277 return -1;
278
279 while (msg_list_head) {
280 struct msg_list *ml = msg_list_head;
281 int n = write(msg_fd_out, ml->buf + written, ml->len - written);
282 if (n < 0) {
283 if (errno == EINTR)
284 continue;
285 if (errno != EWOULDBLOCK && errno != EAGAIN)
286 return -1;
287 if (!flush_it_all)
288 return 0;
289 FD_ZERO(&fds);
290 FD_SET(msg_fd_out, &fds);
e626b29e 291 tv.tv_sec = select_timeout;
d17e1dd2
WD
292 tv.tv_usec = 0;
293 if (!select(msg_fd_out+1, NULL, &fds, NULL, &tv))
294 check_timeout();
295 } else if ((written += n) == ml->len) {
296 free(ml->buf);
297 msg_list_head = ml->next;
298 if (!msg_list_head)
299 msg_list_tail = NULL;
300 free(ml);
301 written = 0;
302 }
554e0a8d 303 }
d17e1dd2
WD
304 return 1;
305}
306
307int get_redo_num(void)
308{
309 struct redo_list *next;
310 int num;
311
312 while (!redo_list_head)
313 read_msg_fd();
554e0a8d 314
d17e1dd2
WD
315 num = redo_list_head->num;
316 next = redo_list_head->next;
317 free(redo_list_head);
318 redo_list_head = next;
319 if (!next)
320 redo_list_tail = NULL;
321
322 return num;
554e0a8d
AT
323}
324
56014c8c
WD
325/**
326 * When we're the receiver and we have a local --files-from list of names
327 * that needs to be sent over the socket to the sender, we have to do two
328 * things at the same time: send the sender a list of what files we're
329 * processing and read the incoming file+info list from the sender. We do
330 * this by augmenting the read_timeout() function to copy this data. It
331 * uses the io_filesfrom_buf to read a block of data from f_in (when it is
332 * ready, since it might be a pipe) and then blast it out f_out (when it
333 * is ready to receive more data).
334 */
335void io_set_filesfrom_fds(int f_in, int f_out)
336{
337 io_filesfrom_f_in = f_in;
338 io_filesfrom_f_out = f_out;
339 io_filesfrom_bp = io_filesfrom_buf;
340 io_filesfrom_lastchar = '\0';
341 io_filesfrom_buflen = 0;
342}
720b47f2 343
880da007
MP
344/**
345 * It's almost always an error to get an EOF when we're trying to read
346 * from the network, because the protocol is self-terminating.
347 *
348 * However, there is one unfortunate cases where it is not, which is
349 * rsync <2.4.6 sending a list of modules on a server, since the list
350 * is terminated by closing the socket. So, for the section of the
351 * program where that is a problem (start_socket_client),
352 * kludge_around_eof is True and we just exit.
353 */
1f75bb10 354static void whine_about_eof(int fd)
7a55d06e 355{
1f75bb10 356 if (kludge_around_eof && fd == sock_f_in)
3151cbae 357 exit_cleanup(0);
3151cbae 358
00bdf899 359 rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
dca68b0a
WD
360 "(%.0f bytes received so far) [%s]\n",
361 (double)stats.total_read, who_am_i());
00bdf899
WD
362
363 exit_cleanup(RERR_STREAMIO);
7a55d06e 364}
720b47f2 365
7a55d06e 366
880da007 367/**
6ed6d7f5 368 * Read from a socket with I/O timeout. return the number of bytes
c3563c46
MP
369 * read. If no bytes can be read then exit, never return a number <= 0.
370 *
8886f8d0
MP
371 * TODO: If the remote shell connection fails, then current versions
372 * actually report an "unexpected EOF" error here. Since it's a
373 * fairly common mistake to try to use rsh when ssh is required, we
374 * should trap that: if we fail to read any data at all, we should
375 * give a better explanation. We can tell whether the connection has
376 * started by looking e.g. at whether the remote version is known yet.
c3563c46 377 */
3151cbae 378static int read_timeout(int fd, char *buf, size_t len)
8d9dc9f9 379{
d62bcc17 380 int n, ret = 0;
4c36ddbe 381
d17e1dd2 382 io_flush(NORMAL_FLUSH);
ea2111d1 383
4c36ddbe 384 while (ret == 0) {
7a55d06e 385 /* until we manage to read *something* */
56014c8c 386 fd_set r_fds, w_fds;
4c36ddbe 387 struct timeval tv;
1ea087a7 388 int maxfd = fd;
a57873b7 389 int count;
4c36ddbe 390
56014c8c 391 FD_ZERO(&r_fds);
a7026ba9 392 FD_ZERO(&w_fds);
56014c8c 393 FD_SET(fd, &r_fds);
d17e1dd2
WD
394 if (msg_fd_in >= 0) {
395 FD_SET(msg_fd_in, &r_fds);
1ea087a7
WD
396 if (msg_fd_in > maxfd)
397 maxfd = msg_fd_in;
4033b80b
WD
398 } else if (msg_list_head) {
399 FD_SET(msg_fd_out, &w_fds);
1ea087a7
WD
400 if (msg_fd_out > maxfd)
401 maxfd = msg_fd_out;
56014c8c 402 }
3309507d 403 if (io_filesfrom_f_out >= 0) {
56014c8c
WD
404 int new_fd;
405 if (io_filesfrom_buflen == 0) {
3309507d 406 if (io_filesfrom_f_in >= 0) {
56014c8c
WD
407 FD_SET(io_filesfrom_f_in, &r_fds);
408 new_fd = io_filesfrom_f_in;
409 } else {
410 io_filesfrom_f_out = -1;
411 new_fd = -1;
412 }
413 } else {
56014c8c
WD
414 FD_SET(io_filesfrom_f_out, &w_fds);
415 new_fd = io_filesfrom_f_out;
416 }
1ea087a7
WD
417 if (new_fd > maxfd)
418 maxfd = new_fd;
554e0a8d
AT
419 }
420
e626b29e 421 tv.tv_sec = select_timeout;
4c36ddbe
AT
422 tv.tv_usec = 0;
423
554e0a8d
AT
424 errno = 0;
425
a7026ba9 426 count = select(maxfd + 1, &r_fds, &w_fds, NULL, &tv);
a57873b7 427
a57873b7 428 if (count <= 0) {
f89b9368 429 if (errno == EBADF)
554e0a8d 430 exit_cleanup(RERR_SOCKETIO);
bd717af8 431 check_timeout();
4c36ddbe
AT
432 continue;
433 }
434
d17e1dd2
WD
435 if (msg_fd_in >= 0 && FD_ISSET(msg_fd_in, &r_fds))
436 read_msg_fd();
4033b80b
WD
437 else if (msg_list_head && FD_ISSET(msg_fd_out, &w_fds))
438 msg_list_push(NORMAL_FLUSH);
554e0a8d 439
3309507d 440 if (io_filesfrom_f_out >= 0) {
56014c8c
WD
441 if (io_filesfrom_buflen) {
442 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
443 int l = write(io_filesfrom_f_out,
444 io_filesfrom_bp,
445 io_filesfrom_buflen);
446 if (l > 0) {
447 if (!(io_filesfrom_buflen -= l))
448 io_filesfrom_bp = io_filesfrom_buf;
449 else
450 io_filesfrom_bp += l;
451 } else {
452 /* XXX should we complain? */
453 io_filesfrom_f_out = -1;
454 }
455 }
3309507d 456 } else if (io_filesfrom_f_in >= 0) {
56014c8c
WD
457 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
458 int l = read(io_filesfrom_f_in,
459 io_filesfrom_buf,
460 sizeof io_filesfrom_buf);
461 if (l <= 0) {
462 /* Send end-of-file marker */
463 io_filesfrom_buf[0] = '\0';
464 io_filesfrom_buf[1] = '\0';
465 io_filesfrom_buflen = io_filesfrom_lastchar? 2 : 1;
466 io_filesfrom_f_in = -1;
467 } else {
56014c8c
WD
468 if (!eol_nulls) {
469 char *s = io_filesfrom_buf + l;
470 /* Transform CR and/or LF into '\0' */
471 while (s-- > io_filesfrom_buf) {
472 if (*s == '\n' || *s == '\r')
473 *s = '\0';
474 }
475 }
476 if (!io_filesfrom_lastchar) {
477 /* Last buf ended with a '\0', so don't
478 * let this buf start with one. */
479 while (l && !*io_filesfrom_bp)
480 io_filesfrom_bp++, l--;
481 }
482 if (!l)
483 io_filesfrom_bp = io_filesfrom_buf;
484 else {
485 char *f = io_filesfrom_bp;
486 char *t = f;
487 char *eob = f + l;
488 /* Eliminate any multi-'\0' runs. */
489 while (f != eob) {
490 if (!(*t++ = *f++)) {
491 while (f != eob && !*f)
492 f++, l--;
493 }
494 }
495 io_filesfrom_lastchar = f[-1];
496 }
497 io_filesfrom_buflen = l;
498 }
499 }
500 }
501 }
502
f89b9368
WD
503 if (!FD_ISSET(fd, &r_fds))
504 continue;
554e0a8d 505
4c36ddbe
AT
506 n = read(fd, buf, len);
507
1ea087a7
WD
508 if (n <= 0) {
509 if (n == 0)
1f75bb10 510 whine_about_eof(fd); /* Doesn't return. */
d62bcc17
WD
511 if (errno == EINTR || errno == EWOULDBLOCK
512 || errno == EAGAIN)
7a55d06e 513 continue;
1f75bb10
WD
514
515 /* Don't write errors on a dead socket. */
516 if (fd == sock_f_in)
7f459268 517 close_multiplexing_out();
1f75bb10
WD
518 rsyserr(FERROR, errno, "read error");
519 exit_cleanup(RERR_STREAMIO);
8d9dc9f9 520 }
00bdf899
WD
521
522 buf += n;
523 len -= n;
524 ret += n;
1f75bb10
WD
525
526 if (io_timeout && fd == sock_f_in)
00bdf899 527 last_io = time(NULL);
4c36ddbe 528 }
8d9dc9f9 529
4c36ddbe
AT
530 return ret;
531}
8d9dc9f9 532
56014c8c
WD
533/**
534 * Read a line into the "fname" buffer (which must be at least MAXPATHLEN
535 * characters long).
536 */
537int read_filesfrom_line(int fd, char *fname)
538{
539 char ch, *s, *eob = fname + MAXPATHLEN - 1;
540 int cnt;
55d5937d 541 int reading_remotely = remote_filesfrom_file != NULL;
56014c8c
WD
542 int nulls = eol_nulls || reading_remotely;
543
544 start:
545 s = fname;
546 while (1) {
547 cnt = read(fd, &ch, 1);
548 if (cnt < 0 && (errno == EWOULDBLOCK
549 || errno == EINTR || errno == EAGAIN)) {
550 struct timeval tv;
551 fd_set fds;
552 FD_ZERO(&fds);
553 FD_SET(fd, &fds);
e626b29e 554 tv.tv_sec = select_timeout;
56014c8c
WD
555 tv.tv_usec = 0;
556 if (!select(fd+1, &fds, NULL, NULL, &tv))
557 check_timeout();
558 continue;
559 }
560 if (cnt != 1)
561 break;
562 if (nulls? !ch : (ch == '\r' || ch == '\n')) {
563 /* Skip empty lines if reading locally. */
564 if (!reading_remotely && s == fname)
565 continue;
566 break;
567 }
568 if (s < eob)
569 *s++ = ch;
570 }
571 *s = '\0';
7a55d06e 572
6b45fcf1
WD
573 /* Dump comments. */
574 if (*fname == '#' || *fname == ';')
56014c8c
WD
575 goto start;
576
577 return s - fname;
578}
7a55d06e
MP
579
580
1f75bb10
WD
581static char *iobuf_out;
582static int iobuf_out_cnt;
583
584void io_start_buffering_out(void)
585{
586 if (iobuf_out)
587 return;
588 if (!(iobuf_out = new_array(char, IO_BUFFER_SIZE)))
589 out_of_memory("io_start_buffering_out");
590 iobuf_out_cnt = 0;
591}
592
593
594static char *iobuf_in;
595static size_t iobuf_in_siz;
596
597void io_start_buffering_in(void)
598{
599 if (iobuf_in)
600 return;
601 iobuf_in_siz = 2 * IO_BUFFER_SIZE;
602 if (!(iobuf_in = new_array(char, iobuf_in_siz)))
603 out_of_memory("io_start_buffering_in");
604}
605
606
607void io_end_buffering(void)
608{
609 io_flush(NORMAL_FLUSH);
610 if (!io_multiplexing_out) {
611 free(iobuf_out);
612 iobuf_out = NULL;
613 }
614}
615
616
880da007
MP
617/**
618 * Continue trying to read len bytes - don't return until len has been
619 * read.
620 **/
3151cbae 621static void read_loop(int fd, char *buf, size_t len)
4c36ddbe
AT
622{
623 while (len) {
624 int n = read_timeout(fd, buf, len);
625
626 buf += n;
627 len -= n;
8d9dc9f9
AT
628 }
629}
630
7a55d06e
MP
631
632/**
633 * Read from the file descriptor handling multiplexing - return number
634 * of bytes read.
d62bcc17
WD
635 *
636 * Never returns <= 0.
7a55d06e 637 */
c399d22a 638static int readfd_unbuffered(int fd, char *buf, size_t len)
8d9dc9f9 639{
6fe25398 640 static size_t remaining;
1f75bb10 641 static size_t iobuf_in_ndx;
909ce14f 642 int tag, ret = 0;
8d9dc9f9
AT
643 char line[1024];
644
1f75bb10 645 if (!iobuf_in || fd != sock_f_in)
4c36ddbe 646 return read_timeout(fd, buf, len);
8d9dc9f9 647
76c21947 648 if (!io_multiplexing_in && remaining == 0) {
1f75bb10
WD
649 remaining = read_timeout(fd, iobuf_in, iobuf_in_siz);
650 iobuf_in_ndx = 0;
76c21947
WD
651 }
652
8d9dc9f9
AT
653 while (ret == 0) {
654 if (remaining) {
655 len = MIN(len, remaining);
1f75bb10
WD
656 memcpy(buf, iobuf_in + iobuf_in_ndx, len);
657 iobuf_in_ndx += len;
8d9dc9f9
AT
658 remaining -= len;
659 ret = len;
76c21947 660 break;
8d9dc9f9
AT
661 }
662
909ce14f 663 read_loop(fd, line, 4);
ff41a59f 664 tag = IVAL(line, 0);
679e7657 665
8d9dc9f9 666 remaining = tag & 0xFFFFFF;
d17e1dd2 667 tag = (tag >> 24) - MPLEX_BASE;
8d9dc9f9 668
d17e1dd2
WD
669 switch (tag) {
670 case MSG_DATA:
1f75bb10
WD
671 if (remaining > iobuf_in_siz) {
672 if (!(iobuf_in = realloc_array(iobuf_in, char,
673 remaining)))
c399d22a 674 out_of_memory("readfd_unbuffered");
1f75bb10 675 iobuf_in_siz = remaining;
76c21947 676 }
1f75bb10
WD
677 read_loop(fd, iobuf_in, remaining);
678 iobuf_in_ndx = 0;
d17e1dd2
WD
679 break;
680 case MSG_INFO:
681 case MSG_ERROR:
682 if (remaining >= sizeof line) {
bd9fca47
WD
683 rprintf(FERROR,
684 "[%s] multiplexing overflow %d:%ld\n\n",
685 who_am_i(), tag, (long)remaining);
d17e1dd2
WD
686 exit_cleanup(RERR_STREAMIO);
687 }
688 read_loop(fd, line, remaining);
689 rwrite((enum logcode)tag, line, remaining);
690 remaining = 0;
691 break;
692 default:
bd9fca47
WD
693 rprintf(FERROR, "[%s] unexpected tag %d\n",
694 who_am_i(), tag);
65417579 695 exit_cleanup(RERR_STREAMIO);
8d9dc9f9 696 }
8d9dc9f9
AT
697 }
698
76c21947 699 if (remaining == 0)
d17e1dd2 700 io_flush(NORMAL_FLUSH);
76c21947 701
8d9dc9f9
AT
702 return ret;
703}
704
705
909ce14f 706
880da007
MP
707/**
708 * Do a buffered read from @p fd. Don't return until all @p n bytes
709 * have been read. If all @p n can't be read then exit with an
710 * error.
711 **/
3151cbae 712static void readfd(int fd, char *buffer, size_t N)
720b47f2 713{
6ba9279f 714 int ret;
d62bcc17 715 size_t total = 0;
3151cbae 716
6ba9279f 717 while (total < N) {
c399d22a 718 ret = readfd_unbuffered(fd, buffer + total, N-total);
6ba9279f 719 total += ret;
7f28dbee 720 }
1b7c47cb 721
b9f592fb
WD
722 if (fd == write_batch_monitor_in) {
723 if ((size_t)write(batch_fd, buffer, total) != total)
724 exit_cleanup(RERR_FILEIO);
725 }
1f75bb10
WD
726
727 if (fd == sock_f_in)
728 stats.total_read += total;
720b47f2
AT
729}
730
731
b7922338 732int32 read_int(int f)
720b47f2 733{
4c36ddbe 734 char b[4];
d730b113
AT
735 int32 ret;
736
4c36ddbe 737 readfd(f,b,4);
d730b113 738 ret = IVAL(b,0);
f89b9368
WD
739 if (ret == (int32)0xffffffff)
740 return -1;
d730b113 741 return ret;
720b47f2
AT
742}
743
71c46176 744int64 read_longint(int f)
3a6a366f 745{
71c46176 746 int64 ret;
3a6a366f
AT
747 char b[8];
748 ret = read_int(f);
71c46176 749
f89b9368 750 if ((int32)ret != (int32)0xffffffff)
8de330a3 751 return ret;
71c46176 752
031fa9ad
WD
753#if SIZEOF_INT64 < 8
754 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
755 exit_cleanup(RERR_UNSUPPORTED);
756#else
91c4da3f
S
757 readfd(f,b,8);
758 ret = IVAL(b,0) | (((int64)IVAL(b,4))<<32);
031fa9ad 759#endif
71c46176 760
3a6a366f
AT
761 return ret;
762}
763
9dd891bb 764void read_buf(int f,char *buf,size_t len)
720b47f2 765{
4c36ddbe 766 readfd(f,buf,len);
720b47f2
AT
767}
768
9dd891bb 769void read_sbuf(int f,char *buf,size_t len)
575f2fca 770{
93095cbe 771 readfd(f, buf, len);
575f2fca
AT
772 buf[len] = 0;
773}
774
182dca5c
AT
775unsigned char read_byte(int f)
776{
4c36ddbe 777 unsigned char c;
93095cbe 778 readfd(f, (char *)&c, 1);
4c36ddbe 779 return c;
182dca5c 780}
720b47f2 781
188fed95
WD
782/* Populate a sum_struct with values from the socket. This is
783 * called by both the sender and the receiver. */
784void read_sum_head(int f, struct sum_struct *sum)
785{
786 sum->count = read_int(f);
787 sum->blength = read_int(f);
788 if (sum->blength < 0 || sum->blength > MAX_BLOCK_SIZE) {
789 rprintf(FERROR, "Invalid block length %ld\n",
790 (long)sum->blength);
791 exit_cleanup(RERR_PROTOCOL);
792 }
793 sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
794 if (sum->s2length < 0 || sum->s2length > MD4_SUM_LENGTH) {
795 rprintf(FERROR, "Invalid checksum length %d\n", sum->s2length);
796 exit_cleanup(RERR_PROTOCOL);
797 }
798 sum->remainder = read_int(f);
799 if (sum->remainder < 0 || sum->remainder > sum->blength) {
800 rprintf(FERROR, "Invalid remainder length %ld\n",
801 (long)sum->remainder);
802 exit_cleanup(RERR_PROTOCOL);
803 }
804}
805
c207d7ec
WD
806/* Send the values from a sum_struct over the socket. Set sum to
807 * NULL if there are no checksums to send. This is called by both
808 * the generator and the sender. */
809void write_sum_head(int f, struct sum_struct *sum)
810{
811 static struct sum_struct null_sum;
812
813 if (sum == NULL)
814 sum = &null_sum;
815
816 write_int(f, sum->count);
817 write_int(f, sum->blength);
818 if (protocol_version >= 27)
819 write_int(f, sum->s2length);
820 write_int(f, sum->remainder);
821}
822
880da007 823
08571358
MP
824/**
825 * Sleep after writing to limit I/O bandwidth usage.
826 *
827 * @todo Rather than sleeping after each write, it might be better to
828 * use some kind of averaging. The current algorithm seems to always
829 * use a bit less bandwidth than specified, because it doesn't make up
830 * for slow periods. But arguably this is a feature. In addition, we
831 * ought to take the time used to write the data into account.
71e58630
WD
832 *
833 * During some phases of big transfers (file FOO is uptodate) this is
834 * called with a small bytes_written every time. As the kernel has to
835 * round small waits up to guarantee that we actually wait at least the
836 * requested number of microseconds, this can become grossly inaccurate.
837 * We therefore keep track of the bytes we've written over time and only
838 * sleep when the accumulated delay is at least 1 tenth of a second.
08571358
MP
839 **/
840static void sleep_for_bwlimit(int bytes_written)
841{
71e58630
WD
842 static struct timeval prior_tv;
843 static long total_written = 0;
844 struct timeval tv, start_tv;
845 long elapsed_usec, sleep_usec;
846
847#define ONE_SEC 1000000L /* # of microseconds in a second */
08571358
MP
848
849 if (!bwlimit)
850 return;
e681e820 851
71e58630
WD
852 total_written += bytes_written;
853
854 gettimeofday(&start_tv, NULL);
855 if (prior_tv.tv_sec) {
856 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
857 + (start_tv.tv_usec - prior_tv.tv_usec);
858 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
859 if (total_written < 0)
860 total_written = 0;
861 }
3151cbae 862
71e58630
WD
863 sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
864 if (sleep_usec < ONE_SEC / 10) {
865 prior_tv = start_tv;
866 return;
867 }
08571358 868
71e58630
WD
869 tv.tv_sec = sleep_usec / ONE_SEC;
870 tv.tv_usec = sleep_usec % ONE_SEC;
98b332ed 871 select(0, NULL, NULL, NULL, &tv);
71e58630
WD
872
873 gettimeofday(&prior_tv, NULL);
874 elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
875 + (prior_tv.tv_usec - start_tv.tv_usec);
876 total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
08571358
MP
877}
878
879
1f75bb10
WD
880/* Write len bytes to the file descriptor fd, looping as necessary to get
881 * the job done and also (in the generator) reading any data on msg_fd_in
882 * (to avoid deadlock).
880da007
MP
883 *
884 * This function underlies the multiplexing system. The body of the
1f75bb10 885 * application never calls this function directly. */
9dd891bb 886static void writefd_unbuffered(int fd,char *buf,size_t len)
720b47f2 887{
1ea087a7 888 size_t n, total = 0;
8d9dc9f9 889 fd_set w_fds, r_fds;
1ea087a7 890 int maxfd, count, ret;
8d9dc9f9 891 struct timeval tv;
720b47f2 892
e44f9a12
AT
893 no_flush++;
894
4c36ddbe 895 while (total < len) {
8d9dc9f9 896 FD_ZERO(&w_fds);
8d9dc9f9 897 FD_SET(fd,&w_fds);
1ea087a7 898 maxfd = fd;
4c36ddbe 899
d17e1dd2 900 if (msg_fd_in >= 0) {
56014c8c 901 FD_ZERO(&r_fds);
d17e1dd2 902 FD_SET(msg_fd_in,&r_fds);
1ea087a7
WD
903 if (msg_fd_in > maxfd)
904 maxfd = msg_fd_in;
8d9dc9f9 905 }
41cfde6b
WD
906 if (fd != sock_f_out && iobuf_out_cnt && no_flush == 1) {
907 FD_SET(sock_f_out, &w_fds);
908 if (sock_f_out > maxfd)
909 maxfd = sock_f_out;
910 }
8d9dc9f9 911
e626b29e 912 tv.tv_sec = select_timeout;
8d9dc9f9 913 tv.tv_usec = 0;
4c36ddbe 914
554e0a8d 915 errno = 0;
1ea087a7 916 count = select(maxfd + 1, msg_fd_in >= 0 ? &r_fds : NULL,
d17e1dd2 917 &w_fds, NULL, &tv);
4c36ddbe
AT
918
919 if (count <= 0) {
1ea087a7 920 if (count < 0 && errno == EBADF)
554e0a8d 921 exit_cleanup(RERR_SOCKETIO);
bd717af8 922 check_timeout();
8d9dc9f9
AT
923 continue;
924 }
4c36ddbe 925
d17e1dd2
WD
926 if (msg_fd_in >= 0 && FD_ISSET(msg_fd_in, &r_fds))
927 read_msg_fd();
554e0a8d 928
41cfde6b
WD
929 if (!FD_ISSET(fd, &w_fds)) {
930 if (fd != sock_f_out && iobuf_out_cnt) {
931 no_flush--;
932 io_flush(NORMAL_FLUSH);
933 no_flush++;
934 }
1ea087a7 935 continue;
41cfde6b 936 }
4c36ddbe 937
1ea087a7
WD
938 n = len - total;
939 if (bwlimit && n > bwlimit_writemax)
940 n = bwlimit_writemax;
941 ret = write(fd, buf + total, n);
942
943 if (ret <= 0) {
3309507d
WD
944 if (ret < 0) {
945 if (errno == EINTR)
946 continue;
947 if (errno == EWOULDBLOCK || errno == EAGAIN) {
948 msleep(1);
949 continue;
950 }
f0359dd0
AT
951 }
952
1ea087a7 953 /* Don't try to write errors back across the stream. */
1f75bb10 954 if (fd == sock_f_out)
7f459268 955 close_multiplexing_out();
1ea087a7 956 rsyserr(FERROR, errno,
dca68b0a
WD
957 "writefd_unbuffered failed to write %ld bytes: phase \"%s\" [%s]",
958 (long)len, io_write_phase, who_am_i());
d1b31da7
WD
959 /* If the other side is sending us error messages, try
960 * to grab any messages they sent before they died. */
7f459268 961 while (fd == sock_f_out && io_multiplexing_in) {
ef0c03ff 962 io_timeout = select_timeout = 30;
d1b31da7
WD
963 readfd_unbuffered(sock_f_in, io_filesfrom_buf,
964 sizeof io_filesfrom_buf);
965 }
1ea087a7
WD
966 exit_cleanup(RERR_STREAMIO);
967 }
4c36ddbe 968
1ea087a7 969 total += ret;
a800434a 970
1f75bb10
WD
971 if (fd == sock_f_out) {
972 if (io_timeout)
973 last_io = time(NULL);
974 sleep_for_bwlimit(ret);
975 }
4c36ddbe 976 }
e44f9a12
AT
977
978 no_flush--;
720b47f2
AT
979}
980
8d9dc9f9 981
880da007
MP
982/**
983 * Write an message to a multiplexed stream. If this fails then rsync
984 * exits.
985 **/
1f75bb10 986static void mplex_write(enum msgcode code, char *buf, size_t len)
ff41a59f
AT
987{
988 char buffer[4096];
06ce139f 989 size_t n = len;
8d9dc9f9 990
ff41a59f
AT
991 SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
992
c399d22a 993 if (n > sizeof buffer - 4)
3151cbae 994 n = sizeof buffer - 4;
ff41a59f
AT
995
996 memcpy(&buffer[4], buf, n);
1f75bb10 997 writefd_unbuffered(sock_f_out, buffer, n+4);
ff41a59f
AT
998
999 len -= n;
1000 buf += n;
1001
1ea087a7 1002 if (len)
1f75bb10 1003 writefd_unbuffered(sock_f_out, buf, len);
d6dead6b
AT
1004}
1005
ff41a59f 1006
d17e1dd2 1007void io_flush(int flush_it_all)
d6dead6b 1008{
d17e1dd2 1009 msg_list_push(flush_it_all);
90ba34e2 1010
1f75bb10 1011 if (!iobuf_out_cnt || no_flush)
d17e1dd2 1012 return;
8d9dc9f9 1013
d17e1dd2 1014 if (io_multiplexing_out)
1f75bb10 1015 mplex_write(MSG_DATA, iobuf_out, iobuf_out_cnt);
d17e1dd2 1016 else
1f75bb10
WD
1017 writefd_unbuffered(sock_f_out, iobuf_out, iobuf_out_cnt);
1018 iobuf_out_cnt = 0;
8d9dc9f9
AT
1019}
1020
0ba48136 1021
9dd891bb 1022static void writefd(int fd,char *buf,size_t len)
d6dead6b 1023{
4033b80b
WD
1024 if (fd == msg_fd_out) {
1025 rprintf(FERROR, "Internal error: wrong write used in receiver.\n");
1026 exit_cleanup(RERR_PROTOCOL);
1027 }
90ba34e2 1028
1f75bb10
WD
1029 if (fd == sock_f_out)
1030 stats.total_written += len;
1031
b9f592fb
WD
1032 if (fd == write_batch_monitor_out) {
1033 if ((size_t)write(batch_fd, buf, len) != len)
1034 exit_cleanup(RERR_FILEIO);
1035 }
1036
1f75bb10 1037 if (!iobuf_out || fd != sock_f_out) {
4c36ddbe
AT
1038 writefd_unbuffered(fd, buf, len);
1039 return;
1040 }
d6dead6b
AT
1041
1042 while (len) {
1f75bb10 1043 int n = MIN((int)len, IO_BUFFER_SIZE - iobuf_out_cnt);
d6dead6b 1044 if (n > 0) {
1f75bb10 1045 memcpy(iobuf_out+iobuf_out_cnt, buf, n);
d6dead6b
AT
1046 buf += n;
1047 len -= n;
1f75bb10 1048 iobuf_out_cnt += n;
d6dead6b 1049 }
3151cbae 1050
1f75bb10 1051 if (iobuf_out_cnt == IO_BUFFER_SIZE)
d17e1dd2 1052 io_flush(NORMAL_FLUSH);
d6dead6b 1053 }
d6dead6b 1054}
720b47f2
AT
1055
1056
b7922338 1057void write_int(int f,int32 x)
720b47f2 1058{
8d9dc9f9
AT
1059 char b[4];
1060 SIVAL(b,0,x);
4c36ddbe 1061 writefd(f,b,4);
720b47f2
AT
1062}
1063
7a24c346 1064
805edf9d
MP
1065void write_int_named(int f, int32 x, const char *phase)
1066{
1067 io_write_phase = phase;
1068 write_int(f, x);
1069 io_write_phase = phase_unknown;
1070}
1071
1072
7a24c346
MP
1073/*
1074 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1075 * 64-bit types on this platform.
1076 */
71c46176 1077void write_longint(int f, int64 x)
3a6a366f 1078{
3a6a366f 1079 char b[8];
3a6a366f 1080
91c4da3f 1081 if (x <= 0x7FFFFFFF) {
3a6a366f
AT
1082 write_int(f, (int)x);
1083 return;
1084 }
1085
031fa9ad
WD
1086#if SIZEOF_INT64 < 8
1087 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1088 exit_cleanup(RERR_UNSUPPORTED);
1089#else
8de330a3 1090 write_int(f, (int32)0xFFFFFFFF);
3a6a366f
AT
1091 SIVAL(b,0,(x&0xFFFFFFFF));
1092 SIVAL(b,4,((x>>32)&0xFFFFFFFF));
1093
4c36ddbe 1094 writefd(f,b,8);
031fa9ad 1095#endif
3a6a366f
AT
1096}
1097
9dd891bb 1098void write_buf(int f,char *buf,size_t len)
720b47f2 1099{
4c36ddbe 1100 writefd(f,buf,len);
720b47f2
AT
1101}
1102
880da007 1103/** Write a string to the connection */
cf338ab1 1104void write_sbuf(int f, char *buf)
f0fca04e 1105{
93095cbe 1106 writefd(f, buf, strlen(buf));
f0fca04e
AT
1107}
1108
182dca5c
AT
1109void write_byte(int f,unsigned char c)
1110{
93095cbe 1111 writefd(f, (char *)&c, 1);
182dca5c
AT
1112}
1113
7a55d06e
MP
1114
1115
914cc65c 1116/**
6ed6d7f5
WD
1117 * Read a line of up to @p maxlen characters into @p buf (not counting
1118 * the trailing null). Strips the (required) trailing newline and all
1119 * carriage returns.
914cc65c 1120 *
6ed6d7f5 1121 * @return 1 for success; 0 for I/O error or truncation.
914cc65c 1122 **/
9dd891bb 1123int read_line(int f, char *buf, size_t maxlen)
f0fca04e
AT
1124{
1125 while (maxlen) {
528bfcd7 1126 buf[0] = 0;
f0fca04e 1127 read_buf(f, buf, 1);
914cc65c
MP
1128 if (buf[0] == 0)
1129 return 0;
6ed6d7f5 1130 if (buf[0] == '\n')
f0fca04e 1131 break;
f0fca04e
AT
1132 if (buf[0] != '\r') {
1133 buf++;
1134 maxlen--;
1135 }
1136 }
6ed6d7f5
WD
1137 *buf = '\0';
1138 return maxlen > 0;
f0fca04e
AT
1139}
1140
1141
1142void io_printf(int fd, const char *format, ...)
1143{
d62bcc17 1144 va_list ap;
f0fca04e
AT
1145 char buf[1024];
1146 int len;
3151cbae 1147
f0fca04e 1148 va_start(ap, format);
3151cbae 1149 len = vsnprintf(buf, sizeof buf, format, ap);
f0fca04e
AT
1150 va_end(ap);
1151
f89b9368
WD
1152 if (len < 0)
1153 exit_cleanup(RERR_STREAMIO);
f0fca04e
AT
1154
1155 write_sbuf(fd, buf);
1156}
8d9dc9f9
AT
1157
1158
d17e1dd2 1159/** Setup for multiplexing a MSG_* stream with the data stream. */
1f75bb10 1160void io_start_multiplex_out(void)
8d9dc9f9 1161{
d17e1dd2 1162 io_flush(NORMAL_FLUSH);
1f75bb10 1163 io_start_buffering_out();
8d9dc9f9
AT
1164 io_multiplexing_out = 1;
1165}
1166
d17e1dd2 1167/** Setup for multiplexing a MSG_* stream with the data stream. */
1f75bb10 1168void io_start_multiplex_in(void)
8d9dc9f9 1169{
d17e1dd2 1170 io_flush(NORMAL_FLUSH);
1f75bb10 1171 io_start_buffering_in();
8d9dc9f9
AT
1172 io_multiplexing_in = 1;
1173}
1174
d17e1dd2
WD
1175/** Write an message to the multiplexed data stream. */
1176int io_multiplex_write(enum msgcode code, char *buf, size_t len)
8d9dc9f9 1177{
f89b9368
WD
1178 if (!io_multiplexing_out)
1179 return 0;
8d9dc9f9 1180
d17e1dd2 1181 io_flush(NORMAL_FLUSH);
1b7c47cb 1182 stats.total_written += (len+4);
1f75bb10 1183 mplex_write(code, buf, len);
8d9dc9f9
AT
1184 return 1;
1185}
1186
7f459268
WD
1187void close_multiplexing_in(void)
1188{
1189 io_multiplexing_in = 0;
1190}
1191
d17e1dd2 1192/** Stop output multiplexing. */
7f459268 1193void close_multiplexing_out(void)
554e0a8d
AT
1194{
1195 io_multiplexing_out = 0;
1196}
1197
b9f592fb
WD
1198void start_write_batch(int fd)
1199{
741d6544
WD
1200 write_stream_flags(batch_fd);
1201
b9f592fb
WD
1202 /* Some communication has already taken place, but we don't
1203 * enable batch writing until here so that we can write a
1204 * canonical record of the communication even though the
1205 * actual communication so far depends on whether a daemon
1206 * is involved. */
1207 write_int(batch_fd, protocol_version);
1208 write_int(batch_fd, checksum_seed);
b9f592fb
WD
1209
1210 if (am_sender)
1211 write_batch_monitor_out = fd;
1212 else
1213 write_batch_monitor_in = fd;
1214}
1215
1216void stop_write_batch(void)
1217{
1218 write_batch_monitor_out = -1;
1219 write_batch_monitor_in = -1;
1220}