Handle the new MSG_SUCCESS message for both the generator and the
[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 batch_fd = -1;
60 int batch_gen_fd = -1;
61
62 /**
63  * The connection might be dropped at some point; perhaps because the
64  * remote instance crashed.  Just giving the offset on the stream is
65  * not very helpful.  So instead we try to make io_phase_name point to
66  * something useful.
67  *
68  * For buffered/multiplexed I/O these names will be somewhat
69  * approximate; perhaps for ease of support we would rather make the
70  * buffer always flush when a single application-level I/O finishes.
71  *
72  * @todo Perhaps we want some simple stack functionality, but there's
73  * no need to overdo it.
74  **/
75 const char *io_write_phase = phase_unknown;
76 const char *io_read_phase = phase_unknown;
77
78 /** Ignore EOF errors while reading a module listing if the remote
79     version is 24 or less. */
80 int kludge_around_eof = False;
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)
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 /**
365  * It's almost always an error to get an EOF when we're trying to read
366  * from the network, because the protocol is self-terminating.
367  *
368  * However, there is one unfortunate cases where it is not, which is
369  * rsync <2.4.6 sending a list of modules on a server, since the list
370  * is terminated by closing the socket. So, for the section of the
371  * program where that is a problem (start_socket_client),
372  * kludge_around_eof is True and we just exit.
373  */
374 static void whine_about_eof(int fd)
375 {
376         if (kludge_around_eof && fd == sock_f_in)
377                 exit_cleanup(0);
378
379         rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
380                 "(%.0f bytes received so far) [%s]\n",
381                 (double)stats.total_read, who_am_i());
382
383         exit_cleanup(RERR_STREAMIO);
384 }
385
386
387 /**
388  * Read from a socket with I/O timeout. return the number of bytes
389  * read. If no bytes can be read then exit, never return a number <= 0.
390  *
391  * TODO: If the remote shell connection fails, then current versions
392  * actually report an "unexpected EOF" error here.  Since it's a
393  * fairly common mistake to try to use rsh when ssh is required, we
394  * should trap that: if we fail to read any data at all, we should
395  * give a better explanation.  We can tell whether the connection has
396  * started by looking e.g. at whether the remote version is known yet.
397  */
398 static int read_timeout(int fd, char *buf, size_t len)
399 {
400         int n, ret = 0;
401
402         io_flush(NORMAL_FLUSH);
403
404         while (ret == 0) {
405                 /* until we manage to read *something* */
406                 fd_set r_fds, w_fds;
407                 struct timeval tv;
408                 int maxfd = fd;
409                 int count;
410
411                 FD_ZERO(&r_fds);
412                 FD_ZERO(&w_fds);
413                 FD_SET(fd, &r_fds);
414                 if (msg_fd_in >= 0) {
415                         FD_SET(msg_fd_in, &r_fds);
416                         if (msg_fd_in > maxfd)
417                                 maxfd = msg_fd_in;
418                 } else if (msg_list_head) {
419                         FD_SET(msg_fd_out, &w_fds);
420                         if (msg_fd_out > maxfd)
421                                 maxfd = msg_fd_out;
422                 }
423                 if (io_filesfrom_f_out >= 0) {
424                         int new_fd;
425                         if (io_filesfrom_buflen == 0) {
426                                 if (io_filesfrom_f_in >= 0) {
427                                         FD_SET(io_filesfrom_f_in, &r_fds);
428                                         new_fd = io_filesfrom_f_in;
429                                 } else {
430                                         io_filesfrom_f_out = -1;
431                                         new_fd = -1;
432                                 }
433                         } else {
434                                 FD_SET(io_filesfrom_f_out, &w_fds);
435                                 new_fd = io_filesfrom_f_out;
436                         }
437                         if (new_fd > maxfd)
438                                 maxfd = new_fd;
439                 }
440
441                 tv.tv_sec = select_timeout;
442                 tv.tv_usec = 0;
443
444                 errno = 0;
445
446                 count = select(maxfd + 1, &r_fds, &w_fds, NULL, &tv);
447
448                 if (count <= 0) {
449                         if (errno == EBADF)
450                                 exit_cleanup(RERR_SOCKETIO);
451                         check_timeout();
452                         continue;
453                 }
454
455                 if (msg_fd_in >= 0 && FD_ISSET(msg_fd_in, &r_fds))
456                         read_msg_fd();
457                 else if (msg_list_head && FD_ISSET(msg_fd_out, &w_fds))
458                         msg_list_push(NORMAL_FLUSH);
459
460                 if (io_filesfrom_f_out >= 0) {
461                         if (io_filesfrom_buflen) {
462                                 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
463                                         int l = write(io_filesfrom_f_out,
464                                                       io_filesfrom_bp,
465                                                       io_filesfrom_buflen);
466                                         if (l > 0) {
467                                                 if (!(io_filesfrom_buflen -= l))
468                                                         io_filesfrom_bp = io_filesfrom_buf;
469                                                 else
470                                                         io_filesfrom_bp += l;
471                                         } else {
472                                                 /* XXX should we complain? */
473                                                 io_filesfrom_f_out = -1;
474                                         }
475                                 }
476                         } else if (io_filesfrom_f_in >= 0) {
477                                 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
478                                         int l = read(io_filesfrom_f_in,
479                                                      io_filesfrom_buf,
480                                                      sizeof io_filesfrom_buf);
481                                         if (l <= 0) {
482                                                 /* Send end-of-file marker */
483                                                 io_filesfrom_buf[0] = '\0';
484                                                 io_filesfrom_buf[1] = '\0';
485                                                 io_filesfrom_buflen = io_filesfrom_lastchar? 2 : 1;
486                                                 io_filesfrom_f_in = -1;
487                                         } else {
488                                                 if (!eol_nulls) {
489                                                         char *s = io_filesfrom_buf + l;
490                                                         /* Transform CR and/or LF into '\0' */
491                                                         while (s-- > io_filesfrom_buf) {
492                                                                 if (*s == '\n' || *s == '\r')
493                                                                         *s = '\0';
494                                                         }
495                                                 }
496                                                 if (!io_filesfrom_lastchar) {
497                                                         /* Last buf ended with a '\0', so don't
498                                                          * let this buf start with one. */
499                                                         while (l && !*io_filesfrom_bp)
500                                                                 io_filesfrom_bp++, l--;
501                                                 }
502                                                 if (!l)
503                                                         io_filesfrom_bp = io_filesfrom_buf;
504                                                 else {
505                                                         char *f = io_filesfrom_bp;
506                                                         char *t = f;
507                                                         char *eob = f + l;
508                                                         /* Eliminate any multi-'\0' runs. */
509                                                         while (f != eob) {
510                                                                 if (!(*t++ = *f++)) {
511                                                                         while (f != eob && !*f)
512                                                                                 f++, l--;
513                                                                 }
514                                                         }
515                                                         io_filesfrom_lastchar = f[-1];
516                                                 }
517                                                 io_filesfrom_buflen = l;
518                                         }
519                                 }
520                         }
521                 }
522
523                 if (!FD_ISSET(fd, &r_fds))
524                         continue;
525
526                 n = read(fd, buf, len);
527
528                 if (n <= 0) {
529                         if (n == 0)
530                                 whine_about_eof(fd); /* Doesn't return. */
531                         if (errno == EINTR || errno == EWOULDBLOCK
532                             || errno == EAGAIN)
533                                 continue;
534
535                         /* Don't write errors on a dead socket. */
536                         if (fd == sock_f_in)
537                                 close_multiplexing_out();
538                         rsyserr(FERROR, errno, "read error");
539                         exit_cleanup(RERR_STREAMIO);
540                 }
541
542                 buf += n;
543                 len -= n;
544                 ret += n;
545
546                 if (io_timeout && fd == sock_f_in)
547                         last_io = time(NULL);
548         }
549
550         return ret;
551 }
552
553 /**
554  * Read a line into the "fname" buffer (which must be at least MAXPATHLEN
555  * characters long).
556  */
557 int read_filesfrom_line(int fd, char *fname)
558 {
559         char ch, *s, *eob = fname + MAXPATHLEN - 1;
560         int cnt;
561         int reading_remotely = remote_filesfrom_file != NULL;
562         int nulls = eol_nulls || reading_remotely;
563
564   start:
565         s = fname;
566         while (1) {
567                 cnt = read(fd, &ch, 1);
568                 if (cnt < 0 && (errno == EWOULDBLOCK
569                   || errno == EINTR || errno == EAGAIN)) {
570                         struct timeval tv;
571                         fd_set fds;
572                         FD_ZERO(&fds);
573                         FD_SET(fd, &fds);
574                         tv.tv_sec = select_timeout;
575                         tv.tv_usec = 0;
576                         if (!select(fd+1, &fds, NULL, NULL, &tv))
577                                 check_timeout();
578                         continue;
579                 }
580                 if (cnt != 1)
581                         break;
582                 if (nulls? !ch : (ch == '\r' || ch == '\n')) {
583                         /* Skip empty lines if reading locally. */
584                         if (!reading_remotely && s == fname)
585                                 continue;
586                         break;
587                 }
588                 if (s < eob)
589                         *s++ = ch;
590         }
591         *s = '\0';
592
593         /* Dump comments. */
594         if (*fname == '#' || *fname == ';')
595                 goto start;
596
597         return s - fname;
598 }
599
600
601 static char *iobuf_out;
602 static int iobuf_out_cnt;
603
604 void io_start_buffering_out(void)
605 {
606         if (iobuf_out)
607                 return;
608         if (!(iobuf_out = new_array(char, IO_BUFFER_SIZE)))
609                 out_of_memory("io_start_buffering_out");
610         iobuf_out_cnt = 0;
611 }
612
613
614 static char *iobuf_in;
615 static size_t iobuf_in_siz;
616
617 void io_start_buffering_in(void)
618 {
619         if (iobuf_in)
620                 return;
621         iobuf_in_siz = 2 * IO_BUFFER_SIZE;
622         if (!(iobuf_in = new_array(char, iobuf_in_siz)))
623                 out_of_memory("io_start_buffering_in");
624 }
625
626
627 void io_end_buffering(void)
628 {
629         io_flush(NORMAL_FLUSH);
630         if (!io_multiplexing_out) {
631                 free(iobuf_out);
632                 iobuf_out = NULL;
633         }
634 }
635
636
637 /**
638  * Continue trying to read len bytes - don't return until len has been
639  * read.
640  **/
641 static void read_loop(int fd, char *buf, size_t len)
642 {
643         while (len) {
644                 int n = read_timeout(fd, buf, len);
645
646                 buf += n;
647                 len -= n;
648         }
649 }
650
651
652 /**
653  * Read from the file descriptor handling multiplexing - return number
654  * of bytes read.
655  *
656  * Never returns <= 0.
657  */
658 static int readfd_unbuffered(int fd, char *buf, size_t len)
659 {
660         static size_t remaining;
661         static size_t iobuf_in_ndx;
662         int tag, ret = 0;
663         char line[MAXPATHLEN+1];
664
665         if (!iobuf_in || fd != sock_f_in)
666                 return read_timeout(fd, buf, len);
667
668         if (!io_multiplexing_in && remaining == 0) {
669                 remaining = read_timeout(fd, iobuf_in, iobuf_in_siz);
670                 iobuf_in_ndx = 0;
671         }
672
673         while (ret == 0) {
674                 if (remaining) {
675                         len = MIN(len, remaining);
676                         memcpy(buf, iobuf_in + iobuf_in_ndx, len);
677                         iobuf_in_ndx += len;
678                         remaining -= len;
679                         ret = len;
680                         break;
681                 }
682
683                 read_loop(fd, line, 4);
684                 tag = IVAL(line, 0);
685
686                 remaining = tag & 0xFFFFFF;
687                 tag = (tag >> 24) - MPLEX_BASE;
688
689                 switch (tag) {
690                 case MSG_DATA:
691                         if (remaining > iobuf_in_siz) {
692                                 if (!(iobuf_in = realloc_array(iobuf_in, char,
693                                                                remaining)))
694                                         out_of_memory("readfd_unbuffered");
695                                 iobuf_in_siz = remaining;
696                         }
697                         read_loop(fd, iobuf_in, remaining);
698                         iobuf_in_ndx = 0;
699                         break;
700                 case MSG_DELETED:
701                         if (remaining >= sizeof line) {
702                                 rprintf(FERROR, "invalid multi-message %d:%ld\n",
703                                         tag, (long)remaining);
704                                 exit_cleanup(RERR_STREAMIO);
705                         }
706                         read_loop(fd, line, remaining);
707                         line[remaining] = '\0';
708                         /* A directory name was sent with the trailing null */
709                         if (remaining > 0 && !line[remaining-1])
710                                 log_delete(line, S_IFDIR);
711                         else
712                                 log_delete(line, S_IFREG);
713                         remaining = 0;
714                         break;
715                 case MSG_SUCCESS:
716                         if (remaining != 4) {
717                                 rprintf(FERROR, "invalid multi-message %d:%ld\n",
718                                         tag, (long)remaining);
719                                 exit_cleanup(RERR_STREAMIO);
720                         }
721                         read_loop(fd, line, remaining);
722                         successful_send(IVAL(line, 0));
723                         remaining = 0;
724                         break;
725                 case MSG_INFO:
726                 case MSG_ERROR:
727                         if (remaining >= sizeof line) {
728                                 rprintf(FERROR,
729                                         "[%s] multiplexing overflow %d:%ld\n\n",
730                                         who_am_i(), tag, (long)remaining);
731                                 exit_cleanup(RERR_STREAMIO);
732                         }
733                         read_loop(fd, line, remaining);
734                         rwrite((enum logcode)tag, line, remaining);
735                         remaining = 0;
736                         break;
737                 default:
738                         rprintf(FERROR, "[%s] unexpected tag %d\n",
739                                 who_am_i(), tag);
740                         exit_cleanup(RERR_STREAMIO);
741                 }
742         }
743
744         if (remaining == 0)
745                 io_flush(NORMAL_FLUSH);
746
747         return ret;
748 }
749
750
751
752 /**
753  * Do a buffered read from @p fd.  Don't return until all @p n bytes
754  * have been read.  If all @p n can't be read then exit with an
755  * error.
756  **/
757 static void readfd(int fd, char *buffer, size_t N)
758 {
759         int  ret;
760         size_t total = 0;
761
762         while (total < N) {
763                 ret = readfd_unbuffered(fd, buffer + total, N-total);
764                 total += ret;
765         }
766
767         if (fd == write_batch_monitor_in) {
768                 if ((size_t)write(batch_fd, buffer, total) != total)
769                         exit_cleanup(RERR_FILEIO);
770         }
771
772         if (fd == sock_f_in)
773                 stats.total_read += total;
774 }
775
776
777 int read_shortint(int f)
778 {
779         uchar b[2];
780         readfd(f, (char *)b, 2);
781         return (b[1] << 8) + b[0];
782 }
783
784
785 int32 read_int(int f)
786 {
787         char b[4];
788         int32 ret;
789
790         readfd(f,b,4);
791         ret = IVAL(b,0);
792         if (ret == (int32)0xffffffff)
793                 return -1;
794         return ret;
795 }
796
797 int64 read_longint(int f)
798 {
799         int64 ret;
800         char b[8];
801         ret = read_int(f);
802
803         if ((int32)ret != (int32)0xffffffff)
804                 return ret;
805
806 #if SIZEOF_INT64 < 8
807         rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
808         exit_cleanup(RERR_UNSUPPORTED);
809 #else
810         readfd(f,b,8);
811         ret = IVAL(b,0) | (((int64)IVAL(b,4))<<32);
812 #endif
813
814         return ret;
815 }
816
817 void read_buf(int f,char *buf,size_t len)
818 {
819         readfd(f,buf,len);
820 }
821
822 void read_sbuf(int f,char *buf,size_t len)
823 {
824         readfd(f, buf, len);
825         buf[len] = 0;
826 }
827
828 uchar read_byte(int f)
829 {
830         uchar c;
831         readfd(f, (char *)&c, 1);
832         return c;
833 }
834
835 /* Populate a sum_struct with values from the socket.  This is
836  * called by both the sender and the receiver. */
837 void read_sum_head(int f, struct sum_struct *sum)
838 {
839         sum->count = read_int(f);
840         sum->blength = read_int(f);
841         if (sum->blength < 0 || sum->blength > MAX_BLOCK_SIZE) {
842                 rprintf(FERROR, "[%s] Invalid block length %ld\n",
843                         who_am_i(), (long)sum->blength);
844                 exit_cleanup(RERR_PROTOCOL);
845         }
846         sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
847         if (sum->s2length < 0 || sum->s2length > MD4_SUM_LENGTH) {
848                 rprintf(FERROR, "[%s] Invalid checksum length %d\n",
849                         who_am_i(), sum->s2length);
850                 exit_cleanup(RERR_PROTOCOL);
851         }
852         sum->remainder = read_int(f);
853         if (sum->remainder < 0 || sum->remainder > sum->blength) {
854                 rprintf(FERROR, "[%s] Invalid remainder length %ld\n",
855                         who_am_i(), (long)sum->remainder);
856                 exit_cleanup(RERR_PROTOCOL);
857         }
858 }
859
860 /* Send the values from a sum_struct over the socket.  Set sum to
861  * NULL if there are no checksums to send.  This is called by both
862  * the generator and the sender. */
863 void write_sum_head(int f, struct sum_struct *sum)
864 {
865         static struct sum_struct null_sum;
866
867         if (sum == NULL)
868                 sum = &null_sum;
869
870         write_int(f, sum->count);
871         write_int(f, sum->blength);
872         if (protocol_version >= 27)
873                 write_int(f, sum->s2length);
874         write_int(f, sum->remainder);
875 }
876
877
878 /**
879  * Sleep after writing to limit I/O bandwidth usage.
880  *
881  * @todo Rather than sleeping after each write, it might be better to
882  * use some kind of averaging.  The current algorithm seems to always
883  * use a bit less bandwidth than specified, because it doesn't make up
884  * for slow periods.  But arguably this is a feature.  In addition, we
885  * ought to take the time used to write the data into account.
886  *
887  * During some phases of big transfers (file FOO is uptodate) this is
888  * called with a small bytes_written every time.  As the kernel has to
889  * round small waits up to guarantee that we actually wait at least the
890  * requested number of microseconds, this can become grossly inaccurate.
891  * We therefore keep track of the bytes we've written over time and only
892  * sleep when the accumulated delay is at least 1 tenth of a second.
893  **/
894 static void sleep_for_bwlimit(int bytes_written)
895 {
896         static struct timeval prior_tv;
897         static long total_written = 0; 
898         struct timeval tv, start_tv;
899         long elapsed_usec, sleep_usec;
900
901 #define ONE_SEC 1000000L /* # of microseconds in a second */
902
903         if (!bwlimit)
904                 return;
905
906         total_written += bytes_written; 
907
908         gettimeofday(&start_tv, NULL);
909         if (prior_tv.tv_sec) {
910                 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
911                              + (start_tv.tv_usec - prior_tv.tv_usec);
912                 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
913                 if (total_written < 0)
914                         total_written = 0;
915         }
916
917         sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
918         if (sleep_usec < ONE_SEC / 10) {
919                 prior_tv = start_tv;
920                 return;
921         }
922
923         tv.tv_sec  = sleep_usec / ONE_SEC;
924         tv.tv_usec = sleep_usec % ONE_SEC;
925         select(0, NULL, NULL, NULL, &tv);
926
927         gettimeofday(&prior_tv, NULL);
928         elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
929                      + (prior_tv.tv_usec - start_tv.tv_usec);
930         total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
931 }
932
933
934 /* Write len bytes to the file descriptor fd, looping as necessary to get
935  * the job done and also (in the generator) reading any data on msg_fd_in
936  * (to avoid deadlock).
937  *
938  * This function underlies the multiplexing system.  The body of the
939  * application never calls this function directly. */
940 static void writefd_unbuffered(int fd,char *buf,size_t len)
941 {
942         size_t n, total = 0;
943         fd_set w_fds, r_fds;
944         int maxfd, count, ret;
945         struct timeval tv;
946
947         no_flush++;
948
949         while (total < len) {
950                 FD_ZERO(&w_fds);
951                 FD_SET(fd,&w_fds);
952                 maxfd = fd;
953
954                 if (msg_fd_in >= 0) {
955                         FD_ZERO(&r_fds);
956                         FD_SET(msg_fd_in,&r_fds);
957                         if (msg_fd_in > maxfd)
958                                 maxfd = msg_fd_in;
959                 }
960                 if (fd != sock_f_out && iobuf_out_cnt && no_flush == 1) {
961                         FD_SET(sock_f_out, &w_fds);
962                         if (sock_f_out > maxfd)
963                                 maxfd = sock_f_out;
964                 }
965
966                 tv.tv_sec = select_timeout;
967                 tv.tv_usec = 0;
968
969                 errno = 0;
970                 count = select(maxfd + 1, msg_fd_in >= 0 ? &r_fds : NULL,
971                                &w_fds, NULL, &tv);
972
973                 if (count <= 0) {
974                         if (count < 0 && errno == EBADF)
975                                 exit_cleanup(RERR_SOCKETIO);
976                         check_timeout();
977                         continue;
978                 }
979
980                 if (msg_fd_in >= 0 && FD_ISSET(msg_fd_in, &r_fds))
981                         read_msg_fd();
982
983                 if (!FD_ISSET(fd, &w_fds)) {
984                         if (fd != sock_f_out && iobuf_out_cnt) {
985                                 no_flush--;
986                                 io_flush(NORMAL_FLUSH);
987                                 no_flush++;
988                         }
989                         continue;
990                 }
991
992                 n = len - total;
993                 if (bwlimit && n > bwlimit_writemax)
994                         n = bwlimit_writemax;
995                 ret = write(fd, buf + total, n);
996
997                 if (ret <= 0) {
998                         if (ret < 0) {
999                                 if (errno == EINTR)
1000                                         continue;
1001                                 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1002                                         msleep(1);
1003                                         continue;
1004                                 }
1005                         }
1006
1007                         /* Don't try to write errors back across the stream. */
1008                         if (fd == sock_f_out)
1009                                 close_multiplexing_out();
1010                         rsyserr(FERROR, errno,
1011                                 "writefd_unbuffered failed to write %ld bytes: phase \"%s\" [%s]",
1012                                 (long)len, io_write_phase, who_am_i());
1013                         /* If the other side is sending us error messages, try
1014                          * to grab any messages they sent before they died. */
1015                         while (fd == sock_f_out && io_multiplexing_in) {
1016                                 io_timeout = select_timeout = 30;
1017                                 readfd_unbuffered(sock_f_in, io_filesfrom_buf,
1018                                                   sizeof io_filesfrom_buf);
1019                         }
1020                         exit_cleanup(RERR_STREAMIO);
1021                 }
1022
1023                 total += ret;
1024
1025                 if (fd == sock_f_out) {
1026                         if (io_timeout)
1027                                 last_io = time(NULL);
1028                         sleep_for_bwlimit(ret);
1029                 }
1030         }
1031
1032         no_flush--;
1033 }
1034
1035
1036 /**
1037  * Write an message to a multiplexed stream. If this fails then rsync
1038  * exits.
1039  **/
1040 static void mplex_write(enum msgcode code, char *buf, size_t len)
1041 {
1042         char buffer[4096];
1043         size_t n = len;
1044
1045         SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
1046
1047         if (n > sizeof buffer - 4)
1048                 n = sizeof buffer - 4;
1049
1050         memcpy(&buffer[4], buf, n);
1051         writefd_unbuffered(sock_f_out, buffer, n+4);
1052
1053         len -= n;
1054         buf += n;
1055
1056         if (len)
1057                 writefd_unbuffered(sock_f_out, buf, len);
1058 }
1059
1060
1061 void io_flush(int flush_it_all)
1062 {
1063         msg_list_push(flush_it_all);
1064
1065         if (!iobuf_out_cnt || no_flush)
1066                 return;
1067
1068         if (io_multiplexing_out)
1069                 mplex_write(MSG_DATA, iobuf_out, iobuf_out_cnt);
1070         else
1071                 writefd_unbuffered(sock_f_out, iobuf_out, iobuf_out_cnt);
1072         iobuf_out_cnt = 0;
1073 }
1074
1075
1076 static void writefd(int fd,char *buf,size_t len)
1077 {
1078         if (fd == msg_fd_out) {
1079                 rprintf(FERROR, "Internal error: wrong write used in receiver.\n");
1080                 exit_cleanup(RERR_PROTOCOL);
1081         }
1082
1083         if (fd == sock_f_out)
1084                 stats.total_written += len;
1085
1086         if (fd == write_batch_monitor_out) {
1087                 if ((size_t)write(batch_fd, buf, len) != len)
1088                         exit_cleanup(RERR_FILEIO);
1089         }
1090
1091         if (!iobuf_out || fd != sock_f_out) {
1092                 writefd_unbuffered(fd, buf, len);
1093                 return;
1094         }
1095
1096         while (len) {
1097                 int n = MIN((int)len, IO_BUFFER_SIZE - iobuf_out_cnt);
1098                 if (n > 0) {
1099                         memcpy(iobuf_out+iobuf_out_cnt, buf, n);
1100                         buf += n;
1101                         len -= n;
1102                         iobuf_out_cnt += n;
1103                 }
1104
1105                 if (iobuf_out_cnt == IO_BUFFER_SIZE)
1106                         io_flush(NORMAL_FLUSH);
1107         }
1108 }
1109
1110
1111 void write_shortint(int f, int x)
1112 {
1113         uchar b[2];
1114         b[0] = x;
1115         b[1] = x >> 8;
1116         writefd(f, (char *)b, 2);
1117 }
1118
1119
1120 void write_int(int f,int32 x)
1121 {
1122         char b[4];
1123         SIVAL(b,0,x);
1124         writefd(f,b,4);
1125 }
1126
1127
1128 void write_int_named(int f, int32 x, const char *phase)
1129 {
1130         io_write_phase = phase;
1131         write_int(f, x);
1132         io_write_phase = phase_unknown;
1133 }
1134
1135
1136 /*
1137  * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1138  * 64-bit types on this platform.
1139  */
1140 void write_longint(int f, int64 x)
1141 {
1142         char b[8];
1143
1144         if (x <= 0x7FFFFFFF) {
1145                 write_int(f, (int)x);
1146                 return;
1147         }
1148
1149 #if SIZEOF_INT64 < 8
1150         rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1151         exit_cleanup(RERR_UNSUPPORTED);
1152 #else
1153         write_int(f, (int32)0xFFFFFFFF);
1154         SIVAL(b,0,(x&0xFFFFFFFF));
1155         SIVAL(b,4,((x>>32)&0xFFFFFFFF));
1156
1157         writefd(f,b,8);
1158 #endif
1159 }
1160
1161 void write_buf(int f,char *buf,size_t len)
1162 {
1163         writefd(f,buf,len);
1164 }
1165
1166
1167 /** Write a string to the connection */
1168 void write_sbuf(int f, char *buf)
1169 {
1170         writefd(f, buf, strlen(buf));
1171 }
1172
1173
1174 void write_byte(int f, uchar c)
1175 {
1176         writefd(f, (char *)&c, 1);
1177 }
1178
1179
1180 /**
1181  * Read a line of up to @p maxlen characters into @p buf (not counting
1182  * the trailing null).  Strips the (required) trailing newline and all
1183  * carriage returns.
1184  *
1185  * @return 1 for success; 0 for I/O error or truncation.
1186  **/
1187 int read_line(int f, char *buf, size_t maxlen)
1188 {
1189         while (maxlen) {
1190                 buf[0] = 0;
1191                 read_buf(f, buf, 1);
1192                 if (buf[0] == 0)
1193                         return 0;
1194                 if (buf[0] == '\n')
1195                         break;
1196                 if (buf[0] != '\r') {
1197                         buf++;
1198                         maxlen--;
1199                 }
1200         }
1201         *buf = '\0';
1202         return maxlen > 0;
1203 }
1204
1205
1206 void io_printf(int fd, const char *format, ...)
1207 {
1208         va_list ap;
1209         char buf[1024];
1210         int len;
1211
1212         va_start(ap, format);
1213         len = vsnprintf(buf, sizeof buf, format, ap);
1214         va_end(ap);
1215
1216         if (len < 0)
1217                 exit_cleanup(RERR_STREAMIO);
1218
1219         write_sbuf(fd, buf);
1220 }
1221
1222
1223 /** Setup for multiplexing a MSG_* stream with the data stream. */
1224 void io_start_multiplex_out(void)
1225 {
1226         io_flush(NORMAL_FLUSH);
1227         io_start_buffering_out();
1228         io_multiplexing_out = 1;
1229 }
1230
1231 /** Setup for multiplexing a MSG_* stream with the data stream. */
1232 void io_start_multiplex_in(void)
1233 {
1234         io_flush(NORMAL_FLUSH);
1235         io_start_buffering_in();
1236         io_multiplexing_in = 1;
1237 }
1238
1239 /** Write an message to the multiplexed data stream. */
1240 int io_multiplex_write(enum msgcode code, char *buf, size_t len)
1241 {
1242         if (!io_multiplexing_out)
1243                 return 0;
1244
1245         io_flush(NORMAL_FLUSH);
1246         stats.total_written += (len+4);
1247         mplex_write(code, buf, len);
1248         return 1;
1249 }
1250
1251 void close_multiplexing_in(void)
1252 {
1253         io_multiplexing_in = 0;
1254 }
1255
1256 /** Stop output multiplexing. */
1257 void close_multiplexing_out(void)
1258 {
1259         io_multiplexing_out = 0;
1260 }
1261
1262 void start_write_batch(int fd)
1263 {
1264         write_stream_flags(batch_fd);
1265
1266         /* Some communication has already taken place, but we don't
1267          * enable batch writing until here so that we can write a
1268          * canonical record of the communication even though the
1269          * actual communication so far depends on whether a daemon
1270          * is involved. */
1271         write_int(batch_fd, protocol_version);
1272         write_int(batch_fd, checksum_seed);
1273
1274         if (am_sender)
1275                 write_batch_monitor_out = fd;
1276         else
1277                 write_batch_monitor_in = fd;
1278 }
1279
1280 void stop_write_batch(void)
1281 {
1282         write_batch_monitor_out = -1;
1283         write_batch_monitor_in = -1;
1284 }