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