Files with the same size should also be skipped by --append.
[rsync/rsync.git] / io.c
1 /*
2  * Socket and pipe I/O utilities used in rsync.
3  *
4  * Copyright (C) 1996-2001 Andrew Tridgell
5  * Copyright (C) 1996 Paul Mackerras
6  * Copyright (C) 2001, 2002 Martin Pool <mbp@samba.org>
7  * Copyright (C) 2003-2007 Wayne Davison
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License along
20  * with this program; if not, visit the http://fsf.org website.
21  */
22
23 /* Rsync provides its own multiplexing system, which is used to send
24  * stderr and stdout over a single socket.
25  *
26  * For historical reasons this is off during the start of the
27  * connection, but it's switched on quite early using
28  * io_start_multiplex_out() and io_start_multiplex_in(). */
29
30 #include "rsync.h"
31
32 /** If no timeout is specified then use a 60 second select timeout */
33 #define SELECT_TIMEOUT 60
34
35 extern int bwlimit;
36 extern size_t bwlimit_writemax;
37 extern int io_timeout;
38 extern int allowed_lull;
39 extern int am_server;
40 extern int am_daemon;
41 extern int am_sender;
42 extern int am_generator;
43 extern int inc_recurse;
44 extern int io_error;
45 extern int eol_nulls;
46 extern int flist_eof;
47 extern int read_batch;
48 extern int csum_length;
49 extern int checksum_seed;
50 extern int protocol_version;
51 extern int remove_source_files;
52 extern int preserve_hard_links;
53 extern char *filesfrom_host;
54 extern struct stats stats;
55 extern struct file_list *cur_flist, *first_flist;
56 #ifdef ICONV_OPTION
57 extern iconv_t ic_send, ic_recv;
58 #endif
59
60 const char phase_unknown[] = "unknown";
61 int ignore_timeout = 0;
62 int batch_fd = -1;
63 int msgdone_cnt = 0;
64
65 /* Ignore an EOF error if non-zero. See whine_about_eof(). */
66 int kluge_around_eof = 0;
67
68 int msg_fd_in = -1;
69 int msg_fd_out = -1;
70 int sock_f_in = -1;
71 int sock_f_out = -1;
72
73 static int iobuf_f_in = -1;
74 static char *iobuf_in;
75 static size_t iobuf_in_siz;
76 static size_t iobuf_in_ndx;
77 static size_t iobuf_in_remaining;
78
79 static int iobuf_f_out = -1;
80 static char *iobuf_out;
81 static int iobuf_out_cnt;
82
83 int flist_forward_from = -1;
84
85 static int io_multiplexing_out;
86 static int io_multiplexing_in;
87 static time_t last_io_in;
88 static time_t last_io_out;
89 static int no_flush;
90
91 static int write_batch_monitor_in = -1;
92 static int write_batch_monitor_out = -1;
93
94 static int io_filesfrom_f_in = -1;
95 static int io_filesfrom_f_out = -1;
96 static char io_filesfrom_buf[2048];
97 #ifdef ICONV_OPTION
98 static char iconv_buf[sizeof io_filesfrom_buf / 2];
99 #endif
100 static char *io_filesfrom_bp;
101 static char io_filesfrom_lastchar;
102 static int io_filesfrom_buflen;
103 static int defer_forwarding_messages = 0;
104 static int select_timeout = SELECT_TIMEOUT;
105 static int active_filecnt = 0;
106 static OFF_T active_bytecnt = 0;
107
108 static char int_byte_extra[64] = {
109         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* (00 - 3F)/4 */
110         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* (40 - 7F)/4 */
111         1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* (80 - BF)/4 */
112         2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 6, /* (C0 - FF)/4 */
113 };
114
115 static void readfd(int fd, char *buffer, size_t N);
116 static void writefd(int fd, const char *buf, size_t len);
117 static void writefd_unbuffered(int fd, const char *buf, size_t len);
118 static void decrement_active_files(int ndx);
119 static void decrement_flist_in_progress(int ndx, int redo);
120 static void mplex_write(int fd, enum msgcode code, const char *buf, size_t len, int convert);
121
122 struct flist_ndx_item {
123         struct flist_ndx_item *next;
124         int ndx;
125 };
126
127 struct flist_ndx_list {
128         struct flist_ndx_item *head, *tail;
129 };
130
131 static struct flist_ndx_list redo_list, hlink_list;
132
133 struct msg_list_item {
134         struct msg_list_item *next;
135         char convert;
136         char buf[1];
137 };
138
139 struct msg_list {
140         struct msg_list_item *head, *tail;
141 };
142
143 static struct msg_list msg_queue;
144
145 static void flist_ndx_push(struct flist_ndx_list *lp, int ndx)
146 {
147         struct flist_ndx_item *item;
148
149         if (!(item = new(struct flist_ndx_item)))
150                 out_of_memory("flist_ndx_push");
151         item->next = NULL;
152         item->ndx = ndx;
153         if (lp->tail)
154                 lp->tail->next = item;
155         else
156                 lp->head = item;
157         lp->tail = item;
158 }
159
160 static int flist_ndx_pop(struct flist_ndx_list *lp)
161 {
162         struct flist_ndx_item *next;
163         int ndx;
164
165         if (!lp->head)
166                 return -1;
167
168         ndx = lp->head->ndx;
169         next = lp->head->next;
170         free(lp->head);
171         lp->head = next;
172         if (!next)
173                 lp->tail = NULL;
174
175         return ndx;
176 }
177
178 static void check_timeout(void)
179 {
180         time_t t;
181
182         if (!io_timeout || ignore_timeout)
183                 return;
184
185         if (!last_io_in) {
186                 last_io_in = time(NULL);
187                 return;
188         }
189
190         t = time(NULL);
191
192         if (t - last_io_in >= io_timeout) {
193                 if (!am_server && !am_daemon) {
194                         rprintf(FERROR, "io timeout after %d seconds -- exiting\n",
195                                 (int)(t-last_io_in));
196                 }
197                 exit_cleanup(RERR_TIMEOUT);
198         }
199 }
200
201 /* Note the fds used for the main socket (which might really be a pipe
202  * for a local transfer, but we can ignore that). */
203 void io_set_sock_fds(int f_in, int f_out)
204 {
205         sock_f_in = f_in;
206         sock_f_out = f_out;
207 }
208
209 void set_io_timeout(int secs)
210 {
211         io_timeout = secs;
212
213         if (!io_timeout || io_timeout > SELECT_TIMEOUT)
214                 select_timeout = SELECT_TIMEOUT;
215         else
216                 select_timeout = io_timeout;
217
218         allowed_lull = read_batch ? 0 : (io_timeout + 1) / 2;
219 }
220
221 /* Setup the fd used to receive MSG_* messages.  Only needed during the
222  * early stages of being a local sender (up through the sending of the
223  * file list) or when we're the generator (to fetch the messages from
224  * the receiver). */
225 void set_msg_fd_in(int fd)
226 {
227         msg_fd_in = fd;
228 }
229
230 /* Setup the fd used to send our MSG_* messages.  Only needed when
231  * we're the receiver (to send our messages to the generator). */
232 void set_msg_fd_out(int fd)
233 {
234         msg_fd_out = fd;
235         set_nonblocking(msg_fd_out);
236 }
237
238 /* Add a message to the pending MSG_* list. */
239 static void msg_list_add(struct msg_list *lst, int code, const char *buf, int len, int convert)
240 {
241         struct msg_list_item *m;
242         int sz = len + 4 + sizeof m[0] - 1;
243
244         if (!(m = (struct msg_list_item *)new_array(char, sz)))
245                 out_of_memory("msg_list_add");
246         m->next = NULL;
247         m->convert = convert;
248         SIVAL(m->buf, 0, ((code+MPLEX_BASE)<<24) | len);
249         memcpy(m->buf + 4, buf, len);
250         if (lst->tail)
251                 lst->tail->next = m;
252         else
253                 lst->head = m;
254         lst->tail = m;
255 }
256
257 static void msg_flush(void)
258 {
259         if (am_generator) {
260                 while (msg_queue.head && io_multiplexing_out) {
261                         struct msg_list_item *m = msg_queue.head;
262                         int len = IVAL(m->buf, 0) & 0xFFFFFF;
263                         int tag = *((uchar*)m->buf+3) - MPLEX_BASE;
264                         if (!(msg_queue.head = m->next))
265                                 msg_queue.tail = NULL;
266                         stats.total_written += len + 4;
267                         defer_forwarding_messages++;
268                         mplex_write(sock_f_out, tag, m->buf + 4, len, m->convert);
269                         defer_forwarding_messages--;
270                         free(m);
271                 }
272         } else {
273                 while (msg_queue.head) {
274                         struct msg_list_item *m = msg_queue.head;
275                         int len = IVAL(m->buf, 0) & 0xFFFFFF;
276                         int tag = *((uchar*)m->buf+3) - MPLEX_BASE;
277                         if (!(msg_queue.head = m->next))
278                                 msg_queue.tail = NULL;
279                         defer_forwarding_messages++;
280                         mplex_write(msg_fd_out, tag, m->buf + 4, len, m->convert);
281                         defer_forwarding_messages--;
282                         free(m);
283                 }
284         }
285 }
286
287 /* Read a message from the MSG_* fd and handle it.  This is called either
288  * during the early stages of being a local sender (up through the sending
289  * of the file list) or when we're the generator (to fetch the messages
290  * from the receiver). */
291 static void read_msg_fd(void)
292 {
293         char buf[2048];
294         size_t n;
295         struct file_list *flist;
296         int fd = msg_fd_in;
297         int tag, len;
298
299         /* Temporarily disable msg_fd_in.  This is needed to avoid looping back
300          * to this routine from writefd_unbuffered(). */
301         no_flush++;
302         msg_fd_in = -1;
303         defer_forwarding_messages++;
304
305         readfd(fd, buf, 4);
306         tag = IVAL(buf, 0);
307
308         len = tag & 0xFFFFFF;
309         tag = (tag >> 24) - MPLEX_BASE;
310
311         switch (tag) {
312         case MSG_DONE:
313                 if (len < 0 || len > 1 || !am_generator) {
314                   invalid_msg:
315                         rprintf(FERROR, "invalid message %d:%d [%s%s]\n",
316                                 tag, len, who_am_i(),
317                                 inc_recurse ? "/inc" : "");
318                         exit_cleanup(RERR_STREAMIO);
319                 }
320                 if (len) {
321                         readfd(fd, buf, len);
322                         stats.total_read = read_varlong(fd, 3);
323                 }
324                 msgdone_cnt++;
325                 break;
326         case MSG_REDO:
327                 if (len != 4 || !am_generator)
328                         goto invalid_msg;
329                 readfd(fd, buf, 4);
330                 if (remove_source_files)
331                         decrement_active_files(IVAL(buf,0));
332                 flist_ndx_push(&redo_list, IVAL(buf,0));
333                 if (inc_recurse)
334                         decrement_flist_in_progress(IVAL(buf,0), 1);
335                 break;
336         case MSG_FLIST:
337                 if (len != 4 || !am_generator || !inc_recurse)
338                         goto invalid_msg;
339                 readfd(fd, buf, 4);
340                 /* Read extra file list from receiver. */
341                 assert(iobuf_in != NULL);
342                 assert(iobuf_f_in == fd);
343                 if (verbose > 3) {
344                         rprintf(FINFO, "[%s] receiving flist for dir %d\n",
345                                 who_am_i(), IVAL(buf,0));
346                 }
347                 flist = recv_file_list(fd);
348                 flist->parent_ndx = IVAL(buf,0);
349                 break;
350         case MSG_FLIST_EOF:
351                 if (len != 0 || !am_generator || !inc_recurse)
352                         goto invalid_msg;
353                 flist_eof = 1;
354                 break;
355         case MSG_DELETED:
356                 if (len >= (int)sizeof buf || !am_generator)
357                         goto invalid_msg;
358                 readfd(fd, buf, len);
359                 send_msg(MSG_DELETED, buf, len, 1);
360                 break;
361         case MSG_SUCCESS:
362                 if (len != 4 || !am_generator)
363                         goto invalid_msg;
364                 readfd(fd, buf, len);
365                 if (remove_source_files) {
366                         decrement_active_files(IVAL(buf,0));
367                         send_msg(MSG_SUCCESS, buf, len, 0);
368                 }
369                 if (preserve_hard_links)
370                         flist_ndx_push(&hlink_list, IVAL(buf,0));
371                 if (inc_recurse)
372                         decrement_flist_in_progress(IVAL(buf,0), 0);
373                 break;
374         case MSG_NO_SEND:
375                 if (len != 4 || !am_generator)
376                         goto invalid_msg;
377                 readfd(fd, buf, len);
378                 if (inc_recurse)
379                         decrement_flist_in_progress(IVAL(buf,0), 0);
380                 break;
381         case MSG_SOCKERR:
382         case MSG_CLIENT:
383                 if (!am_generator)
384                         goto invalid_msg;
385                 if (tag == MSG_SOCKERR)
386                         io_end_multiplex_out();
387                 /* FALL THROUGH */
388         case MSG_INFO:
389         case MSG_ERROR:
390         case MSG_LOG:
391                 while (len) {
392                         n = len;
393                         if (n >= sizeof buf)
394                                 n = sizeof buf - 1;
395                         readfd(fd, buf, n);
396                         rwrite((enum logcode)tag, buf, n, !am_generator);
397                         len -= n;
398                 }
399                 break;
400         default:
401                 rprintf(FERROR, "unknown message %d:%d [%s]\n",
402                         tag, len, who_am_i());
403                 exit_cleanup(RERR_STREAMIO);
404         }
405
406         no_flush--;
407         msg_fd_in = fd;
408         if (!--defer_forwarding_messages)
409                 msg_flush();
410 }
411
412 /* This is used by the generator to limit how many file transfers can
413  * be active at once when --remove-source-files is specified.  Without
414  * this, sender-side deletions were mostly happening at the end. */
415 void increment_active_files(int ndx, int itemizing, enum logcode code)
416 {
417         /* TODO: tune these limits? */
418         while (active_filecnt >= (active_bytecnt >= 128*1024 ? 10 : 50)) {
419                 check_for_finished_files(itemizing, code, 0);
420                 if (iobuf_out_cnt)
421                         io_flush(NORMAL_FLUSH);
422                 else
423                         read_msg_fd();
424         }
425
426         active_filecnt++;
427         active_bytecnt += F_LENGTH(cur_flist->files[ndx - cur_flist->ndx_start]);
428 }
429
430 static void decrement_active_files(int ndx)
431 {
432         struct file_list *flist = flist_for_ndx(ndx);
433         assert(flist != NULL);
434         active_filecnt--;
435         active_bytecnt -= F_LENGTH(flist->files[ndx - flist->ndx_start]);
436 }
437
438 static void decrement_flist_in_progress(int ndx, int redo)
439 {
440         struct file_list *flist = cur_flist ? cur_flist : first_flist;
441
442         while (ndx < flist->ndx_start) {
443                 if (flist == first_flist) {
444                   invalid_ndx:
445                         rprintf(FERROR,
446                                 "Invalid file index: %d (%d - %d) [%s]\n",
447                                 ndx, first_flist->ndx_start,
448                                 first_flist->prev->ndx_end,
449                                 who_am_i());
450                         exit_cleanup(RERR_PROTOCOL);
451                 }
452                 flist = flist->prev;
453         }
454         while (ndx > flist->ndx_end) {
455                 if (!(flist = flist->next))
456                         goto invalid_ndx;
457         }
458
459         flist->in_progress--;
460         if (redo)
461                 flist->to_redo++;
462 }
463
464 /* Write an message to a multiplexed stream. If this fails, rsync exits. */
465 static void mplex_write(int fd, enum msgcode code, const char *buf, size_t len, int convert)
466 {
467         char buffer[BIGPATHBUFLEN]; /* Oversized for use by iconv code. */
468         size_t n = len;
469
470         SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
471
472 #ifdef ICONV_OPTION
473         if (convert && ic_send == (iconv_t)-1)
474 #endif
475                 convert = 0;
476
477         if (convert || n > 1024 - 4) /* BIGPATHBUFLEN can handle 1024 bytes */
478                 n = 0;
479         else
480                 memcpy(buffer + 4, buf, n);
481
482         writefd_unbuffered(fd, buffer, n+4);
483
484         len -= n;
485         buf += n;
486
487 #ifdef ICONV_OPTION
488         if (convert) {
489                 iconv(ic_send, NULL, 0, NULL, 0);
490                 defer_forwarding_messages++;
491                 while (len) {
492                         ICONV_CONST char *ibuf = (ICONV_CONST char *)buf;
493                         char *obuf = buffer;
494                         size_t ocnt = sizeof buffer;
495                         while (len && iconv(ic_send, &ibuf,&len,
496                                             &obuf,&ocnt) == (size_t)-1) {
497                                 if (errno == E2BIG || !ocnt)
498                                         break;
499                                 *obuf++ = *ibuf++;
500                                 ocnt--, len--;
501                         }
502                         n = obuf - buffer;
503                         writefd_unbuffered(fd, buffer, n);
504                 }
505                 if (!--defer_forwarding_messages)
506                         msg_flush();
507         } else
508 #endif
509         if (len) {
510                 defer_forwarding_messages++;
511                 writefd_unbuffered(fd, buf, len);
512                 if (!--defer_forwarding_messages)
513                         msg_flush();
514         }
515 }
516
517 int send_msg(enum msgcode code, const char *buf, int len, int convert)
518 {
519         if (msg_fd_out < 0) {
520                 if (!defer_forwarding_messages)
521                         return io_multiplex_write(code, buf, len, convert);
522                 if (!io_multiplexing_out)
523                         return 0;
524                 msg_list_add(&msg_queue, code, buf, len, convert);
525                 return 1;
526         }
527         if (flist_forward_from >= 0)
528                 msg_list_add(&msg_queue, code, buf, len, convert);
529         else
530                 mplex_write(msg_fd_out, code, buf, len, convert);
531         return 1;
532 }
533
534 void send_msg_int(enum msgcode code, int num)
535 {
536         char numbuf[4];
537         SIVAL(numbuf, 0, num);
538         send_msg(code, numbuf, 4, 0);
539 }
540
541 void wait_for_receiver(void)
542 {
543         if (iobuf_out_cnt)
544                 io_flush(NORMAL_FLUSH);
545         else
546                 read_msg_fd();
547 }
548
549 int get_redo_num(void)
550 {
551         return flist_ndx_pop(&redo_list);
552 }
553
554 int get_hlink_num(void)
555 {
556         return flist_ndx_pop(&hlink_list);
557 }
558
559 /**
560  * When we're the receiver and we have a local --files-from list of names
561  * that needs to be sent over the socket to the sender, we have to do two
562  * things at the same time: send the sender a list of what files we're
563  * processing and read the incoming file+info list from the sender.  We do
564  * this by augmenting the read_timeout() function to copy this data.  It
565  * uses the io_filesfrom_buf to read a block of data from f_in (when it is
566  * ready, since it might be a pipe) and then blast it out f_out (when it
567  * is ready to receive more data).
568  */
569 void io_set_filesfrom_fds(int f_in, int f_out)
570 {
571         io_filesfrom_f_in = f_in;
572         io_filesfrom_f_out = f_out;
573         io_filesfrom_bp = io_filesfrom_buf;
574         io_filesfrom_lastchar = '\0';
575         io_filesfrom_buflen = 0;
576 }
577
578 /* It's almost always an error to get an EOF when we're trying to read from the
579  * network, because the protocol is (for the most part) self-terminating.
580  *
581  * There is one case for the receiver when it is at the end of the transfer
582  * (hanging around reading any keep-alive packets that might come its way): if
583  * the sender dies before the generator's kill-signal comes through, we can end
584  * up here needing to loop until the kill-signal arrives.  In this situation,
585  * kluge_around_eof will be < 0.
586  *
587  * There is another case for older protocol versions (< 24) where the module
588  * listing was not terminated, so we must ignore an EOF error in that case and
589  * exit.  In this situation, kluge_around_eof will be > 0. */
590 static void whine_about_eof(int fd)
591 {
592         if (kluge_around_eof && fd == sock_f_in) {
593                 int i;
594                 if (kluge_around_eof > 0)
595                         exit_cleanup(0);
596                 /* If we're still here after 10 seconds, exit with an error. */
597                 for (i = 10*1000/20; i--; )
598                         msleep(20);
599         }
600
601         rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
602                 "(%.0f bytes received so far) [%s]\n",
603                 (double)stats.total_read, who_am_i());
604
605         exit_cleanup(RERR_STREAMIO);
606 }
607
608 /**
609  * Read from a socket with I/O timeout. return the number of bytes
610  * read. If no bytes can be read then exit, never return a number <= 0.
611  *
612  * TODO: If the remote shell connection fails, then current versions
613  * actually report an "unexpected EOF" error here.  Since it's a
614  * fairly common mistake to try to use rsh when ssh is required, we
615  * should trap that: if we fail to read any data at all, we should
616  * give a better explanation.  We can tell whether the connection has
617  * started by looking e.g. at whether the remote version is known yet.
618  */
619 static int read_timeout(int fd, char *buf, size_t len)
620 {
621         int n, cnt = 0;
622
623         io_flush(FULL_FLUSH);
624
625         while (cnt == 0) {
626                 /* until we manage to read *something* */
627                 fd_set r_fds, w_fds;
628                 struct timeval tv;
629                 int maxfd = fd;
630                 int count;
631
632                 FD_ZERO(&r_fds);
633                 FD_ZERO(&w_fds);
634                 FD_SET(fd, &r_fds);
635                 if (io_filesfrom_f_out >= 0) {
636                         int new_fd;
637                         if (io_filesfrom_buflen == 0) {
638                                 if (io_filesfrom_f_in >= 0) {
639                                         FD_SET(io_filesfrom_f_in, &r_fds);
640                                         new_fd = io_filesfrom_f_in;
641                                 } else {
642                                         io_filesfrom_f_out = -1;
643                                         new_fd = -1;
644                                 }
645                         } else {
646                                 FD_SET(io_filesfrom_f_out, &w_fds);
647                                 new_fd = io_filesfrom_f_out;
648                         }
649                         if (new_fd > maxfd)
650                                 maxfd = new_fd;
651                 }
652
653                 tv.tv_sec = select_timeout;
654                 tv.tv_usec = 0;
655
656                 errno = 0;
657
658                 count = select(maxfd + 1, &r_fds, &w_fds, NULL, &tv);
659
660                 if (count <= 0) {
661                         if (errno == EBADF) {
662                                 defer_forwarding_messages = 0;
663                                 exit_cleanup(RERR_SOCKETIO);
664                         }
665                         check_timeout();
666                         continue;
667                 }
668
669                 if (io_filesfrom_f_out >= 0) {
670                         if (io_filesfrom_buflen) {
671                                 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
672                                         int l = write(io_filesfrom_f_out,
673                                                       io_filesfrom_bp,
674                                                       io_filesfrom_buflen);
675                                         if (l > 0) {
676                                                 if (!(io_filesfrom_buflen -= l))
677                                                         io_filesfrom_bp = io_filesfrom_buf;
678                                                 else
679                                                         io_filesfrom_bp += l;
680                                         } else if (errno != EINTR) {
681                                                 /* XXX should we complain? */
682                                                 io_filesfrom_f_out = -1;
683                                         }
684                                 }
685                         } else if (io_filesfrom_f_in >= 0) {
686                                 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
687                                         int l = read(io_filesfrom_f_in,
688                                                      io_filesfrom_buf,
689                                                      sizeof io_filesfrom_buf);
690                                         if (l <= 0) {
691                                                 if (l == 0 || errno != EINTR) {
692                                                         /* Send end-of-file marker */
693                                                         io_filesfrom_buf[0] = '\0';
694                                                         io_filesfrom_buf[1] = '\0';
695                                                         io_filesfrom_buflen = io_filesfrom_lastchar? 2 : 1;
696                                                         io_filesfrom_f_in = -1;
697                                                 }
698                                         } else {
699                                                 if (!eol_nulls) {
700                                                         char *s = io_filesfrom_buf + l;
701                                                         /* Transform CR and/or LF into '\0' */
702                                                         while (s-- > io_filesfrom_buf) {
703                                                                 if (*s == '\n' || *s == '\r')
704                                                                         *s = '\0';
705                                                         }
706                                                 }
707                                                 if (!io_filesfrom_lastchar) {
708                                                         /* Last buf ended with a '\0', so don't
709                                                          * let this buf start with one. */
710                                                         while (l && !*io_filesfrom_bp)
711                                                                 io_filesfrom_bp++, l--;
712                                                 }
713                                                 if (!l)
714                                                         io_filesfrom_bp = io_filesfrom_buf;
715                                                 else {
716                                                         char *f = io_filesfrom_bp;
717                                                         char *t = f;
718                                                         char *eob = f + l;
719                                                         /* Eliminate any multi-'\0' runs. */
720                                                         while (f != eob) {
721                                                                 if (!(*t++ = *f++)) {
722                                                                         while (f != eob && !*f)
723                                                                                 f++, l--;
724                                                                 }
725                                                         }
726                                                         io_filesfrom_lastchar = f[-1];
727                                                 }
728                                                 io_filesfrom_buflen = l;
729                                         }
730                                 }
731                         }
732                 }
733
734                 if (!FD_ISSET(fd, &r_fds))
735                         continue;
736
737                 n = read(fd, buf, len);
738
739                 if (n <= 0) {
740                         if (n == 0)
741                                 whine_about_eof(fd); /* Doesn't return. */
742                         if (errno == EINTR || errno == EWOULDBLOCK
743                             || errno == EAGAIN)
744                                 continue;
745
746                         /* Don't write errors on a dead socket. */
747                         if (fd == sock_f_in) {
748                                 io_end_multiplex_out();
749                                 rsyserr(FSOCKERR, errno, "read error");
750                         } else
751                                 rsyserr(FERROR, errno, "read error");
752                         exit_cleanup(RERR_STREAMIO);
753                 }
754
755                 buf += n;
756                 len -= n;
757                 cnt += n;
758
759                 if (fd == sock_f_in && io_timeout)
760                         last_io_in = time(NULL);
761         }
762
763         return cnt;
764 }
765
766 /* Read a line into the "fname" buffer (which must be at least MAXPATHLEN
767  * characters long). */
768 int read_filesfrom_line(int fd, char *fname)
769 {
770         char ch, *s, *eob = fname + MAXPATHLEN - 1;
771         int cnt;
772         int reading_remotely = filesfrom_host != NULL;
773         int nulls = eol_nulls || reading_remotely;
774
775   start:
776         s = fname;
777         while (1) {
778                 cnt = read(fd, &ch, 1);
779                 if (cnt < 0 && (errno == EWOULDBLOCK
780                   || errno == EINTR || errno == EAGAIN)) {
781                         struct timeval tv;
782                         fd_set r_fds, e_fds;
783                         FD_ZERO(&r_fds);
784                         FD_SET(fd, &r_fds);
785                         FD_ZERO(&e_fds);
786                         FD_SET(fd, &e_fds);
787                         tv.tv_sec = select_timeout;
788                         tv.tv_usec = 0;
789                         if (!select(fd+1, &r_fds, NULL, &e_fds, &tv))
790                                 check_timeout();
791                         if (FD_ISSET(fd, &e_fds)) {
792                                 rsyserr(FINFO, errno,
793                                         "select exception on fd %d", fd);
794                         }
795                         continue;
796                 }
797                 if (cnt != 1)
798                         break;
799                 if (nulls? !ch : (ch == '\r' || ch == '\n')) {
800                         /* Skip empty lines if reading locally. */
801                         if (!reading_remotely && s == fname)
802                                 continue;
803                         break;
804                 }
805                 if (s < eob)
806                         *s++ = ch;
807         }
808         *s = '\0';
809
810         /* Dump comments. */
811         if (*fname == '#' || *fname == ';')
812                 goto start;
813
814         return s - fname;
815 }
816
817 int io_start_buffering_out(int f_out)
818 {
819         if (iobuf_out) {
820                 assert(f_out == iobuf_f_out);
821                 return 0;
822         }
823         if (!(iobuf_out = new_array(char, IO_BUFFER_SIZE)))
824                 out_of_memory("io_start_buffering_out");
825         iobuf_out_cnt = 0;
826         iobuf_f_out = f_out;
827         return 1;
828 }
829
830 int io_start_buffering_in(int f_in)
831 {
832         if (iobuf_in) {
833                 assert(f_in == iobuf_f_in);
834                 return 0;
835         }
836         iobuf_in_siz = 2 * IO_BUFFER_SIZE;
837         if (!(iobuf_in = new_array(char, iobuf_in_siz)))
838                 out_of_memory("io_start_buffering_in");
839         iobuf_f_in = f_in;
840         return 1;
841 }
842
843 void io_end_buffering_in(void)
844 {
845         if (!iobuf_in)
846                 return;
847         free(iobuf_in);
848         iobuf_in = NULL;
849         iobuf_in_ndx = 0;
850         iobuf_in_remaining = 0;
851         iobuf_f_in = -1;
852 }
853
854 void io_end_buffering_out(void)
855 {
856         if (!iobuf_out)
857                 return;
858         io_flush(FULL_FLUSH);
859         free(iobuf_out);
860         iobuf_out = NULL;
861         iobuf_f_out = -1;
862 }
863
864 void maybe_flush_socket(int important)
865 {
866         if (iobuf_out && iobuf_out_cnt
867          && (important || time(NULL) - last_io_out >= 5))
868                 io_flush(NORMAL_FLUSH);
869 }
870
871 void maybe_send_keepalive(void)
872 {
873         if (time(NULL) - last_io_out >= allowed_lull) {
874                 if (!iobuf_out || !iobuf_out_cnt) {
875                         if (protocol_version < 29)
876                                 return; /* there's nothing we can do */
877                         if (protocol_version >= 30)
878                                 send_msg(MSG_NOOP, "", 0, 0);
879                         else {
880                                 write_int(sock_f_out, cur_flist->used);
881                                 write_shortint(sock_f_out, ITEM_IS_NEW);
882                         }
883                 }
884                 if (iobuf_out)
885                         io_flush(NORMAL_FLUSH);
886         }
887 }
888
889 void start_flist_forward(int f_in)
890 {
891         assert(iobuf_out != NULL);
892         assert(iobuf_f_out == msg_fd_out);
893         flist_forward_from = f_in;
894 }
895
896 void stop_flist_forward()
897 {
898         flist_forward_from = -1;
899         io_flush(FULL_FLUSH);
900 }
901
902 /**
903  * Continue trying to read len bytes - don't return until len has been
904  * read.
905  **/
906 static void read_loop(int fd, char *buf, size_t len)
907 {
908         while (len) {
909                 int n = read_timeout(fd, buf, len);
910
911                 buf += n;
912                 len -= n;
913         }
914 }
915
916 /**
917  * Read from the file descriptor handling multiplexing - return number
918  * of bytes read.
919  *
920  * Never returns <= 0.
921  */
922 static int readfd_unbuffered(int fd, char *buf, size_t len)
923 {
924         size_t msg_bytes;
925         int tag, cnt = 0;
926         char line[BIGPATHBUFLEN];
927
928         if (!iobuf_in || fd != iobuf_f_in)
929                 return read_timeout(fd, buf, len);
930
931         if (!io_multiplexing_in && iobuf_in_remaining == 0) {
932                 iobuf_in_remaining = read_timeout(fd, iobuf_in, iobuf_in_siz);
933                 iobuf_in_ndx = 0;
934         }
935
936         while (cnt == 0) {
937                 if (iobuf_in_remaining) {
938                         len = MIN(len, iobuf_in_remaining);
939                         memcpy(buf, iobuf_in + iobuf_in_ndx, len);
940                         iobuf_in_ndx += len;
941                         iobuf_in_remaining -= len;
942                         cnt = len;
943                         break;
944                 }
945
946                 read_loop(fd, line, 4);
947                 tag = IVAL(line, 0);
948
949                 msg_bytes = tag & 0xFFFFFF;
950                 tag = (tag >> 24) - MPLEX_BASE;
951
952                 switch (tag) {
953                 case MSG_DATA:
954                         if (msg_bytes > iobuf_in_siz) {
955                                 if (!(iobuf_in = realloc_array(iobuf_in, char,
956                                                                msg_bytes)))
957                                         out_of_memory("readfd_unbuffered");
958                                 iobuf_in_siz = msg_bytes;
959                         }
960                         read_loop(fd, iobuf_in, msg_bytes);
961                         iobuf_in_remaining = msg_bytes;
962                         iobuf_in_ndx = 0;
963                         break;
964                 case MSG_NOOP:
965                         if (am_sender)
966                                 maybe_send_keepalive();
967                         break;
968                 case MSG_IO_ERROR:
969                         if (msg_bytes != 4)
970                                 goto invalid_msg;
971                         read_loop(fd, line, msg_bytes);
972                         io_error |= IVAL(line, 0);
973                         break;
974                 case MSG_DELETED:
975                         if (msg_bytes >= sizeof line)
976                                 goto overflow;
977 #ifdef ICONV_OPTION
978                         if (ic_recv != (iconv_t)-1) {
979                                 ICONV_CONST char *ibuf;
980                                 char *obuf = line;
981                                 size_t icnt, ocnt = sizeof line - 1;
982                                 int add_null = 0;
983                                 iconv(ic_send, NULL, 0, NULL, 0);
984                                 while (msg_bytes) {
985                                         icnt = msg_bytes > sizeof iconv_buf
986                                              ? sizeof iconv_buf : msg_bytes;
987                                         read_loop(fd, iconv_buf, icnt);
988                                         if (!(msg_bytes -= icnt) && !iconv_buf[icnt-1])
989                                                 icnt--, add_null = 1;
990                                         ibuf = (ICONV_CONST char *)iconv_buf;
991                                         if (iconv(ic_send, &ibuf,&icnt,
992                                                   &obuf,&ocnt) == (size_t)-1)
993                                                 goto overflow; // XXX
994                                 }
995                                 if (add_null)
996                                         *obuf++ = '\0';
997                                 msg_bytes = obuf - line;
998                         } else
999 #endif
1000                                 read_loop(fd, line, msg_bytes);
1001                         /* A directory name was sent with the trailing null */
1002                         if (msg_bytes > 0 && !line[msg_bytes-1])
1003                                 log_delete(line, S_IFDIR);
1004                         else {
1005                                 line[msg_bytes] = '\0';
1006                                 log_delete(line, S_IFREG);
1007                         }
1008                         break;
1009                 case MSG_SUCCESS:
1010                         if (msg_bytes != 4) {
1011                           invalid_msg:
1012                                 rprintf(FERROR, "invalid multi-message %d:%ld [%s]\n",
1013                                         tag, (long)msg_bytes, who_am_i());
1014                                 exit_cleanup(RERR_STREAMIO);
1015                         }
1016                         read_loop(fd, line, msg_bytes);
1017                         successful_send(IVAL(line, 0));
1018                         break;
1019                 case MSG_NO_SEND:
1020                         if (msg_bytes != 4)
1021                                 goto invalid_msg;
1022                         read_loop(fd, line, msg_bytes);
1023                         send_msg_int(MSG_NO_SEND, IVAL(line, 0));
1024                         break;
1025                 case MSG_INFO:
1026                 case MSG_ERROR:
1027                         if (msg_bytes >= sizeof line) {
1028                             overflow:
1029                                 rprintf(FERROR,
1030                                         "multiplexing overflow %d:%ld [%s]\n",
1031                                         tag, (long)msg_bytes, who_am_i());
1032                                 exit_cleanup(RERR_STREAMIO);
1033                         }
1034                         read_loop(fd, line, msg_bytes);
1035                         rwrite((enum logcode)tag, line, msg_bytes, 1);
1036                         break;
1037                 default:
1038                         rprintf(FERROR, "unexpected tag %d [%s]\n",
1039                                 tag, who_am_i());
1040                         exit_cleanup(RERR_STREAMIO);
1041                 }
1042         }
1043
1044         if (iobuf_in_remaining == 0)
1045                 io_flush(NORMAL_FLUSH);
1046
1047         return cnt;
1048 }
1049
1050 /* Do a buffered read from fd.  Don't return until all N bytes have
1051  * been read.  If all N can't be read then exit with an error. */
1052 static void readfd(int fd, char *buffer, size_t N)
1053 {
1054         int  cnt;
1055         size_t total = 0;
1056
1057         while (total < N) {
1058                 cnt = readfd_unbuffered(fd, buffer + total, N-total);
1059                 total += cnt;
1060         }
1061
1062         if (fd == write_batch_monitor_in) {
1063                 if ((size_t)write(batch_fd, buffer, total) != total)
1064                         exit_cleanup(RERR_FILEIO);
1065         }
1066
1067         if (fd == flist_forward_from)
1068                 writefd(iobuf_f_out, buffer, total);
1069
1070         if (fd == sock_f_in)
1071                 stats.total_read += total;
1072 }
1073
1074 unsigned short read_shortint(int f)
1075 {
1076         char b[2];
1077         readfd(f, b, 2);
1078         return (UVAL(b, 1) << 8) + UVAL(b, 0);
1079 }
1080
1081 int32 read_int(int f)
1082 {
1083         char b[4];
1084         int32 num;
1085
1086         readfd(f, b, 4);
1087         num = IVAL(b, 0);
1088 #if SIZEOF_INT32 > 4
1089         if (num & (int32)0x80000000)
1090                 num |= ~(int32)0xffffffff;
1091 #endif
1092         return num;
1093 }
1094
1095 int32 read_varint(int f)
1096 {
1097         union {
1098             char b[5];
1099             int32 x;
1100         } u;
1101         uchar ch;
1102         int extra;
1103
1104         u.x = 0;
1105         readfd(f, (char*)&ch, 1);
1106         extra = int_byte_extra[ch / 4];
1107         if (extra) {
1108                 uchar bit = ((uchar)1<<(8-extra));
1109                 if (extra >= (int)sizeof u.b) {
1110                         rprintf(FERROR, "Overflow in read_varint()\n");
1111                         exit_cleanup(RERR_STREAMIO);
1112                 }
1113                 readfd(f, u.b, extra);
1114                 u.b[extra] = ch & (bit-1);
1115         } else
1116                 u.b[0] = ch;
1117 #if CAREFUL_ALIGNMENT
1118         u.x = IVAL(u.b,0);
1119 #endif
1120 #if SIZEOF_INT32 > 4
1121         if (u.x & (int32)0x80000000)
1122                 u.x |= ~(int32)0xffffffff;
1123 #endif
1124         return u.x;
1125 }
1126
1127 int64 read_varlong(int f, uchar min_bytes)
1128 {
1129         union {
1130             char b[9];
1131             int64 x;
1132         } u;
1133         char b2[8];
1134         int extra;
1135
1136 #if SIZEOF_INT64 < 8
1137         memset(u.b, 0, 8);
1138 #else
1139         u.x = 0;
1140 #endif
1141         readfd(f, b2, min_bytes);
1142         memcpy(u.b, b2+1, min_bytes-1);
1143         extra = int_byte_extra[CVAL(b2, 0) / 4];
1144         if (extra) {
1145                 uchar bit = ((uchar)1<<(8-extra));
1146                 if (min_bytes + extra > (int)sizeof u.b) {
1147                         rprintf(FERROR, "Overflow in read_varlong()\n");
1148                         exit_cleanup(RERR_STREAMIO);
1149                 }
1150                 readfd(f, u.b + min_bytes - 1, extra);
1151                 u.b[min_bytes + extra - 1] = CVAL(b2, 0) & (bit-1);
1152 #if SIZEOF_INT64 < 8
1153                 if (min_bytes + extra > 5 || u.b[4] || CVAL(u.b,3) & 0x80) {
1154                         rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1155                         exit_cleanup(RERR_UNSUPPORTED);
1156                 }
1157 #endif
1158         } else
1159                 u.b[min_bytes + extra - 1] = CVAL(b2, 0);
1160 #if SIZEOF_INT64 < 8
1161         u.x = IVAL(u.b,0);
1162 #elif CAREFUL_ALIGNMENT
1163         u.x = IVAL(u.b,0) | (((int64)IVAL(u.b,4))<<32);
1164 #endif
1165         return u.x;
1166 }
1167
1168 int64 read_longint(int f)
1169 {
1170 #if SIZEOF_INT64 >= 8
1171         char b[9];
1172 #endif
1173         int32 num = read_int(f);
1174
1175         if (num != (int32)0xffffffff)
1176                 return num;
1177
1178 #if SIZEOF_INT64 < 8
1179         rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1180         exit_cleanup(RERR_UNSUPPORTED);
1181 #else
1182         readfd(f, b, 8);
1183         return IVAL(b,0) | (((int64)IVAL(b,4))<<32);
1184 #endif
1185 }
1186
1187 void read_buf(int f, char *buf, size_t len)
1188 {
1189         readfd(f,buf,len);
1190 }
1191
1192 void read_sbuf(int f, char *buf, size_t len)
1193 {
1194         readfd(f, buf, len);
1195         buf[len] = '\0';
1196 }
1197
1198 uchar read_byte(int f)
1199 {
1200         uchar c;
1201         readfd(f, (char *)&c, 1);
1202         return c;
1203 }
1204
1205 int read_vstring(int f, char *buf, int bufsize)
1206 {
1207         int len = read_byte(f);
1208
1209         if (len & 0x80)
1210                 len = (len & ~0x80) * 0x100 + read_byte(f);
1211
1212         if (len >= bufsize) {
1213                 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
1214                         len, bufsize - 1);
1215                 return -1;
1216         }
1217
1218         if (len)
1219                 readfd(f, buf, len);
1220         buf[len] = '\0';
1221         return len;
1222 }
1223
1224 /* Populate a sum_struct with values from the socket.  This is
1225  * called by both the sender and the receiver. */
1226 void read_sum_head(int f, struct sum_struct *sum)
1227 {
1228         sum->count = read_int(f);
1229         if (sum->count < 0) {
1230                 rprintf(FERROR, "Invalid checksum count %ld [%s]\n",
1231                         (long)sum->count, who_am_i());
1232                 exit_cleanup(RERR_PROTOCOL);
1233         }
1234         sum->blength = read_int(f);
1235         if (sum->blength < 0 || sum->blength > MAX_BLOCK_SIZE) {
1236                 rprintf(FERROR, "Invalid block length %ld [%s]\n",
1237                         (long)sum->blength, who_am_i());
1238                 exit_cleanup(RERR_PROTOCOL);
1239         }
1240         sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
1241         if (sum->s2length < 0 || sum->s2length > MAX_DIGEST_LEN) {
1242                 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
1243                         sum->s2length, who_am_i());
1244                 exit_cleanup(RERR_PROTOCOL);
1245         }
1246         sum->remainder = read_int(f);
1247         if (sum->remainder < 0 || sum->remainder > sum->blength) {
1248                 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
1249                         (long)sum->remainder, who_am_i());
1250                 exit_cleanup(RERR_PROTOCOL);
1251         }
1252 }
1253
1254 /* Send the values from a sum_struct over the socket.  Set sum to
1255  * NULL if there are no checksums to send.  This is called by both
1256  * the generator and the sender. */
1257 void write_sum_head(int f, struct sum_struct *sum)
1258 {
1259         static struct sum_struct null_sum;
1260
1261         if (sum == NULL)
1262                 sum = &null_sum;
1263
1264         write_int(f, sum->count);
1265         write_int(f, sum->blength);
1266         if (protocol_version >= 27)
1267                 write_int(f, sum->s2length);
1268         write_int(f, sum->remainder);
1269 }
1270
1271 /**
1272  * Sleep after writing to limit I/O bandwidth usage.
1273  *
1274  * @todo Rather than sleeping after each write, it might be better to
1275  * use some kind of averaging.  The current algorithm seems to always
1276  * use a bit less bandwidth than specified, because it doesn't make up
1277  * for slow periods.  But arguably this is a feature.  In addition, we
1278  * ought to take the time used to write the data into account.
1279  *
1280  * During some phases of big transfers (file FOO is uptodate) this is
1281  * called with a small bytes_written every time.  As the kernel has to
1282  * round small waits up to guarantee that we actually wait at least the
1283  * requested number of microseconds, this can become grossly inaccurate.
1284  * We therefore keep track of the bytes we've written over time and only
1285  * sleep when the accumulated delay is at least 1 tenth of a second.
1286  **/
1287 static void sleep_for_bwlimit(int bytes_written)
1288 {
1289         static struct timeval prior_tv;
1290         static long total_written = 0;
1291         struct timeval tv, start_tv;
1292         long elapsed_usec, sleep_usec;
1293
1294 #define ONE_SEC 1000000L /* # of microseconds in a second */
1295
1296         if (!bwlimit_writemax)
1297                 return;
1298
1299         total_written += bytes_written;
1300
1301         gettimeofday(&start_tv, NULL);
1302         if (prior_tv.tv_sec) {
1303                 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
1304                              + (start_tv.tv_usec - prior_tv.tv_usec);
1305                 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
1306                 if (total_written < 0)
1307                         total_written = 0;
1308         }
1309
1310         sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1311         if (sleep_usec < ONE_SEC / 10) {
1312                 prior_tv = start_tv;
1313                 return;
1314         }
1315
1316         tv.tv_sec  = sleep_usec / ONE_SEC;
1317         tv.tv_usec = sleep_usec % ONE_SEC;
1318         select(0, NULL, NULL, NULL, &tv);
1319
1320         gettimeofday(&prior_tv, NULL);
1321         elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1322                      + (prior_tv.tv_usec - start_tv.tv_usec);
1323         total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
1324 }
1325
1326 /* Write len bytes to the file descriptor fd, looping as necessary to get
1327  * the job done and also (in certain circumstances) reading any data on
1328  * msg_fd_in to avoid deadlock.
1329  *
1330  * This function underlies the multiplexing system.  The body of the
1331  * application never calls this function directly. */
1332 static void writefd_unbuffered(int fd, const char *buf, size_t len)
1333 {
1334         size_t n, total = 0;
1335         fd_set w_fds, r_fds, e_fds;
1336         int maxfd, count, cnt, using_r_fds;
1337         int defer_inc = 0;
1338         struct timeval tv;
1339
1340         if (no_flush++)
1341                 defer_forwarding_messages++, defer_inc++;
1342
1343         while (total < len) {
1344                 FD_ZERO(&w_fds);
1345                 FD_SET(fd, &w_fds);
1346                 FD_ZERO(&e_fds);
1347                 FD_SET(fd, &e_fds);
1348                 maxfd = fd;
1349
1350                 if (msg_fd_in >= 0) {
1351                         FD_ZERO(&r_fds);
1352                         FD_SET(msg_fd_in, &r_fds);
1353                         if (msg_fd_in > maxfd)
1354                                 maxfd = msg_fd_in;
1355                         using_r_fds = 1;
1356                 } else
1357                         using_r_fds = 0;
1358
1359                 tv.tv_sec = select_timeout;
1360                 tv.tv_usec = 0;
1361
1362                 errno = 0;
1363                 count = select(maxfd + 1, using_r_fds ? &r_fds : NULL,
1364                                &w_fds, &e_fds, &tv);
1365
1366                 if (count <= 0) {
1367                         if (count < 0 && errno == EBADF)
1368                                 exit_cleanup(RERR_SOCKETIO);
1369                         check_timeout();
1370                         continue;
1371                 }
1372
1373                 if (FD_ISSET(fd, &e_fds)) {
1374                         rsyserr(FINFO, errno,
1375                                 "select exception on fd %d", fd);
1376                 }
1377
1378                 if (using_r_fds && FD_ISSET(msg_fd_in, &r_fds))
1379                         read_msg_fd();
1380
1381                 if (!FD_ISSET(fd, &w_fds))
1382                         continue;
1383
1384                 n = len - total;
1385                 if (bwlimit_writemax && n > bwlimit_writemax)
1386                         n = bwlimit_writemax;
1387                 cnt = write(fd, buf + total, n);
1388
1389                 if (cnt <= 0) {
1390                         if (cnt < 0) {
1391                                 if (errno == EINTR)
1392                                         continue;
1393                                 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1394                                         msleep(1);
1395                                         continue;
1396                                 }
1397                         }
1398
1399                         /* Don't try to write errors back across the stream. */
1400                         if (fd == sock_f_out)
1401                                 io_end_multiplex_out();
1402                         /* Don't try to write errors down a failing msg pipe. */
1403                         if (am_server && fd == msg_fd_out)
1404                                 exit_cleanup(RERR_STREAMIO);
1405                         rsyserr(FERROR, errno,
1406                                 "writefd_unbuffered failed to write %ld bytes [%s]",
1407                                 (long)len, who_am_i());
1408                         /* If the other side is sending us error messages, try
1409                          * to grab any messages they sent before they died. */
1410                         while (fd == sock_f_out && io_multiplexing_in) {
1411                                 set_io_timeout(30);
1412                                 ignore_timeout = 0;
1413                                 readfd_unbuffered(sock_f_in, io_filesfrom_buf,
1414                                                   sizeof io_filesfrom_buf);
1415                         }
1416                         exit_cleanup(RERR_STREAMIO);
1417                 }
1418
1419                 total += cnt;
1420                 defer_forwarding_messages++, defer_inc++;
1421
1422                 if (fd == sock_f_out) {
1423                         if (io_timeout || am_generator)
1424                                 last_io_out = time(NULL);
1425                         sleep_for_bwlimit(cnt);
1426                 }
1427         }
1428
1429         no_flush--;
1430         if (!(defer_forwarding_messages -= defer_inc))
1431                 msg_flush();
1432 }
1433
1434 void io_flush(int flush_it_all)
1435 {
1436         if (!iobuf_out_cnt || no_flush)
1437                 return;
1438
1439         if (io_multiplexing_out)
1440                 mplex_write(sock_f_out, MSG_DATA, iobuf_out, iobuf_out_cnt, 0);
1441         else
1442                 writefd_unbuffered(iobuf_f_out, iobuf_out, iobuf_out_cnt);
1443         iobuf_out_cnt = 0;
1444
1445         if (flush_it_all && !defer_forwarding_messages)
1446                 msg_flush();
1447 }
1448
1449 static void writefd(int fd, const char *buf, size_t len)
1450 {
1451         if (fd == sock_f_out)
1452                 stats.total_written += len;
1453
1454         if (fd == write_batch_monitor_out) {
1455                 if ((size_t)write(batch_fd, buf, len) != len)
1456                         exit_cleanup(RERR_FILEIO);
1457         }
1458
1459         if (!iobuf_out || fd != iobuf_f_out) {
1460                 writefd_unbuffered(fd, buf, len);
1461                 return;
1462         }
1463
1464         while (len) {
1465                 int n = MIN((int)len, IO_BUFFER_SIZE - iobuf_out_cnt);
1466                 if (n > 0) {
1467                         memcpy(iobuf_out+iobuf_out_cnt, buf, n);
1468                         buf += n;
1469                         len -= n;
1470                         iobuf_out_cnt += n;
1471                 }
1472
1473                 if (iobuf_out_cnt == IO_BUFFER_SIZE)
1474                         io_flush(NORMAL_FLUSH);
1475         }
1476 }
1477
1478 void write_shortint(int f, unsigned short x)
1479 {
1480         char b[2];
1481         b[0] = (char)x;
1482         b[1] = (char)(x >> 8);
1483         writefd(f, b, 2);
1484 }
1485
1486 void write_int(int f, int32 x)
1487 {
1488         char b[4];
1489         SIVAL(b, 0, x);
1490         writefd(f, b, 4);
1491 }
1492
1493 void write_varint(int f, int32 x)
1494 {
1495         char b[5];
1496         uchar bit;
1497         int cnt = 4;
1498
1499         SIVAL(b, 1, x);
1500
1501         while (cnt > 1 && b[cnt] == 0)
1502                 cnt--;
1503         bit = ((uchar)1<<(7-cnt+1));
1504         if (CVAL(b, cnt) >= bit) {
1505                 cnt++;
1506                 *b = ~(bit-1);
1507         } else if (cnt > 1)
1508                 *b = b[cnt] | ~(bit*2-1);
1509         else
1510                 *b = b[cnt];
1511
1512         writefd(f, b, cnt);
1513 }
1514
1515 void write_varlong(int f, int64 x, uchar min_bytes)
1516 {
1517         char b[9];
1518         uchar bit;
1519         int cnt = 8;
1520
1521         SIVAL(b, 1, x);
1522 #if SIZEOF_INT64 >= 8
1523         SIVAL(b, 5, x >> 32);
1524 #else
1525         if (x <= 0x7FFFFFFF && x >= 0)
1526                 memset(b + 5, 0, 4);
1527         else {
1528                 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1529                 exit_cleanup(RERR_UNSUPPORTED);
1530         }
1531 #endif
1532
1533         while (cnt > min_bytes && b[cnt] == 0)
1534                 cnt--;
1535         bit = ((uchar)1<<(7-cnt+min_bytes));
1536         if (CVAL(b, cnt) >= bit) {
1537                 cnt++;
1538                 *b = ~(bit-1);
1539         } else if (cnt > min_bytes)
1540                 *b = b[cnt] | ~(bit*2-1);
1541         else
1542                 *b = b[cnt];
1543
1544         writefd(f, b, cnt);
1545 }
1546
1547 /*
1548  * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1549  * 64-bit types on this platform.
1550  */
1551 void write_longint(int f, int64 x)
1552 {
1553         char b[12], * const s = b+4;
1554
1555         SIVAL(s, 0, x);
1556         if (x <= 0x7FFFFFFF && x >= 0) {
1557                 writefd(f, s, 4);
1558                 return;
1559         }
1560
1561 #if SIZEOF_INT64 < 8
1562         rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1563         exit_cleanup(RERR_UNSUPPORTED);
1564 #else
1565         memset(b, 0xFF, 4);
1566         SIVAL(s, 4, x >> 32);
1567         writefd(f, b, 12);
1568 #endif
1569 }
1570
1571 void write_buf(int f, const char *buf, size_t len)
1572 {
1573         writefd(f,buf,len);
1574 }
1575
1576 /** Write a string to the connection */
1577 void write_sbuf(int f, const char *buf)
1578 {
1579         writefd(f, buf, strlen(buf));
1580 }
1581
1582 void write_byte(int f, uchar c)
1583 {
1584         writefd(f, (char *)&c, 1);
1585 }
1586
1587 void write_vstring(int f, const char *str, int len)
1588 {
1589         uchar lenbuf[3], *lb = lenbuf;
1590
1591         if (len > 0x7F) {
1592                 if (len > 0x7FFF) {
1593                         rprintf(FERROR,
1594                                 "attempting to send over-long vstring (%d > %d)\n",
1595                                 len, 0x7FFF);
1596                         exit_cleanup(RERR_PROTOCOL);
1597                 }
1598                 *lb++ = len / 0x100 + 0x80;
1599         }
1600         *lb = len;
1601
1602         writefd(f, (char*)lenbuf, lb - lenbuf + 1);
1603         if (len)
1604                 writefd(f, str, len);
1605 }
1606
1607 /* Send a file-list index using a byte-reduction method. */
1608 void write_ndx(int f, int32 ndx)
1609 {
1610         static int32 prev_positive = -1, prev_negative = 1;
1611         int32 diff, cnt = 0;
1612         char b[6];
1613
1614         if (protocol_version < 30 || read_batch) {
1615                 write_int(f, ndx);
1616                 return;
1617         }
1618
1619         /* Send NDX_DONE as a single-byte 0 with no side effects.  Send
1620          * negative nums as a positive after sending a leading 0xFF. */
1621         if (ndx >= 0) {
1622                 diff = ndx - prev_positive;
1623                 prev_positive = ndx;
1624         } else if (ndx == NDX_DONE) {
1625                 *b = 0;
1626                 writefd(f, b, 1);
1627                 return;
1628         } else {
1629                 b[cnt++] = (char)0xFF;
1630                 ndx = -ndx;
1631                 diff = ndx - prev_negative;
1632                 prev_negative = ndx;
1633         }
1634
1635         /* A diff of 1 - 253 is sent as a one-byte diff; a diff of 254 - 32767
1636          * or 0 is sent as a 0xFE + a two-byte diff; otherwise we send 0xFE
1637          * & all 4 bytes of the (non-negative) num with the high-bit set. */
1638         if (diff < 0xFE && diff > 0)
1639                 b[cnt++] = (char)diff;
1640         else if (diff < 0 || diff > 0x7FFF) {
1641                 b[cnt++] = (char)0xFE;
1642                 b[cnt++] = (char)((ndx >> 24) | 0x80);
1643                 b[cnt++] = (char)ndx;
1644                 b[cnt++] = (char)(ndx >> 8);
1645                 b[cnt++] = (char)(ndx >> 16);
1646         } else {
1647                 b[cnt++] = (char)0xFE;
1648                 b[cnt++] = (char)(diff >> 8);
1649                 b[cnt++] = (char)diff;
1650         }
1651         writefd(f, b, cnt);
1652 }
1653
1654 /* Receive a file-list index using a byte-reduction method. */
1655 int32 read_ndx(int f)
1656 {
1657         static int32 prev_positive = -1, prev_negative = 1;
1658         int32 *prev_ptr, num;
1659         char b[4];
1660
1661         if (protocol_version < 30)
1662                 return read_int(f);
1663
1664         readfd(f, b, 1);
1665         if (CVAL(b, 0) == 0xFF) {
1666                 readfd(f, b, 1);
1667                 prev_ptr = &prev_negative;
1668         } else if (CVAL(b, 0) == 0)
1669                 return NDX_DONE;
1670         else
1671                 prev_ptr = &prev_positive;
1672         if (CVAL(b, 0) == 0xFE) {
1673                 readfd(f, b, 2);
1674                 if (CVAL(b, 0) & 0x80) {
1675                         b[3] = CVAL(b, 0) & ~0x80;
1676                         b[0] = b[1];
1677                         readfd(f, b+1, 2);
1678                         num = IVAL(b, 0);
1679                 } else
1680                         num = (UVAL(b,0)<<8) + UVAL(b,1) + *prev_ptr;
1681         } else
1682                 num = UVAL(b, 0) + *prev_ptr;
1683         *prev_ptr = num;
1684         if (prev_ptr == &prev_negative)
1685                 num = -num;
1686         return num;
1687 }
1688
1689 /**
1690  * Read a line of up to @p maxlen characters into @p buf (not counting
1691  * the trailing null).  Strips the (required) trailing newline and all
1692  * carriage returns.
1693  *
1694  * @return 1 for success; 0 for I/O error or truncation.
1695  **/
1696 int read_line(int f, char *buf, size_t maxlen)
1697 {
1698         while (maxlen) {
1699                 buf[0] = 0;
1700                 read_buf(f, buf, 1);
1701                 if (buf[0] == 0)
1702                         return 0;
1703                 if (buf[0] == '\n')
1704                         break;
1705                 if (buf[0] != '\r') {
1706                         buf++;
1707                         maxlen--;
1708                 }
1709         }
1710         *buf = '\0';
1711         return maxlen > 0;
1712 }
1713
1714 void io_printf(int fd, const char *format, ...)
1715 {
1716         va_list ap;
1717         char buf[BIGPATHBUFLEN];
1718         int len;
1719
1720         va_start(ap, format);
1721         len = vsnprintf(buf, sizeof buf, format, ap);
1722         va_end(ap);
1723
1724         if (len < 0)
1725                 exit_cleanup(RERR_STREAMIO);
1726
1727         if (len > (int)sizeof buf) {
1728                 rprintf(FERROR, "io_printf() was too long for the buffer.\n");
1729                 exit_cleanup(RERR_STREAMIO);
1730         }
1731
1732         write_sbuf(fd, buf);
1733 }
1734
1735 /** Setup for multiplexing a MSG_* stream with the data stream. */
1736 void io_start_multiplex_out(void)
1737 {
1738         io_flush(NORMAL_FLUSH);
1739         io_start_buffering_out(sock_f_out);
1740         io_multiplexing_out = 1;
1741 }
1742
1743 /** Setup for multiplexing a MSG_* stream with the data stream. */
1744 void io_start_multiplex_in(void)
1745 {
1746         io_flush(NORMAL_FLUSH);
1747         io_start_buffering_in(sock_f_in);
1748         io_multiplexing_in = 1;
1749 }
1750
1751 /** Write an message to the multiplexed data stream. */
1752 int io_multiplex_write(enum msgcode code, const char *buf, size_t len, int convert)
1753 {
1754         if (!io_multiplexing_out)
1755                 return 0;
1756         io_flush(NORMAL_FLUSH);
1757         stats.total_written += (len+4);
1758         mplex_write(sock_f_out, code, buf, len, convert);
1759         return 1;
1760 }
1761
1762 void io_end_multiplex_in(void)
1763 {
1764         io_multiplexing_in = 0;
1765         io_end_buffering_in();
1766 }
1767
1768 /** Stop output multiplexing. */
1769 void io_end_multiplex_out(void)
1770 {
1771         io_multiplexing_out = 0;
1772         io_end_buffering_out();
1773 }
1774
1775 void start_write_batch(int fd)
1776 {
1777         /* Some communication has already taken place, but we don't
1778          * enable batch writing until here so that we can write a
1779          * canonical record of the communication even though the
1780          * actual communication so far depends on whether a daemon
1781          * is involved. */
1782         write_int(batch_fd, protocol_version);
1783         write_int(batch_fd, checksum_seed);
1784
1785         if (am_sender)
1786                 write_batch_monitor_out = fd;
1787         else
1788                 write_batch_monitor_in = fd;
1789 }
1790
1791 void stop_write_batch(void)
1792 {
1793         write_batch_monitor_out = -1;
1794         write_batch_monitor_in = -1;
1795 }