Make use of new iconvbufs() function.
[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 struct stats stats;
54 extern struct file_list *cur_flist, *first_flist;
55 #ifdef ICONV_OPTION
56 extern iconv_t ic_send, ic_recv;
57 #endif
58
59 const char phase_unknown[] = "unknown";
60 int ignore_timeout = 0;
61 int batch_fd = -1;
62 int msgdone_cnt = 0;
63
64 /* Ignore an EOF error if non-zero. See whine_about_eof(). */
65 int kluge_around_eof = 0;
66
67 int msg_fd_in = -1;
68 int msg_fd_out = -1;
69 int sock_f_in = -1;
70 int sock_f_out = -1;
71
72 static int iobuf_f_in = -1;
73 static char *iobuf_in;
74 static size_t iobuf_in_siz;
75 static size_t iobuf_in_ndx;
76 static size_t iobuf_in_remaining;
77
78 static int iobuf_f_out = -1;
79 static char *iobuf_out;
80 static int iobuf_out_cnt;
81
82 int flist_forward_from = -1;
83
84 static int io_multiplexing_out;
85 static int io_multiplexing_in;
86 static time_t last_io_in;
87 static time_t last_io_out;
88 static int no_flush;
89
90 static int write_batch_monitor_in = -1;
91 static int write_batch_monitor_out = -1;
92
93 static int io_filesfrom_f_in = -1;
94 static int io_filesfrom_f_out = -1;
95 static char io_filesfrom_buf[2048];
96 #ifdef ICONV_OPTION
97 static char iconv_buf[sizeof io_filesfrom_buf / 2];
98 #endif
99 static char *io_filesfrom_bp;
100 static char io_filesfrom_lastchar;
101 static int io_filesfrom_buflen;
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                 iconv(ic_send, NULL, 0, NULL, 0);
483                 defer_forwarding_messages++;
484                 while (len) {
485                         ICONV_CONST char *ibuf = (ICONV_CONST char *)buf;
486                         char *obuf = buffer;
487                         size_t ocnt = sizeof buffer;
488                         while (len && iconv(ic_send, &ibuf,&len,
489                                             &obuf,&ocnt) == (size_t)-1) {
490                                 if (errno == E2BIG || !ocnt)
491                                         break;
492                                 *obuf++ = *ibuf++;
493                                 ocnt--, len--;
494                         }
495                         n = obuf - buffer;
496                         writefd_unbuffered(fd, buffer, n);
497                 }
498                 if (!--defer_forwarding_messages)
499                         msg_flush();
500         } else
501 #endif
502         if (len) {
503                 defer_forwarding_messages++;
504                 writefd_unbuffered(fd, buf, len);
505                 if (!--defer_forwarding_messages)
506                         msg_flush();
507         }
508 }
509
510 int send_msg(enum msgcode code, const char *buf, int len, int convert)
511 {
512         if (msg_fd_out < 0) {
513                 if (!defer_forwarding_messages)
514                         return io_multiplex_write(code, buf, len, convert);
515                 if (!io_multiplexing_out)
516                         return 0;
517                 msg_list_add(&msg_queue, code, buf, len, convert);
518                 return 1;
519         }
520         if (flist_forward_from >= 0)
521                 msg_list_add(&msg_queue, code, buf, len, convert);
522         else
523                 mplex_write(msg_fd_out, code, buf, len, convert);
524         return 1;
525 }
526
527 void send_msg_int(enum msgcode code, int num)
528 {
529         char numbuf[4];
530         SIVAL(numbuf, 0, num);
531         send_msg(code, numbuf, 4, 0);
532 }
533
534 void wait_for_receiver(void)
535 {
536         if (iobuf_out_cnt)
537                 io_flush(NORMAL_FLUSH);
538         else
539                 read_msg_fd();
540 }
541
542 int get_redo_num(void)
543 {
544         return flist_ndx_pop(&redo_list);
545 }
546
547 int get_hlink_num(void)
548 {
549         return flist_ndx_pop(&hlink_list);
550 }
551
552 /**
553  * When we're the receiver and we have a local --files-from list of names
554  * that needs to be sent over the socket to the sender, we have to do two
555  * things at the same time: send the sender a list of what files we're
556  * processing and read the incoming file+info list from the sender.  We do
557  * this by augmenting the read_timeout() function to copy this data.  It
558  * uses the io_filesfrom_buf to read a block of data from f_in (when it is
559  * ready, since it might be a pipe) and then blast it out f_out (when it
560  * is ready to receive more data).
561  */
562 void io_set_filesfrom_fds(int f_in, int f_out)
563 {
564         io_filesfrom_f_in = f_in;
565         io_filesfrom_f_out = f_out;
566         io_filesfrom_bp = io_filesfrom_buf;
567         io_filesfrom_lastchar = '\0';
568         io_filesfrom_buflen = 0;
569 }
570
571 /* It's almost always an error to get an EOF when we're trying to read from the
572  * network, because the protocol is (for the most part) self-terminating.
573  *
574  * There is one case for the receiver when it is at the end of the transfer
575  * (hanging around reading any keep-alive packets that might come its way): if
576  * the sender dies before the generator's kill-signal comes through, we can end
577  * up here needing to loop until the kill-signal arrives.  In this situation,
578  * kluge_around_eof will be < 0.
579  *
580  * There is another case for older protocol versions (< 24) where the module
581  * listing was not terminated, so we must ignore an EOF error in that case and
582  * exit.  In this situation, kluge_around_eof will be > 0. */
583 static void whine_about_eof(int fd)
584 {
585         if (kluge_around_eof && fd == sock_f_in) {
586                 int i;
587                 if (kluge_around_eof > 0)
588                         exit_cleanup(0);
589                 /* If we're still here after 10 seconds, exit with an error. */
590                 for (i = 10*1000/20; i--; )
591                         msleep(20);
592         }
593
594         rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
595                 "(%.0f bytes received so far) [%s]\n",
596                 (double)stats.total_read, who_am_i());
597
598         exit_cleanup(RERR_STREAMIO);
599 }
600
601 /**
602  * Read from a socket with I/O timeout. return the number of bytes
603  * read. If no bytes can be read then exit, never return a number <= 0.
604  *
605  * TODO: If the remote shell connection fails, then current versions
606  * actually report an "unexpected EOF" error here.  Since it's a
607  * fairly common mistake to try to use rsh when ssh is required, we
608  * should trap that: if we fail to read any data at all, we should
609  * give a better explanation.  We can tell whether the connection has
610  * started by looking e.g. at whether the remote version is known yet.
611  */
612 static int read_timeout(int fd, char *buf, size_t len)
613 {
614         int n, cnt = 0;
615
616         io_flush(FULL_FLUSH);
617
618         while (cnt == 0) {
619                 /* until we manage to read *something* */
620                 fd_set r_fds, w_fds;
621                 struct timeval tv;
622                 int maxfd = fd;
623                 int count;
624
625                 FD_ZERO(&r_fds);
626                 FD_ZERO(&w_fds);
627                 FD_SET(fd, &r_fds);
628                 if (io_filesfrom_f_out >= 0) {
629                         int new_fd;
630                         if (io_filesfrom_buflen == 0) {
631                                 if (io_filesfrom_f_in >= 0) {
632                                         FD_SET(io_filesfrom_f_in, &r_fds);
633                                         new_fd = io_filesfrom_f_in;
634                                 } else {
635                                         io_filesfrom_f_out = -1;
636                                         new_fd = -1;
637                                 }
638                         } else {
639                                 FD_SET(io_filesfrom_f_out, &w_fds);
640                                 new_fd = io_filesfrom_f_out;
641                         }
642                         if (new_fd > maxfd)
643                                 maxfd = new_fd;
644                 }
645
646                 tv.tv_sec = select_timeout;
647                 tv.tv_usec = 0;
648
649                 errno = 0;
650
651                 count = select(maxfd + 1, &r_fds, &w_fds, NULL, &tv);
652
653                 if (count <= 0) {
654                         if (errno == EBADF) {
655                                 defer_forwarding_messages = 0;
656                                 exit_cleanup(RERR_SOCKETIO);
657                         }
658                         check_timeout();
659                         continue;
660                 }
661
662                 if (io_filesfrom_f_out >= 0) {
663                         if (io_filesfrom_buflen) {
664                                 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
665                                         int l = write(io_filesfrom_f_out,
666                                                       io_filesfrom_bp,
667                                                       io_filesfrom_buflen);
668                                         if (l > 0) {
669                                                 if (!(io_filesfrom_buflen -= l))
670                                                         io_filesfrom_bp = io_filesfrom_buf;
671                                                 else
672                                                         io_filesfrom_bp += l;
673                                         } else if (errno != EINTR) {
674                                                 /* XXX should we complain? */
675                                                 io_filesfrom_f_out = -1;
676                                         }
677                                 }
678                         } else if (io_filesfrom_f_in >= 0) {
679                                 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
680                                         int l = read(io_filesfrom_f_in,
681                                                      io_filesfrom_buf,
682                                                      sizeof io_filesfrom_buf);
683                                         if (l <= 0) {
684                                                 if (l == 0 || errno != EINTR) {
685                                                         /* Send end-of-file marker */
686                                                         io_filesfrom_buf[0] = '\0';
687                                                         io_filesfrom_buf[1] = '\0';
688                                                         io_filesfrom_buflen = io_filesfrom_lastchar? 2 : 1;
689                                                         io_filesfrom_f_in = -1;
690                                                 }
691                                         } else {
692                                                 if (!eol_nulls) {
693                                                         char *s = io_filesfrom_buf + l;
694                                                         /* Transform CR and/or LF into '\0' */
695                                                         while (s-- > io_filesfrom_buf) {
696                                                                 if (*s == '\n' || *s == '\r')
697                                                                         *s = '\0';
698                                                         }
699                                                 }
700                                                 if (!io_filesfrom_lastchar) {
701                                                         /* Last buf ended with a '\0', so don't
702                                                          * let this buf start with one. */
703                                                         while (l && !*io_filesfrom_bp)
704                                                                 io_filesfrom_bp++, l--;
705                                                 }
706                                                 if (!l)
707                                                         io_filesfrom_bp = io_filesfrom_buf;
708                                                 else {
709                                                         char *f = io_filesfrom_bp;
710                                                         char *t = f;
711                                                         char *eob = f + l;
712                                                         /* Eliminate any multi-'\0' runs. */
713                                                         while (f != eob) {
714                                                                 if (!(*t++ = *f++)) {
715                                                                         while (f != eob && !*f)
716                                                                                 f++, l--;
717                                                                 }
718                                                         }
719                                                         io_filesfrom_lastchar = f[-1];
720                                                 }
721                                                 io_filesfrom_buflen = l;
722                                         }
723                                 }
724                         }
725                 }
726
727                 if (!FD_ISSET(fd, &r_fds))
728                         continue;
729
730                 n = read(fd, buf, len);
731
732                 if (n <= 0) {
733                         if (n == 0)
734                                 whine_about_eof(fd); /* Doesn't return. */
735                         if (errno == EINTR || errno == EWOULDBLOCK
736                             || errno == EAGAIN)
737                                 continue;
738
739                         /* Don't write errors on a dead socket. */
740                         if (fd == sock_f_in) {
741                                 io_end_multiplex_out();
742                                 rsyserr(FSOCKERR, errno, "read error");
743                         } else
744                                 rsyserr(FERROR, errno, "read error");
745                         exit_cleanup(RERR_STREAMIO);
746                 }
747
748                 buf += n;
749                 len -= n;
750                 cnt += n;
751
752                 if (fd == sock_f_in && io_timeout)
753                         last_io_in = time(NULL);
754         }
755
756         return cnt;
757 }
758
759 /* Read a line into the "buf" buffer. */
760 int read_line(int fd, char *buf, size_t bufsiz, int dump_comments, int rl_nulls)
761 {
762         char ch, *s, *eob = buf + bufsiz - 1;
763         int cnt;
764
765   start:
766         s = buf;
767         while (1) {
768                 cnt = read(fd, &ch, 1);
769                 if (cnt < 0 && (errno == EWOULDBLOCK
770                   || errno == EINTR || errno == EAGAIN)) {
771                         struct timeval tv;
772                         fd_set r_fds, e_fds;
773                         FD_ZERO(&r_fds);
774                         FD_SET(fd, &r_fds);
775                         FD_ZERO(&e_fds);
776                         FD_SET(fd, &e_fds);
777                         tv.tv_sec = select_timeout;
778                         tv.tv_usec = 0;
779                         if (!select(fd+1, &r_fds, NULL, &e_fds, &tv))
780                                 check_timeout();
781                         /*if (FD_ISSET(fd, &e_fds))
782                                 rprintf(FINFO, "select exception on fd %d\n", fd); */
783                         continue;
784                 }
785                 if (cnt != 1)
786                         break;
787                 if (rl_nulls ? ch == '\0' : (ch == '\r' || ch == '\n')) {
788                         /* Skip empty lines if dumping comments. */
789                         if (dump_comments && s == buf)
790                                 continue;
791                         break;
792                 }
793                 if (s < eob)
794                         *s++ = ch;
795         }
796         *s = '\0';
797
798         if (dump_comments && (*buf == '#' || *buf == ';'))
799                 goto start;
800
801         return s - buf;
802 }
803
804 int read_args(int f_in, char *mod_name, char *buf, size_t bufsiz, int rl_nulls,
805               char ***argv_p, int *argc_p, char **request_p)
806 {
807         int maxargs = MAX_ARGS;
808         int dot_pos = 0;
809         int argc = 0;
810         char **argv, *p;
811
812         if (!(argv = new_array(char *, maxargs)))
813                 out_of_memory("read_args");
814         if (mod_name)
815                 argv[argc++] = "rsyncd";
816
817         while (1) {
818                 if (read_line(f_in, buf, bufsiz, 0, rl_nulls) == 0)
819                         break;
820
821                 if (argc == maxargs) {
822                         maxargs += MAX_ARGS;
823                         if (!(argv = realloc_array(argv, char *, maxargs)))
824                                 out_of_memory("read_args");
825                 }
826
827                 if (dot_pos) {
828                         if (request_p) {
829                                 *request_p = strdup(buf);
830                                 request_p = NULL;
831                         }
832                         if (mod_name)
833                                 glob_expand_module(mod_name, buf, &argv, &argc, &maxargs);
834                         else
835                                 glob_expand(buf, &argv, &argc, &maxargs);
836                 } else {
837                         if (!(p = strdup(buf)))
838                                 out_of_memory("read_args");
839                         argv[argc++] = p;
840                         if (*p == '.' && p[1] == '\0')
841                                 dot_pos = argc;
842                 }
843         }
844
845         *argc_p = argc;
846         *argv_p = argv;
847
848         return dot_pos ? dot_pos : argc;
849 }
850
851 int io_start_buffering_out(int f_out)
852 {
853         if (iobuf_out) {
854                 assert(f_out == iobuf_f_out);
855                 return 0;
856         }
857         if (!(iobuf_out = new_array(char, IO_BUFFER_SIZE)))
858                 out_of_memory("io_start_buffering_out");
859         iobuf_out_cnt = 0;
860         iobuf_f_out = f_out;
861         return 1;
862 }
863
864 int io_start_buffering_in(int f_in)
865 {
866         if (iobuf_in) {
867                 assert(f_in == iobuf_f_in);
868                 return 0;
869         }
870         iobuf_in_siz = 2 * IO_BUFFER_SIZE;
871         if (!(iobuf_in = new_array(char, iobuf_in_siz)))
872                 out_of_memory("io_start_buffering_in");
873         iobuf_f_in = f_in;
874         return 1;
875 }
876
877 void io_end_buffering_in(void)
878 {
879         if (!iobuf_in)
880                 return;
881         free(iobuf_in);
882         iobuf_in = NULL;
883         iobuf_in_ndx = 0;
884         iobuf_in_remaining = 0;
885         iobuf_f_in = -1;
886 }
887
888 void io_end_buffering_out(void)
889 {
890         if (!iobuf_out)
891                 return;
892         io_flush(FULL_FLUSH);
893         free(iobuf_out);
894         iobuf_out = NULL;
895         iobuf_f_out = -1;
896 }
897
898 void maybe_flush_socket(int important)
899 {
900         if (iobuf_out && iobuf_out_cnt
901          && (important || time(NULL) - last_io_out >= 5))
902                 io_flush(NORMAL_FLUSH);
903 }
904
905 void maybe_send_keepalive(void)
906 {
907         if (time(NULL) - last_io_out >= allowed_lull) {
908                 if (!iobuf_out || !iobuf_out_cnt) {
909                         if (protocol_version < 29)
910                                 return; /* there's nothing we can do */
911                         if (protocol_version >= 30)
912                                 send_msg(MSG_NOOP, "", 0, 0);
913                         else {
914                                 write_int(sock_f_out, cur_flist->used);
915                                 write_shortint(sock_f_out, ITEM_IS_NEW);
916                         }
917                 }
918                 if (iobuf_out)
919                         io_flush(NORMAL_FLUSH);
920         }
921 }
922
923 void start_flist_forward(int f_in)
924 {
925         assert(iobuf_out != NULL);
926         assert(iobuf_f_out == msg_fd_out);
927         flist_forward_from = f_in;
928 }
929
930 void stop_flist_forward()
931 {
932         flist_forward_from = -1;
933         io_flush(FULL_FLUSH);
934 }
935
936 /**
937  * Continue trying to read len bytes - don't return until len has been
938  * read.
939  **/
940 static void read_loop(int fd, char *buf, size_t len)
941 {
942         while (len) {
943                 int n = read_timeout(fd, buf, len);
944
945                 buf += n;
946                 len -= n;
947         }
948 }
949
950 /**
951  * Read from the file descriptor handling multiplexing - return number
952  * of bytes read.
953  *
954  * Never returns <= 0.
955  */
956 static int readfd_unbuffered(int fd, char *buf, size_t len)
957 {
958         size_t msg_bytes;
959         int tag, cnt = 0;
960         char line[BIGPATHBUFLEN];
961
962         if (!iobuf_in || fd != iobuf_f_in)
963                 return read_timeout(fd, buf, len);
964
965         if (!io_multiplexing_in && iobuf_in_remaining == 0) {
966                 iobuf_in_remaining = read_timeout(fd, iobuf_in, iobuf_in_siz);
967                 iobuf_in_ndx = 0;
968         }
969
970         while (cnt == 0) {
971                 if (iobuf_in_remaining) {
972                         len = MIN(len, iobuf_in_remaining);
973                         memcpy(buf, iobuf_in + iobuf_in_ndx, len);
974                         iobuf_in_ndx += len;
975                         iobuf_in_remaining -= len;
976                         cnt = len;
977                         break;
978                 }
979
980                 read_loop(fd, line, 4);
981                 tag = IVAL(line, 0);
982
983                 msg_bytes = tag & 0xFFFFFF;
984                 tag = (tag >> 24) - MPLEX_BASE;
985
986                 switch (tag) {
987                 case MSG_DATA:
988                         if (msg_bytes > iobuf_in_siz) {
989                                 if (!(iobuf_in = realloc_array(iobuf_in, char,
990                                                                msg_bytes)))
991                                         out_of_memory("readfd_unbuffered");
992                                 iobuf_in_siz = msg_bytes;
993                         }
994                         read_loop(fd, iobuf_in, msg_bytes);
995                         iobuf_in_remaining = msg_bytes;
996                         iobuf_in_ndx = 0;
997                         break;
998                 case MSG_NOOP:
999                         if (am_sender)
1000                                 maybe_send_keepalive();
1001                         break;
1002                 case MSG_IO_ERROR:
1003                         if (msg_bytes != 4)
1004                                 goto invalid_msg;
1005                         read_loop(fd, line, msg_bytes);
1006                         io_error |= IVAL(line, 0);
1007                         break;
1008                 case MSG_DELETED:
1009                         if (msg_bytes >= sizeof line)
1010                                 goto overflow;
1011 #ifdef ICONV_OPTION
1012                         if (ic_recv != (iconv_t)-1) {
1013                                 ICONV_CONST char *ibuf;
1014                                 char *obuf = line;
1015                                 size_t icnt, ocnt = sizeof line - 1;
1016                                 int add_null = 0;
1017                                 iconv(ic_send, NULL, 0, NULL, 0);
1018                                 while (msg_bytes) {
1019                                         icnt = msg_bytes > sizeof iconv_buf
1020                                              ? sizeof iconv_buf : msg_bytes;
1021                                         read_loop(fd, iconv_buf, icnt);
1022                                         if (!(msg_bytes -= icnt) && !iconv_buf[icnt-1])
1023                                                 icnt--, add_null = 1;
1024                                         ibuf = (ICONV_CONST char *)iconv_buf;
1025                                         if (iconv(ic_send, &ibuf,&icnt,
1026                                                   &obuf,&ocnt) == (size_t)-1)
1027                                                 goto overflow; // XXX
1028                                 }
1029                                 if (add_null)
1030                                         *obuf++ = '\0';
1031                                 msg_bytes = obuf - line;
1032                         } else
1033 #endif
1034                                 read_loop(fd, line, msg_bytes);
1035                         /* A directory name was sent with the trailing null */
1036                         if (msg_bytes > 0 && !line[msg_bytes-1])
1037                                 log_delete(line, S_IFDIR);
1038                         else {
1039                                 line[msg_bytes] = '\0';
1040                                 log_delete(line, S_IFREG);
1041                         }
1042                         break;
1043                 case MSG_SUCCESS:
1044                         if (msg_bytes != 4) {
1045                           invalid_msg:
1046                                 rprintf(FERROR, "invalid multi-message %d:%ld [%s]\n",
1047                                         tag, (long)msg_bytes, who_am_i());
1048                                 exit_cleanup(RERR_STREAMIO);
1049                         }
1050                         read_loop(fd, line, msg_bytes);
1051                         successful_send(IVAL(line, 0));
1052                         break;
1053                 case MSG_NO_SEND:
1054                         if (msg_bytes != 4)
1055                                 goto invalid_msg;
1056                         read_loop(fd, line, msg_bytes);
1057                         send_msg_int(MSG_NO_SEND, IVAL(line, 0));
1058                         break;
1059                 case MSG_INFO:
1060                 case MSG_ERROR:
1061                         if (msg_bytes >= sizeof line) {
1062                             overflow:
1063                                 rprintf(FERROR,
1064                                         "multiplexing overflow %d:%ld [%s]\n",
1065                                         tag, (long)msg_bytes, who_am_i());
1066                                 exit_cleanup(RERR_STREAMIO);
1067                         }
1068                         read_loop(fd, line, msg_bytes);
1069                         rwrite((enum logcode)tag, line, msg_bytes, 1);
1070                         break;
1071                 default:
1072                         rprintf(FERROR, "unexpected tag %d [%s]\n",
1073                                 tag, who_am_i());
1074                         exit_cleanup(RERR_STREAMIO);
1075                 }
1076         }
1077
1078         if (iobuf_in_remaining == 0)
1079                 io_flush(NORMAL_FLUSH);
1080
1081         return cnt;
1082 }
1083
1084 /* Do a buffered read from fd.  Don't return until all N bytes have
1085  * been read.  If all N can't be read then exit with an error. */
1086 static void readfd(int fd, char *buffer, size_t N)
1087 {
1088         int  cnt;
1089         size_t total = 0;
1090
1091         while (total < N) {
1092                 cnt = readfd_unbuffered(fd, buffer + total, N-total);
1093                 total += cnt;
1094         }
1095
1096         if (fd == write_batch_monitor_in) {
1097                 if ((size_t)write(batch_fd, buffer, total) != total)
1098                         exit_cleanup(RERR_FILEIO);
1099         }
1100
1101         if (fd == flist_forward_from)
1102                 writefd(iobuf_f_out, buffer, total);
1103
1104         if (fd == sock_f_in)
1105                 stats.total_read += total;
1106 }
1107
1108 unsigned short read_shortint(int f)
1109 {
1110         char b[2];
1111         readfd(f, b, 2);
1112         return (UVAL(b, 1) << 8) + UVAL(b, 0);
1113 }
1114
1115 int32 read_int(int f)
1116 {
1117         char b[4];
1118         int32 num;
1119
1120         readfd(f, b, 4);
1121         num = IVAL(b, 0);
1122 #if SIZEOF_INT32 > 4
1123         if (num & (int32)0x80000000)
1124                 num |= ~(int32)0xffffffff;
1125 #endif
1126         return num;
1127 }
1128
1129 int32 read_varint(int f)
1130 {
1131         union {
1132             char b[5];
1133             int32 x;
1134         } u;
1135         uchar ch;
1136         int extra;
1137
1138         u.x = 0;
1139         readfd(f, (char*)&ch, 1);
1140         extra = int_byte_extra[ch / 4];
1141         if (extra) {
1142                 uchar bit = ((uchar)1<<(8-extra));
1143                 if (extra >= (int)sizeof u.b) {
1144                         rprintf(FERROR, "Overflow in read_varint()\n");
1145                         exit_cleanup(RERR_STREAMIO);
1146                 }
1147                 readfd(f, u.b, extra);
1148                 u.b[extra] = ch & (bit-1);
1149         } else
1150                 u.b[0] = ch;
1151 #if CAREFUL_ALIGNMENT
1152         u.x = IVAL(u.b,0);
1153 #endif
1154 #if SIZEOF_INT32 > 4
1155         if (u.x & (int32)0x80000000)
1156                 u.x |= ~(int32)0xffffffff;
1157 #endif
1158         return u.x;
1159 }
1160
1161 int64 read_varlong(int f, uchar min_bytes)
1162 {
1163         union {
1164             char b[9];
1165             int64 x;
1166         } u;
1167         char b2[8];
1168         int extra;
1169
1170 #if SIZEOF_INT64 < 8
1171         memset(u.b, 0, 8);
1172 #else
1173         u.x = 0;
1174 #endif
1175         readfd(f, b2, min_bytes);
1176         memcpy(u.b, b2+1, min_bytes-1);
1177         extra = int_byte_extra[CVAL(b2, 0) / 4];
1178         if (extra) {
1179                 uchar bit = ((uchar)1<<(8-extra));
1180                 if (min_bytes + extra > (int)sizeof u.b) {
1181                         rprintf(FERROR, "Overflow in read_varlong()\n");
1182                         exit_cleanup(RERR_STREAMIO);
1183                 }
1184                 readfd(f, u.b + min_bytes - 1, extra);
1185                 u.b[min_bytes + extra - 1] = CVAL(b2, 0) & (bit-1);
1186 #if SIZEOF_INT64 < 8
1187                 if (min_bytes + extra > 5 || u.b[4] || CVAL(u.b,3) & 0x80) {
1188                         rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1189                         exit_cleanup(RERR_UNSUPPORTED);
1190                 }
1191 #endif
1192         } else
1193                 u.b[min_bytes + extra - 1] = CVAL(b2, 0);
1194 #if SIZEOF_INT64 < 8
1195         u.x = IVAL(u.b,0);
1196 #elif CAREFUL_ALIGNMENT
1197         u.x = IVAL(u.b,0) | (((int64)IVAL(u.b,4))<<32);
1198 #endif
1199         return u.x;
1200 }
1201
1202 int64 read_longint(int f)
1203 {
1204 #if SIZEOF_INT64 >= 8
1205         char b[9];
1206 #endif
1207         int32 num = read_int(f);
1208
1209         if (num != (int32)0xffffffff)
1210                 return num;
1211
1212 #if SIZEOF_INT64 < 8
1213         rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1214         exit_cleanup(RERR_UNSUPPORTED);
1215 #else
1216         readfd(f, b, 8);
1217         return IVAL(b,0) | (((int64)IVAL(b,4))<<32);
1218 #endif
1219 }
1220
1221 void read_buf(int f, char *buf, size_t len)
1222 {
1223         readfd(f,buf,len);
1224 }
1225
1226 void read_sbuf(int f, char *buf, size_t len)
1227 {
1228         readfd(f, buf, len);
1229         buf[len] = '\0';
1230 }
1231
1232 uchar read_byte(int f)
1233 {
1234         uchar c;
1235         readfd(f, (char *)&c, 1);
1236         return c;
1237 }
1238
1239 int read_vstring(int f, char *buf, int bufsize)
1240 {
1241         int len = read_byte(f);
1242
1243         if (len & 0x80)
1244                 len = (len & ~0x80) * 0x100 + read_byte(f);
1245
1246         if (len >= bufsize) {
1247                 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
1248                         len, bufsize - 1);
1249                 return -1;
1250         }
1251
1252         if (len)
1253                 readfd(f, buf, len);
1254         buf[len] = '\0';
1255         return len;
1256 }
1257
1258 /* Populate a sum_struct with values from the socket.  This is
1259  * called by both the sender and the receiver. */
1260 void read_sum_head(int f, struct sum_struct *sum)
1261 {
1262         sum->count = read_int(f);
1263         if (sum->count < 0) {
1264                 rprintf(FERROR, "Invalid checksum count %ld [%s]\n",
1265                         (long)sum->count, who_am_i());
1266                 exit_cleanup(RERR_PROTOCOL);
1267         }
1268         sum->blength = read_int(f);
1269         if (sum->blength < 0 || sum->blength > MAX_BLOCK_SIZE) {
1270                 rprintf(FERROR, "Invalid block length %ld [%s]\n",
1271                         (long)sum->blength, who_am_i());
1272                 exit_cleanup(RERR_PROTOCOL);
1273         }
1274         sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
1275         if (sum->s2length < 0 || sum->s2length > MAX_DIGEST_LEN) {
1276                 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
1277                         sum->s2length, who_am_i());
1278                 exit_cleanup(RERR_PROTOCOL);
1279         }
1280         sum->remainder = read_int(f);
1281         if (sum->remainder < 0 || sum->remainder > sum->blength) {
1282                 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
1283                         (long)sum->remainder, who_am_i());
1284                 exit_cleanup(RERR_PROTOCOL);
1285         }
1286 }
1287
1288 /* Send the values from a sum_struct over the socket.  Set sum to
1289  * NULL if there are no checksums to send.  This is called by both
1290  * the generator and the sender. */
1291 void write_sum_head(int f, struct sum_struct *sum)
1292 {
1293         static struct sum_struct null_sum;
1294
1295         if (sum == NULL)
1296                 sum = &null_sum;
1297
1298         write_int(f, sum->count);
1299         write_int(f, sum->blength);
1300         if (protocol_version >= 27)
1301                 write_int(f, sum->s2length);
1302         write_int(f, sum->remainder);
1303 }
1304
1305 /**
1306  * Sleep after writing to limit I/O bandwidth usage.
1307  *
1308  * @todo Rather than sleeping after each write, it might be better to
1309  * use some kind of averaging.  The current algorithm seems to always
1310  * use a bit less bandwidth than specified, because it doesn't make up
1311  * for slow periods.  But arguably this is a feature.  In addition, we
1312  * ought to take the time used to write the data into account.
1313  *
1314  * During some phases of big transfers (file FOO is uptodate) this is
1315  * called with a small bytes_written every time.  As the kernel has to
1316  * round small waits up to guarantee that we actually wait at least the
1317  * requested number of microseconds, this can become grossly inaccurate.
1318  * We therefore keep track of the bytes we've written over time and only
1319  * sleep when the accumulated delay is at least 1 tenth of a second.
1320  **/
1321 static void sleep_for_bwlimit(int bytes_written)
1322 {
1323         static struct timeval prior_tv;
1324         static long total_written = 0;
1325         struct timeval tv, start_tv;
1326         long elapsed_usec, sleep_usec;
1327
1328 #define ONE_SEC 1000000L /* # of microseconds in a second */
1329
1330         if (!bwlimit_writemax)
1331                 return;
1332
1333         total_written += bytes_written;
1334
1335         gettimeofday(&start_tv, NULL);
1336         if (prior_tv.tv_sec) {
1337                 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
1338                              + (start_tv.tv_usec - prior_tv.tv_usec);
1339                 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
1340                 if (total_written < 0)
1341                         total_written = 0;
1342         }
1343
1344         sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1345         if (sleep_usec < ONE_SEC / 10) {
1346                 prior_tv = start_tv;
1347                 return;
1348         }
1349
1350         tv.tv_sec  = sleep_usec / ONE_SEC;
1351         tv.tv_usec = sleep_usec % ONE_SEC;
1352         select(0, NULL, NULL, NULL, &tv);
1353
1354         gettimeofday(&prior_tv, NULL);
1355         elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1356                      + (prior_tv.tv_usec - start_tv.tv_usec);
1357         total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
1358 }
1359
1360 /* Write len bytes to the file descriptor fd, looping as necessary to get
1361  * the job done and also (in certain circumstances) reading any data on
1362  * msg_fd_in to avoid deadlock.
1363  *
1364  * This function underlies the multiplexing system.  The body of the
1365  * application never calls this function directly. */
1366 static void writefd_unbuffered(int fd, const char *buf, size_t len)
1367 {
1368         size_t n, total = 0;
1369         fd_set w_fds, r_fds, e_fds;
1370         int maxfd, count, cnt, using_r_fds;
1371         int defer_inc = 0;
1372         struct timeval tv;
1373
1374         if (no_flush++)
1375                 defer_forwarding_messages++, defer_inc++;
1376
1377         while (total < len) {
1378                 FD_ZERO(&w_fds);
1379                 FD_SET(fd, &w_fds);
1380                 FD_ZERO(&e_fds);
1381                 FD_SET(fd, &e_fds);
1382                 maxfd = fd;
1383
1384                 if (msg_fd_in >= 0) {
1385                         FD_ZERO(&r_fds);
1386                         FD_SET(msg_fd_in, &r_fds);
1387                         if (msg_fd_in > maxfd)
1388                                 maxfd = msg_fd_in;
1389                         using_r_fds = 1;
1390                 } else
1391                         using_r_fds = 0;
1392
1393                 tv.tv_sec = select_timeout;
1394                 tv.tv_usec = 0;
1395
1396                 errno = 0;
1397                 count = select(maxfd + 1, using_r_fds ? &r_fds : NULL,
1398                                &w_fds, &e_fds, &tv);
1399
1400                 if (count <= 0) {
1401                         if (count < 0 && errno == EBADF)
1402                                 exit_cleanup(RERR_SOCKETIO);
1403                         check_timeout();
1404                         continue;
1405                 }
1406
1407                 /*if (FD_ISSET(fd, &e_fds))
1408                         rprintf(FINFO, "select exception on fd %d\n", fd); */
1409
1410                 if (using_r_fds && FD_ISSET(msg_fd_in, &r_fds))
1411                         read_msg_fd();
1412
1413                 if (!FD_ISSET(fd, &w_fds))
1414                         continue;
1415
1416                 n = len - total;
1417                 if (bwlimit_writemax && n > bwlimit_writemax)
1418                         n = bwlimit_writemax;
1419                 cnt = write(fd, buf + total, n);
1420
1421                 if (cnt <= 0) {
1422                         if (cnt < 0) {
1423                                 if (errno == EINTR)
1424                                         continue;
1425                                 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1426                                         msleep(1);
1427                                         continue;
1428                                 }
1429                         }
1430
1431                         /* Don't try to write errors back across the stream. */
1432                         if (fd == sock_f_out)
1433                                 io_end_multiplex_out();
1434                         /* Don't try to write errors down a failing msg pipe. */
1435                         if (am_server && fd == msg_fd_out)
1436                                 exit_cleanup(RERR_STREAMIO);
1437                         rsyserr(FERROR, errno,
1438                                 "writefd_unbuffered failed to write %ld bytes [%s]",
1439                                 (long)len, who_am_i());
1440                         /* If the other side is sending us error messages, try
1441                          * to grab any messages they sent before they died. */
1442                         while (!am_server && fd == sock_f_out && io_multiplexing_in) {
1443                                 set_io_timeout(30);
1444                                 ignore_timeout = 0;
1445                                 readfd_unbuffered(sock_f_in, io_filesfrom_buf,
1446                                                   sizeof io_filesfrom_buf);
1447                         }
1448                         exit_cleanup(RERR_STREAMIO);
1449                 }
1450
1451                 total += cnt;
1452                 defer_forwarding_messages++, defer_inc++;
1453
1454                 if (fd == sock_f_out) {
1455                         if (io_timeout || am_generator)
1456                                 last_io_out = time(NULL);
1457                         sleep_for_bwlimit(cnt);
1458                 }
1459         }
1460
1461         no_flush--;
1462         if (!(defer_forwarding_messages -= defer_inc))
1463                 msg_flush();
1464 }
1465
1466 void io_flush(int flush_it_all)
1467 {
1468         if (!iobuf_out_cnt || no_flush)
1469                 return;
1470
1471         if (io_multiplexing_out)
1472                 mplex_write(sock_f_out, MSG_DATA, iobuf_out, iobuf_out_cnt, 0);
1473         else
1474                 writefd_unbuffered(iobuf_f_out, iobuf_out, iobuf_out_cnt);
1475         iobuf_out_cnt = 0;
1476
1477         if (flush_it_all && !defer_forwarding_messages)
1478                 msg_flush();
1479 }
1480
1481 static void writefd(int fd, const char *buf, size_t len)
1482 {
1483         if (fd == sock_f_out)
1484                 stats.total_written += len;
1485
1486         if (fd == write_batch_monitor_out) {
1487                 if ((size_t)write(batch_fd, buf, len) != len)
1488                         exit_cleanup(RERR_FILEIO);
1489         }
1490
1491         if (!iobuf_out || fd != iobuf_f_out) {
1492                 writefd_unbuffered(fd, buf, len);
1493                 return;
1494         }
1495
1496         while (len) {
1497                 int n = MIN((int)len, IO_BUFFER_SIZE - iobuf_out_cnt);
1498                 if (n > 0) {
1499                         memcpy(iobuf_out+iobuf_out_cnt, buf, n);
1500                         buf += n;
1501                         len -= n;
1502                         iobuf_out_cnt += n;
1503                 }
1504
1505                 if (iobuf_out_cnt == IO_BUFFER_SIZE)
1506                         io_flush(NORMAL_FLUSH);
1507         }
1508 }
1509
1510 void write_shortint(int f, unsigned short x)
1511 {
1512         char b[2];
1513         b[0] = (char)x;
1514         b[1] = (char)(x >> 8);
1515         writefd(f, b, 2);
1516 }
1517
1518 void write_int(int f, int32 x)
1519 {
1520         char b[4];
1521         SIVAL(b, 0, x);
1522         writefd(f, b, 4);
1523 }
1524
1525 void write_varint(int f, int32 x)
1526 {
1527         char b[5];
1528         uchar bit;
1529         int cnt = 4;
1530
1531         SIVAL(b, 1, x);
1532
1533         while (cnt > 1 && b[cnt] == 0)
1534                 cnt--;
1535         bit = ((uchar)1<<(7-cnt+1));
1536         if (CVAL(b, cnt) >= bit) {
1537                 cnt++;
1538                 *b = ~(bit-1);
1539         } else if (cnt > 1)
1540                 *b = b[cnt] | ~(bit*2-1);
1541         else
1542                 *b = b[cnt];
1543
1544         writefd(f, b, cnt);
1545 }
1546
1547 void write_varlong(int f, int64 x, uchar min_bytes)
1548 {
1549         char b[9];
1550         uchar bit;
1551         int cnt = 8;
1552
1553         SIVAL(b, 1, x);
1554 #if SIZEOF_INT64 >= 8
1555         SIVAL(b, 5, x >> 32);
1556 #else
1557         if (x <= 0x7FFFFFFF && x >= 0)
1558                 memset(b + 5, 0, 4);
1559         else {
1560                 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1561                 exit_cleanup(RERR_UNSUPPORTED);
1562         }
1563 #endif
1564
1565         while (cnt > min_bytes && b[cnt] == 0)
1566                 cnt--;
1567         bit = ((uchar)1<<(7-cnt+min_bytes));
1568         if (CVAL(b, cnt) >= bit) {
1569                 cnt++;
1570                 *b = ~(bit-1);
1571         } else if (cnt > min_bytes)
1572                 *b = b[cnt] | ~(bit*2-1);
1573         else
1574                 *b = b[cnt];
1575
1576         writefd(f, b, cnt);
1577 }
1578
1579 /*
1580  * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1581  * 64-bit types on this platform.
1582  */
1583 void write_longint(int f, int64 x)
1584 {
1585         char b[12], * const s = b+4;
1586
1587         SIVAL(s, 0, x);
1588         if (x <= 0x7FFFFFFF && x >= 0) {
1589                 writefd(f, s, 4);
1590                 return;
1591         }
1592
1593 #if SIZEOF_INT64 < 8
1594         rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1595         exit_cleanup(RERR_UNSUPPORTED);
1596 #else
1597         memset(b, 0xFF, 4);
1598         SIVAL(s, 4, x >> 32);
1599         writefd(f, b, 12);
1600 #endif
1601 }
1602
1603 void write_buf(int f, const char *buf, size_t len)
1604 {
1605         writefd(f,buf,len);
1606 }
1607
1608 /** Write a string to the connection */
1609 void write_sbuf(int f, const char *buf)
1610 {
1611         writefd(f, buf, strlen(buf));
1612 }
1613
1614 void write_byte(int f, uchar c)
1615 {
1616         writefd(f, (char *)&c, 1);
1617 }
1618
1619 void write_vstring(int f, const char *str, int len)
1620 {
1621         uchar lenbuf[3], *lb = lenbuf;
1622
1623         if (len > 0x7F) {
1624                 if (len > 0x7FFF) {
1625                         rprintf(FERROR,
1626                                 "attempting to send over-long vstring (%d > %d)\n",
1627                                 len, 0x7FFF);
1628                         exit_cleanup(RERR_PROTOCOL);
1629                 }
1630                 *lb++ = len / 0x100 + 0x80;
1631         }
1632         *lb = len;
1633
1634         writefd(f, (char*)lenbuf, lb - lenbuf + 1);
1635         if (len)
1636                 writefd(f, str, len);
1637 }
1638
1639 /* Send a file-list index using a byte-reduction method. */
1640 void write_ndx(int f, int32 ndx)
1641 {
1642         static int32 prev_positive = -1, prev_negative = 1;
1643         int32 diff, cnt = 0;
1644         char b[6];
1645
1646         if (protocol_version < 30 || read_batch) {
1647                 write_int(f, ndx);
1648                 return;
1649         }
1650
1651         /* Send NDX_DONE as a single-byte 0 with no side effects.  Send
1652          * negative nums as a positive after sending a leading 0xFF. */
1653         if (ndx >= 0) {
1654                 diff = ndx - prev_positive;
1655                 prev_positive = ndx;
1656         } else if (ndx == NDX_DONE) {
1657                 *b = 0;
1658                 writefd(f, b, 1);
1659                 return;
1660         } else {
1661                 b[cnt++] = (char)0xFF;
1662                 ndx = -ndx;
1663                 diff = ndx - prev_negative;
1664                 prev_negative = ndx;
1665         }
1666
1667         /* A diff of 1 - 253 is sent as a one-byte diff; a diff of 254 - 32767
1668          * or 0 is sent as a 0xFE + a two-byte diff; otherwise we send 0xFE
1669          * & all 4 bytes of the (non-negative) num with the high-bit set. */
1670         if (diff < 0xFE && diff > 0)
1671                 b[cnt++] = (char)diff;
1672         else if (diff < 0 || diff > 0x7FFF) {
1673                 b[cnt++] = (char)0xFE;
1674                 b[cnt++] = (char)((ndx >> 24) | 0x80);
1675                 b[cnt++] = (char)ndx;
1676                 b[cnt++] = (char)(ndx >> 8);
1677                 b[cnt++] = (char)(ndx >> 16);
1678         } else {
1679                 b[cnt++] = (char)0xFE;
1680                 b[cnt++] = (char)(diff >> 8);
1681                 b[cnt++] = (char)diff;
1682         }
1683         writefd(f, b, cnt);
1684 }
1685
1686 /* Receive a file-list index using a byte-reduction method. */
1687 int32 read_ndx(int f)
1688 {
1689         static int32 prev_positive = -1, prev_negative = 1;
1690         int32 *prev_ptr, num;
1691         char b[4];
1692
1693         if (protocol_version < 30)
1694                 return read_int(f);
1695
1696         readfd(f, b, 1);
1697         if (CVAL(b, 0) == 0xFF) {
1698                 readfd(f, b, 1);
1699                 prev_ptr = &prev_negative;
1700         } else if (CVAL(b, 0) == 0)
1701                 return NDX_DONE;
1702         else
1703                 prev_ptr = &prev_positive;
1704         if (CVAL(b, 0) == 0xFE) {
1705                 readfd(f, b, 2);
1706                 if (CVAL(b, 0) & 0x80) {
1707                         b[3] = CVAL(b, 0) & ~0x80;
1708                         b[0] = b[1];
1709                         readfd(f, b+1, 2);
1710                         num = IVAL(b, 0);
1711                 } else
1712                         num = (UVAL(b,0)<<8) + UVAL(b,1) + *prev_ptr;
1713         } else
1714                 num = UVAL(b, 0) + *prev_ptr;
1715         *prev_ptr = num;
1716         if (prev_ptr == &prev_negative)
1717                 num = -num;
1718         return num;
1719 }
1720
1721 /* Read a line of up to bufsiz-1 characters into buf.  Strips
1722  * the (required) trailing newline and all carriage returns.
1723  * Returns 1 for success; 0 for I/O error or truncation. */
1724 int read_line_old(int f, char *buf, size_t bufsiz)
1725 {
1726         bufsiz--; /* leave room for the null */
1727         while (bufsiz > 0) {
1728                 buf[0] = 0;
1729                 read_buf(f, buf, 1);
1730                 if (buf[0] == 0)
1731                         return 0;
1732                 if (buf[0] == '\n')
1733                         break;
1734                 if (buf[0] != '\r') {
1735                         buf++;
1736                         bufsiz--;
1737                 }
1738         }
1739         *buf = '\0';
1740         return bufsiz > 0;
1741 }
1742
1743 void io_printf(int fd, const char *format, ...)
1744 {
1745         va_list ap;
1746         char buf[BIGPATHBUFLEN];
1747         int len;
1748
1749         va_start(ap, format);
1750         len = vsnprintf(buf, sizeof buf, format, ap);
1751         va_end(ap);
1752
1753         if (len < 0)
1754                 exit_cleanup(RERR_STREAMIO);
1755
1756         if (len > (int)sizeof buf) {
1757                 rprintf(FERROR, "io_printf() was too long for the buffer.\n");
1758                 exit_cleanup(RERR_STREAMIO);
1759         }
1760
1761         write_sbuf(fd, buf);
1762 }
1763
1764 /** Setup for multiplexing a MSG_* stream with the data stream. */
1765 void io_start_multiplex_out(void)
1766 {
1767         io_flush(NORMAL_FLUSH);
1768         io_start_buffering_out(sock_f_out);
1769         io_multiplexing_out = 1;
1770 }
1771
1772 /** Setup for multiplexing a MSG_* stream with the data stream. */
1773 void io_start_multiplex_in(void)
1774 {
1775         io_flush(NORMAL_FLUSH);
1776         io_start_buffering_in(sock_f_in);
1777         io_multiplexing_in = 1;
1778 }
1779
1780 /** Write an message to the multiplexed data stream. */
1781 int io_multiplex_write(enum msgcode code, const char *buf, size_t len, int convert)
1782 {
1783         if (!io_multiplexing_out)
1784                 return 0;
1785         io_flush(NORMAL_FLUSH);
1786         stats.total_written += (len+4);
1787         mplex_write(sock_f_out, code, buf, len, convert);
1788         return 1;
1789 }
1790
1791 void io_end_multiplex_in(void)
1792 {
1793         io_multiplexing_in = 0;
1794         io_end_buffering_in();
1795 }
1796
1797 /** Stop output multiplexing. */
1798 void io_end_multiplex_out(void)
1799 {
1800         io_multiplexing_out = 0;
1801         io_end_buffering_out();
1802 }
1803
1804 void start_write_batch(int fd)
1805 {
1806         /* Some communication has already taken place, but we don't
1807          * enable batch writing until here so that we can write a
1808          * canonical record of the communication even though the
1809          * actual communication so far depends on whether a daemon
1810          * is involved. */
1811         write_int(batch_fd, protocol_version);
1812         write_int(batch_fd, checksum_seed);
1813
1814         if (am_sender)
1815                 write_batch_monitor_out = fd;
1816         else
1817                 write_batch_monitor_in = fd;
1818 }
1819
1820 void stop_write_batch(void)
1821 {
1822         write_batch_monitor_out = -1;
1823         write_batch_monitor_in = -1;
1824 }