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