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