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