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