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