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