- Call log_delete() instead of outputting a "deleting ..." message.
[rsync/rsync.git] / io.c
... / ...
CommitLineData
1/* -*- c-file-style: "linux" -*-
2 *
3 * Copyright (C) 1996-2001 by Andrew Tridgell
4 * Copyright (C) Paul Mackerras 1996
5 * Copyright (C) 2001, 2002 by Martin Pool <mbp@samba.org>
6 *
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.
11 *
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.
16 *
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 */
21
22/**
23 * @file io.c
24 *
25 * Socket and pipe I/O utilities used in rsync.
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 **/
36
37#include "rsync.h"
38
39/** If no timeout is specified then use a 60 second select timeout */
40#define SELECT_TIMEOUT 60
41
42extern int bwlimit;
43extern size_t bwlimit_writemax;
44extern int verbose;
45extern int io_timeout;
46extern int am_server;
47extern int am_daemon;
48extern int am_sender;
49extern int am_generator;
50extern int eol_nulls;
51extern int csum_length;
52extern int checksum_seed;
53extern int protocol_version;
54extern char *remote_filesfrom_file;
55extern struct stats stats;
56
57const char phase_unknown[] = "unknown";
58int select_timeout = SELECT_TIMEOUT;
59int batch_fd = -1;
60int batch_gen_fd = -1;
61
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.
67 *
68 * For buffered/multiplexed I/O these names will be somewhat
69 * approximate; perhaps for ease of support we would rather make the
70 * buffer always flush when a single application-level I/O finishes.
71 *
72 * @todo Perhaps we want some simple stack functionality, but there's
73 * no need to overdo it.
74 **/
75const char *io_write_phase = phase_unknown;
76const char *io_read_phase = phase_unknown;
77
78/** Ignore EOF errors while reading a module listing if the remote
79 version is 24 or less. */
80int kludge_around_eof = False;
81
82int msg_fd_in = -1;
83int msg_fd_out = -1;
84
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
92static int write_batch_monitor_in = -1;
93static int write_batch_monitor_out = -1;
94
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;
101
102static void read_loop(int fd, char *buf, size_t len);
103
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
136static void check_timeout(void)
137{
138 time_t t;
139
140 if (!io_timeout)
141 return;
142
143 if (!last_io) {
144 last_io = time(NULL);
145 return;
146 }
147
148 t = time(NULL);
149
150 if (t - last_io >= io_timeout) {
151 if (!am_server && !am_daemon) {
152 rprintf(FERROR, "io timeout after %d seconds -- exiting\n",
153 (int)(t-last_io));
154 }
155 exit_cleanup(RERR_TIMEOUT);
156 }
157}
158
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
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). */
171void set_msg_fd_in(int fd)
172{
173 msg_fd_in = fd;
174}
175
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). */
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)
186{
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;
202}
203
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
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). */
214static void read_msg_fd(void)
215{
216 char buf[2048];
217 size_t n;
218 int fd = msg_fd_in;
219 int tag, len;
220
221 /* Temporarily disable msg_fd_in. This is needed to avoid looping back
222 * to this routine from read_timeout() and writefd_unbuffered(). */
223 msg_fd_in = -1;
224
225 read_loop(fd, buf, 4);
226 tag = IVAL(buf, 0);
227
228 len = tag & 0xFFFFFF;
229 tag = (tag >> 24) - MPLEX_BASE;
230
231 switch (tag) {
232 case MSG_DONE:
233 if (len != 0 || !am_generator) {
234 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
235 exit_cleanup(RERR_STREAMIO);
236 }
237 redo_list_add(-1);
238 break;
239 case MSG_REDO:
240 if (len != 4 || !am_generator) {
241 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
242 exit_cleanup(RERR_STREAMIO);
243 }
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:
260 rprintf(FERROR, "unknown message %d:%d\n", tag, len);
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.
269 * This is only active in the receiver. */
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);
291 tv.tv_sec = select_timeout;
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 }
303 }
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();
314
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;
323}
324
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}
343
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 */
354static void whine_about_eof(int fd)
355{
356 if (kludge_around_eof && fd == sock_f_in)
357 exit_cleanup(0);
358
359 rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
360 "(%.0f bytes received so far) [%s]\n",
361 (double)stats.total_read, who_am_i());
362
363 exit_cleanup(RERR_STREAMIO);
364}
365
366
367/**
368 * Read from a socket with I/O timeout. return the number of bytes
369 * read. If no bytes can be read then exit, never return a number <= 0.
370 *
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.
377 */
378static int read_timeout(int fd, char *buf, size_t len)
379{
380 int n, ret = 0;
381
382 io_flush(NORMAL_FLUSH);
383
384 while (ret == 0) {
385 /* until we manage to read *something* */
386 fd_set r_fds, w_fds;
387 struct timeval tv;
388 int maxfd = fd;
389 int count;
390
391 FD_ZERO(&r_fds);
392 FD_ZERO(&w_fds);
393 FD_SET(fd, &r_fds);
394 if (msg_fd_in >= 0) {
395 FD_SET(msg_fd_in, &r_fds);
396 if (msg_fd_in > maxfd)
397 maxfd = msg_fd_in;
398 } else if (msg_list_head) {
399 FD_SET(msg_fd_out, &w_fds);
400 if (msg_fd_out > maxfd)
401 maxfd = msg_fd_out;
402 }
403 if (io_filesfrom_f_out >= 0) {
404 int new_fd;
405 if (io_filesfrom_buflen == 0) {
406 if (io_filesfrom_f_in >= 0) {
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 {
414 FD_SET(io_filesfrom_f_out, &w_fds);
415 new_fd = io_filesfrom_f_out;
416 }
417 if (new_fd > maxfd)
418 maxfd = new_fd;
419 }
420
421 tv.tv_sec = select_timeout;
422 tv.tv_usec = 0;
423
424 errno = 0;
425
426 count = select(maxfd + 1, &r_fds, &w_fds, NULL, &tv);
427
428 if (count <= 0) {
429 if (errno == EBADF)
430 exit_cleanup(RERR_SOCKETIO);
431 check_timeout();
432 continue;
433 }
434
435 if (msg_fd_in >= 0 && FD_ISSET(msg_fd_in, &r_fds))
436 read_msg_fd();
437 else if (msg_list_head && FD_ISSET(msg_fd_out, &w_fds))
438 msg_list_push(NORMAL_FLUSH);
439
440 if (io_filesfrom_f_out >= 0) {
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 }
456 } else if (io_filesfrom_f_in >= 0) {
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 {
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
503 if (!FD_ISSET(fd, &r_fds))
504 continue;
505
506 n = read(fd, buf, len);
507
508 if (n <= 0) {
509 if (n == 0)
510 whine_about_eof(fd); /* Doesn't return. */
511 if (errno == EINTR || errno == EWOULDBLOCK
512 || errno == EAGAIN)
513 continue;
514
515 /* Don't write errors on a dead socket. */
516 if (fd == sock_f_in)
517 close_multiplexing_out();
518 rsyserr(FERROR, errno, "read error");
519 exit_cleanup(RERR_STREAMIO);
520 }
521
522 buf += n;
523 len -= n;
524 ret += n;
525
526 if (io_timeout && fd == sock_f_in)
527 last_io = time(NULL);
528 }
529
530 return ret;
531}
532
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;
541 int reading_remotely = remote_filesfrom_file != NULL;
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);
554 tv.tv_sec = select_timeout;
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';
572
573 /* Dump comments. */
574 if (*fname == '#' || *fname == ';')
575 goto start;
576
577 return s - fname;
578}
579
580
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
617/**
618 * Continue trying to read len bytes - don't return until len has been
619 * read.
620 **/
621static void read_loop(int fd, char *buf, size_t len)
622{
623 while (len) {
624 int n = read_timeout(fd, buf, len);
625
626 buf += n;
627 len -= n;
628 }
629}
630
631
632/**
633 * Read from the file descriptor handling multiplexing - return number
634 * of bytes read.
635 *
636 * Never returns <= 0.
637 */
638static int readfd_unbuffered(int fd, char *buf, size_t len)
639{
640 static size_t remaining;
641 static size_t iobuf_in_ndx;
642 int tag, ret = 0;
643 char line[1024];
644
645 if (!iobuf_in || fd != sock_f_in)
646 return read_timeout(fd, buf, len);
647
648 if (!io_multiplexing_in && remaining == 0) {
649 remaining = read_timeout(fd, iobuf_in, iobuf_in_siz);
650 iobuf_in_ndx = 0;
651 }
652
653 while (ret == 0) {
654 if (remaining) {
655 len = MIN(len, remaining);
656 memcpy(buf, iobuf_in + iobuf_in_ndx, len);
657 iobuf_in_ndx += len;
658 remaining -= len;
659 ret = len;
660 break;
661 }
662
663 read_loop(fd, line, 4);
664 tag = IVAL(line, 0);
665
666 remaining = tag & 0xFFFFFF;
667 tag = (tag >> 24) - MPLEX_BASE;
668
669 switch (tag) {
670 case MSG_DATA:
671 if (remaining > iobuf_in_siz) {
672 if (!(iobuf_in = realloc_array(iobuf_in, char,
673 remaining)))
674 out_of_memory("readfd_unbuffered");
675 iobuf_in_siz = remaining;
676 }
677 read_loop(fd, iobuf_in, remaining);
678 iobuf_in_ndx = 0;
679 break;
680 case MSG_INFO:
681 case MSG_ERROR:
682 if (remaining >= sizeof line) {
683 rprintf(FERROR,
684 "[%s] multiplexing overflow %d:%ld\n\n",
685 who_am_i(), tag, (long)remaining);
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:
693 rprintf(FERROR, "[%s] unexpected tag %d\n",
694 who_am_i(), tag);
695 exit_cleanup(RERR_STREAMIO);
696 }
697 }
698
699 if (remaining == 0)
700 io_flush(NORMAL_FLUSH);
701
702 return ret;
703}
704
705
706
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 **/
712static void readfd(int fd, char *buffer, size_t N)
713{
714 int ret;
715 size_t total = 0;
716
717 while (total < N) {
718 ret = readfd_unbuffered(fd, buffer + total, N-total);
719 total += ret;
720 }
721
722 if (fd == write_batch_monitor_in) {
723 if ((size_t)write(batch_fd, buffer, total) != total)
724 exit_cleanup(RERR_FILEIO);
725 }
726
727 if (fd == sock_f_in)
728 stats.total_read += total;
729}
730
731
732unsigned short read_short(int f)
733{
734 uchar b[2];
735 readfd(f, (char *)b, 2);
736 return (b[1] << 8) + b[0];
737}
738
739
740int32 read_int(int f)
741{
742 char b[4];
743 int32 ret;
744
745 readfd(f,b,4);
746 ret = IVAL(b,0);
747 if (ret == (int32)0xffffffff)
748 return -1;
749 return ret;
750}
751
752int64 read_longint(int f)
753{
754 int64 ret;
755 char b[8];
756 ret = read_int(f);
757
758 if ((int32)ret != (int32)0xffffffff)
759 return ret;
760
761#if SIZEOF_INT64 < 8
762 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
763 exit_cleanup(RERR_UNSUPPORTED);
764#else
765 readfd(f,b,8);
766 ret = IVAL(b,0) | (((int64)IVAL(b,4))<<32);
767#endif
768
769 return ret;
770}
771
772void read_buf(int f,char *buf,size_t len)
773{
774 readfd(f,buf,len);
775}
776
777void read_sbuf(int f,char *buf,size_t len)
778{
779 readfd(f, buf, len);
780 buf[len] = 0;
781}
782
783uchar read_byte(int f)
784{
785 uchar c;
786 readfd(f, (char *)&c, 1);
787 return c;
788}
789
790/* Populate a sum_struct with values from the socket. This is
791 * called by both the sender and the receiver. */
792void read_sum_head(int f, struct sum_struct *sum)
793{
794 sum->count = read_int(f);
795 sum->blength = read_int(f);
796 if (sum->blength < 0 || sum->blength > MAX_BLOCK_SIZE) {
797 rprintf(FERROR, "[%s] Invalid block length %ld\n",
798 who_am_i(), (long)sum->blength);
799 exit_cleanup(RERR_PROTOCOL);
800 }
801 sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
802 if (sum->s2length < 0 || sum->s2length > MD4_SUM_LENGTH) {
803 rprintf(FERROR, "[%s] Invalid checksum length %d\n",
804 who_am_i(), sum->s2length);
805 exit_cleanup(RERR_PROTOCOL);
806 }
807 sum->remainder = read_int(f);
808 if (sum->remainder < 0 || sum->remainder > sum->blength) {
809 rprintf(FERROR, "[%s] Invalid remainder length %ld\n",
810 who_am_i(), (long)sum->remainder);
811 exit_cleanup(RERR_PROTOCOL);
812 }
813}
814
815/* Send the values from a sum_struct over the socket. Set sum to
816 * NULL if there are no checksums to send. This is called by both
817 * the generator and the sender. */
818void write_sum_head(int f, struct sum_struct *sum)
819{
820 static struct sum_struct null_sum;
821
822 if (sum == NULL)
823 sum = &null_sum;
824
825 write_int(f, sum->count);
826 write_int(f, sum->blength);
827 if (protocol_version >= 27)
828 write_int(f, sum->s2length);
829 write_int(f, sum->remainder);
830}
831
832
833/**
834 * Sleep after writing to limit I/O bandwidth usage.
835 *
836 * @todo Rather than sleeping after each write, it might be better to
837 * use some kind of averaging. The current algorithm seems to always
838 * use a bit less bandwidth than specified, because it doesn't make up
839 * for slow periods. But arguably this is a feature. In addition, we
840 * ought to take the time used to write the data into account.
841 *
842 * During some phases of big transfers (file FOO is uptodate) this is
843 * called with a small bytes_written every time. As the kernel has to
844 * round small waits up to guarantee that we actually wait at least the
845 * requested number of microseconds, this can become grossly inaccurate.
846 * We therefore keep track of the bytes we've written over time and only
847 * sleep when the accumulated delay is at least 1 tenth of a second.
848 **/
849static void sleep_for_bwlimit(int bytes_written)
850{
851 static struct timeval prior_tv;
852 static long total_written = 0;
853 struct timeval tv, start_tv;
854 long elapsed_usec, sleep_usec;
855
856#define ONE_SEC 1000000L /* # of microseconds in a second */
857
858 if (!bwlimit)
859 return;
860
861 total_written += bytes_written;
862
863 gettimeofday(&start_tv, NULL);
864 if (prior_tv.tv_sec) {
865 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
866 + (start_tv.tv_usec - prior_tv.tv_usec);
867 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
868 if (total_written < 0)
869 total_written = 0;
870 }
871
872 sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
873 if (sleep_usec < ONE_SEC / 10) {
874 prior_tv = start_tv;
875 return;
876 }
877
878 tv.tv_sec = sleep_usec / ONE_SEC;
879 tv.tv_usec = sleep_usec % ONE_SEC;
880 select(0, NULL, NULL, NULL, &tv);
881
882 gettimeofday(&prior_tv, NULL);
883 elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
884 + (prior_tv.tv_usec - start_tv.tv_usec);
885 total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
886}
887
888
889/* Write len bytes to the file descriptor fd, looping as necessary to get
890 * the job done and also (in the generator) reading any data on msg_fd_in
891 * (to avoid deadlock).
892 *
893 * This function underlies the multiplexing system. The body of the
894 * application never calls this function directly. */
895static void writefd_unbuffered(int fd,char *buf,size_t len)
896{
897 size_t n, total = 0;
898 fd_set w_fds, r_fds;
899 int maxfd, count, ret;
900 struct timeval tv;
901
902 no_flush++;
903
904 while (total < len) {
905 FD_ZERO(&w_fds);
906 FD_SET(fd,&w_fds);
907 maxfd = fd;
908
909 if (msg_fd_in >= 0) {
910 FD_ZERO(&r_fds);
911 FD_SET(msg_fd_in,&r_fds);
912 if (msg_fd_in > maxfd)
913 maxfd = msg_fd_in;
914 }
915 if (fd != sock_f_out && iobuf_out_cnt && no_flush == 1) {
916 FD_SET(sock_f_out, &w_fds);
917 if (sock_f_out > maxfd)
918 maxfd = sock_f_out;
919 }
920
921 tv.tv_sec = select_timeout;
922 tv.tv_usec = 0;
923
924 errno = 0;
925 count = select(maxfd + 1, msg_fd_in >= 0 ? &r_fds : NULL,
926 &w_fds, NULL, &tv);
927
928 if (count <= 0) {
929 if (count < 0 && errno == EBADF)
930 exit_cleanup(RERR_SOCKETIO);
931 check_timeout();
932 continue;
933 }
934
935 if (msg_fd_in >= 0 && FD_ISSET(msg_fd_in, &r_fds))
936 read_msg_fd();
937
938 if (!FD_ISSET(fd, &w_fds)) {
939 if (fd != sock_f_out && iobuf_out_cnt) {
940 no_flush--;
941 io_flush(NORMAL_FLUSH);
942 no_flush++;
943 }
944 continue;
945 }
946
947 n = len - total;
948 if (bwlimit && n > bwlimit_writemax)
949 n = bwlimit_writemax;
950 ret = write(fd, buf + total, n);
951
952 if (ret <= 0) {
953 if (ret < 0) {
954 if (errno == EINTR)
955 continue;
956 if (errno == EWOULDBLOCK || errno == EAGAIN) {
957 msleep(1);
958 continue;
959 }
960 }
961
962 /* Don't try to write errors back across the stream. */
963 if (fd == sock_f_out)
964 close_multiplexing_out();
965 rsyserr(FERROR, errno,
966 "writefd_unbuffered failed to write %ld bytes: phase \"%s\" [%s]",
967 (long)len, io_write_phase, who_am_i());
968 /* If the other side is sending us error messages, try
969 * to grab any messages they sent before they died. */
970 while (fd == sock_f_out && io_multiplexing_in) {
971 io_timeout = select_timeout = 30;
972 readfd_unbuffered(sock_f_in, io_filesfrom_buf,
973 sizeof io_filesfrom_buf);
974 }
975 exit_cleanup(RERR_STREAMIO);
976 }
977
978 total += ret;
979
980 if (fd == sock_f_out) {
981 if (io_timeout)
982 last_io = time(NULL);
983 sleep_for_bwlimit(ret);
984 }
985 }
986
987 no_flush--;
988}
989
990
991/**
992 * Write an message to a multiplexed stream. If this fails then rsync
993 * exits.
994 **/
995static void mplex_write(enum msgcode code, char *buf, size_t len)
996{
997 char buffer[4096];
998 size_t n = len;
999
1000 SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
1001
1002 if (n > sizeof buffer - 4)
1003 n = sizeof buffer - 4;
1004
1005 memcpy(&buffer[4], buf, n);
1006 writefd_unbuffered(sock_f_out, buffer, n+4);
1007
1008 len -= n;
1009 buf += n;
1010
1011 if (len)
1012 writefd_unbuffered(sock_f_out, buf, len);
1013}
1014
1015
1016void io_flush(int flush_it_all)
1017{
1018 msg_list_push(flush_it_all);
1019
1020 if (!iobuf_out_cnt || no_flush)
1021 return;
1022
1023 if (io_multiplexing_out)
1024 mplex_write(MSG_DATA, iobuf_out, iobuf_out_cnt);
1025 else
1026 writefd_unbuffered(sock_f_out, iobuf_out, iobuf_out_cnt);
1027 iobuf_out_cnt = 0;
1028}
1029
1030
1031static void writefd(int fd,char *buf,size_t len)
1032{
1033 if (fd == msg_fd_out) {
1034 rprintf(FERROR, "Internal error: wrong write used in receiver.\n");
1035 exit_cleanup(RERR_PROTOCOL);
1036 }
1037
1038 if (fd == sock_f_out)
1039 stats.total_written += len;
1040
1041 if (fd == write_batch_monitor_out) {
1042 if ((size_t)write(batch_fd, buf, len) != len)
1043 exit_cleanup(RERR_FILEIO);
1044 }
1045
1046 if (!iobuf_out || fd != sock_f_out) {
1047 writefd_unbuffered(fd, buf, len);
1048 return;
1049 }
1050
1051 while (len) {
1052 int n = MIN((int)len, IO_BUFFER_SIZE - iobuf_out_cnt);
1053 if (n > 0) {
1054 memcpy(iobuf_out+iobuf_out_cnt, buf, n);
1055 buf += n;
1056 len -= n;
1057 iobuf_out_cnt += n;
1058 }
1059
1060 if (iobuf_out_cnt == IO_BUFFER_SIZE)
1061 io_flush(NORMAL_FLUSH);
1062 }
1063}
1064
1065
1066void write_short(int f, unsigned short x)
1067{
1068 uchar b[2];
1069 b[0] = x;
1070 b[1] = x >> 8;
1071 writefd(f, (char *)b, 2);
1072}
1073
1074
1075void write_int(int f,int32 x)
1076{
1077 char b[4];
1078 SIVAL(b,0,x);
1079 writefd(f,b,4);
1080}
1081
1082
1083void write_int_named(int f, int32 x, const char *phase)
1084{
1085 io_write_phase = phase;
1086 write_int(f, x);
1087 io_write_phase = phase_unknown;
1088}
1089
1090
1091/*
1092 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1093 * 64-bit types on this platform.
1094 */
1095void write_longint(int f, int64 x)
1096{
1097 char b[8];
1098
1099 if (x <= 0x7FFFFFFF) {
1100 write_int(f, (int)x);
1101 return;
1102 }
1103
1104#if SIZEOF_INT64 < 8
1105 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1106 exit_cleanup(RERR_UNSUPPORTED);
1107#else
1108 write_int(f, (int32)0xFFFFFFFF);
1109 SIVAL(b,0,(x&0xFFFFFFFF));
1110 SIVAL(b,4,((x>>32)&0xFFFFFFFF));
1111
1112 writefd(f,b,8);
1113#endif
1114}
1115
1116void write_buf(int f,char *buf,size_t len)
1117{
1118 writefd(f,buf,len);
1119}
1120
1121
1122/** Write a string to the connection */
1123void write_sbuf(int f, char *buf)
1124{
1125 writefd(f, buf, strlen(buf));
1126}
1127
1128
1129void write_byte(int f, uchar c)
1130{
1131 writefd(f, (char *)&c, 1);
1132}
1133
1134
1135/**
1136 * Read a line of up to @p maxlen characters into @p buf (not counting
1137 * the trailing null). Strips the (required) trailing newline and all
1138 * carriage returns.
1139 *
1140 * @return 1 for success; 0 for I/O error or truncation.
1141 **/
1142int read_line(int f, char *buf, size_t maxlen)
1143{
1144 while (maxlen) {
1145 buf[0] = 0;
1146 read_buf(f, buf, 1);
1147 if (buf[0] == 0)
1148 return 0;
1149 if (buf[0] == '\n')
1150 break;
1151 if (buf[0] != '\r') {
1152 buf++;
1153 maxlen--;
1154 }
1155 }
1156 *buf = '\0';
1157 return maxlen > 0;
1158}
1159
1160
1161void io_printf(int fd, const char *format, ...)
1162{
1163 va_list ap;
1164 char buf[1024];
1165 int len;
1166
1167 va_start(ap, format);
1168 len = vsnprintf(buf, sizeof buf, format, ap);
1169 va_end(ap);
1170
1171 if (len < 0)
1172 exit_cleanup(RERR_STREAMIO);
1173
1174 write_sbuf(fd, buf);
1175}
1176
1177
1178/** Setup for multiplexing a MSG_* stream with the data stream. */
1179void io_start_multiplex_out(void)
1180{
1181 io_flush(NORMAL_FLUSH);
1182 io_start_buffering_out();
1183 io_multiplexing_out = 1;
1184}
1185
1186/** Setup for multiplexing a MSG_* stream with the data stream. */
1187void io_start_multiplex_in(void)
1188{
1189 io_flush(NORMAL_FLUSH);
1190 io_start_buffering_in();
1191 io_multiplexing_in = 1;
1192}
1193
1194/** Write an message to the multiplexed data stream. */
1195int io_multiplex_write(enum msgcode code, char *buf, size_t len)
1196{
1197 if (!io_multiplexing_out)
1198 return 0;
1199
1200 io_flush(NORMAL_FLUSH);
1201 stats.total_written += (len+4);
1202 mplex_write(code, buf, len);
1203 return 1;
1204}
1205
1206void close_multiplexing_in(void)
1207{
1208 io_multiplexing_in = 0;
1209}
1210
1211/** Stop output multiplexing. */
1212void close_multiplexing_out(void)
1213{
1214 io_multiplexing_out = 0;
1215}
1216
1217void start_write_batch(int fd)
1218{
1219 write_stream_flags(batch_fd);
1220
1221 /* Some communication has already taken place, but we don't
1222 * enable batch writing until here so that we can write a
1223 * canonical record of the communication even though the
1224 * actual communication so far depends on whether a daemon
1225 * is involved. */
1226 write_int(batch_fd, protocol_version);
1227 write_int(batch_fd, checksum_seed);
1228
1229 if (am_sender)
1230 write_batch_monitor_out = fd;
1231 else
1232 write_batch_monitor_in = fd;
1233}
1234
1235void stop_write_batch(void)
1236{
1237 write_batch_monitor_out = -1;
1238 write_batch_monitor_in = -1;
1239}