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