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