Optimized the reacquisition of the code value from the msg2sndr list.
[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 io_timeout;
45 extern int allowed_lull;
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 read_batch;
52 extern int csum_length;
53 extern int checksum_seed;
54 extern int protocol_version;
55 extern int remove_sent_files;
56 extern int preserve_hard_links;
57 extern char *filesfrom_host;
58 extern struct stats stats;
59 extern struct file_list *the_file_list;
60
61 const char phase_unknown[] = "unknown";
62 int ignore_timeout = 0;
63 int batch_fd = -1;
64 int batch_gen_fd = -1;
65
66 /**
67  * The connection might be dropped at some point; perhaps because the
68  * remote instance crashed.  Just giving the offset on the stream is
69  * not very helpful.  So instead we try to make io_phase_name point to
70  * something useful.
71  *
72  * For buffered/multiplexed I/O these names will be somewhat
73  * approximate; perhaps for ease of support we would rather make the
74  * buffer always flush when a single application-level I/O finishes.
75  *
76  * @todo Perhaps we want some simple stack functionality, but there's
77  * no need to overdo it.
78  **/
79 const char *io_write_phase = phase_unknown;
80 const char *io_read_phase = phase_unknown;
81
82 /* Ignore an EOF error if non-zero. See whine_about_eof(). */
83 int kluge_around_eof = 0;
84
85 int msg_fd_in = -1;
86 int msg_fd_out = -1;
87 int sock_f_in = -1;
88 int sock_f_out = -1;
89
90 static int io_multiplexing_out;
91 static int io_multiplexing_in;
92 static time_t last_io_in;
93 static time_t last_io_out;
94 static int no_flush;
95
96 static int write_batch_monitor_in = -1;
97 static int write_batch_monitor_out = -1;
98
99 static int io_filesfrom_f_in = -1;
100 static int io_filesfrom_f_out = -1;
101 static char io_filesfrom_buf[2048];
102 static char *io_filesfrom_bp;
103 static char io_filesfrom_lastchar;
104 static int io_filesfrom_buflen;
105 static int defer_forwarding_messages = 0;
106 static int select_timeout = SELECT_TIMEOUT;
107 static int active_filecnt = 0;
108 static OFF_T active_bytecnt = 0;
109
110 static void read_loop(int fd, char *buf, size_t len);
111
112 struct flist_ndx_item {
113         struct flist_ndx_item *next;
114         int ndx;
115 };
116
117 struct flist_ndx_list {
118         struct flist_ndx_item *head, *tail;
119 };
120
121 static struct flist_ndx_list redo_list, hlink_list;
122
123 struct msg_list_item {
124         struct msg_list_item *next;
125         int len;
126         char buf[1];
127 };
128
129 struct msg_list {
130         struct msg_list_item *head, *tail;
131 };
132
133 static struct msg_list msg2genr, msg2sndr;
134
135 static void flist_ndx_push(struct flist_ndx_list *lp, int ndx)
136 {
137         struct flist_ndx_item *item;
138
139         if (!(item = new(struct flist_ndx_item)))
140                 out_of_memory("flist_ndx_push");
141         item->next = NULL;
142         item->ndx = ndx;
143         if (lp->tail)
144                 lp->tail->next = item;
145         else
146                 lp->head = item;
147         lp->tail = item;
148 }
149
150 static int flist_ndx_pop(struct flist_ndx_list *lp)
151 {
152         struct flist_ndx_item *next;
153         int ndx;
154
155         if (!lp->head)
156                 return -1;
157
158         ndx = lp->head->ndx;
159         next = lp->head->next;
160         free(lp->head);
161         lp->head = next;
162         if (!next)
163                 lp->tail = NULL;
164
165         return ndx;
166 }
167
168 static void check_timeout(void)
169 {
170         time_t t;
171
172         if (!io_timeout || ignore_timeout)
173                 return;
174
175         if (!last_io_in) {
176                 last_io_in = time(NULL);
177                 return;
178         }
179
180         t = time(NULL);
181
182         if (t - last_io_in >= io_timeout) {
183                 if (!am_server && !am_daemon) {
184                         rprintf(FERROR, "io timeout after %d seconds -- exiting\n",
185                                 (int)(t-last_io_in));
186                 }
187                 exit_cleanup(RERR_TIMEOUT);
188         }
189 }
190
191 /* Note the fds used for the main socket (which might really be a pipe
192  * for a local transfer, but we can ignore that). */
193 void io_set_sock_fds(int f_in, int f_out)
194 {
195         sock_f_in = f_in;
196         sock_f_out = f_out;
197 }
198
199 void set_io_timeout(int secs)
200 {
201         io_timeout = secs;
202
203         if (!io_timeout || io_timeout > SELECT_TIMEOUT)
204                 select_timeout = SELECT_TIMEOUT;
205         else
206                 select_timeout = io_timeout;
207
208         allowed_lull = read_batch ? 0 : (io_timeout + 1) / 2;
209 }
210
211 /* Setup the fd used to receive MSG_* messages.  Only needed during the
212  * early stages of being a local sender (up through the sending of the
213  * file list) or when we're the generator (to fetch the messages from
214  * the receiver). */
215 void set_msg_fd_in(int fd)
216 {
217         msg_fd_in = fd;
218 }
219
220 /* Setup the fd used to send our MSG_* messages.  Only needed when
221  * we're the receiver (to send our messages to the generator). */
222 void set_msg_fd_out(int fd)
223 {
224         msg_fd_out = fd;
225         set_nonblocking(msg_fd_out);
226 }
227
228 /* Add a message to the pending MSG_* list. */
229 static void msg_list_add(struct msg_list *lst, int code, char *buf, int len)
230 {
231         struct msg_list_item *m;
232         int sz = len + 4 + sizeof m[0] - 1;
233
234         if (!(m = (struct msg_list_item *)new_array(char, sz)))
235                 out_of_memory("msg_list_add");
236         m->next = NULL;
237         m->len = len + 4;
238         SIVAL(m->buf, 0, ((code+MPLEX_BASE)<<24) | len);
239         memcpy(m->buf + 4, buf, len);
240         if (lst->tail)
241                 lst->tail->next = m;
242         else
243                 lst->head = m;
244         lst->tail = m;
245 }
246
247 /* Read a message from the MSG_* fd and handle it.  This is called either
248  * during the early stages of being a local sender (up through the sending
249  * of the file list) or when we're the generator (to fetch the messages
250  * from the receiver). */
251 static void read_msg_fd(void)
252 {
253         char buf[2048];
254         size_t n;
255         int fd = msg_fd_in;
256         int tag, len;
257
258         /* Temporarily disable msg_fd_in.  This is needed to avoid looping back
259          * to this routine from writefd_unbuffered(). */
260         msg_fd_in = -1;
261
262         read_loop(fd, buf, 4);
263         tag = IVAL(buf, 0);
264
265         len = tag & 0xFFFFFF;
266         tag = (tag >> 24) - MPLEX_BASE;
267
268         switch (tag) {
269         case MSG_DONE:
270                 if (len != 0 || !am_generator) {
271                         rprintf(FERROR, "invalid message %d:%d\n", tag, len);
272                         exit_cleanup(RERR_STREAMIO);
273                 }
274                 flist_ndx_push(&redo_list, -1);
275                 break;
276         case MSG_REDO:
277                 if (len != 4 || !am_generator) {
278                         rprintf(FERROR, "invalid message %d:%d\n", tag, len);
279                         exit_cleanup(RERR_STREAMIO);
280                 }
281                 read_loop(fd, buf, 4);
282                 if (remove_sent_files)
283                         decrement_active_files(IVAL(buf,0));
284                 flist_ndx_push(&redo_list, IVAL(buf,0));
285                 break;
286         case MSG_DELETED:
287                 if (len >= (int)sizeof buf || !am_generator) {
288                         rprintf(FERROR, "invalid message %d:%d\n", tag, len);
289                         exit_cleanup(RERR_STREAMIO);
290                 }
291                 read_loop(fd, buf, len);
292                 if (defer_forwarding_messages)
293                         msg_list_add(&msg2sndr, MSG_DELETED, buf, len);
294                 else
295                         io_multiplex_write(MSG_DELETED, buf, len);
296                 break;
297         case MSG_SUCCESS:
298                 if (len != 4 || !am_generator) {
299                         rprintf(FERROR, "invalid message %d:%d\n", tag, len);
300                         exit_cleanup(RERR_STREAMIO);
301                 }
302                 read_loop(fd, buf, len);
303                 if (remove_sent_files) {
304                         decrement_active_files(IVAL(buf,0));
305                         if (defer_forwarding_messages)
306                                 msg_list_add(&msg2sndr, MSG_SUCCESS, buf, len);
307                         else
308                                 io_multiplex_write(MSG_SUCCESS, buf, len);
309                 }
310                 if (preserve_hard_links)
311                         flist_ndx_push(&hlink_list, IVAL(buf,0));
312                 break;
313         case MSG_SOCKERR:
314                 if (!am_generator) {
315                         rprintf(FERROR, "invalid message %d:%d\n", tag, len);
316                         exit_cleanup(RERR_STREAMIO);
317                 }
318                 close_multiplexing_out();
319                 /* FALL THROUGH */
320         case MSG_INFO:
321         case MSG_ERROR:
322         case MSG_LOG:
323                 while (len) {
324                         n = len;
325                         if (n >= sizeof buf)
326                                 n = sizeof buf - 1;
327                         read_loop(fd, buf, n);
328                         if (am_generator && am_server && defer_forwarding_messages)
329                                 msg_list_add(&msg2sndr, tag, buf, n);
330                         else
331                                 rwrite((enum logcode)tag, buf, n);
332                         len -= n;
333                 }
334                 break;
335         default:
336                 rprintf(FERROR, "unknown message %d:%d\n", tag, len);
337                 exit_cleanup(RERR_STREAMIO);
338         }
339
340         msg_fd_in = fd;
341 }
342
343 /* This is used by the generator to limit how many file transfers can
344  * be active at once when --remove-sent-files is specified.  Without
345  * this, sender-side deletions were mostly happening at the end. */
346 void increment_active_files(int ndx, int itemizing, enum logcode code)
347 {
348         /* TODO: tune these limits? */
349         while (active_filecnt >= (active_bytecnt >= 128*1024 ? 10 : 50)) {
350                 if (hlink_list.head)
351                         check_for_finished_hlinks(itemizing, code);
352                 read_msg_fd();
353         }
354
355         active_filecnt++;
356         active_bytecnt += the_file_list->files[ndx]->length;
357 }
358
359 void decrement_active_files(int ndx)
360 {
361         active_filecnt--;
362         active_bytecnt -= the_file_list->files[ndx]->length;
363 }
364
365 /* Try to push messages off the list onto the wire.  If we leave with more
366  * to do, return 0.  On error, return -1.  If everything flushed, return 1.
367  * This is only active in the receiver. */
368 static int msg2genr_flush(int flush_it_all)
369 {
370         static int written = 0;
371         struct timeval tv;
372         fd_set fds;
373
374         if (msg_fd_out < 0)
375                 return -1;
376
377         while (msg2genr.head) {
378                 struct msg_list_item *m = msg2genr.head;
379                 int n = write(msg_fd_out, m->buf + written, m->len - written);
380                 if (n < 0) {
381                         if (errno == EINTR)
382                                 continue;
383                         if (errno != EWOULDBLOCK && errno != EAGAIN)
384                                 return -1;
385                         if (!flush_it_all)
386                                 return 0;
387                         FD_ZERO(&fds);
388                         FD_SET(msg_fd_out, &fds);
389                         tv.tv_sec = select_timeout;
390                         tv.tv_usec = 0;
391                         if (!select(msg_fd_out+1, NULL, &fds, NULL, &tv))
392                                 check_timeout();
393                 } else if ((written += n) == m->len) {
394                         msg2genr.head = m->next;
395                         if (!msg2genr.head)
396                                 msg2genr.tail = NULL;
397                         free(m);
398                         written = 0;
399                 }
400         }
401         return 1;
402 }
403
404 void send_msg(enum msgcode code, char *buf, int len)
405 {
406         if (msg_fd_out < 0) {
407                 io_multiplex_write(code, buf, len);
408                 return;
409         }
410         msg_list_add(&msg2genr, code, buf, len);
411         msg2genr_flush(NORMAL_FLUSH);
412 }
413
414 int get_redo_num(int itemizing, enum logcode code)
415 {
416         while (1) {
417                 if (hlink_list.head)
418                         check_for_finished_hlinks(itemizing, code);
419                 if (redo_list.head)
420                         break;
421                 read_msg_fd();
422         }
423
424         return flist_ndx_pop(&redo_list);
425 }
426
427 int get_hlink_num(void)
428 {
429         return flist_ndx_pop(&hlink_list);
430 }
431
432 /**
433  * When we're the receiver and we have a local --files-from list of names
434  * that needs to be sent over the socket to the sender, we have to do two
435  * things at the same time: send the sender a list of what files we're
436  * processing and read the incoming file+info list from the sender.  We do
437  * this by augmenting the read_timeout() function to copy this data.  It
438  * uses the io_filesfrom_buf to read a block of data from f_in (when it is
439  * ready, since it might be a pipe) and then blast it out f_out (when it
440  * is ready to receive more data).
441  */
442 void io_set_filesfrom_fds(int f_in, int f_out)
443 {
444         io_filesfrom_f_in = f_in;
445         io_filesfrom_f_out = f_out;
446         io_filesfrom_bp = io_filesfrom_buf;
447         io_filesfrom_lastchar = '\0';
448         io_filesfrom_buflen = 0;
449 }
450
451 /* It's almost always an error to get an EOF when we're trying to read from the
452  * network, because the protocol is (for the most part) self-terminating.
453  *
454  * There is one case for the receiver when it is at the end of the transfer
455  * (hanging around reading any keep-alive packets that might come its way): if
456  * the sender dies before the generator's kill-signal comes through, we can end
457  * up here needing to loop until the kill-signal arrives.  In this situation,
458  * kluge_around_eof will be < 0.
459  *
460  * There is another case for older protocol versions (< 24) where the module
461  * listing was not terminated, so we must ignore an EOF error in that case and
462  * exit.  In this situation, kluge_around_eof will be > 0. */
463 static void whine_about_eof(int fd)
464 {
465         if (kluge_around_eof && fd == sock_f_in) {
466                 int i;
467                 if (kluge_around_eof > 0)
468                         exit_cleanup(0);
469                 /* If we're still here after 10 seconds, exit with an error. */
470                 for (i = 10*1000/20; i--; )
471                         msleep(20);
472         }
473
474         rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
475                 "(%.0f bytes received so far) [%s]\n",
476                 (double)stats.total_read, who_am_i());
477
478         exit_cleanup(RERR_STREAMIO);
479 }
480
481 /**
482  * Read from a socket with I/O timeout. return the number of bytes
483  * read. If no bytes can be read then exit, never return a number <= 0.
484  *
485  * TODO: If the remote shell connection fails, then current versions
486  * actually report an "unexpected EOF" error here.  Since it's a
487  * fairly common mistake to try to use rsh when ssh is required, we
488  * should trap that: if we fail to read any data at all, we should
489  * give a better explanation.  We can tell whether the connection has
490  * started by looking e.g. at whether the remote version is known yet.
491  */
492 static int read_timeout(int fd, char *buf, size_t len)
493 {
494         int n, cnt = 0;
495
496         io_flush(NORMAL_FLUSH);
497
498         while (cnt == 0) {
499                 /* until we manage to read *something* */
500                 fd_set r_fds, w_fds;
501                 struct timeval tv;
502                 int maxfd = fd;
503                 int count;
504
505                 FD_ZERO(&r_fds);
506                 FD_ZERO(&w_fds);
507                 FD_SET(fd, &r_fds);
508                 if (msg2genr.head) {
509                         FD_SET(msg_fd_out, &w_fds);
510                         if (msg_fd_out > maxfd)
511                                 maxfd = msg_fd_out;
512                 }
513                 if (io_filesfrom_f_out >= 0) {
514                         int new_fd;
515                         if (io_filesfrom_buflen == 0) {
516                                 if (io_filesfrom_f_in >= 0) {
517                                         FD_SET(io_filesfrom_f_in, &r_fds);
518                                         new_fd = io_filesfrom_f_in;
519                                 } else {
520                                         io_filesfrom_f_out = -1;
521                                         new_fd = -1;
522                                 }
523                         } else {
524                                 FD_SET(io_filesfrom_f_out, &w_fds);
525                                 new_fd = io_filesfrom_f_out;
526                         }
527                         if (new_fd > maxfd)
528                                 maxfd = new_fd;
529                 }
530
531                 tv.tv_sec = select_timeout;
532                 tv.tv_usec = 0;
533
534                 errno = 0;
535
536                 count = select(maxfd + 1, &r_fds, &w_fds, NULL, &tv);
537
538                 if (count <= 0) {
539                         if (errno == EBADF)
540                                 exit_cleanup(RERR_SOCKETIO);
541                         check_timeout();
542                         continue;
543                 }
544
545                 if (msg2genr.head && FD_ISSET(msg_fd_out, &w_fds))
546                         msg2genr_flush(NORMAL_FLUSH);
547
548                 if (io_filesfrom_f_out >= 0) {
549                         if (io_filesfrom_buflen) {
550                                 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
551                                         int l = write(io_filesfrom_f_out,
552                                                       io_filesfrom_bp,
553                                                       io_filesfrom_buflen);
554                                         if (l > 0) {
555                                                 if (!(io_filesfrom_buflen -= l))
556                                                         io_filesfrom_bp = io_filesfrom_buf;
557                                                 else
558                                                         io_filesfrom_bp += l;
559                                         } else {
560                                                 /* XXX should we complain? */
561                                                 io_filesfrom_f_out = -1;
562                                         }
563                                 }
564                         } else if (io_filesfrom_f_in >= 0) {
565                                 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
566                                         int l = read(io_filesfrom_f_in,
567                                                      io_filesfrom_buf,
568                                                      sizeof io_filesfrom_buf);
569                                         if (l <= 0) {
570                                                 /* Send end-of-file marker */
571                                                 io_filesfrom_buf[0] = '\0';
572                                                 io_filesfrom_buf[1] = '\0';
573                                                 io_filesfrom_buflen = io_filesfrom_lastchar? 2 : 1;
574                                                 io_filesfrom_f_in = -1;
575                                         } else {
576                                                 if (!eol_nulls) {
577                                                         char *s = io_filesfrom_buf + l;
578                                                         /* Transform CR and/or LF into '\0' */
579                                                         while (s-- > io_filesfrom_buf) {
580                                                                 if (*s == '\n' || *s == '\r')
581                                                                         *s = '\0';
582                                                         }
583                                                 }
584                                                 if (!io_filesfrom_lastchar) {
585                                                         /* Last buf ended with a '\0', so don't
586                                                          * let this buf start with one. */
587                                                         while (l && !*io_filesfrom_bp)
588                                                                 io_filesfrom_bp++, l--;
589                                                 }
590                                                 if (!l)
591                                                         io_filesfrom_bp = io_filesfrom_buf;
592                                                 else {
593                                                         char *f = io_filesfrom_bp;
594                                                         char *t = f;
595                                                         char *eob = f + l;
596                                                         /* Eliminate any multi-'\0' runs. */
597                                                         while (f != eob) {
598                                                                 if (!(*t++ = *f++)) {
599                                                                         while (f != eob && !*f)
600                                                                                 f++, l--;
601                                                                 }
602                                                         }
603                                                         io_filesfrom_lastchar = f[-1];
604                                                 }
605                                                 io_filesfrom_buflen = l;
606                                         }
607                                 }
608                         }
609                 }
610
611                 if (!FD_ISSET(fd, &r_fds))
612                         continue;
613
614                 n = read(fd, buf, len);
615
616                 if (n <= 0) {
617                         if (n == 0)
618                                 whine_about_eof(fd); /* Doesn't return. */
619                         if (errno == EINTR || errno == EWOULDBLOCK
620                             || errno == EAGAIN)
621                                 continue;
622
623                         /* Don't write errors on a dead socket. */
624                         if (fd == sock_f_in) {
625                                 close_multiplexing_out();
626                                 rsyserr(FSOCKERR, errno, "read error");
627                         } else
628                                 rsyserr(FERROR, errno, "read error");
629                         exit_cleanup(RERR_STREAMIO);
630                 }
631
632                 buf += n;
633                 len -= n;
634                 cnt += n;
635
636                 if (fd == sock_f_in && io_timeout)
637                         last_io_in = time(NULL);
638         }
639
640         return cnt;
641 }
642
643 /**
644  * Read a line into the "fname" buffer (which must be at least MAXPATHLEN
645  * characters long).
646  */
647 int read_filesfrom_line(int fd, char *fname)
648 {
649         char ch, *s, *eob = fname + MAXPATHLEN - 1;
650         int cnt;
651         int reading_remotely = filesfrom_host != NULL;
652         int nulls = eol_nulls || reading_remotely;
653
654   start:
655         s = fname;
656         while (1) {
657                 cnt = read(fd, &ch, 1);
658                 if (cnt < 0 && (errno == EWOULDBLOCK
659                   || errno == EINTR || errno == EAGAIN)) {
660                         struct timeval tv;
661                         fd_set fds;
662                         FD_ZERO(&fds);
663                         FD_SET(fd, &fds);
664                         tv.tv_sec = select_timeout;
665                         tv.tv_usec = 0;
666                         if (!select(fd+1, &fds, NULL, NULL, &tv))
667                                 check_timeout();
668                         continue;
669                 }
670                 if (cnt != 1)
671                         break;
672                 if (nulls? !ch : (ch == '\r' || ch == '\n')) {
673                         /* Skip empty lines if reading locally. */
674                         if (!reading_remotely && s == fname)
675                                 continue;
676                         break;
677                 }
678                 if (s < eob)
679                         *s++ = ch;
680         }
681         *s = '\0';
682
683         /* Dump comments. */
684         if (*fname == '#' || *fname == ';')
685                 goto start;
686
687         return s - fname;
688 }
689
690 static char *iobuf_out;
691 static int iobuf_out_cnt;
692
693 void io_start_buffering_out(void)
694 {
695         if (iobuf_out)
696                 return;
697         if (!(iobuf_out = new_array(char, IO_BUFFER_SIZE)))
698                 out_of_memory("io_start_buffering_out");
699         iobuf_out_cnt = 0;
700 }
701
702 static char *iobuf_in;
703 static size_t iobuf_in_siz;
704
705 void io_start_buffering_in(void)
706 {
707         if (iobuf_in)
708                 return;
709         iobuf_in_siz = 2 * IO_BUFFER_SIZE;
710         if (!(iobuf_in = new_array(char, iobuf_in_siz)))
711                 out_of_memory("io_start_buffering_in");
712 }
713
714 void io_end_buffering(void)
715 {
716         io_flush(NORMAL_FLUSH);
717         if (!io_multiplexing_out) {
718                 free(iobuf_out);
719                 iobuf_out = NULL;
720         }
721 }
722
723 void maybe_flush_socket(void)
724 {
725         if (iobuf_out && iobuf_out_cnt && time(NULL) - last_io_out >= 5)
726                 io_flush(NORMAL_FLUSH);
727 }
728
729 void maybe_send_keepalive(void)
730 {
731         if (time(NULL) - last_io_out >= allowed_lull) {
732                 if (!iobuf_out || !iobuf_out_cnt) {
733                         if (protocol_version < 29)
734                                 return; /* there's nothing we can do */
735                         write_int(sock_f_out, the_file_list->count);
736                         write_shortint(sock_f_out, ITEM_IS_NEW);
737                 }
738                 if (iobuf_out)
739                         io_flush(NORMAL_FLUSH);
740         }
741 }
742
743 /**
744  * Continue trying to read len bytes - don't return until len has been
745  * read.
746  **/
747 static void read_loop(int fd, char *buf, size_t len)
748 {
749         while (len) {
750                 int n = read_timeout(fd, buf, len);
751
752                 buf += n;
753                 len -= n;
754         }
755 }
756
757 /**
758  * Read from the file descriptor handling multiplexing - return number
759  * of bytes read.
760  *
761  * Never returns <= 0.
762  */
763 static int readfd_unbuffered(int fd, char *buf, size_t len)
764 {
765         static size_t remaining;
766         static size_t iobuf_in_ndx;
767         size_t msg_bytes;
768         int tag, cnt = 0;
769         char line[BIGPATHBUFLEN];
770
771         if (!iobuf_in || fd != sock_f_in)
772                 return read_timeout(fd, buf, len);
773
774         if (!io_multiplexing_in && remaining == 0) {
775                 remaining = read_timeout(fd, iobuf_in, iobuf_in_siz);
776                 iobuf_in_ndx = 0;
777         }
778
779         while (cnt == 0) {
780                 if (remaining) {
781                         len = MIN(len, remaining);
782                         memcpy(buf, iobuf_in + iobuf_in_ndx, len);
783                         iobuf_in_ndx += len;
784                         remaining -= len;
785                         cnt = len;
786                         break;
787                 }
788
789                 read_loop(fd, line, 4);
790                 tag = IVAL(line, 0);
791
792                 msg_bytes = tag & 0xFFFFFF;
793                 tag = (tag >> 24) - MPLEX_BASE;
794
795                 switch (tag) {
796                 case MSG_DATA:
797                         if (msg_bytes > iobuf_in_siz) {
798                                 if (!(iobuf_in = realloc_array(iobuf_in, char,
799                                                                msg_bytes)))
800                                         out_of_memory("readfd_unbuffered");
801                                 iobuf_in_siz = msg_bytes;
802                         }
803                         read_loop(fd, iobuf_in, msg_bytes);
804                         remaining = msg_bytes;
805                         iobuf_in_ndx = 0;
806                         break;
807                 case MSG_DELETED:
808                         if (msg_bytes >= sizeof line)
809                                 goto overflow;
810                         read_loop(fd, line, msg_bytes);
811                         /* A directory name was sent with the trailing null */
812                         if (msg_bytes > 0 && !line[msg_bytes-1])
813                                 log_delete(line, S_IFDIR);
814                         else {
815                                 line[msg_bytes] = '\0';
816                                 log_delete(line, S_IFREG);
817                         }
818                         break;
819                 case MSG_SUCCESS:
820                         if (msg_bytes != 4) {
821                                 rprintf(FERROR, "invalid multi-message %d:%ld [%s]\n",
822                                         tag, (long)msg_bytes, who_am_i());
823                                 exit_cleanup(RERR_STREAMIO);
824                         }
825                         read_loop(fd, line, msg_bytes);
826                         successful_send(IVAL(line, 0));
827                         break;
828                 case MSG_INFO:
829                 case MSG_ERROR:
830                         if (msg_bytes >= sizeof line) {
831                             overflow:
832                                 rprintf(FERROR,
833                                         "multiplexing overflow %d:%ld [%s]\n",
834                                         tag, (long)msg_bytes, who_am_i());
835                                 exit_cleanup(RERR_STREAMIO);
836                         }
837                         read_loop(fd, line, msg_bytes);
838                         rwrite((enum logcode)tag, line, msg_bytes);
839                         break;
840                 default:
841                         rprintf(FERROR, "unexpected tag %d [%s]\n",
842                                 tag, who_am_i());
843                         exit_cleanup(RERR_STREAMIO);
844                 }
845         }
846
847         if (remaining == 0)
848                 io_flush(NORMAL_FLUSH);
849
850         return cnt;
851 }
852
853 /**
854  * Do a buffered read from @p fd.  Don't return until all @p n bytes
855  * have been read.  If all @p n can't be read then exit with an
856  * error.
857  **/
858 static void readfd(int fd, char *buffer, size_t N)
859 {
860         int  cnt;
861         size_t total = 0;
862
863         while (total < N) {
864                 cnt = readfd_unbuffered(fd, buffer + total, N-total);
865                 total += cnt;
866         }
867
868         if (fd == write_batch_monitor_in) {
869                 if ((size_t)write(batch_fd, buffer, total) != total)
870                         exit_cleanup(RERR_FILEIO);
871         }
872
873         if (fd == sock_f_in)
874                 stats.total_read += total;
875 }
876
877 int read_shortint(int f)
878 {
879         uchar b[2];
880         readfd(f, (char *)b, 2);
881         return (b[1] << 8) + b[0];
882 }
883
884 int32 read_int(int f)
885 {
886         char b[4];
887         int32 num;
888
889         readfd(f,b,4);
890         num = IVAL(b,0);
891         if (num == (int32)0xffffffff)
892                 return -1;
893         return num;
894 }
895
896 int64 read_longint(int f)
897 {
898         int64 num;
899         char b[8];
900         num = read_int(f);
901
902         if ((int32)num != (int32)0xffffffff)
903                 return num;
904
905 #if SIZEOF_INT64 < 8
906         rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
907         exit_cleanup(RERR_UNSUPPORTED);
908 #else
909         readfd(f,b,8);
910         num = IVAL(b,0) | (((int64)IVAL(b,4))<<32);
911 #endif
912
913         return num;
914 }
915
916 void read_buf(int f,char *buf,size_t len)
917 {
918         readfd(f,buf,len);
919 }
920
921 void read_sbuf(int f,char *buf,size_t len)
922 {
923         readfd(f, buf, len);
924         buf[len] = '\0';
925 }
926
927 uchar read_byte(int f)
928 {
929         uchar c;
930         readfd(f, (char *)&c, 1);
931         return c;
932 }
933
934 int read_vstring(int f, char *buf, int bufsize)
935 {
936         int len = read_byte(f);
937
938         if (len & 0x80)
939                 len = (len & ~0x80) * 0x100 + read_byte(f);
940
941         if (len >= bufsize) {
942                 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
943                         len, bufsize - 1);
944                 return -1;
945         }
946
947         if (len)
948                 readfd(f, buf, len);
949         buf[len] = '\0';
950         return len;
951 }
952
953 /* Populate a sum_struct with values from the socket.  This is
954  * called by both the sender and the receiver. */
955 void read_sum_head(int f, struct sum_struct *sum)
956 {
957         sum->count = read_int(f);
958         if (sum->count < 0) {
959                 rprintf(FERROR, "Invalid checksum count %ld [%s]\n",
960                         (long)sum->count, who_am_i());
961                 exit_cleanup(RERR_PROTOCOL);
962         }
963         sum->blength = read_int(f);
964         if (sum->blength < 0 || sum->blength > MAX_BLOCK_SIZE) {
965                 rprintf(FERROR, "Invalid block length %ld [%s]\n",
966                         (long)sum->blength, who_am_i());
967                 exit_cleanup(RERR_PROTOCOL);
968         }
969         sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
970         if (sum->s2length < 0 || sum->s2length > MD4_SUM_LENGTH) {
971                 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
972                         sum->s2length, who_am_i());
973                 exit_cleanup(RERR_PROTOCOL);
974         }
975         sum->remainder = read_int(f);
976         if (sum->remainder < 0 || sum->remainder > sum->blength) {
977                 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
978                         (long)sum->remainder, who_am_i());
979                 exit_cleanup(RERR_PROTOCOL);
980         }
981 }
982
983 /* Send the values from a sum_struct over the socket.  Set sum to
984  * NULL if there are no checksums to send.  This is called by both
985  * the generator and the sender. */
986 void write_sum_head(int f, struct sum_struct *sum)
987 {
988         static struct sum_struct null_sum;
989
990         if (sum == NULL)
991                 sum = &null_sum;
992
993         write_int(f, sum->count);
994         write_int(f, sum->blength);
995         if (protocol_version >= 27)
996                 write_int(f, sum->s2length);
997         write_int(f, sum->remainder);
998 }
999
1000 /**
1001  * Sleep after writing to limit I/O bandwidth usage.
1002  *
1003  * @todo Rather than sleeping after each write, it might be better to
1004  * use some kind of averaging.  The current algorithm seems to always
1005  * use a bit less bandwidth than specified, because it doesn't make up
1006  * for slow periods.  But arguably this is a feature.  In addition, we
1007  * ought to take the time used to write the data into account.
1008  *
1009  * During some phases of big transfers (file FOO is uptodate) this is
1010  * called with a small bytes_written every time.  As the kernel has to
1011  * round small waits up to guarantee that we actually wait at least the
1012  * requested number of microseconds, this can become grossly inaccurate.
1013  * We therefore keep track of the bytes we've written over time and only
1014  * sleep when the accumulated delay is at least 1 tenth of a second.
1015  **/
1016 static void sleep_for_bwlimit(int bytes_written)
1017 {
1018         static struct timeval prior_tv;
1019         static long total_written = 0; 
1020         struct timeval tv, start_tv;
1021         long elapsed_usec, sleep_usec;
1022
1023 #define ONE_SEC 1000000L /* # of microseconds in a second */
1024
1025         if (!bwlimit_writemax)
1026                 return;
1027
1028         total_written += bytes_written; 
1029
1030         gettimeofday(&start_tv, NULL);
1031         if (prior_tv.tv_sec) {
1032                 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
1033                              + (start_tv.tv_usec - prior_tv.tv_usec);
1034                 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
1035                 if (total_written < 0)
1036                         total_written = 0;
1037         }
1038
1039         sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1040         if (sleep_usec < ONE_SEC / 10) {
1041                 prior_tv = start_tv;
1042                 return;
1043         }
1044
1045         tv.tv_sec  = sleep_usec / ONE_SEC;
1046         tv.tv_usec = sleep_usec % ONE_SEC;
1047         select(0, NULL, NULL, NULL, &tv);
1048
1049         gettimeofday(&prior_tv, NULL);
1050         elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1051                      + (prior_tv.tv_usec - start_tv.tv_usec);
1052         total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
1053 }
1054
1055 /* Write len bytes to the file descriptor fd, looping as necessary to get
1056  * the job done and also (in certain circumstances) reading any data on
1057  * msg_fd_in to avoid deadlock.
1058  *
1059  * This function underlies the multiplexing system.  The body of the
1060  * application never calls this function directly. */
1061 static void writefd_unbuffered(int fd,char *buf,size_t len)
1062 {
1063         size_t n, total = 0;
1064         fd_set w_fds, r_fds;
1065         int maxfd, count, cnt, using_r_fds;
1066         struct timeval tv;
1067
1068         no_flush++;
1069
1070         while (total < len) {
1071                 FD_ZERO(&w_fds);
1072                 FD_SET(fd,&w_fds);
1073                 maxfd = fd;
1074
1075                 if (msg_fd_in >= 0) {
1076                         FD_ZERO(&r_fds);
1077                         FD_SET(msg_fd_in,&r_fds);
1078                         if (msg_fd_in > maxfd)
1079                                 maxfd = msg_fd_in;
1080                         using_r_fds = 1;
1081                 } else
1082                         using_r_fds = 0;
1083
1084                 tv.tv_sec = select_timeout;
1085                 tv.tv_usec = 0;
1086
1087                 errno = 0;
1088                 count = select(maxfd + 1, using_r_fds ? &r_fds : NULL,
1089                                &w_fds, NULL, &tv);
1090
1091                 if (count <= 0) {
1092                         if (count < 0 && errno == EBADF)
1093                                 exit_cleanup(RERR_SOCKETIO);
1094                         check_timeout();
1095                         continue;
1096                 }
1097
1098                 if (using_r_fds && FD_ISSET(msg_fd_in, &r_fds))
1099                         read_msg_fd();
1100
1101                 if (!FD_ISSET(fd, &w_fds))
1102                         continue;
1103
1104                 if (msg2sndr.head && !defer_forwarding_messages) {
1105                         struct msg_list_item *m = msg2sndr.head;
1106                         int code = *((uchar*)m->buf+3) - MPLEX_BASE;
1107                         if (!(msg2sndr.head = m->next))
1108                                 msg2sndr.tail = NULL;
1109                         defer_forwarding_messages = 1;
1110                         io_multiplex_write(code, m->buf+4, m->len-4);
1111                         defer_forwarding_messages = 0;
1112                         free(m);
1113                         continue;
1114                 }
1115
1116                 n = len - total;
1117                 if (bwlimit_writemax && n > bwlimit_writemax)
1118                         n = bwlimit_writemax;
1119                 cnt = write(fd, buf + total, n);
1120
1121                 if (cnt <= 0) {
1122                         if (cnt < 0) {
1123                                 if (errno == EINTR)
1124                                         continue;
1125                                 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1126                                         msleep(1);
1127                                         continue;
1128                                 }
1129                         }
1130
1131                         /* Don't try to write errors back across the stream. */
1132                         if (fd == sock_f_out)
1133                                 close_multiplexing_out();
1134                         rsyserr(FERROR, errno,
1135                                 "writefd_unbuffered failed to write %ld bytes: phase \"%s\" [%s]",
1136                                 (long)len, io_write_phase, who_am_i());
1137                         /* If the other side is sending us error messages, try
1138                          * to grab any messages they sent before they died. */
1139                         while (fd == sock_f_out && io_multiplexing_in) {
1140                                 set_io_timeout(30);
1141                                 ignore_timeout = 0;
1142                                 readfd_unbuffered(sock_f_in, io_filesfrom_buf,
1143                                                   sizeof io_filesfrom_buf);
1144                         }
1145                         exit_cleanup(RERR_STREAMIO);
1146                 }
1147
1148                 total += cnt;
1149                 defer_forwarding_messages = 1;
1150
1151                 if (fd == sock_f_out) {
1152                         if (io_timeout || am_generator)
1153                                 last_io_out = time(NULL);
1154                         sleep_for_bwlimit(cnt);
1155                 }
1156         }
1157         defer_forwarding_messages = 0;
1158
1159         no_flush--;
1160 }
1161
1162 /**
1163  * Write an message to a multiplexed stream. If this fails then rsync
1164  * exits.
1165  **/
1166 static void mplex_write(enum msgcode code, char *buf, size_t len)
1167 {
1168         char buffer[1024];
1169         size_t n = len;
1170
1171         SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
1172
1173         if (n > sizeof buffer - 4)
1174                 n = 0;
1175         else
1176                 memcpy(buffer + 4, buf, n);
1177
1178         writefd_unbuffered(sock_f_out, buffer, n+4);
1179
1180         len -= n;
1181         buf += n;
1182
1183         if (len)
1184                 writefd_unbuffered(sock_f_out, buf, len);
1185 }
1186
1187 void io_flush(int flush_it_all)
1188 {
1189         msg2genr_flush(flush_it_all);
1190
1191         if (!iobuf_out_cnt || no_flush)
1192                 return;
1193
1194         if (io_multiplexing_out)
1195                 mplex_write(MSG_DATA, iobuf_out, iobuf_out_cnt);
1196         else
1197                 writefd_unbuffered(sock_f_out, iobuf_out, iobuf_out_cnt);
1198         iobuf_out_cnt = 0;
1199 }
1200
1201 static void writefd(int fd,char *buf,size_t len)
1202 {
1203         if (fd == msg_fd_out) {
1204                 rprintf(FERROR, "Internal error: wrong write used in receiver.\n");
1205                 exit_cleanup(RERR_PROTOCOL);
1206         }
1207
1208         if (fd == sock_f_out)
1209                 stats.total_written += len;
1210
1211         if (fd == write_batch_monitor_out) {
1212                 if ((size_t)write(batch_fd, buf, len) != len)
1213                         exit_cleanup(RERR_FILEIO);
1214         }
1215
1216         if (!iobuf_out || fd != sock_f_out) {
1217                 writefd_unbuffered(fd, buf, len);
1218                 return;
1219         }
1220
1221         while (len) {
1222                 int n = MIN((int)len, IO_BUFFER_SIZE - iobuf_out_cnt);
1223                 if (n > 0) {
1224                         memcpy(iobuf_out+iobuf_out_cnt, buf, n);
1225                         buf += n;
1226                         len -= n;
1227                         iobuf_out_cnt += n;
1228                 }
1229
1230                 if (iobuf_out_cnt == IO_BUFFER_SIZE)
1231                         io_flush(NORMAL_FLUSH);
1232         }
1233 }
1234
1235 void write_shortint(int f, int x)
1236 {
1237         uchar b[2];
1238         b[0] = x;
1239         b[1] = x >> 8;
1240         writefd(f, (char *)b, 2);
1241 }
1242
1243 void write_int(int f,int32 x)
1244 {
1245         char b[4];
1246         SIVAL(b,0,x);
1247         writefd(f,b,4);
1248 }
1249
1250 void write_int_named(int f, int32 x, const char *phase)
1251 {
1252         io_write_phase = phase;
1253         write_int(f, x);
1254         io_write_phase = phase_unknown;
1255 }
1256
1257 /*
1258  * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1259  * 64-bit types on this platform.
1260  */
1261 void write_longint(int f, int64 x)
1262 {
1263         char b[8];
1264
1265         if (x <= 0x7FFFFFFF) {
1266                 write_int(f, (int)x);
1267                 return;
1268         }
1269
1270 #if SIZEOF_INT64 < 8
1271         rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1272         exit_cleanup(RERR_UNSUPPORTED);
1273 #else
1274         write_int(f, (int32)0xFFFFFFFF);
1275         SIVAL(b,0,(x&0xFFFFFFFF));
1276         SIVAL(b,4,((x>>32)&0xFFFFFFFF));
1277
1278         writefd(f,b,8);
1279 #endif
1280 }
1281
1282 void write_buf(int f,char *buf,size_t len)
1283 {
1284         writefd(f,buf,len);
1285 }
1286
1287 /** Write a string to the connection */
1288 void write_sbuf(int f, char *buf)
1289 {
1290         writefd(f, buf, strlen(buf));
1291 }
1292
1293 void write_byte(int f, uchar c)
1294 {
1295         writefd(f, (char *)&c, 1);
1296 }
1297
1298 void write_vstring(int f, char *str, int len)
1299 {
1300         uchar lenbuf[3], *lb = lenbuf;
1301
1302         if (len > 0x7F) {
1303                 if (len > 0x7FFF) {
1304                         rprintf(FERROR,
1305                                 "attempting to send over-long vstring (%d > %d)\n",
1306                                 len, 0x7FFF);
1307                         exit_cleanup(RERR_PROTOCOL);
1308                 }
1309                 *lb++ = len / 0x100 + 0x80;
1310         }
1311         *lb = len;
1312
1313         writefd(f, (char*)lenbuf, lb - lenbuf + 1);
1314         if (len)
1315                 writefd(f, str, len);
1316 }
1317
1318 /**
1319  * Read a line of up to @p maxlen characters into @p buf (not counting
1320  * the trailing null).  Strips the (required) trailing newline and all
1321  * carriage returns.
1322  *
1323  * @return 1 for success; 0 for I/O error or truncation.
1324  **/
1325 int read_line(int f, char *buf, size_t maxlen)
1326 {
1327         while (maxlen) {
1328                 buf[0] = 0;
1329                 read_buf(f, buf, 1);
1330                 if (buf[0] == 0)
1331                         return 0;
1332                 if (buf[0] == '\n')
1333                         break;
1334                 if (buf[0] != '\r') {
1335                         buf++;
1336                         maxlen--;
1337                 }
1338         }
1339         *buf = '\0';
1340         return maxlen > 0;
1341 }
1342
1343 void io_printf(int fd, const char *format, ...)
1344 {
1345         va_list ap;
1346         char buf[BIGPATHBUFLEN];
1347         int len;
1348
1349         va_start(ap, format);
1350         len = vsnprintf(buf, sizeof buf, format, ap);
1351         va_end(ap);
1352
1353         if (len < 0)
1354                 exit_cleanup(RERR_STREAMIO);
1355
1356         if (len > (int)sizeof buf) {
1357                 rprintf(FERROR, "io_printf() was too long for the buffer.\n");
1358                 exit_cleanup(RERR_STREAMIO);
1359         }
1360
1361         write_sbuf(fd, buf);
1362 }
1363
1364 /** Setup for multiplexing a MSG_* stream with the data stream. */
1365 void io_start_multiplex_out(void)
1366 {
1367         io_flush(NORMAL_FLUSH);
1368         io_start_buffering_out();
1369         io_multiplexing_out = 1;
1370 }
1371
1372 /** Setup for multiplexing a MSG_* stream with the data stream. */
1373 void io_start_multiplex_in(void)
1374 {
1375         io_flush(NORMAL_FLUSH);
1376         io_start_buffering_in();
1377         io_multiplexing_in = 1;
1378 }
1379
1380 /** Write an message to the multiplexed data stream. */
1381 int io_multiplex_write(enum msgcode code, char *buf, size_t len)
1382 {
1383         if (!io_multiplexing_out)
1384                 return 0;
1385
1386         io_flush(NORMAL_FLUSH);
1387         stats.total_written += (len+4);
1388         mplex_write(code, buf, len);
1389         return 1;
1390 }
1391
1392 void close_multiplexing_in(void)
1393 {
1394         io_multiplexing_in = 0;
1395 }
1396
1397 /** Stop output multiplexing. */
1398 void close_multiplexing_out(void)
1399 {
1400         io_multiplexing_out = 0;
1401 }
1402
1403 void start_write_batch(int fd)
1404 {
1405         write_stream_flags(batch_fd);
1406
1407         /* Some communication has already taken place, but we don't
1408          * enable batch writing until here so that we can write a
1409          * canonical record of the communication even though the
1410          * actual communication so far depends on whether a daemon
1411          * is involved. */
1412         write_int(batch_fd, protocol_version);
1413         write_int(batch_fd, checksum_seed);
1414
1415         if (am_sender)
1416                 write_batch_monitor_out = fd;
1417         else
1418                 write_batch_monitor_in = fd;
1419 }
1420
1421 void stop_write_batch(void)
1422 {
1423         write_batch_monitor_out = -1;
1424         write_batch_monitor_in = -1;
1425 }