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