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