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