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