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