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