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