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
;
46 extern int allowed_lull
;
50 extern int am_generator
;
52 extern int csum_length
;
53 extern int checksum_seed
;
54 extern int protocol_version
;
55 extern int remove_sent_files
;
56 extern int preserve_hard_links
;
57 extern char *filesfrom_host
;
58 extern struct stats stats
;
59 extern struct file_list
*the_file_list
;
61 const char phase_unknown
[] = "unknown";
62 int select_timeout
= SELECT_TIMEOUT
;
63 int ignore_timeout
= 0;
65 int batch_gen_fd
= -1;
68 * The connection might be dropped at some point; perhaps because the
69 * remote instance crashed. Just giving the offset on the stream is
70 * not very helpful. So instead we try to make io_phase_name point to
73 * For buffered/multiplexed I/O these names will be somewhat
74 * approximate; perhaps for ease of support we would rather make the
75 * buffer always flush when a single application-level I/O finishes.
77 * @todo Perhaps we want some simple stack functionality, but there's
78 * no need to overdo it.
80 const char *io_write_phase
= phase_unknown
;
81 const char *io_read_phase
= phase_unknown
;
83 /* Ignore an EOF error if non-zero. See whine_about_eof(). */
84 int kluge_around_eof
= 0;
91 static int io_multiplexing_out
;
92 static int io_multiplexing_in
;
93 static time_t last_io
;
96 static int write_batch_monitor_in
= -1;
97 static int write_batch_monitor_out
= -1;
99 static int io_filesfrom_f_in
= -1;
100 static int io_filesfrom_f_out
= -1;
101 static char io_filesfrom_buf
[2048];
102 static char *io_filesfrom_bp
;
103 static char io_filesfrom_lastchar
;
104 static int io_filesfrom_buflen
;
105 static size_t contiguous_write_len
= 0;
107 static void read_loop(int fd
, char *buf
, size_t len
);
109 struct flist_ndx_item
{
110 struct flist_ndx_item
*next
;
114 struct flist_ndx_list
{
115 struct flist_ndx_item
*head
, *tail
;
118 static struct flist_ndx_list redo_list
, hlink_list
;
121 struct msg_list
*next
;
126 static struct msg_list
*msg_list_head
;
127 static struct msg_list
*msg_list_tail
;
129 static void flist_ndx_push(struct flist_ndx_list
*lp
, int ndx
)
131 struct flist_ndx_item
*item
;
133 if (!(item
= new(struct flist_ndx_item
)))
134 out_of_memory("flist_ndx_push");
138 lp
->tail
->next
= item
;
144 static int flist_ndx_pop(struct flist_ndx_list
*lp
)
146 struct flist_ndx_item
*next
;
153 next
= lp
->head
->next
;
162 static void check_timeout(void)
166 if (!io_timeout
|| ignore_timeout
)
170 last_io
= time(NULL
);
176 if (t
- last_io
>= io_timeout
) {
177 if (!am_server
&& !am_daemon
) {
178 rprintf(FERROR
, "io timeout after %d seconds -- exiting\n",
181 exit_cleanup(RERR_TIMEOUT
);
185 /* Note the fds used for the main socket (which might really be a pipe
186 * for a local transfer, but we can ignore that). */
187 void io_set_sock_fds(int f_in
, int f_out
)
193 /* Setup the fd used to receive MSG_* messages. Only needed during the
194 * early stages of being a local sender (up through the sending of the
195 * file list) or when we're the generator (to fetch the messages from
197 void set_msg_fd_in(int fd
)
202 /* Setup the fd used to send our MSG_* messages. Only needed when
203 * we're the receiver (to send our messages to the generator). */
204 void set_msg_fd_out(int fd
)
207 set_nonblocking(msg_fd_out
);
210 /* Add a message to the pending MSG_* list. */
211 static void msg_list_add(int code
, char *buf
, int len
)
215 if (!(ml
= new(struct msg_list
)))
216 out_of_memory("msg_list_add");
218 if (!(ml
->buf
= new_array(char, len
+4)))
219 out_of_memory("msg_list_add");
220 SIVAL(ml
->buf
, 0, ((code
+MPLEX_BASE
)<<24) | len
);
221 memcpy(ml
->buf
+4, buf
, len
);
224 msg_list_tail
->next
= ml
;
230 void send_msg(enum msgcode code
, char *buf
, int len
)
232 if (msg_fd_out
< 0) {
233 io_multiplex_write(code
, buf
, len
);
236 msg_list_add(code
, buf
, len
);
237 msg_list_push(NORMAL_FLUSH
);
240 /* Read a message from the MSG_* fd and handle it. This is called either
241 * during the early stages of being a local sender (up through the sending
242 * of the file list) or when we're the generator (to fetch the messages
243 * from the receiver). */
244 static void read_msg_fd(void)
251 /* Temporarily disable msg_fd_in. This is needed to avoid looping back
252 * to this routine from writefd_unbuffered(). */
255 read_loop(fd
, buf
, 4);
258 len
= tag
& 0xFFFFFF;
259 tag
= (tag
>> 24) - MPLEX_BASE
;
263 if (len
!= 0 || !am_generator
) {
264 rprintf(FERROR
, "invalid message %d:%d\n", tag
, len
);
265 exit_cleanup(RERR_STREAMIO
);
267 flist_ndx_push(&redo_list
, -1);
270 if (len
!= 4 || !am_generator
) {
271 rprintf(FERROR
, "invalid message %d:%d\n", tag
, len
);
272 exit_cleanup(RERR_STREAMIO
);
274 read_loop(fd
, buf
, 4);
275 flist_ndx_push(&redo_list
, IVAL(buf
,0));
278 if (len
>= (int)sizeof buf
|| !am_generator
) {
279 rprintf(FERROR
, "invalid message %d:%d\n", tag
, len
);
280 exit_cleanup(RERR_STREAMIO
);
282 read_loop(fd
, buf
, len
);
283 io_multiplex_write(MSG_DELETED
, buf
, len
);
286 if (len
!= 4 || !am_generator
) {
287 rprintf(FERROR
, "invalid message %d:%d\n", tag
, len
);
288 exit_cleanup(RERR_STREAMIO
);
290 read_loop(fd
, buf
, len
);
291 if (remove_sent_files
)
292 io_multiplex_write(MSG_SUCCESS
, buf
, len
);
293 if (preserve_hard_links
)
294 flist_ndx_push(&hlink_list
, IVAL(buf
,0));
303 read_loop(fd
, buf
, n
);
304 rwrite((enum logcode
)tag
, buf
, n
);
309 rprintf(FERROR
, "unknown message %d:%d\n", tag
, len
);
310 exit_cleanup(RERR_STREAMIO
);
316 /* Try to push messages off the list onto the wire. If we leave with more
317 * to do, return 0. On error, return -1. If everything flushed, return 1.
318 * This is only active in the receiver. */
319 int msg_list_push(int flush_it_all
)
321 static int written
= 0;
328 while (msg_list_head
) {
329 struct msg_list
*ml
= msg_list_head
;
330 int n
= write(msg_fd_out
, ml
->buf
+ written
, ml
->len
- written
);
334 if (errno
!= EWOULDBLOCK
&& errno
!= EAGAIN
)
339 FD_SET(msg_fd_out
, &fds
);
340 tv
.tv_sec
= select_timeout
;
342 if (!select(msg_fd_out
+1, NULL
, &fds
, NULL
, &tv
))
344 } else if ((written
+= n
) == ml
->len
) {
346 msg_list_head
= ml
->next
;
348 msg_list_tail
= NULL
;
356 int get_redo_num(int itemizing
, enum logcode code
)
360 check_for_finished_hlinks(itemizing
, code
);
366 return flist_ndx_pop(&redo_list
);
369 int get_hlink_num(void)
371 return flist_ndx_pop(&hlink_list
);
375 * When we're the receiver and we have a local --files-from list of names
376 * that needs to be sent over the socket to the sender, we have to do two
377 * things at the same time: send the sender a list of what files we're
378 * processing and read the incoming file+info list from the sender. We do
379 * this by augmenting the read_timeout() function to copy this data. It
380 * uses the io_filesfrom_buf to read a block of data from f_in (when it is
381 * ready, since it might be a pipe) and then blast it out f_out (when it
382 * is ready to receive more data).
384 void io_set_filesfrom_fds(int f_in
, int f_out
)
386 io_filesfrom_f_in
= f_in
;
387 io_filesfrom_f_out
= f_out
;
388 io_filesfrom_bp
= io_filesfrom_buf
;
389 io_filesfrom_lastchar
= '\0';
390 io_filesfrom_buflen
= 0;
393 /* It's almost always an error to get an EOF when we're trying to read from the
394 * network, because the protocol is (for the most part) self-terminating.
396 * There is one case for the receiver when it is at the end of the transfer
397 * (hanging around reading any keep-alive packets that might come its way): if
398 * the sender dies before the generator's kill-signal comes through, we can end
399 * up here needing to loop until the kill-signal arrives. In this situation,
400 * kluge_around_eof will be < 0.
402 * There is another case for older protocol versions (< 24) where the module
403 * listing was not terminated, so we must ignore an EOF error in that case and
404 * exit. In this situation, kluge_around_eof will be > 0. */
405 static void whine_about_eof(int fd
)
407 if (kluge_around_eof
&& fd
== sock_f_in
) {
409 if (kluge_around_eof
> 0)
411 /* If we're still here after 10 seconds, exit with an error. */
412 for (i
= 10*1000/20; i
--; )
416 rprintf(FERROR
, RSYNC_NAME
": connection unexpectedly closed "
417 "(%.0f bytes received so far) [%s]\n",
418 (double)stats
.total_read
, who_am_i());
420 exit_cleanup(RERR_STREAMIO
);
425 * Read from a socket with I/O timeout. return the number of bytes
426 * read. If no bytes can be read then exit, never return a number <= 0.
428 * TODO: If the remote shell connection fails, then current versions
429 * actually report an "unexpected EOF" error here. Since it's a
430 * fairly common mistake to try to use rsh when ssh is required, we
431 * should trap that: if we fail to read any data at all, we should
432 * give a better explanation. We can tell whether the connection has
433 * started by looking e.g. at whether the remote version is known yet.
435 static int read_timeout(int fd
, char *buf
, size_t len
)
439 io_flush(NORMAL_FLUSH
);
442 /* until we manage to read *something* */
452 FD_SET(msg_fd_out
, &w_fds
);
453 if (msg_fd_out
> maxfd
)
456 if (io_filesfrom_f_out
>= 0) {
458 if (io_filesfrom_buflen
== 0) {
459 if (io_filesfrom_f_in
>= 0) {
460 FD_SET(io_filesfrom_f_in
, &r_fds
);
461 new_fd
= io_filesfrom_f_in
;
463 io_filesfrom_f_out
= -1;
467 FD_SET(io_filesfrom_f_out
, &w_fds
);
468 new_fd
= io_filesfrom_f_out
;
474 tv
.tv_sec
= select_timeout
;
479 count
= select(maxfd
+ 1, &r_fds
, &w_fds
, NULL
, &tv
);
483 exit_cleanup(RERR_SOCKETIO
);
488 if (msg_list_head
&& FD_ISSET(msg_fd_out
, &w_fds
))
489 msg_list_push(NORMAL_FLUSH
);
491 if (io_filesfrom_f_out
>= 0) {
492 if (io_filesfrom_buflen
) {
493 if (FD_ISSET(io_filesfrom_f_out
, &w_fds
)) {
494 int l
= write(io_filesfrom_f_out
,
496 io_filesfrom_buflen
);
498 if (!(io_filesfrom_buflen
-= l
))
499 io_filesfrom_bp
= io_filesfrom_buf
;
501 io_filesfrom_bp
+= l
;
503 /* XXX should we complain? */
504 io_filesfrom_f_out
= -1;
507 } else if (io_filesfrom_f_in
>= 0) {
508 if (FD_ISSET(io_filesfrom_f_in
, &r_fds
)) {
509 int l
= read(io_filesfrom_f_in
,
511 sizeof io_filesfrom_buf
);
513 /* Send end-of-file marker */
514 io_filesfrom_buf
[0] = '\0';
515 io_filesfrom_buf
[1] = '\0';
516 io_filesfrom_buflen
= io_filesfrom_lastchar
? 2 : 1;
517 io_filesfrom_f_in
= -1;
520 char *s
= io_filesfrom_buf
+ l
;
521 /* Transform CR and/or LF into '\0' */
522 while (s
-- > io_filesfrom_buf
) {
523 if (*s
== '\n' || *s
== '\r')
527 if (!io_filesfrom_lastchar
) {
528 /* Last buf ended with a '\0', so don't
529 * let this buf start with one. */
530 while (l
&& !*io_filesfrom_bp
)
531 io_filesfrom_bp
++, l
--;
534 io_filesfrom_bp
= io_filesfrom_buf
;
536 char *f
= io_filesfrom_bp
;
539 /* Eliminate any multi-'\0' runs. */
541 if (!(*t
++ = *f
++)) {
542 while (f
!= eob
&& !*f
)
546 io_filesfrom_lastchar
= f
[-1];
548 io_filesfrom_buflen
= l
;
554 if (!FD_ISSET(fd
, &r_fds
))
557 n
= read(fd
, buf
, len
);
561 whine_about_eof(fd
); /* Doesn't return. */
562 if (errno
== EINTR
|| errno
== EWOULDBLOCK
566 /* Don't write errors on a dead socket. */
568 close_multiplexing_out();
569 rsyserr(FERROR
, errno
, "read error");
570 exit_cleanup(RERR_STREAMIO
);
577 if (io_timeout
&& fd
== sock_f_in
)
578 last_io
= time(NULL
);
585 * Read a line into the "fname" buffer (which must be at least MAXPATHLEN
588 int read_filesfrom_line(int fd
, char *fname
)
590 char ch
, *s
, *eob
= fname
+ MAXPATHLEN
- 1;
592 int reading_remotely
= filesfrom_host
!= NULL
;
593 int nulls
= eol_nulls
|| reading_remotely
;
598 cnt
= read(fd
, &ch
, 1);
599 if (cnt
< 0 && (errno
== EWOULDBLOCK
600 || errno
== EINTR
|| errno
== EAGAIN
)) {
605 tv
.tv_sec
= select_timeout
;
607 if (!select(fd
+1, &fds
, NULL
, NULL
, &tv
))
613 if (nulls
? !ch
: (ch
== '\r' || ch
== '\n')) {
614 /* Skip empty lines if reading locally. */
615 if (!reading_remotely
&& s
== fname
)
625 if (*fname
== '#' || *fname
== ';')
632 static char *iobuf_out
;
633 static int iobuf_out_cnt
;
635 void io_start_buffering_out(void)
639 if (!(iobuf_out
= new_array(char, IO_BUFFER_SIZE
)))
640 out_of_memory("io_start_buffering_out");
645 static char *iobuf_in
;
646 static size_t iobuf_in_siz
;
648 void io_start_buffering_in(void)
652 iobuf_in_siz
= 2 * IO_BUFFER_SIZE
;
653 if (!(iobuf_in
= new_array(char, iobuf_in_siz
)))
654 out_of_memory("io_start_buffering_in");
658 void io_end_buffering(void)
660 io_flush(NORMAL_FLUSH
);
661 if (!io_multiplexing_out
) {
668 void maybe_send_keepalive(void)
670 if (time(NULL
) - last_io
>= allowed_lull
) {
671 if (!iobuf_out
|| !iobuf_out_cnt
) {
672 if (protocol_version
< 29)
673 return; /* there's nothing we can do */
674 write_int(sock_f_out
, the_file_list
->count
);
675 write_shortint(sock_f_out
, ITEM_IS_NEW
);
678 io_flush(NORMAL_FLUSH
);
684 * Continue trying to read len bytes - don't return until len has been
687 static void read_loop(int fd
, char *buf
, size_t len
)
690 int n
= read_timeout(fd
, buf
, len
);
699 * Read from the file descriptor handling multiplexing - return number
702 * Never returns <= 0.
704 static int readfd_unbuffered(int fd
, char *buf
, size_t len
)
706 static size_t remaining
;
707 static size_t iobuf_in_ndx
;
709 char line
[MAXPATHLEN
+1];
711 if (!iobuf_in
|| fd
!= sock_f_in
)
712 return read_timeout(fd
, buf
, len
);
714 if (!io_multiplexing_in
&& remaining
== 0) {
715 remaining
= read_timeout(fd
, iobuf_in
, iobuf_in_siz
);
721 len
= MIN(len
, remaining
);
722 memcpy(buf
, iobuf_in
+ iobuf_in_ndx
, len
);
729 read_loop(fd
, line
, 4);
732 remaining
= tag
& 0xFFFFFF;
733 tag
= (tag
>> 24) - MPLEX_BASE
;
737 if (remaining
> iobuf_in_siz
) {
738 if (!(iobuf_in
= realloc_array(iobuf_in
, char,
740 out_of_memory("readfd_unbuffered");
741 iobuf_in_siz
= remaining
;
743 read_loop(fd
, iobuf_in
, remaining
);
747 if (remaining
>= sizeof line
) {
748 rprintf(FERROR
, "invalid multi-message %d:%ld\n",
749 tag
, (long)remaining
);
750 exit_cleanup(RERR_STREAMIO
);
752 read_loop(fd
, line
, remaining
);
753 line
[remaining
] = '\0';
754 /* A directory name was sent with the trailing null */
755 if (remaining
> 0 && !line
[remaining
-1])
756 log_delete(line
, S_IFDIR
);
758 log_delete(line
, S_IFREG
);
762 if (remaining
!= 4) {
763 rprintf(FERROR
, "invalid multi-message %d:%ld [%s]\n",
764 tag
, (long)remaining
, who_am_i());
765 exit_cleanup(RERR_STREAMIO
);
767 read_loop(fd
, line
, remaining
);
768 successful_send(IVAL(line
, 0));
773 if (remaining
>= sizeof line
) {
775 "multiplexing overflow %d:%ld [%s]\n",
776 tag
, (long)remaining
, who_am_i());
777 exit_cleanup(RERR_STREAMIO
);
779 read_loop(fd
, line
, remaining
);
780 rwrite((enum logcode
)tag
, line
, remaining
);
784 rprintf(FERROR
, "unexpected tag %d [%s]\n",
786 exit_cleanup(RERR_STREAMIO
);
791 io_flush(NORMAL_FLUSH
);
799 * Do a buffered read from @p fd. Don't return until all @p n bytes
800 * have been read. If all @p n can't be read then exit with an
803 static void readfd(int fd
, char *buffer
, size_t N
)
809 ret
= readfd_unbuffered(fd
, buffer
+ total
, N
-total
);
813 if (fd
== write_batch_monitor_in
) {
814 if ((size_t)write(batch_fd
, buffer
, total
) != total
)
815 exit_cleanup(RERR_FILEIO
);
819 stats
.total_read
+= total
;
823 int read_shortint(int f
)
826 readfd(f
, (char *)b
, 2);
827 return (b
[1] << 8) + b
[0];
831 int32
read_int(int f
)
838 if (ret
== (int32
)0xffffffff)
843 int64
read_longint(int f
)
849 if ((int32
)ret
!= (int32
)0xffffffff)
853 rprintf(FERROR
, "Integer overflow: attempted 64-bit offset\n");
854 exit_cleanup(RERR_UNSUPPORTED
);
857 ret
= IVAL(b
,0) | (((int64
)IVAL(b
,4))<<32);
863 void read_buf(int f
,char *buf
,size_t len
)
868 void read_sbuf(int f
,char *buf
,size_t len
)
874 uchar
read_byte(int f
)
877 readfd(f
, (char *)&c
, 1);
881 int read_vstring(int f
, char *buf
, int bufsize
)
883 int len
= read_byte(f
);
886 len
= (len
& ~0x80) * 0x100 + read_byte(f
);
888 if (len
>= bufsize
) {
889 rprintf(FERROR
, "over-long vstring received (%d > %d)\n",
900 /* Populate a sum_struct with values from the socket. This is
901 * called by both the sender and the receiver. */
902 void read_sum_head(int f
, struct sum_struct
*sum
)
904 sum
->count
= read_int(f
);
905 sum
->blength
= read_int(f
);
906 if (sum
->blength
< 0 || sum
->blength
> MAX_BLOCK_SIZE
) {
907 rprintf(FERROR
, "Invalid block length %ld [%s]\n",
908 (long)sum
->blength
, who_am_i());
909 exit_cleanup(RERR_PROTOCOL
);
911 sum
->s2length
= protocol_version
< 27 ? csum_length
: (int)read_int(f
);
912 if (sum
->s2length
< 0 || sum
->s2length
> MD4_SUM_LENGTH
) {
913 rprintf(FERROR
, "Invalid checksum length %d [%s]\n",
914 sum
->s2length
, who_am_i());
915 exit_cleanup(RERR_PROTOCOL
);
917 sum
->remainder
= read_int(f
);
918 if (sum
->remainder
< 0 || sum
->remainder
> sum
->blength
) {
919 rprintf(FERROR
, "Invalid remainder length %ld [%s]\n",
920 (long)sum
->remainder
, who_am_i());
921 exit_cleanup(RERR_PROTOCOL
);
925 /* Send the values from a sum_struct over the socket. Set sum to
926 * NULL if there are no checksums to send. This is called by both
927 * the generator and the sender. */
928 void write_sum_head(int f
, struct sum_struct
*sum
)
930 static struct sum_struct null_sum
;
935 write_int(f
, sum
->count
);
936 write_int(f
, sum
->blength
);
937 if (protocol_version
>= 27)
938 write_int(f
, sum
->s2length
);
939 write_int(f
, sum
->remainder
);
944 * Sleep after writing to limit I/O bandwidth usage.
946 * @todo Rather than sleeping after each write, it might be better to
947 * use some kind of averaging. The current algorithm seems to always
948 * use a bit less bandwidth than specified, because it doesn't make up
949 * for slow periods. But arguably this is a feature. In addition, we
950 * ought to take the time used to write the data into account.
952 * During some phases of big transfers (file FOO is uptodate) this is
953 * called with a small bytes_written every time. As the kernel has to
954 * round small waits up to guarantee that we actually wait at least the
955 * requested number of microseconds, this can become grossly inaccurate.
956 * We therefore keep track of the bytes we've written over time and only
957 * sleep when the accumulated delay is at least 1 tenth of a second.
959 static void sleep_for_bwlimit(int bytes_written
)
961 static struct timeval prior_tv
;
962 static long total_written
= 0;
963 struct timeval tv
, start_tv
;
964 long elapsed_usec
, sleep_usec
;
966 #define ONE_SEC 1000000L /* # of microseconds in a second */
971 total_written
+= bytes_written
;
973 gettimeofday(&start_tv
, NULL
);
974 if (prior_tv
.tv_sec
) {
975 elapsed_usec
= (start_tv
.tv_sec
- prior_tv
.tv_sec
) * ONE_SEC
976 + (start_tv
.tv_usec
- prior_tv
.tv_usec
);
977 total_written
-= elapsed_usec
* bwlimit
/ (ONE_SEC
/1024);
978 if (total_written
< 0)
982 sleep_usec
= total_written
* (ONE_SEC
/1024) / bwlimit
;
983 if (sleep_usec
< ONE_SEC
/ 10) {
988 tv
.tv_sec
= sleep_usec
/ ONE_SEC
;
989 tv
.tv_usec
= sleep_usec
% ONE_SEC
;
990 select(0, NULL
, NULL
, NULL
, &tv
);
992 gettimeofday(&prior_tv
, NULL
);
993 elapsed_usec
= (prior_tv
.tv_sec
- start_tv
.tv_sec
) * ONE_SEC
994 + (prior_tv
.tv_usec
- start_tv
.tv_usec
);
995 total_written
= (sleep_usec
- elapsed_usec
) * bwlimit
/ (ONE_SEC
/1024);
999 /* Write len bytes to the file descriptor fd, looping as necessary to get
1000 * the job done and also (in certain circumstnces) reading any data on
1001 * msg_fd_in to avoid deadlock.
1003 * This function underlies the multiplexing system. The body of the
1004 * application never calls this function directly. */
1005 static void writefd_unbuffered(int fd
,char *buf
,size_t len
)
1007 size_t n
, total
= 0;
1008 fd_set w_fds
, r_fds
;
1009 int maxfd
, count
, ret
;
1014 while (total
< len
) {
1019 if (msg_fd_in
>= 0 && len
-total
>= contiguous_write_len
) {
1021 FD_SET(msg_fd_in
,&r_fds
);
1022 if (msg_fd_in
> maxfd
)
1025 if (fd
!= sock_f_out
&& iobuf_out_cnt
&& no_flush
== 1) {
1026 FD_SET(sock_f_out
, &w_fds
);
1027 if (sock_f_out
> maxfd
)
1031 tv
.tv_sec
= select_timeout
;
1035 count
= select(maxfd
+ 1, msg_fd_in
>= 0 ? &r_fds
: NULL
,
1039 if (count
< 0 && errno
== EBADF
)
1040 exit_cleanup(RERR_SOCKETIO
);
1045 if (msg_fd_in
>= 0 && FD_ISSET(msg_fd_in
, &r_fds
))
1048 if (!FD_ISSET(fd
, &w_fds
))
1052 if (bwlimit
&& n
> bwlimit_writemax
)
1053 n
= bwlimit_writemax
;
1054 ret
= write(fd
, buf
+ total
, n
);
1060 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
) {
1066 /* Don't try to write errors back across the stream. */
1067 if (fd
== sock_f_out
)
1068 close_multiplexing_out();
1069 rsyserr(FERROR
, errno
,
1070 "writefd_unbuffered failed to write %ld bytes: phase \"%s\" [%s]",
1071 (long)len
, io_write_phase
, who_am_i());
1072 /* If the other side is sending us error messages, try
1073 * to grab any messages they sent before they died. */
1074 while (fd
== sock_f_out
&& io_multiplexing_in
) {
1075 io_timeout
= select_timeout
= 30;
1077 readfd_unbuffered(sock_f_in
, io_filesfrom_buf
,
1078 sizeof io_filesfrom_buf
);
1080 exit_cleanup(RERR_STREAMIO
);
1085 if (fd
== sock_f_out
) {
1087 last_io
= time(NULL
);
1088 sleep_for_bwlimit(ret
);
1097 * Write an message to a multiplexed stream. If this fails then rsync
1100 static void mplex_write(enum msgcode code
, char *buf
, size_t len
)
1105 SIVAL(buffer
, 0, ((MPLEX_BASE
+ (int)code
)<<24) + len
);
1107 /* When the generator reads messages from the msg_fd_in pipe, it can
1108 * cause output to occur down the socket. Setting contiguous_write_len
1109 * prevents the reading of msg_fd_in once we actually start to write
1110 * this sequence of data (though we might read it before the start). */
1111 if (am_generator
&& msg_fd_in
>= 0)
1112 contiguous_write_len
= len
+ 4;
1114 if (n
> sizeof buffer
- 4)
1115 n
= sizeof buffer
- 4;
1117 memcpy(&buffer
[4], buf
, n
);
1118 writefd_unbuffered(sock_f_out
, buffer
, n
+4);
1124 writefd_unbuffered(sock_f_out
, buf
, len
);
1126 if (am_generator
&& msg_fd_in
>= 0)
1127 contiguous_write_len
= 0;
1131 void io_flush(int flush_it_all
)
1133 msg_list_push(flush_it_all
);
1135 if (!iobuf_out_cnt
|| no_flush
)
1138 if (io_multiplexing_out
)
1139 mplex_write(MSG_DATA
, iobuf_out
, iobuf_out_cnt
);
1141 writefd_unbuffered(sock_f_out
, iobuf_out
, iobuf_out_cnt
);
1146 static void writefd(int fd
,char *buf
,size_t len
)
1148 if (fd
== msg_fd_out
) {
1149 rprintf(FERROR
, "Internal error: wrong write used in receiver.\n");
1150 exit_cleanup(RERR_PROTOCOL
);
1153 if (fd
== sock_f_out
)
1154 stats
.total_written
+= len
;
1156 if (fd
== write_batch_monitor_out
) {
1157 if ((size_t)write(batch_fd
, buf
, len
) != len
)
1158 exit_cleanup(RERR_FILEIO
);
1161 if (!iobuf_out
|| fd
!= sock_f_out
) {
1162 writefd_unbuffered(fd
, buf
, len
);
1167 int n
= MIN((int)len
, IO_BUFFER_SIZE
- iobuf_out_cnt
);
1169 memcpy(iobuf_out
+iobuf_out_cnt
, buf
, n
);
1175 if (iobuf_out_cnt
== IO_BUFFER_SIZE
)
1176 io_flush(NORMAL_FLUSH
);
1181 void write_shortint(int f
, int x
)
1186 writefd(f
, (char *)b
, 2);
1190 void write_int(int f
,int32 x
)
1198 void write_int_named(int f
, int32 x
, const char *phase
)
1200 io_write_phase
= phase
;
1202 io_write_phase
= phase_unknown
;
1207 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1208 * 64-bit types on this platform.
1210 void write_longint(int f
, int64 x
)
1214 if (x
<= 0x7FFFFFFF) {
1215 write_int(f
, (int)x
);
1219 #if SIZEOF_INT64 < 8
1220 rprintf(FERROR
, "Integer overflow: attempted 64-bit offset\n");
1221 exit_cleanup(RERR_UNSUPPORTED
);
1223 write_int(f
, (int32
)0xFFFFFFFF);
1224 SIVAL(b
,0,(x
&0xFFFFFFFF));
1225 SIVAL(b
,4,((x
>>32)&0xFFFFFFFF));
1231 void write_buf(int f
,char *buf
,size_t len
)
1236 /** Write a string to the connection */
1237 void write_sbuf(int f
, char *buf
)
1239 writefd(f
, buf
, strlen(buf
));
1242 void write_byte(int f
, uchar c
)
1244 writefd(f
, (char *)&c
, 1);
1247 void write_vstring(int f
, char *str
, int len
)
1249 uchar lenbuf
[3], *lb
= lenbuf
;
1254 "attempting to send over-long vstring (%d > %d)\n",
1256 exit_cleanup(RERR_PROTOCOL
);
1258 *lb
++ = len
/ 0x100 + 0x80;
1262 writefd(f
, (char*)lenbuf
, lb
- lenbuf
+ 1);
1264 writefd(f
, str
, len
);
1269 * Read a line of up to @p maxlen characters into @p buf (not counting
1270 * the trailing null). Strips the (required) trailing newline and all
1273 * @return 1 for success; 0 for I/O error or truncation.
1275 int read_line(int f
, char *buf
, size_t maxlen
)
1279 read_buf(f
, buf
, 1);
1284 if (buf
[0] != '\r') {
1294 void io_printf(int fd
, const char *format
, ...)
1300 va_start(ap
, format
);
1301 len
= vsnprintf(buf
, sizeof buf
, format
, ap
);
1305 exit_cleanup(RERR_STREAMIO
);
1307 write_sbuf(fd
, buf
);
1311 /** Setup for multiplexing a MSG_* stream with the data stream. */
1312 void io_start_multiplex_out(void)
1314 io_flush(NORMAL_FLUSH
);
1315 io_start_buffering_out();
1316 io_multiplexing_out
= 1;
1319 /** Setup for multiplexing a MSG_* stream with the data stream. */
1320 void io_start_multiplex_in(void)
1322 io_flush(NORMAL_FLUSH
);
1323 io_start_buffering_in();
1324 io_multiplexing_in
= 1;
1327 /** Write an message to the multiplexed data stream. */
1328 int io_multiplex_write(enum msgcode code
, char *buf
, size_t len
)
1330 if (!io_multiplexing_out
)
1333 io_flush(NORMAL_FLUSH
);
1334 stats
.total_written
+= (len
+4);
1335 mplex_write(code
, buf
, len
);
1339 void close_multiplexing_in(void)
1341 io_multiplexing_in
= 0;
1344 /** Stop output multiplexing. */
1345 void close_multiplexing_out(void)
1347 io_multiplexing_out
= 0;
1350 void start_write_batch(int fd
)
1352 write_stream_flags(batch_fd
);
1354 /* Some communication has already taken place, but we don't
1355 * enable batch writing until here so that we can write a
1356 * canonical record of the communication even though the
1357 * actual communication so far depends on whether a daemon
1359 write_int(batch_fd
, protocol_version
);
1360 write_int(batch_fd
, checksum_seed
);
1363 write_batch_monitor_out
= fd
;
1365 write_batch_monitor_in
= fd
;
1368 void stop_write_batch(void)
1370 write_batch_monitor_out
= -1;
1371 write_batch_monitor_in
= -1;