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