1 /* -*- c-file-style: "linux" -*-
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>
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.
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.
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.
25 * Socket and pipe I/O utilities used in rsync.
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
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().
39 /** If no timeout is specified then use a 60 second select timeout */
40 #define SELECT_TIMEOUT 60
43 extern size_t bwlimit_writemax;
45 extern int io_timeout;
49 extern int am_generator;
51 extern int csum_length;
52 extern int checksum_seed;
53 extern int protocol_version;
54 extern char *filesfrom_host;
55 extern struct stats stats;
57 const char phase_unknown[] = "unknown";
58 int select_timeout = SELECT_TIMEOUT;
59 int ignore_timeout = 0;
61 int batch_gen_fd = -1;
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
69 * For buffered/multiplexed I/O these names will be somewhat
70 * approximate; perhaps for ease of support we would rather make the
71 * buffer always flush when a single application-level I/O finishes.
73 * @todo Perhaps we want some simple stack functionality, but there's
74 * no need to overdo it.
76 const char *io_write_phase = phase_unknown;
77 const char *io_read_phase = phase_unknown;
79 /* Ignore an EOF error if non-zero. See whine_about_eof(). */
80 int kluge_around_eof = 0;
85 static int io_multiplexing_out;
86 static int io_multiplexing_in;
87 static int sock_f_in = -1;
88 static int sock_f_out = -1;
89 static time_t last_io;
92 static int write_batch_monitor_in = -1;
93 static int write_batch_monitor_out = -1;
95 static int io_filesfrom_f_in = -1;
96 static int io_filesfrom_f_out = -1;
97 static char io_filesfrom_buf[2048];
98 static char *io_filesfrom_bp;
99 static char io_filesfrom_lastchar;
100 static int io_filesfrom_buflen;
101 static size_t contiguous_write_len = 0;
103 static void read_loop(int fd, char *buf, size_t len);
105 struct flist_ndx_item {
106 struct flist_ndx_item *next;
110 struct flist_ndx_list {
111 struct flist_ndx_item *head, *tail;
114 static struct flist_ndx_list redo_list;
117 struct msg_list *next;
122 static struct msg_list *msg_list_head;
123 static struct msg_list *msg_list_tail;
125 static void flist_ndx_push(struct flist_ndx_list *lp, int ndx)
127 struct flist_ndx_item *item;
129 if (!(item = new(struct flist_ndx_item)))
130 out_of_memory("flist_ndx_push");
134 lp->tail->next = item;
140 static int flist_ndx_pop(struct flist_ndx_list *lp)
142 struct flist_ndx_item *next;
149 next = lp->head->next;
158 static void check_timeout(void)
162 if (!io_timeout || ignore_timeout)
166 last_io = time(NULL);
172 if (t - last_io >= io_timeout) {
173 if (!am_server && !am_daemon) {
174 rprintf(FERROR, "io timeout after %d seconds -- exiting\n",
177 exit_cleanup(RERR_TIMEOUT);
181 /* Note the fds used for the main socket (which might really be a pipe
182 * for a local transfer, but we can ignore that). */
183 void io_set_sock_fds(int f_in, int f_out)
189 /* Setup the fd used to receive MSG_* messages. Only needed during the
190 * early stages of being a local sender (up through the sending of the
191 * file list) or when we're the generator (to fetch the messages from
193 void set_msg_fd_in(int fd)
198 /* Setup the fd used to send our MSG_* messages. Only needed when
199 * we're the receiver (to send our messages to the generator). */
200 void set_msg_fd_out(int fd)
203 set_nonblocking(msg_fd_out);
206 /* Add a message to the pending MSG_* list. */
207 static void msg_list_add(int code, char *buf, int len)
211 if (!(ml = new(struct msg_list)))
212 out_of_memory("msg_list_add");
214 if (!(ml->buf = new_array(char, len+4)))
215 out_of_memory("msg_list_add");
216 SIVAL(ml->buf, 0, ((code+MPLEX_BASE)<<24) | len);
217 memcpy(ml->buf+4, buf, len);
220 msg_list_tail->next = ml;
226 void send_msg(enum msgcode code, char *buf, int len)
228 if (msg_fd_out < 0) {
229 io_multiplex_write(code, buf, len);
232 msg_list_add(code, buf, len);
233 msg_list_push(NORMAL_FLUSH);
236 /* Read a message from the MSG_* fd and handle it. This is called either
237 * during the early stages of being a local sender (up through the sending
238 * of the file list) or when we're the generator (to fetch the messages
239 * from the receiver). */
240 static void read_msg_fd(void)
247 /* Temporarily disable msg_fd_in. This is needed to avoid looping back
248 * to this routine from writefd_unbuffered(). */
251 read_loop(fd, buf, 4);
254 len = tag & 0xFFFFFF;
255 tag = (tag >> 24) - MPLEX_BASE;
259 if (len != 0 || !am_generator) {
260 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
261 exit_cleanup(RERR_STREAMIO);
263 flist_ndx_push(&redo_list, -1);
266 if (len != 4 || !am_generator) {
267 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
268 exit_cleanup(RERR_STREAMIO);
270 read_loop(fd, buf, 4);
271 flist_ndx_push(&redo_list, IVAL(buf,0));
274 if (len >= (int)sizeof buf || !am_generator) {
275 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
276 exit_cleanup(RERR_STREAMIO);
278 read_loop(fd, buf, len);
279 io_multiplex_write(MSG_DELETED, buf, len);
282 if (len != 4 || !am_generator) {
283 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
284 exit_cleanup(RERR_STREAMIO);
286 read_loop(fd, buf, len);
287 io_multiplex_write(MSG_SUCCESS, buf, len);
296 read_loop(fd, buf, n);
297 rwrite((enum logcode)tag, buf, n);
302 rprintf(FERROR, "unknown message %d:%d\n", tag, len);
303 exit_cleanup(RERR_STREAMIO);
309 /* Try to push messages off the list onto the wire. If we leave with more
310 * to do, return 0. On error, return -1. If everything flushed, return 1.
311 * This is only active in the receiver. */
312 int msg_list_push(int flush_it_all)
314 static int written = 0;
321 while (msg_list_head) {
322 struct msg_list *ml = msg_list_head;
323 int n = write(msg_fd_out, ml->buf + written, ml->len - written);
327 if (errno != EWOULDBLOCK && errno != EAGAIN)
332 FD_SET(msg_fd_out, &fds);
333 tv.tv_sec = select_timeout;
335 if (!select(msg_fd_out+1, NULL, &fds, NULL, &tv))
337 } else if ((written += n) == ml->len) {
339 msg_list_head = ml->next;
341 msg_list_tail = NULL;
349 int get_redo_num(void)
351 while (!redo_list.head) {
355 return flist_ndx_pop(&redo_list);
359 * When we're the receiver and we have a local --files-from list of names
360 * that needs to be sent over the socket to the sender, we have to do two
361 * things at the same time: send the sender a list of what files we're
362 * processing and read the incoming file+info list from the sender. We do
363 * this by augmenting the read_timeout() function to copy this data. It
364 * uses the io_filesfrom_buf to read a block of data from f_in (when it is
365 * ready, since it might be a pipe) and then blast it out f_out (when it
366 * is ready to receive more data).
368 void io_set_filesfrom_fds(int f_in, int f_out)
370 io_filesfrom_f_in = f_in;
371 io_filesfrom_f_out = f_out;
372 io_filesfrom_bp = io_filesfrom_buf;
373 io_filesfrom_lastchar = '\0';
374 io_filesfrom_buflen = 0;
377 /* It's almost always an error to get an EOF when we're trying to read from the
378 * network, because the protocol is (for the most part) self-terminating.
380 * There is one case for the receiver when it is at the end of the transfer
381 * (hanging around reading any keep-alive packets that might come its way): if
382 * the sender dies before the generator's kill-signal comes through, we can end
383 * up here needing to loop until the kill-signal arrives. In this situation,
384 * kluge_around_eof will be < 0.
386 * There is another case for older protocol versions (< 24) where the module
387 * listing was not terminated, so we must ignore an EOF error in that case and
388 * exit. In this situation, kluge_around_eof will be > 0. */
389 static void whine_about_eof(int fd)
391 if (kluge_around_eof && fd == sock_f_in) {
393 if (kluge_around_eof > 0)
395 /* If we're still here after 10 seconds, exit with an error. */
396 for (i = 10*1000/20; i--; )
400 rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
401 "(%.0f bytes received so far) [%s]\n",
402 (double)stats.total_read, who_am_i());
404 exit_cleanup(RERR_STREAMIO);
409 * Read from a socket with I/O timeout. return the number of bytes
410 * read. If no bytes can be read then exit, never return a number <= 0.
412 * TODO: If the remote shell connection fails, then current versions
413 * actually report an "unexpected EOF" error here. Since it's a
414 * fairly common mistake to try to use rsh when ssh is required, we
415 * should trap that: if we fail to read any data at all, we should
416 * give a better explanation. We can tell whether the connection has
417 * started by looking e.g. at whether the remote version is known yet.
419 static int read_timeout(int fd, char *buf, size_t len)
423 io_flush(NORMAL_FLUSH);
426 /* until we manage to read *something* */
436 FD_SET(msg_fd_out, &w_fds);
437 if (msg_fd_out > maxfd)
440 if (io_filesfrom_f_out >= 0) {
442 if (io_filesfrom_buflen == 0) {
443 if (io_filesfrom_f_in >= 0) {
444 FD_SET(io_filesfrom_f_in, &r_fds);
445 new_fd = io_filesfrom_f_in;
447 io_filesfrom_f_out = -1;
451 FD_SET(io_filesfrom_f_out, &w_fds);
452 new_fd = io_filesfrom_f_out;
458 tv.tv_sec = select_timeout;
463 count = select(maxfd + 1, &r_fds, &w_fds, NULL, &tv);
467 exit_cleanup(RERR_SOCKETIO);
472 if (msg_list_head && FD_ISSET(msg_fd_out, &w_fds))
473 msg_list_push(NORMAL_FLUSH);
475 if (io_filesfrom_f_out >= 0) {
476 if (io_filesfrom_buflen) {
477 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
478 int l = write(io_filesfrom_f_out,
480 io_filesfrom_buflen);
482 if (!(io_filesfrom_buflen -= l))
483 io_filesfrom_bp = io_filesfrom_buf;
485 io_filesfrom_bp += l;
487 /* XXX should we complain? */
488 io_filesfrom_f_out = -1;
491 } else if (io_filesfrom_f_in >= 0) {
492 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
493 int l = read(io_filesfrom_f_in,
495 sizeof io_filesfrom_buf);
497 /* Send end-of-file marker */
498 io_filesfrom_buf[0] = '\0';
499 io_filesfrom_buf[1] = '\0';
500 io_filesfrom_buflen = io_filesfrom_lastchar? 2 : 1;
501 io_filesfrom_f_in = -1;
504 char *s = io_filesfrom_buf + l;
505 /* Transform CR and/or LF into '\0' */
506 while (s-- > io_filesfrom_buf) {
507 if (*s == '\n' || *s == '\r')
511 if (!io_filesfrom_lastchar) {
512 /* Last buf ended with a '\0', so don't
513 * let this buf start with one. */
514 while (l && !*io_filesfrom_bp)
515 io_filesfrom_bp++, l--;
518 io_filesfrom_bp = io_filesfrom_buf;
520 char *f = io_filesfrom_bp;
523 /* Eliminate any multi-'\0' runs. */
525 if (!(*t++ = *f++)) {
526 while (f != eob && !*f)
530 io_filesfrom_lastchar = f[-1];
532 io_filesfrom_buflen = l;
538 if (!FD_ISSET(fd, &r_fds))
541 n = read(fd, buf, len);
545 whine_about_eof(fd); /* Doesn't return. */
546 if (errno == EINTR || errno == EWOULDBLOCK
550 /* Don't write errors on a dead socket. */
552 close_multiplexing_out();
553 rsyserr(FERROR, errno, "read error");
554 exit_cleanup(RERR_STREAMIO);
561 if (io_timeout && fd == sock_f_in)
562 last_io = time(NULL);
569 * Read a line into the "fname" buffer (which must be at least MAXPATHLEN
572 int read_filesfrom_line(int fd, char *fname)
574 char ch, *s, *eob = fname + MAXPATHLEN - 1;
576 int reading_remotely = filesfrom_host != NULL;
577 int nulls = eol_nulls || reading_remotely;
582 cnt = read(fd, &ch, 1);
583 if (cnt < 0 && (errno == EWOULDBLOCK
584 || errno == EINTR || errno == EAGAIN)) {
589 tv.tv_sec = select_timeout;
591 if (!select(fd+1, &fds, NULL, NULL, &tv))
597 if (nulls? !ch : (ch == '\r' || ch == '\n')) {
598 /* Skip empty lines if reading locally. */
599 if (!reading_remotely && s == fname)
609 if (*fname == '#' || *fname == ';')
616 static char *iobuf_out;
617 static int iobuf_out_cnt;
619 void io_start_buffering_out(void)
623 if (!(iobuf_out = new_array(char, IO_BUFFER_SIZE)))
624 out_of_memory("io_start_buffering_out");
629 static char *iobuf_in;
630 static size_t iobuf_in_siz;
632 void io_start_buffering_in(void)
636 iobuf_in_siz = 2 * IO_BUFFER_SIZE;
637 if (!(iobuf_in = new_array(char, iobuf_in_siz)))
638 out_of_memory("io_start_buffering_in");
642 void io_end_buffering(void)
644 io_flush(NORMAL_FLUSH);
645 if (!io_multiplexing_out) {
652 void maybe_send_keepalive(int allowed_lull, int ndx)
654 if (time(NULL) - last_io >= allowed_lull) {
655 if (!iobuf_out || !iobuf_out_cnt) {
656 if (protocol_version < 29)
657 return; /* there's nothing we can do */
658 write_int(sock_f_out, ndx);
659 write_shortint(sock_f_out, ITEM_IS_NEW);
662 io_flush(NORMAL_FLUSH);
668 * Continue trying to read len bytes - don't return until len has been
671 static void read_loop(int fd, char *buf, size_t len)
674 int n = read_timeout(fd, buf, len);
683 * Read from the file descriptor handling multiplexing - return number
686 * Never returns <= 0.
688 static int readfd_unbuffered(int fd, char *buf, size_t len)
690 static size_t remaining;
691 static size_t iobuf_in_ndx;
693 char line[MAXPATHLEN+1];
695 if (!iobuf_in || fd != sock_f_in)
696 return read_timeout(fd, buf, len);
698 if (!io_multiplexing_in && remaining == 0) {
699 remaining = read_timeout(fd, iobuf_in, iobuf_in_siz);
705 len = MIN(len, remaining);
706 memcpy(buf, iobuf_in + iobuf_in_ndx, len);
713 read_loop(fd, line, 4);
716 remaining = tag & 0xFFFFFF;
717 tag = (tag >> 24) - MPLEX_BASE;
721 if (remaining > iobuf_in_siz) {
722 if (!(iobuf_in = realloc_array(iobuf_in, char,
724 out_of_memory("readfd_unbuffered");
725 iobuf_in_siz = remaining;
727 read_loop(fd, iobuf_in, remaining);
731 if (remaining >= sizeof line) {
732 rprintf(FERROR, "invalid multi-message %d:%ld\n",
733 tag, (long)remaining);
734 exit_cleanup(RERR_STREAMIO);
736 read_loop(fd, line, remaining);
737 line[remaining] = '\0';
738 /* A directory name was sent with the trailing null */
739 if (remaining > 0 && !line[remaining-1])
740 log_delete(line, S_IFDIR);
742 log_delete(line, S_IFREG);
746 if (remaining != 4) {
747 rprintf(FERROR, "invalid multi-message %d:%ld\n",
748 tag, (long)remaining);
749 exit_cleanup(RERR_STREAMIO);
751 read_loop(fd, line, remaining);
752 successful_send(IVAL(line, 0));
757 if (remaining >= sizeof line) {
759 "[%s] multiplexing overflow %d:%ld\n\n",
760 who_am_i(), tag, (long)remaining);
761 exit_cleanup(RERR_STREAMIO);
763 read_loop(fd, line, remaining);
764 rwrite((enum logcode)tag, line, remaining);
768 rprintf(FERROR, "[%s] unexpected tag %d\n",
770 exit_cleanup(RERR_STREAMIO);
775 io_flush(NORMAL_FLUSH);
783 * Do a buffered read from @p fd. Don't return until all @p n bytes
784 * have been read. If all @p n can't be read then exit with an
787 static void readfd(int fd, char *buffer, size_t N)
793 ret = readfd_unbuffered(fd, buffer + total, N-total);
797 if (fd == write_batch_monitor_in) {
798 if ((size_t)write(batch_fd, buffer, total) != total)
799 exit_cleanup(RERR_FILEIO);
803 stats.total_read += total;
807 int read_shortint(int f)
810 readfd(f, (char *)b, 2);
811 return (b[1] << 8) + b[0];
815 int32 read_int(int f)
822 if (ret == (int32)0xffffffff)
827 int64 read_longint(int f)
833 if ((int32)ret != (int32)0xffffffff)
837 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
838 exit_cleanup(RERR_UNSUPPORTED);
841 ret = IVAL(b,0) | (((int64)IVAL(b,4))<<32);
847 void read_buf(int f,char *buf,size_t len)
852 void read_sbuf(int f,char *buf,size_t len)
858 uchar read_byte(int f)
861 readfd(f, (char *)&c, 1);
865 int read_vstring(int f, char *buf, int bufsize)
867 int len = read_byte(f);
870 len = (len & ~0x80) * 0x100 + read_byte(f);
872 if (len >= bufsize) {
873 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
875 exit_cleanup(RERR_PROTOCOL);
884 /* Populate a sum_struct with values from the socket. This is
885 * called by both the sender and the receiver. */
886 void read_sum_head(int f, struct sum_struct *sum)
888 sum->count = read_int(f);
889 sum->blength = read_int(f);
890 if (sum->blength < 0 || sum->blength > MAX_BLOCK_SIZE) {
891 rprintf(FERROR, "[%s] Invalid block length %ld\n",
892 who_am_i(), (long)sum->blength);
893 exit_cleanup(RERR_PROTOCOL);
895 sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
896 if (sum->s2length < 0 || sum->s2length > MD4_SUM_LENGTH) {
897 rprintf(FERROR, "[%s] Invalid checksum length %d\n",
898 who_am_i(), sum->s2length);
899 exit_cleanup(RERR_PROTOCOL);
901 sum->remainder = read_int(f);
902 if (sum->remainder < 0 || sum->remainder > sum->blength) {
903 rprintf(FERROR, "[%s] Invalid remainder length %ld\n",
904 who_am_i(), (long)sum->remainder);
905 exit_cleanup(RERR_PROTOCOL);
909 /* Send the values from a sum_struct over the socket. Set sum to
910 * NULL if there are no checksums to send. This is called by both
911 * the generator and the sender. */
912 void write_sum_head(int f, struct sum_struct *sum)
914 static struct sum_struct null_sum;
919 write_int(f, sum->count);
920 write_int(f, sum->blength);
921 if (protocol_version >= 27)
922 write_int(f, sum->s2length);
923 write_int(f, sum->remainder);
928 * Sleep after writing to limit I/O bandwidth usage.
930 * @todo Rather than sleeping after each write, it might be better to
931 * use some kind of averaging. The current algorithm seems to always
932 * use a bit less bandwidth than specified, because it doesn't make up
933 * for slow periods. But arguably this is a feature. In addition, we
934 * ought to take the time used to write the data into account.
936 * During some phases of big transfers (file FOO is uptodate) this is
937 * called with a small bytes_written every time. As the kernel has to
938 * round small waits up to guarantee that we actually wait at least the
939 * requested number of microseconds, this can become grossly inaccurate.
940 * We therefore keep track of the bytes we've written over time and only
941 * sleep when the accumulated delay is at least 1 tenth of a second.
943 static void sleep_for_bwlimit(int bytes_written)
945 static struct timeval prior_tv;
946 static long total_written = 0;
947 struct timeval tv, start_tv;
948 long elapsed_usec, sleep_usec;
950 #define ONE_SEC 1000000L /* # of microseconds in a second */
955 total_written += bytes_written;
957 gettimeofday(&start_tv, NULL);
958 if (prior_tv.tv_sec) {
959 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
960 + (start_tv.tv_usec - prior_tv.tv_usec);
961 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
962 if (total_written < 0)
966 sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
967 if (sleep_usec < ONE_SEC / 10) {
972 tv.tv_sec = sleep_usec / ONE_SEC;
973 tv.tv_usec = sleep_usec % ONE_SEC;
974 select(0, NULL, NULL, NULL, &tv);
976 gettimeofday(&prior_tv, NULL);
977 elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
978 + (prior_tv.tv_usec - start_tv.tv_usec);
979 total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
983 /* Write len bytes to the file descriptor fd, looping as necessary to get
984 * the job done and also (in certain circumstnces) reading any data on
985 * msg_fd_in to avoid deadlock.
987 * This function underlies the multiplexing system. The body of the
988 * application never calls this function directly. */
989 static void writefd_unbuffered(int fd,char *buf,size_t len)
993 int maxfd, count, ret;
998 while (total < len) {
1003 if (msg_fd_in >= 0 && len-total >= contiguous_write_len) {
1005 FD_SET(msg_fd_in,&r_fds);
1006 if (msg_fd_in > maxfd)
1009 if (fd != sock_f_out && iobuf_out_cnt && no_flush == 1) {
1010 FD_SET(sock_f_out, &w_fds);
1011 if (sock_f_out > maxfd)
1015 tv.tv_sec = select_timeout;
1019 count = select(maxfd + 1, msg_fd_in >= 0 ? &r_fds : NULL,
1023 if (count < 0 && errno == EBADF)
1024 exit_cleanup(RERR_SOCKETIO);
1029 if (msg_fd_in >= 0 && FD_ISSET(msg_fd_in, &r_fds))
1032 if (!FD_ISSET(fd, &w_fds)) {
1033 if (fd != sock_f_out && iobuf_out_cnt) {
1035 io_flush(NORMAL_FLUSH);
1042 if (bwlimit && n > bwlimit_writemax)
1043 n = bwlimit_writemax;
1044 ret = write(fd, buf + total, n);
1050 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1056 /* Don't try to write errors back across the stream. */
1057 if (fd == sock_f_out)
1058 close_multiplexing_out();
1059 rsyserr(FERROR, errno,
1060 "writefd_unbuffered failed to write %ld bytes: phase \"%s\" [%s]",
1061 (long)len, io_write_phase, who_am_i());
1062 /* If the other side is sending us error messages, try
1063 * to grab any messages they sent before they died. */
1064 while (fd == sock_f_out && io_multiplexing_in) {
1065 io_timeout = select_timeout = 30;
1067 readfd_unbuffered(sock_f_in, io_filesfrom_buf,
1068 sizeof io_filesfrom_buf);
1070 exit_cleanup(RERR_STREAMIO);
1075 if (fd == sock_f_out) {
1077 last_io = time(NULL);
1078 sleep_for_bwlimit(ret);
1087 * Write an message to a multiplexed stream. If this fails then rsync
1090 static void mplex_write(enum msgcode code, char *buf, size_t len)
1095 SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
1097 /* When the generator reads messages from the msg_fd_in pipe, it can
1098 * cause output to occur down the socket. Setting contiguous_write_len
1099 * prevents the reading of msg_fd_in once we actually start to write
1100 * this sequence of data (though we might read it before the start). */
1101 if (am_generator && msg_fd_in >= 0)
1102 contiguous_write_len = len + 4;
1104 if (n > sizeof buffer - 4)
1105 n = sizeof buffer - 4;
1107 memcpy(&buffer[4], buf, n);
1108 writefd_unbuffered(sock_f_out, buffer, n+4);
1114 writefd_unbuffered(sock_f_out, buf, len);
1116 if (am_generator && msg_fd_in >= 0)
1117 contiguous_write_len = 0;
1121 void io_flush(int flush_it_all)
1123 msg_list_push(flush_it_all);
1125 if (!iobuf_out_cnt || no_flush)
1128 if (io_multiplexing_out)
1129 mplex_write(MSG_DATA, iobuf_out, iobuf_out_cnt);
1131 writefd_unbuffered(sock_f_out, iobuf_out, iobuf_out_cnt);
1136 static void writefd(int fd,char *buf,size_t len)
1138 if (fd == msg_fd_out) {
1139 rprintf(FERROR, "Internal error: wrong write used in receiver.\n");
1140 exit_cleanup(RERR_PROTOCOL);
1143 if (fd == sock_f_out)
1144 stats.total_written += len;
1146 if (fd == write_batch_monitor_out) {
1147 if ((size_t)write(batch_fd, buf, len) != len)
1148 exit_cleanup(RERR_FILEIO);
1151 if (!iobuf_out || fd != sock_f_out) {
1152 writefd_unbuffered(fd, buf, len);
1157 int n = MIN((int)len, IO_BUFFER_SIZE - iobuf_out_cnt);
1159 memcpy(iobuf_out+iobuf_out_cnt, buf, n);
1165 if (iobuf_out_cnt == IO_BUFFER_SIZE)
1166 io_flush(NORMAL_FLUSH);
1171 void write_shortint(int f, int x)
1176 writefd(f, (char *)b, 2);
1180 void write_int(int f,int32 x)
1188 void write_int_named(int f, int32 x, const char *phase)
1190 io_write_phase = phase;
1192 io_write_phase = phase_unknown;
1197 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1198 * 64-bit types on this platform.
1200 void write_longint(int f, int64 x)
1204 if (x <= 0x7FFFFFFF) {
1205 write_int(f, (int)x);
1209 #if SIZEOF_INT64 < 8
1210 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1211 exit_cleanup(RERR_UNSUPPORTED);
1213 write_int(f, (int32)0xFFFFFFFF);
1214 SIVAL(b,0,(x&0xFFFFFFFF));
1215 SIVAL(b,4,((x>>32)&0xFFFFFFFF));
1221 void write_buf(int f,char *buf,size_t len)
1226 /** Write a string to the connection */
1227 void write_sbuf(int f, char *buf)
1229 writefd(f, buf, strlen(buf));
1232 void write_byte(int f, uchar c)
1234 writefd(f, (char *)&c, 1);
1237 void write_vstring(int f, char *str, int len)
1239 uchar lenbuf[3], *lb = lenbuf;
1244 "attempting to send over-long vstring (%d > %d)\n",
1246 exit_cleanup(RERR_PROTOCOL);
1248 *lb++ = len / 0x100 + 0x80;
1252 writefd(f, (char*)lenbuf, lb - lenbuf + 1);
1254 writefd(f, str, len);
1259 * Read a line of up to @p maxlen characters into @p buf (not counting
1260 * the trailing null). Strips the (required) trailing newline and all
1263 * @return 1 for success; 0 for I/O error or truncation.
1265 int read_line(int f, char *buf, size_t maxlen)
1269 read_buf(f, buf, 1);
1274 if (buf[0] != '\r') {
1284 void io_printf(int fd, const char *format, ...)
1290 va_start(ap, format);
1291 len = vsnprintf(buf, sizeof buf, format, ap);
1295 exit_cleanup(RERR_STREAMIO);
1297 write_sbuf(fd, buf);
1301 /** Setup for multiplexing a MSG_* stream with the data stream. */
1302 void io_start_multiplex_out(void)
1304 io_flush(NORMAL_FLUSH);
1305 io_start_buffering_out();
1306 io_multiplexing_out = 1;
1309 /** Setup for multiplexing a MSG_* stream with the data stream. */
1310 void io_start_multiplex_in(void)
1312 io_flush(NORMAL_FLUSH);
1313 io_start_buffering_in();
1314 io_multiplexing_in = 1;
1317 /** Write an message to the multiplexed data stream. */
1318 int io_multiplex_write(enum msgcode code, char *buf, size_t len)
1320 if (!io_multiplexing_out)
1323 io_flush(NORMAL_FLUSH);
1324 stats.total_written += (len+4);
1325 mplex_write(code, buf, len);
1329 void close_multiplexing_in(void)
1331 io_multiplexing_in = 0;
1334 /** Stop output multiplexing. */
1335 void close_multiplexing_out(void)
1337 io_multiplexing_out = 0;
1340 void start_write_batch(int fd)
1342 write_stream_flags(batch_fd);
1344 /* Some communication has already taken place, but we don't
1345 * enable batch writing until here so that we can write a
1346 * canonical record of the communication even though the
1347 * actual communication so far depends on whether a daemon
1349 write_int(batch_fd, protocol_version);
1350 write_int(batch_fd, checksum_seed);
1353 write_batch_monitor_out = fd;
1355 write_batch_monitor_in = fd;
1358 void stop_write_batch(void)
1360 write_batch_monitor_out = -1;
1361 write_batch_monitor_in = -1;