b717b431b071fb8a7e4b8301a525096d336b7c27
[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 msgs2stderr;
45 extern int inc_recurse;
46 extern int io_error;
47 extern int eol_nulls;
48 extern int flist_eof;
49 extern int file_total;
50 extern int file_old_total;
51 extern int list_only;
52 extern int read_batch;
53 extern int protect_args;
54 extern int checksum_seed;
55 extern int protocol_version;
56 extern int remove_source_files;
57 extern int preserve_hard_links;
58 extern BOOL extra_flist_sending_enabled;
59 extern struct stats stats;
60 extern struct file_list *cur_flist;
61 #ifdef ICONV_OPTION
62 extern int filesfrom_convert;
63 extern iconv_t ic_send, ic_recv;
64 #endif
65
66 int csum_length = SHORT_SUM_LENGTH; /* initial value */
67 int allowed_lull = 0;
68 int ignore_timeout = 0;
69 int batch_fd = -1;
70 int msgdone_cnt = 0;
71 int forward_flist_data = 0;
72
73 /* Ignore an EOF error if non-zero. See whine_about_eof(). */
74 int kluge_around_eof = 0;
75
76 int sock_f_in = -1;
77 int sock_f_out = -1;
78
79 int64 total_data_read = 0;
80 int64 total_data_written = 0;
81
82 static struct {
83         xbuf in, out, msg;
84         int in_fd;
85         int out_fd; /* Both "out" and "msg" go to this fd. */
86         BOOL in_multiplexed;
87         unsigned out_empty_len;
88         size_t raw_data_header_pos;      /* in the out xbuf */
89         size_t raw_flushing_ends_before; /* in the out xbuf */
90         size_t raw_input_ends_before;    /* in the in xbuf */
91 } iobuf = { .in_fd = -1, .out_fd = -1 };
92
93 static time_t last_io_in;
94 static time_t last_io_out;
95
96 static int write_batch_monitor_in = -1;
97 static int write_batch_monitor_out = -1;
98
99 static int ff_forward_fd = -1;
100 static int ff_reenable_multiplex = -1;
101 static char ff_lastchar = '\0';
102 static xbuf ff_xb = EMPTY_XBUF;
103 #ifdef ICONV_OPTION
104 static xbuf iconv_buf = EMPTY_XBUF;
105 #endif
106 static int select_timeout = SELECT_TIMEOUT;
107 static int active_filecnt = 0;
108 static OFF_T active_bytecnt = 0;
109 static int first_message = 1;
110
111 static char int_byte_extra[64] = {
112         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* (00 - 3F)/4 */
113         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* (40 - 7F)/4 */
114         1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* (80 - BF)/4 */
115         2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 6, /* (C0 - FF)/4 */
116 };
117
118 #define IN_MULTIPLEXED (iobuf.in_multiplexed)
119 #define OUT_MULTIPLEXED (iobuf.out_empty_len != 0)
120
121 #define PIO_NEED_INPUT (1<<0) /* The *_NEED_* flags are mutually exclusive. */
122 #define PIO_NEED_OUTROOM (1<<1)
123 #define PIO_NEED_MSGROOM (1<<2)
124
125 #define PIO_CONSUME_INPUT (1<<4) /* Must becombined with PIO_NEED_INPUT. */
126
127 #define PIO_INPUT_AND_CONSUME (PIO_NEED_INPUT | PIO_CONSUME_INPUT)
128 #define PIO_NEED_FLAGS (PIO_NEED_INPUT | PIO_NEED_OUTROOM | PIO_NEED_MSGROOM)
129
130 #define REMOTE_OPTION_ERROR "rsync: on remote machine: -"
131 #define REMOTE_OPTION_ERROR2 ": unknown option"
132
133 #define FILESFROM_BUFLEN 2048
134
135 enum festatus { FES_SUCCESS, FES_REDO, FES_NO_SEND };
136
137 static flist_ndx_list redo_list, hlink_list;
138
139 static void sleep_for_bwlimit(int bytes_written);
140
141 static void check_timeout(void)
142 {
143         time_t t;
144
145         if (!io_timeout || ignore_timeout)
146                 return;
147
148         if (!last_io_in) {
149                 last_io_in = time(NULL);
150                 return;
151         }
152
153         t = time(NULL);
154
155         if (t - last_io_in >= io_timeout) {
156                 if (!am_server && !am_daemon) {
157                         rprintf(FERROR, "io timeout after %d seconds -- exiting\n",
158                                 (int)(t-last_io_in));
159                 }
160                 exit_cleanup(RERR_TIMEOUT);
161         }
162 }
163
164 /* It's almost always an error to get an EOF when we're trying to read from the
165  * network, because the protocol is (for the most part) self-terminating.
166  *
167  * There is one case for the receiver when it is at the end of the transfer
168  * (hanging around reading any keep-alive packets that might come its way): if
169  * the sender dies before the generator's kill-signal comes through, we can end
170  * up here needing to loop until the kill-signal arrives.  In this situation,
171  * kluge_around_eof will be < 0.
172  *
173  * There is another case for older protocol versions (< 24) where the module
174  * listing was not terminated, so we must ignore an EOF error in that case and
175  * exit.  In this situation, kluge_around_eof will be > 0. */
176 static NORETURN void whine_about_eof(int fd)
177 {
178         if (kluge_around_eof && fd == sock_f_in) {
179                 int i;
180                 if (kluge_around_eof > 0)
181                         exit_cleanup(0);
182                 /* If we're still here after 10 seconds, exit with an error. */
183                 for (i = 10*1000/20; i--; )
184                         msleep(20);
185         }
186
187         rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
188                 "(%s bytes received so far) [%s]\n",
189                 big_num(stats.total_read), who_am_i());
190
191         exit_cleanup(RERR_STREAMIO);
192 }
193
194 /* Do a safe read, handling any needed looping and error handling.
195  * Returns the count of the bytes read, which will only be different
196  * from "len" if we encountered an EOF.  This routine is not used on
197  * the socket except very early in the transfer. */
198 static size_t safe_read(int fd, char *buf, size_t len)
199 {
200         size_t got;
201         int n;
202
203         assert(fd != iobuf.in_fd);
204
205         n = read(fd, buf, len);
206         if ((size_t)n == len || n == 0) {
207                 if (DEBUG_GTE(IO, 2))
208                         rprintf(FINFO, "[%s] safe_read(%d)=%ld\n", who_am_i(), fd, (long)n);
209                 return n;
210         }
211         if (n < 0) {
212                 if (errno != EINTR && errno != EWOULDBLOCK && errno != EAGAIN) {
213                   read_failed:
214                         rsyserr(FERROR, errno, "safe_read failed to read %ld bytes [%s]",
215                                 (long)len, who_am_i());
216                         exit_cleanup(RERR_STREAMIO);
217                 }
218                 got = 0;
219         } else
220                 got = n;
221
222         while (1) {
223                 struct timeval tv;
224                 fd_set r_fds, e_fds;
225                 int cnt;
226
227                 FD_ZERO(&r_fds);
228                 FD_SET(fd, &r_fds);
229                 FD_ZERO(&e_fds);
230                 FD_SET(fd, &e_fds);
231                 tv.tv_sec = select_timeout;
232                 tv.tv_usec = 0;
233
234                 cnt = select(fd+1, &r_fds, NULL, &e_fds, &tv);
235                 if (cnt <= 0) {
236                         if (cnt < 0 && errno == EBADF) {
237                                 rsyserr(FERROR, errno, "safe_read select failed [%s]",
238                                         who_am_i());
239                                 exit_cleanup(RERR_FILEIO);
240                         }
241                         check_timeout();
242                         continue;
243                 }
244
245                 /*if (FD_ISSET(fd, &e_fds))
246                         rprintf(FINFO, "select exception on fd %d\n", fd); */
247
248                 if (FD_ISSET(fd, &r_fds)) {
249                         n = read(fd, buf + got, len - got);
250                         if (DEBUG_GTE(IO, 2))
251                                 rprintf(FINFO, "[%s] safe_read(%d)=%ld\n", who_am_i(), fd, (long)n);
252                         if (n == 0)
253                                 break;
254                         if (n < 0) {
255                                 if (errno == EINTR)
256                                         continue;
257                                 goto read_failed;
258                         }
259                         if ((got += (size_t)n) == len)
260                                 break;
261                 }
262         }
263
264         return got;
265 }
266
267 static const char *what_fd_is(int fd)
268 {
269         static char buf[20];
270
271         if (fd == sock_f_out)
272                 return "socket";
273         else if (fd == iobuf.out_fd)
274                 return "message fd";
275         else if (fd == batch_fd)
276                 return "batch file";
277         else {
278                 snprintf(buf, sizeof buf, "fd %d", fd);
279                 return buf;
280         }
281 }
282
283 /* Do a safe write, handling any needed looping and error handling.
284  * Returns only if everything was successfully written.  This routine
285  * is not used on the socket except very early in the transfer. */
286 static void safe_write(int fd, const char *buf, size_t len)
287 {
288         int n;
289
290         assert(fd != iobuf.out_fd);
291
292         n = write(fd, buf, len);
293         if ((size_t)n == len)
294                 return;
295         if (n < 0) {
296                 if (errno != EINTR && errno != EWOULDBLOCK && errno != EAGAIN) {
297                   write_failed:
298                         rsyserr(FERROR, errno,
299                                 "safe_write failed to write %ld bytes to %s [%s]",
300                                 (long)len, what_fd_is(fd), who_am_i());
301                         exit_cleanup(RERR_STREAMIO);
302                 }
303         } else {
304                 buf += n;
305                 len -= n;
306         }
307
308         while (len) {
309                 struct timeval tv;
310                 fd_set w_fds;
311                 int cnt;
312
313                 FD_ZERO(&w_fds);
314                 FD_SET(fd, &w_fds);
315                 tv.tv_sec = select_timeout;
316                 tv.tv_usec = 0;
317
318                 cnt = select(fd + 1, NULL, &w_fds, NULL, &tv);
319                 if (cnt <= 0) {
320                         if (cnt < 0 && errno == EBADF) {
321                                 rsyserr(FERROR, errno, "safe_write select failed on %s [%s]",
322                                         what_fd_is(fd), who_am_i());
323                                 exit_cleanup(RERR_FILEIO);
324                         }
325                         check_timeout();
326                         continue;
327                 }
328
329                 if (FD_ISSET(fd, &w_fds)) {
330                         n = write(fd, buf, len);
331                         if (n < 0) {
332                                 if (errno == EINTR)
333                                         continue;
334                                 goto write_failed;
335                         }
336                         buf += n;
337                         len -= n;
338                 }
339         }
340 }
341
342 /* This is only called when files-from data is known to be available.  We read
343  * a chunk of data and put it into the output buffer. */
344 static void forward_filesfrom_data(void)
345 {
346         int len;
347
348         len = read(ff_forward_fd, ff_xb.buf + ff_xb.len, ff_xb.size - ff_xb.len);
349         if (len <= 0) {
350                 if (len == 0 || errno != EINTR) {
351                         /* Send end-of-file marker */
352                         ff_forward_fd = -1;
353                         write_buf(iobuf.out_fd, "\0\0", ff_lastchar ? 2 : 1);
354                         free_xbuf(&ff_xb);
355                         if (ff_reenable_multiplex >= 0)
356                                 io_start_multiplex_out(ff_reenable_multiplex);
357                 }
358                 return;
359         }
360
361         if (DEBUG_GTE(IO, 2))
362                 rprintf(FINFO, "[%s] files-from read=%ld\n", who_am_i(), (long)len);
363
364 #ifdef ICONV_OPTION
365         len += ff_xb.len;
366 #endif
367
368         if (!eol_nulls) {
369                 char *s = ff_xb.buf + len;
370                 /* Transform CR and/or LF into '\0' */
371                 while (s-- > ff_xb.buf) {
372                         if (*s == '\n' || *s == '\r')
373                                 *s = '\0';
374                 }
375         }
376
377         if (ff_lastchar)
378                 ff_xb.pos = 0;
379         else {
380                 char *s = ff_xb.buf;
381                 /* Last buf ended with a '\0', so don't let this buf start with one. */
382                 while (len && *s == '\0')
383                         s++, len--;
384                 ff_xb.pos = s - ff_xb.buf;
385         }
386
387 #ifdef ICONV_OPTION
388         if (filesfrom_convert && len) {
389                 char *sob = ff_xb.buf + ff_xb.pos, *s = sob;
390                 char *eob = sob + len;
391                 int flags = ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE | ICB_CIRCULAR_OUT;
392                 if (ff_lastchar == '\0')
393                         flags |= ICB_INIT;
394                 /* Convert/send each null-terminated string separately, skipping empties. */
395                 while (s != eob) {
396                         if (*s++ == '\0') {
397                                 ff_xb.len = s - sob - 1;
398                                 if (iconvbufs(ic_send, &ff_xb, &iobuf.out, flags) < 0)
399                                         exit_cleanup(RERR_PROTOCOL); /* impossible? */
400                                 write_buf(iobuf.out_fd, s-1, 1); /* Send the '\0'. */
401                                 while (s != eob && *s == '\0')
402                                         s++;
403                                 sob = s;
404                                 ff_xb.pos = sob - ff_xb.buf;
405                                 flags |= ICB_INIT;
406                         }
407                 }
408
409                 if ((ff_xb.len = s - sob) == 0)
410                         ff_lastchar = '\0';
411                 else {
412                         /* Handle a partial string specially, saving any incomplete chars. */
413                         flags &= ~ICB_INCLUDE_INCOMPLETE;
414                         if (iconvbufs(ic_send, &ff_xb, &iobuf.out, flags) < 0) {
415                                 if (errno == E2BIG)
416                                         exit_cleanup(RERR_PROTOCOL); /* impossible? */
417                                 if (ff_xb.pos)
418                                         memmove(ff_xb.buf, ff_xb.buf + ff_xb.pos, ff_xb.len);
419                         }
420                         ff_lastchar = 'x'; /* Anything non-zero. */
421                 }
422         } else
423 #endif
424
425         if (len) {
426                 char *f = ff_xb.buf + ff_xb.pos;
427                 char *t = ff_xb.buf;
428                 char *eob = f + len;
429                 /* Eliminate any multi-'\0' runs. */
430                 while (f != eob) {
431                         if (!(*t++ = *f++)) {
432                                 while (f != eob && *f == '\0')
433                                         f++;
434                         }
435                 }
436                 ff_lastchar = f[-1];
437                 if ((len = t - ff_xb.buf) != 0) {
438                         /* This will not circle back to perform_io() because we only get
439                          * called when there is plenty of room in the output buffer. */
440                         write_buf(iobuf.out_fd, ff_xb.buf, len);
441                 }
442         }
443 }
444
445 /* Perform buffered input and output until specified conditions are met.  When
446  * given a "needed" read requirement, we'll return without doing any I/O if the
447  * iobuf.in bytes are already available.  When reading, we'll read as many
448  * bytes as we can into the buffer, and return as soon as we meet the minimum
449  * read requirement.  When given a "needed" write requirement, we'll return
450  * without doing any I/O if that many bytes will fit in the output buffer (we
451  * check either iobuf.out or iobuf.msg, depending on the flags).  When writing,
452  * we write out as much as we can, and return as soon as the given free-space
453  * requirement is available.
454  *
455  * The iobuf.out and iobuf.msg buffers are circular, so some writes into them
456  * will need to be split when the data needs to wrap around to the start.  In
457  * order to help make this easier for some operations (such as the use of
458  * SIVAL() into the buffer) the buffers MUST have 4 bytes of overflow space at
459  * the end that is not not counted in the "size".  The iobuf.in buffer is not
460  * (currently) circular.  To facilitate the handling of MSG_DATA bytes as they
461  * are read-from/written-into the buffers, see the three raw_* iobuf vars.
462  *
463  * When writing, we flush data in the following priority order:
464  *
465  * 1. Finish writing any in-progress MSG_DATA sequence from iobuf.out.
466  *
467  * 2. Write out all the messages from the message buf (if iobuf.msg is active).
468  *    Yes, this means that a PIO_NEED_OUTROOM call will completely flush any
469  *    messages before getting to the iobuf.out flushing (except for rule 1).
470  *
471  * 3. Write out the raw data from iobuf.out, possibly filling in the multiplexed
472  *    MSG_DATA header that was pre-allocated (when output is multiplexed).
473  *
474  * TODO:  items for possible future work:
475  *
476  *    - Make this routine able to read the generator-to-receiver batch flow?
477  *
478  *    - Make the input buffer circular?
479  *
480  * Unlike the old routines that this replaces, it is OK to read ahead as far as
481  * we can because the read_a_msg() routine now reads its bytes out of the input
482  * buffer.  In the old days, only raw data was in the input buffer, and any
483  * unused raw data in the buf would prevent the reading of socket data. */
484 static char *perform_io(size_t needed, int flags)
485 {
486         fd_set r_fds, e_fds, w_fds;
487         struct timeval tv;
488         int cnt, max_fd;
489         size_t empty_buf_len = 0;
490         xbuf *out;
491         char *data;
492
493         if (iobuf.in.len == 0 && iobuf.in.pos != 0) {
494                 if (iobuf.raw_input_ends_before)
495                         iobuf.raw_input_ends_before -= iobuf.in.pos;
496                 iobuf.in.pos = 0;
497         }
498
499         switch (flags & PIO_NEED_FLAGS) {
500         case PIO_NEED_INPUT:
501                 if (DEBUG_GTE(IO, 3)) {
502                         rprintf(FINFO, "[%s] perform_io(%ld, %sinput)\n",
503                                 who_am_i(), (long)needed, flags & PIO_CONSUME_INPUT ? "consume&" : "");
504                 }
505
506                 /* Make sure the input buffer is big enough to hold "needed" bytes.
507                  * Also make sure it will fit in the free space at the end, or
508                  * else we need to shift some bytes. */
509                 if (needed && iobuf.in.size < needed) {
510                         if (!(iobuf.in.buf = realloc_array(iobuf.in.buf, char, needed)))
511                                 out_of_memory("perform_io");
512                         if (DEBUG_GTE(IO, 4)) {
513                                 rprintf(FINFO, "[%s] resized input buffer from %ld to %ld bytes.\n",
514                                         who_am_i(), (long)iobuf.in.size, (long)needed);
515                         }
516                         iobuf.in.size = needed;
517                 }
518                 if (iobuf.in.size - iobuf.in.pos < needed
519                  || (iobuf.in.len < needed && iobuf.in.len < 1024
520                   && iobuf.in.size - (iobuf.in.pos + iobuf.in.len) < 1024)) {
521                         memmove(iobuf.in.buf, iobuf.in.buf + iobuf.in.pos, iobuf.in.len);
522                         if (DEBUG_GTE(IO, 4)) {
523                                 rprintf(FINFO,
524                                         "[%s] moved %ld bytes from %ld to 0 in the input buffer (size=%ld, needed=%ld).\n",
525                                         who_am_i(), (long)iobuf.in.len, (long)iobuf.in.pos, (long)iobuf.in.size, (long)needed);
526                         }
527                         if (iobuf.raw_input_ends_before)
528                                 iobuf.raw_input_ends_before -= iobuf.in.pos;
529                         iobuf.in.pos = 0;
530                 }
531                 break;
532
533         case PIO_NEED_OUTROOM:
534                 /* We never resize the circular output buffer. */
535                 if (iobuf.out.size - iobuf.out_empty_len < needed) {
536                         fprintf(stderr, "need to write %ld bytes, iobuf.out.buf is only %ld bytes.\n",
537                                 (long)needed, (long)(iobuf.out.size - iobuf.out_empty_len));
538                         exit_cleanup(RERR_PROTOCOL);
539                 }
540
541                 if (DEBUG_GTE(IO, 3)) {
542                         rprintf(FINFO, "[%s] perform_io(%ld, outroom) needs to flush %ld\n",
543                                 who_am_i(), (long)needed,
544                                 iobuf.out.len + needed > iobuf.out.size
545                                 ? (long)(iobuf.out.len + needed - iobuf.out.size) : 0L);
546                 }
547                 break;
548
549         case PIO_NEED_MSGROOM:
550                 /* We never resize the circular message buffer. */
551                 if (iobuf.msg.size < needed) {
552                         fprintf(stderr, "need to write %ld bytes, iobuf.msg.buf is only %ld bytes.\n",
553                                 (long)needed, (long)iobuf.msg.size);
554                         exit_cleanup(RERR_PROTOCOL);
555                 }
556
557                 if (DEBUG_GTE(IO, 3)) {
558                         rprintf(FINFO, "[%s] perform_io(%ld, msgroom) needs to flush %ld\n",
559                                 who_am_i(), (long)needed,
560                                 iobuf.msg.len + needed > iobuf.msg.size
561                                 ? (long)(iobuf.msg.len + needed - iobuf.msg.size) : 0L);
562                 }
563                 break;
564
565         case 0:
566                 if (DEBUG_GTE(IO, 3))
567                         rprintf(FINFO, "[%s] perform_io(%ld, %d)\n", who_am_i(), (long)needed, flags);
568                 break;
569
570         default:
571                 exit_cleanup(RERR_UNSUPPORTED);
572         }
573
574         while (1) {
575                 switch (flags & PIO_NEED_FLAGS) {
576                 case PIO_NEED_INPUT:
577                         if (iobuf.in.len >= needed)
578                                 goto double_break;
579                         break;
580                 case PIO_NEED_OUTROOM:
581                         /* Note that iobuf.out_empty_len doesn't factor into this check
582                          * because iobuf.out.len already holds any needed header len. */
583                         if (iobuf.out.len + needed <= iobuf.out.size)
584                                 goto double_break;
585                         break;
586                 case PIO_NEED_MSGROOM:
587                         if (iobuf.msg.len + needed <= iobuf.msg.size)
588                                 goto double_break;
589                         break;
590                 }
591
592                 max_fd = -1;
593
594                 FD_ZERO(&r_fds);
595                 FD_ZERO(&e_fds);
596                 if (iobuf.in_fd >= 0 && iobuf.in.size - (iobuf.in.pos + iobuf.in.len)) {
597                         if (!read_batch || batch_fd >= 0) {
598                                 FD_SET(iobuf.in_fd, &r_fds);
599                                 FD_SET(iobuf.in_fd, &e_fds);
600                         }
601                         if (iobuf.in_fd > max_fd)
602                                 max_fd = iobuf.in_fd;
603                 }
604
605                 /* Only do more filesfrom processing if there is enough room in the out buffer. */
606                 if (ff_forward_fd >= 0 && iobuf.out.size - iobuf.out.len > FILESFROM_BUFLEN*2) {
607                         FD_SET(ff_forward_fd, &r_fds);
608                         if (ff_forward_fd > max_fd)
609                                 max_fd = ff_forward_fd;
610                 }
611
612                 FD_ZERO(&w_fds);
613                 if (iobuf.out_fd >= 0) {
614                         if (iobuf.raw_flushing_ends_before
615                          || (!iobuf.msg.len && iobuf.out.len > iobuf.out_empty_len && !(flags & PIO_NEED_MSGROOM))) {
616                                 if (OUT_MULTIPLEXED && !iobuf.raw_flushing_ends_before) {
617                                         size_t val;
618
619                                         /* The iobuf.raw_flushing_ends_before value can point off the end
620                                          * of the iobuf.out buffer for a while, for easier subtracting. */
621                                         iobuf.raw_flushing_ends_before = iobuf.out.pos + iobuf.out.len;
622
623                                         SIVAL(iobuf.out.buf + iobuf.raw_data_header_pos, 0,
624                                               ((MPLEX_BASE + (int)MSG_DATA)<<24) + iobuf.out.len - 4);
625                                         if ((val = iobuf.out.size - iobuf.raw_data_header_pos) < 4) {
626                                                 /* We used some of the overflow bytes, so move them. */
627                                                 if (DEBUG_GTE(IO, 4)) {
628                                                         rprintf(FINFO, "[%s] wrap-bytes moved: %d (perform_io)\n",
629                                                                 who_am_i(), (int)val);
630                                                 }
631                                                 memcpy(iobuf.out.buf, iobuf.out.buf + iobuf.out.size, 4 - val);
632                                         }
633
634                                         if (DEBUG_GTE(IO, 1)) {
635                                                 rprintf(FINFO, "[%s] send_msg(%d, %ld)\n",
636                                                         who_am_i(), (int)MSG_DATA, (long)iobuf.out.len - 4);
637                                         }
638
639                                         /* reserve room for the next MSG_DATA header */
640                                         iobuf.raw_data_header_pos = iobuf.raw_flushing_ends_before;
641                                         if (iobuf.raw_data_header_pos >= iobuf.out.size)
642                                                 iobuf.raw_data_header_pos -= iobuf.out.size;
643                                         /* Yes, it is possible for this to make len > size for a while. */
644                                         iobuf.out.len += 4;
645                                 }
646
647                                 empty_buf_len = iobuf.out_empty_len;
648                                 out = &iobuf.out;
649                         } else if (iobuf.msg.len) {
650                                 empty_buf_len = 0;
651                                 out = &iobuf.msg;
652                         } else
653                                 out = NULL;
654                         if (out) {
655                                 FD_SET(iobuf.out_fd, &w_fds);
656                                 if (iobuf.out_fd > max_fd)
657                                         max_fd = iobuf.out_fd;
658                         }
659                 } else
660                         out = NULL;
661
662                 if (max_fd < 0) {
663                         switch (flags & PIO_NEED_FLAGS) {
664                         case PIO_NEED_INPUT:
665                                 rprintf(FERROR, "error in perform_io: no fd for input.\n");
666                                 exit_cleanup(RERR_PROTOCOL);
667                         case PIO_NEED_OUTROOM:
668                         case PIO_NEED_MSGROOM:
669                                 msgs2stderr = 1;
670                                 rprintf(FERROR, "error in perform_io: no fd for output.\n");
671                                 exit_cleanup(RERR_PROTOCOL);
672                         default:
673                                 /* No stated needs, so I guess this is OK. */
674                                 break;
675                         }
676                         break;
677                 }
678
679                 if (extra_flist_sending_enabled) {
680                         if (file_total - file_old_total < MAX_FILECNT_LOOKAHEAD
681                          && file_total - file_old_total >= MIN_FILECNT_LOOKAHEAD)
682                                 tv.tv_sec = 0;
683                         else {
684                                 extra_flist_sending_enabled = False;
685                                 tv.tv_sec = select_timeout;
686                         }
687                 } else
688                         tv.tv_sec = select_timeout;
689                 tv.tv_usec = 0;
690
691                 cnt = select(max_fd + 1, &r_fds, &w_fds, &e_fds, &tv);
692
693                 if (cnt <= 0) {
694                         if (cnt < 0 && errno == EBADF) {
695                                 msgs2stderr = 1;
696                                 exit_cleanup(RERR_SOCKETIO);
697                         }
698                         if (extra_flist_sending_enabled) {
699                                 extra_flist_sending_enabled = False;
700                                 send_extra_file_list(sock_f_out, -1);
701                                 extra_flist_sending_enabled = !flist_eof;
702                         } else
703                                 check_timeout();
704                         FD_ZERO(&r_fds); /* Just in case... */
705                         FD_ZERO(&w_fds);
706                 }
707
708                 if (iobuf.in_fd >= 0 && FD_ISSET(iobuf.in_fd, &r_fds)) {
709                         size_t pos = iobuf.in.pos + iobuf.in.len;
710                         size_t len = iobuf.in.size - pos;
711                         int n;
712                         if ((n = read(iobuf.in_fd, iobuf.in.buf + pos, len)) <= 0) {
713                                 if (n == 0) {
714                                         if (!read_batch || batch_fd < 0 || am_generator)
715                                                 whine_about_eof(iobuf.in_fd); /* Doesn't return. */
716                                         batch_fd = -1;
717                                         continue;
718                                 }
719                                 if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
720                                         n = 0;
721                                 else {
722                                         /* Don't write errors on a dead socket. */
723                                         if (iobuf.in_fd == sock_f_in) {
724                                                 if (am_sender)
725                                                         msgs2stderr = 1;
726                                                 rsyserr(FERROR_SOCKET, errno, "read error");
727                                         } else
728                                                 rsyserr(FERROR, errno, "read error");
729                                         exit_cleanup(RERR_STREAMIO);
730                                 }
731                         }
732                         if (msgs2stderr && DEBUG_GTE(IO, 2))
733                                 rprintf(FINFO, "[%s] recv=%ld\n", who_am_i(), (long)n);
734
735                         if (io_timeout)
736                                 last_io_in = time(NULL);
737                         stats.total_read += n;
738
739                         iobuf.in.len += n;
740                 }
741
742                 if (iobuf.out_fd >= 0 && FD_ISSET(iobuf.out_fd, &w_fds)) {
743                         size_t len = iobuf.raw_flushing_ends_before ? iobuf.raw_flushing_ends_before - out->pos : out->len;
744                         int n;
745
746                         if (bwlimit_writemax && len > bwlimit_writemax)
747                                 len = bwlimit_writemax;
748
749                         if (out->pos + len > out->size)
750                                 len = out->size - out->pos;
751                         if ((n = write(iobuf.out_fd, out->buf + out->pos, len)) <= 0) {
752                                 if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
753                                         n = 0;
754                                 else {
755                                         /* Don't write errors on a dead socket. */
756                                         msgs2stderr = 1;
757                                         out->len = iobuf.raw_flushing_ends_before = out->pos = 0;
758                                         rsyserr(FERROR_SOCKET, errno, "[%s] write error", who_am_i());
759                                         exit_cleanup(RERR_STREAMIO);
760                                 }
761                         }
762                         if (msgs2stderr && DEBUG_GTE(IO, 2)) {
763                                 rprintf(FINFO, "[%s] %s sent=%ld\n",
764                                         who_am_i(), out == &iobuf.out ? "out" : "msg", (long)n);
765                         }
766
767                         if (io_timeout)
768                                 last_io_out = time(NULL);
769                         stats.total_written += n;
770
771                         if (bwlimit_writemax)
772                                 sleep_for_bwlimit(n);
773
774                         if ((out->pos += n) == out->size) {
775                                 if (iobuf.raw_flushing_ends_before)
776                                         iobuf.raw_flushing_ends_before -= out->size;
777                                 out->pos = 0;
778                         }
779                         if (out->pos == iobuf.raw_flushing_ends_before)
780                                 iobuf.raw_flushing_ends_before = 0;
781                         if ((out->len -= n) == empty_buf_len) {
782                                 out->pos = 0;
783                                 if (empty_buf_len)
784                                         iobuf.raw_data_header_pos = 0;
785                         }
786                 }
787
788                 if (ff_forward_fd >= 0 && FD_ISSET(ff_forward_fd, &r_fds)) {
789                         /* This can potentially flush all output and enable
790                          * multiplexed output, so keep this last in the loop
791                          * and be sure to not cache anything that would break
792                          * such a change. */
793                         forward_filesfrom_data();
794                 }
795         }
796   double_break:
797
798         data = iobuf.in.buf + iobuf.in.pos;
799
800         if (flags & PIO_CONSUME_INPUT) {
801                 iobuf.in.len -= needed;
802                 iobuf.in.pos += needed;
803         }
804
805         return data;
806 }
807
808 void noop_io_until_death(void)
809 {
810         char buf[1024];
811
812         kluge_around_eof = 1;
813         set_io_timeout(protocol_version >= 31 ? 10 : 1);
814
815         while (1)
816                 read_buf(iobuf.in_fd, buf, sizeof buf);
817 }
818
819 /* Buffer a message for the multiplexed output stream.  Is never used for MSG_DATA. */
820 int send_msg(enum msgcode code, const char *buf, size_t len, int convert)
821 {
822         char *hdr;
823         size_t pos;
824         BOOL want_debug = DEBUG_GTE(IO, 1) && convert >= 0 && (msgs2stderr || code != MSG_INFO);
825
826         if (!OUT_MULTIPLEXED)
827                 return 0;
828
829         if (want_debug)
830                 rprintf(FINFO, "[%s] send_msg(%d, %ld)\n", who_am_i(), (int)code, (long)len);
831
832 #ifdef ICONV_OPTION
833         if (convert > 0 && ic_send == (iconv_t)-1)
834                 convert = 0;
835         if (convert > 0) {
836                 /* Ensuring double-size room leaves space for a potential conversion. */
837                 if (iobuf.msg.len + len*2 + 4 > iobuf.msg.size)
838                         perform_io(len*2 + 4, PIO_NEED_MSGROOM);
839         } else
840 #endif
841         if (iobuf.msg.len + len + 4 > iobuf.msg.size)
842                 perform_io(len + 4, PIO_NEED_MSGROOM);
843
844         pos = iobuf.msg.pos + iobuf.msg.len; /* Must be set after any flushing. */
845         if (pos >= iobuf.msg.size)
846                 pos -= iobuf.msg.size;
847         hdr = iobuf.msg.buf + pos;
848
849         iobuf.msg.len += 4; /* Leave room for the coming header bytes. */
850
851 #ifdef ICONV_OPTION
852         if (convert > 0) {
853                 xbuf inbuf;
854
855                 INIT_XBUF(inbuf, (char*)buf, len, (size_t)-1);
856
857                 len = iobuf.msg.len;
858                 iconvbufs(ic_send, &inbuf, &iobuf.msg,
859                           ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE | ICB_CIRCULAR_OUT | ICB_INIT);
860                 if (inbuf.len > 0) {
861                         rprintf(FERROR, "overflowed iobuf.msg buffer in send_msg");
862                         exit_cleanup(RERR_UNSUPPORTED);
863                 }
864                 len = iobuf.msg.len - len;
865         } else
866 #endif
867         {
868                 size_t siz;
869
870                 if ((pos += 4) >= iobuf.msg.size)
871                         pos -= iobuf.msg.size;
872
873                 /* Handle a split copy if we wrap around the end of the circular buffer. */
874                 if (pos >= iobuf.msg.pos && (siz = iobuf.msg.size - pos) < len) {
875                         memcpy(iobuf.msg.buf + pos, buf, siz);
876                         memcpy(iobuf.msg.buf, buf + siz, len - siz);
877                 } else
878                         memcpy(iobuf.msg.buf + pos, buf, len);
879
880                 iobuf.msg.len += len;
881         }
882
883         SIVAL(hdr, 0, ((MPLEX_BASE + (int)code)<<24) + len);
884         /* If the header used any overflow bytes, move them to the start. */
885         if ((pos = hdr+4 - iobuf.msg.buf) > iobuf.msg.size) {
886                 size_t siz = pos - iobuf.msg.size;
887                 if (DEBUG_GTE(IO, 4))
888                         rprintf(FINFO, "[%s] wrap-bytes moved: %d (send_msg)\n", who_am_i(), (int)siz);
889                 memcpy(iobuf.msg.buf, hdr+4 - siz, siz);
890         }
891
892         if (want_debug && convert > 0)
893                 rprintf(FINFO, "[%s] converted msg len=%ld\n", who_am_i(), (long)len);
894
895         return 1;
896 }
897
898 void send_msg_int(enum msgcode code, int num)
899 {
900         char numbuf[4];
901
902         if (DEBUG_GTE(IO, 1))
903                 rprintf(FINFO, "[%s] send_msg_int(%d, %d)\n", who_am_i(), (int)code, num);
904
905         SIVAL(numbuf, 0, num);
906         send_msg(code, numbuf, 4, -1);
907 }
908
909 static void got_flist_entry_status(enum festatus status, int ndx)
910 {
911         struct file_list *flist = flist_for_ndx(ndx, "got_flist_entry_status");
912
913         if (remove_source_files) {
914                 active_filecnt--;
915                 active_bytecnt -= F_LENGTH(flist->files[ndx - flist->ndx_start]);
916         }
917
918         if (inc_recurse)
919                 flist->in_progress--;
920
921         switch (status) {
922         case FES_SUCCESS:
923                 if (remove_source_files)
924                         send_msg_int(MSG_SUCCESS, ndx);
925                 if (preserve_hard_links) {
926                         struct file_struct *file = flist->files[ndx - flist->ndx_start];
927                         if (F_IS_HLINKED(file)) {
928                                 flist_ndx_push(&hlink_list, ndx);
929                                 flist->in_progress++;
930                         }
931                 }
932                 break;
933         case FES_REDO:
934                 if (read_batch) {
935                         if (inc_recurse)
936                                 flist->in_progress++;
937                         break;
938                 }
939                 if (inc_recurse)
940                         flist->to_redo++;
941                 flist_ndx_push(&redo_list, ndx);
942                 break;
943         case FES_NO_SEND:
944                 break;
945         }
946 }
947
948 /* Note the fds used for the main socket (which might really be a pipe
949  * for a local transfer, but we can ignore that). */
950 void io_set_sock_fds(int f_in, int f_out)
951 {
952         sock_f_in = f_in;
953         sock_f_out = f_out;
954 }
955
956 void set_io_timeout(int secs)
957 {
958         io_timeout = secs;
959
960         if (!io_timeout || io_timeout > SELECT_TIMEOUT)
961                 select_timeout = SELECT_TIMEOUT;
962         else
963                 select_timeout = io_timeout;
964
965         allowed_lull = read_batch ? 0 : (io_timeout + 1) / 2;
966 }
967
968 static void check_for_d_option_error(const char *msg)
969 {
970         static char rsync263_opts[] = "BCDHIKLPRSTWabceghlnopqrtuvxz";
971         char *colon;
972         int saw_d = 0;
973
974         if (*msg != 'r'
975          || strncmp(msg, REMOTE_OPTION_ERROR, sizeof REMOTE_OPTION_ERROR - 1) != 0)
976                 return;
977
978         msg += sizeof REMOTE_OPTION_ERROR - 1;
979         if (*msg == '-' || (colon = strchr(msg, ':')) == NULL
980          || strncmp(colon, REMOTE_OPTION_ERROR2, sizeof REMOTE_OPTION_ERROR2 - 1) != 0)
981                 return;
982
983         for ( ; *msg != ':'; msg++) {
984                 if (*msg == 'd')
985                         saw_d = 1;
986                 else if (*msg == 'e')
987                         break;
988                 else if (strchr(rsync263_opts, *msg) == NULL)
989                         return;
990         }
991
992         if (saw_d) {
993                 rprintf(FWARNING,
994                     "*** Try using \"--old-d\" if remote rsync is <= 2.6.3 ***\n");
995         }
996 }
997
998 /* This is used by the generator to limit how many file transfers can
999  * be active at once when --remove-source-files is specified.  Without
1000  * this, sender-side deletions were mostly happening at the end. */
1001 void increment_active_files(int ndx, int itemizing, enum logcode code)
1002 {
1003         while (1) {
1004                 /* TODO: tune these limits? */
1005                 int limit = active_bytecnt >= 128*1024 ? 10 : 50;
1006                 if (active_filecnt < limit)
1007                         break;
1008                 check_for_finished_files(itemizing, code, 0);
1009                 if (active_filecnt < limit)
1010                         break;
1011                 wait_for_receiver();
1012         }
1013
1014         active_filecnt++;
1015         active_bytecnt += F_LENGTH(cur_flist->files[ndx - cur_flist->ndx_start]);
1016 }
1017
1018 int get_redo_num(void)
1019 {
1020         return flist_ndx_pop(&redo_list);
1021 }
1022
1023 int get_hlink_num(void)
1024 {
1025         return flist_ndx_pop(&hlink_list);
1026 }
1027
1028 /* When we're the receiver and we have a local --files-from list of names
1029  * that needs to be sent over the socket to the sender, we have to do two
1030  * things at the same time: send the sender a list of what files we're
1031  * processing and read the incoming file+info list from the sender.  We do
1032  * this by making recv_file_list() call forward_filesfrom_data(), which
1033  * will ensure that we forward data to the sender until we get some data
1034  * for recv_file_list() to use. */
1035 void start_filesfrom_forwarding(int fd)
1036 {
1037         if (protocol_version < 31 && OUT_MULTIPLEXED) {
1038                 /* Older protocols send the files-from data w/o packaging
1039                  * it in multiplexed I/O packets, so temporarily switch
1040                  * to buffered I/O to match this behavior. */
1041                 iobuf.msg.pos = iobuf.msg.len = 0; /* Be extra sure no messages go out. */
1042                 ff_reenable_multiplex = io_end_multiplex_out(MPLX_TO_BUFFERED);
1043         }
1044         ff_forward_fd = fd;
1045
1046         alloc_xbuf(&ff_xb, FILESFROM_BUFLEN);
1047 }
1048
1049 /* Read a line into the "buf" buffer. */
1050 int read_line(int fd, char *buf, size_t bufsiz, int flags)
1051 {
1052         char ch, *s, *eob;
1053
1054 #ifdef ICONV_OPTION
1055         if (flags & RL_CONVERT && iconv_buf.size < bufsiz)
1056                 realloc_xbuf(&iconv_buf, bufsiz + 1024);
1057 #endif
1058
1059   start:
1060 #ifdef ICONV_OPTION
1061         s = flags & RL_CONVERT ? iconv_buf.buf : buf;
1062 #else
1063         s = buf;
1064 #endif
1065         eob = s + bufsiz - 1;
1066         while (1) {
1067                 /* We avoid read_byte() for files because files can return an EOF. */
1068                 if (fd == iobuf.in_fd)
1069                         ch = read_byte(fd);
1070                 else if (safe_read(fd, &ch, 1) == 0)
1071                         break;
1072                 if (flags & RL_EOL_NULLS ? ch == '\0' : (ch == '\r' || ch == '\n')) {
1073                         /* Skip empty lines if dumping comments. */
1074                         if (flags & RL_DUMP_COMMENTS && s == buf)
1075                                 continue;
1076                         break;
1077                 }
1078                 if (s < eob)
1079                         *s++ = ch;
1080         }
1081         *s = '\0';
1082
1083         if (flags & RL_DUMP_COMMENTS && (*buf == '#' || *buf == ';'))
1084                 goto start;
1085
1086 #ifdef ICONV_OPTION
1087         if (flags & RL_CONVERT) {
1088                 xbuf outbuf;
1089                 INIT_XBUF(outbuf, buf, 0, bufsiz);
1090                 iconv_buf.pos = 0;
1091                 iconv_buf.len = s - iconv_buf.buf;
1092                 iconvbufs(ic_recv, &iconv_buf, &outbuf,
1093                           ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE | ICB_INIT);
1094                 outbuf.buf[outbuf.len] = '\0';
1095                 return outbuf.len;
1096         }
1097 #endif
1098
1099         return s - buf;
1100 }
1101
1102 void read_args(int f_in, char *mod_name, char *buf, size_t bufsiz, int rl_nulls,
1103                char ***argv_p, int *argc_p, char **request_p)
1104 {
1105         int maxargs = MAX_ARGS;
1106         int dot_pos = 0;
1107         int argc = 0;
1108         char **argv, *p;
1109         int rl_flags = (rl_nulls ? RL_EOL_NULLS : 0);
1110
1111 #ifdef ICONV_OPTION
1112         rl_flags |= (protect_args && ic_recv != (iconv_t)-1 ? RL_CONVERT : 0);
1113 #endif
1114
1115         if (!(argv = new_array(char *, maxargs)))
1116                 out_of_memory("read_args");
1117         if (mod_name && !protect_args)
1118                 argv[argc++] = "rsyncd";
1119
1120         while (1) {
1121                 if (read_line(f_in, buf, bufsiz, rl_flags) == 0)
1122                         break;
1123
1124                 if (argc == maxargs-1) {
1125                         maxargs += MAX_ARGS;
1126                         if (!(argv = realloc_array(argv, char *, maxargs)))
1127                                 out_of_memory("read_args");
1128                 }
1129
1130                 if (dot_pos) {
1131                         if (request_p) {
1132                                 *request_p = strdup(buf);
1133                                 request_p = NULL;
1134                         }
1135                         if (mod_name)
1136                                 glob_expand_module(mod_name, buf, &argv, &argc, &maxargs);
1137                         else
1138                                 glob_expand(buf, &argv, &argc, &maxargs);
1139                 } else {
1140                         if (!(p = strdup(buf)))
1141                                 out_of_memory("read_args");
1142                         argv[argc++] = p;
1143                         if (*p == '.' && p[1] == '\0')
1144                                 dot_pos = argc;
1145                 }
1146         }
1147         argv[argc] = NULL;
1148
1149         glob_expand(NULL, NULL, NULL, NULL);
1150
1151         *argc_p = argc;
1152         *argv_p = argv;
1153 }
1154
1155 BOOL io_start_buffering_out(int f_out)
1156 {
1157         if (msgs2stderr && DEBUG_GTE(IO, 2))
1158                 rprintf(FINFO, "[%s] io_start_buffering_out(%d)\n", who_am_i(), f_out);
1159
1160         if (OUT_MULTIPLEXED && !iobuf.msg.buf) {
1161                 iobuf.msg.size = IO_BUFFER_SIZE - 4;
1162                 if (!(iobuf.msg.buf = new_array(char, iobuf.msg.size + 4)))
1163                         out_of_memory("io_start_buffering_out");
1164                 iobuf.msg.pos = iobuf.msg.len = 0;
1165         }
1166
1167         if (iobuf.out.buf) {
1168                 if (iobuf.out_fd == -1)
1169                         iobuf.out_fd = f_out;
1170                 assert(f_out == iobuf.out_fd);
1171                 return False;
1172         }
1173
1174         iobuf.out.size = IO_BUFFER_SIZE * 2 - 4;
1175         /* The 4 overflow bytes makes some circular-buffer wrapping operations easier. */
1176         if (!(iobuf.out.buf = new_array(char, iobuf.out.size + 4)))
1177                 out_of_memory("io_start_buffering_out");
1178         iobuf.out.pos = iobuf.out.len = 0;
1179         iobuf.out_fd = f_out;
1180
1181         return True;
1182 }
1183
1184 BOOL io_start_buffering_in(int f_in)
1185 {
1186         if (msgs2stderr && DEBUG_GTE(IO, 2))
1187                 rprintf(FINFO, "[%s] io_start_buffering_in(%d)\n", who_am_i(), f_in);
1188
1189         if (iobuf.in.buf) {
1190                 if (iobuf.in_fd == -1)
1191                         iobuf.in_fd = f_in;
1192                 assert(f_in == iobuf.in_fd);
1193                 return False;
1194         }
1195
1196         iobuf.in.size = IO_BUFFER_SIZE;
1197         if (!(iobuf.in.buf = new_array(char, iobuf.in.size)))
1198                 out_of_memory("io_start_buffering_in");
1199
1200         iobuf.in.pos = iobuf.in.len = 0;
1201
1202         iobuf.in_fd = f_in;
1203
1204         return True;
1205 }
1206
1207 void io_end_buffering_in(BOOL free_buffers)
1208 {
1209         if (msgs2stderr && DEBUG_GTE(IO, 2)) {
1210                 rprintf(FINFO, "[%s] io_end_buffering_in(IOBUF_%s_BUFS)\n",
1211                         who_am_i(), free_buffers ? "FREE" : "KEEP");
1212         }
1213
1214         if (free_buffers)
1215                 free_xbuf(&iobuf.in);
1216         else
1217                 iobuf.in.pos = iobuf.in.len = 0;
1218
1219         iobuf.in_fd = -1;
1220 }
1221
1222 void io_end_buffering_out(BOOL free_buffers)
1223 {
1224         if (msgs2stderr && DEBUG_GTE(IO, 2)) {
1225                 rprintf(FINFO, "[%s] io_end_buffering_out(IOBUF_%s_BUFS)\n",
1226                         who_am_i(), free_buffers ? "FREE" : "KEEP");
1227         }
1228
1229         io_flush(FULL_FLUSH);
1230
1231         if (free_buffers) {
1232                 free_xbuf(&iobuf.out);
1233                 free_xbuf(&iobuf.msg);
1234         }
1235
1236         iobuf.out_fd = -1;
1237 }
1238
1239 void maybe_flush_socket(int important)
1240 {
1241         if (flist_eof && iobuf.out.buf && iobuf.out.len > iobuf.out_empty_len
1242          && (important || time(NULL) - last_io_out >= 5))
1243                 io_flush(NORMAL_FLUSH);
1244 }
1245
1246 void maybe_send_keepalive(void)
1247 {
1248         if (time(NULL) - last_io_out >= allowed_lull) {
1249                 if (!iobuf.msg.len && iobuf.out.len == iobuf.out_empty_len) {
1250                         if (protocol_version < 29)
1251                                 return; /* there's nothing we can do */
1252                         if (protocol_version >= 30)
1253                                 send_msg(MSG_NOOP, "", 0, 0);
1254                         else {
1255                                 write_int(iobuf.out_fd, cur_flist->used);
1256                                 write_shortint(iobuf.out_fd, ITEM_IS_NEW);
1257                         }
1258                 }
1259                 if (iobuf.msg.len)
1260                         perform_io(iobuf.msg.size - iobuf.msg.len + 1, PIO_NEED_MSGROOM);
1261                 else if (iobuf.out.len > iobuf.out_empty_len)
1262                         io_flush(NORMAL_FLUSH);
1263         }
1264 }
1265
1266 void start_flist_forward(int ndx)
1267 {
1268         write_int(iobuf.out_fd, ndx);
1269         forward_flist_data = 1;
1270 }
1271
1272 void stop_flist_forward(void)
1273 {
1274         forward_flist_data = 0;
1275 }
1276
1277 /* Read a message from a multiplexed source. */
1278 static void read_a_msg(void)
1279 {
1280         char *data, line[BIGPATHBUFLEN];
1281         int tag, val;
1282         size_t msg_bytes;
1283
1284         data = perform_io(4, PIO_INPUT_AND_CONSUME);
1285         tag = IVAL(data, 0);
1286
1287         msg_bytes = tag & 0xFFFFFF;
1288         tag = (tag >> 24) - MPLEX_BASE;
1289
1290         if (DEBUG_GTE(IO, 1) && (msgs2stderr || tag != MSG_INFO))
1291                 rprintf(FINFO, "[%s] got msg=%d, len=%ld\n", who_am_i(), (int)tag, (long)msg_bytes);
1292
1293         switch (tag) {
1294         case MSG_DATA:
1295                 assert(iobuf.raw_input_ends_before == 0);
1296                 /* Though this does not yet read the data, we do mark where in
1297                  * the buffer the msg data will end once it is read.  It is
1298                  * possible that this points off the end of the buffer, in
1299                  * which case the gradual reading of the input stream will
1300                  * cause this value to decrease and eventually become real. */
1301                 iobuf.raw_input_ends_before = iobuf.in.pos + msg_bytes;
1302                 break;
1303         case MSG_STATS:
1304                 if (msg_bytes != sizeof stats.total_read || !am_generator)
1305                         goto invalid_msg;
1306                 data = perform_io(sizeof stats.total_read, PIO_INPUT_AND_CONSUME);
1307                 memcpy((char*)&stats.total_read, data, sizeof stats.total_read);
1308                 break;
1309         case MSG_REDO:
1310                 if (msg_bytes != 4 || !am_generator)
1311                         goto invalid_msg;
1312                 data = perform_io(4, PIO_INPUT_AND_CONSUME);
1313                 got_flist_entry_status(FES_REDO, IVAL(data, 0));
1314                 break;
1315         case MSG_IO_ERROR:
1316                 if (msg_bytes != 4 || am_sender)
1317                         goto invalid_msg;
1318                 data = perform_io(4, PIO_INPUT_AND_CONSUME);
1319                 val = IVAL(data, 0);
1320                 io_error |= val;
1321                 if (!am_generator)
1322                         send_msg_int(MSG_IO_ERROR, val);
1323                 break;
1324         case MSG_IO_TIMEOUT:
1325                 if (msg_bytes != 4 || am_server || am_generator)
1326                         goto invalid_msg;
1327                 data = perform_io(4, PIO_INPUT_AND_CONSUME);
1328                 val = IVAL(data, 0);
1329                 if (!io_timeout || io_timeout > val) {
1330                         if (INFO_GTE(MISC, 2))
1331                                 rprintf(FINFO, "Setting --timeout=%d to match server\n", val);
1332                         set_io_timeout(val);
1333                 }
1334                 break;
1335         case MSG_NOOP:
1336                 if (am_sender)
1337                         maybe_send_keepalive();
1338                 break;
1339         case MSG_DELETED:
1340                 if (msg_bytes >= sizeof line)
1341                         goto overflow;
1342                 if (am_generator) {
1343                         memcpy(line, perform_io(msg_bytes, PIO_INPUT_AND_CONSUME), msg_bytes);
1344                         send_msg(MSG_DELETED, line, msg_bytes, 1);
1345                         break;
1346                 }
1347 #ifdef ICONV_OPTION
1348                 if (ic_recv != (iconv_t)-1) {
1349                         xbuf outbuf, inbuf;
1350                         char ibuf[512];
1351                         int add_null = 0;
1352                         int flags = ICB_INCLUDE_BAD | ICB_INIT;
1353
1354                         INIT_CONST_XBUF(outbuf, line);
1355                         INIT_XBUF(inbuf, ibuf, 0, (size_t)-1);
1356
1357                         while (msg_bytes) {
1358                                 size_t len = msg_bytes > sizeof ibuf - inbuf.len ? sizeof ibuf - inbuf.len : msg_bytes;
1359                                 memcpy(ibuf + inbuf.len, perform_io(len, PIO_INPUT_AND_CONSUME), len);
1360                                 inbuf.pos = 0;
1361                                 inbuf.len += len;
1362                                 if (!(msg_bytes -= len) && !ibuf[inbuf.len-1])
1363                                         inbuf.len--, add_null = 1;
1364                                 if (iconvbufs(ic_send, &inbuf, &outbuf, flags) < 0) {
1365                                         if (errno == E2BIG)
1366                                                 goto overflow;
1367                                         /* Buffer ended with an incomplete char, so move the
1368                                          * bytes to the start of the buffer and continue. */
1369                                         memmove(ibuf, ibuf + inbuf.pos, inbuf.len);
1370                                 }
1371                                 flags &= ~ICB_INIT;
1372                         }
1373                         if (add_null) {
1374                                 if (outbuf.len == outbuf.size)
1375                                         goto overflow;
1376                                 outbuf.buf[outbuf.len++] = '\0';
1377                         }
1378                         msg_bytes = outbuf.len;
1379                 } else
1380 #endif
1381                         memcpy(line, perform_io(msg_bytes, PIO_INPUT_AND_CONSUME), msg_bytes);
1382                 /* A directory name was sent with the trailing null */
1383                 if (msg_bytes > 0 && !line[msg_bytes-1])
1384                         log_delete(line, S_IFDIR);
1385                 else {
1386                         line[msg_bytes] = '\0';
1387                         log_delete(line, S_IFREG);
1388                 }
1389                 break;
1390         case MSG_SUCCESS:
1391                 if (msg_bytes != 4) {
1392                   invalid_msg:
1393                         rprintf(FERROR, "invalid multi-message %d:%lu [%s%s]\n",
1394                                 tag, (unsigned long)msg_bytes, who_am_i(),
1395                                 inc_recurse ? "/inc" : "");
1396                         exit_cleanup(RERR_STREAMIO);
1397                 }
1398                 data = perform_io(4, PIO_INPUT_AND_CONSUME);
1399                 val = IVAL(data, 0);
1400                 if (am_generator)
1401                         got_flist_entry_status(FES_SUCCESS, val);
1402                 else
1403                         successful_send(val);
1404                 break;
1405         case MSG_NO_SEND:
1406                 if (msg_bytes != 4)
1407                         goto invalid_msg;
1408                 data = perform_io(4, PIO_INPUT_AND_CONSUME);
1409                 val = IVAL(data, 0);
1410                 if (am_generator)
1411                         got_flist_entry_status(FES_NO_SEND, val);
1412                 else
1413                         send_msg_int(MSG_NO_SEND, val);
1414                 break;
1415         case MSG_ERROR_SOCKET:
1416         case MSG_ERROR_UTF8:
1417         case MSG_CLIENT:
1418         case MSG_LOG:
1419                 if (!am_generator)
1420                         goto invalid_msg;
1421                 if (tag == MSG_ERROR_SOCKET)
1422                         msgs2stderr = 1;
1423                 /* FALL THROUGH */
1424         case MSG_INFO:
1425         case MSG_ERROR:
1426         case MSG_ERROR_XFER:
1427         case MSG_WARNING:
1428                 if (msg_bytes >= sizeof line) {
1429                     overflow:
1430                         rprintf(FERROR,
1431                                 "multiplexing overflow %d:%lu [%s%s]\n",
1432                                 tag, (unsigned long)msg_bytes, who_am_i(),
1433                                 inc_recurse ? "/inc" : "");
1434                         exit_cleanup(RERR_STREAMIO);
1435                 }
1436                 memcpy(line, perform_io(msg_bytes, PIO_INPUT_AND_CONSUME), msg_bytes);
1437                 rwrite((enum logcode)tag, line, msg_bytes, !am_generator);
1438                 if (first_message) {
1439                         if (list_only && !am_sender && tag == 1 && msg_bytes < sizeof line) {
1440                                 line[msg_bytes] = '\0';
1441                                 check_for_d_option_error(line);
1442                         }
1443                         first_message = 0;
1444                 }
1445                 break;
1446         case MSG_ERROR_EXIT:
1447                 if (msg_bytes == 0) {
1448                         if (!am_sender && !am_generator) {
1449                                 send_msg(MSG_ERROR_EXIT, "", 0, 0);
1450                                 io_flush(FULL_FLUSH);
1451                         }
1452                         val = 0;
1453                 } else if (msg_bytes == 4) {
1454                         data = perform_io(4, PIO_INPUT_AND_CONSUME);
1455                         val = IVAL(data, 0);
1456                         if (protocol_version >= 31) {
1457                                 if (am_generator)
1458                                         send_msg_int(MSG_ERROR_EXIT, val);
1459                                 else
1460                                         send_msg(MSG_ERROR_EXIT, "", 0, 0);
1461                         }
1462                 } else
1463                         goto invalid_msg;
1464                 /* Send a negative linenum so that we don't end up
1465                  * with a duplicate exit message. */
1466                 _exit_cleanup(val, __FILE__, 0 - __LINE__);
1467         default:
1468                 rprintf(FERROR, "unexpected tag %d [%s%s]\n",
1469                         tag, who_am_i(), inc_recurse ? "/inc" : "");
1470                 exit_cleanup(RERR_STREAMIO);
1471         }
1472 }
1473
1474 void wait_for_receiver(void)
1475 {
1476         if (!iobuf.raw_input_ends_before)
1477                 read_a_msg();
1478
1479         if (iobuf.raw_input_ends_before) {
1480                 int ndx = read_int(iobuf.in_fd);
1481                 if (ndx < 0) {
1482                         switch (ndx) {
1483                         case NDX_FLIST_EOF:
1484                                 flist_eof = 1;
1485                                 if (DEBUG_GTE(FLIST, 3))
1486                                         rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
1487                                 break;
1488                         case NDX_DONE:
1489                                 msgdone_cnt++;
1490                                 break;
1491                         default:
1492                                 exit_cleanup(RERR_STREAMIO);
1493                         }
1494                 } else {
1495                         struct file_list *flist;
1496                         if (DEBUG_GTE(FLIST, 2)) {
1497                                 rprintf(FINFO, "[%s] receiving flist for dir %d\n",
1498                                         who_am_i(), ndx);
1499                         }
1500                         flist = recv_file_list(iobuf.in_fd);
1501                         flist->parent_ndx = ndx;
1502 #ifdef SUPPORT_HARD_LINKS
1503                         if (preserve_hard_links)
1504                                 match_hard_links(flist);
1505 #endif
1506                 }
1507         }
1508 }
1509
1510 unsigned short read_shortint(int f)
1511 {
1512         char b[2];
1513         read_buf(f, b, 2);
1514         return (UVAL(b, 1) << 8) + UVAL(b, 0);
1515 }
1516
1517 int32 read_int(int f)
1518 {
1519         char b[4];
1520         int32 num;
1521
1522         read_buf(f, b, 4);
1523         num = IVAL(b, 0);
1524 #if SIZEOF_INT32 > 4
1525         if (num & (int32)0x80000000)
1526                 num |= ~(int32)0xffffffff;
1527 #endif
1528         return num;
1529 }
1530
1531 int32 read_varint(int f)
1532 {
1533         union {
1534                 char b[5];
1535                 int32 x;
1536         } u;
1537         uchar ch;
1538         int extra;
1539
1540         u.x = 0;
1541         ch = read_byte(f);
1542         extra = int_byte_extra[ch / 4];
1543         if (extra) {
1544                 uchar bit = ((uchar)1<<(8-extra));
1545                 if (extra >= (int)sizeof u.b) {
1546                         rprintf(FERROR, "Overflow in read_varint()\n");
1547                         exit_cleanup(RERR_STREAMIO);
1548                 }
1549                 read_buf(f, u.b, extra);
1550                 u.b[extra] = ch & (bit-1);
1551         } else
1552                 u.b[0] = ch;
1553 #if CAREFUL_ALIGNMENT
1554         u.x = IVAL(u.b,0);
1555 #endif
1556 #if SIZEOF_INT32 > 4
1557         if (u.x & (int32)0x80000000)
1558                 u.x |= ~(int32)0xffffffff;
1559 #endif
1560         return u.x;
1561 }
1562
1563 int64 read_varlong(int f, uchar min_bytes)
1564 {
1565         union {
1566                 char b[9];
1567                 int64 x;
1568         } u;
1569         char b2[8];
1570         int extra;
1571
1572 #if SIZEOF_INT64 < 8
1573         memset(u.b, 0, 8);
1574 #else
1575         u.x = 0;
1576 #endif
1577         read_buf(f, b2, min_bytes);
1578         memcpy(u.b, b2+1, min_bytes-1);
1579         extra = int_byte_extra[CVAL(b2, 0) / 4];
1580         if (extra) {
1581                 uchar bit = ((uchar)1<<(8-extra));
1582                 if (min_bytes + extra > (int)sizeof u.b) {
1583                         rprintf(FERROR, "Overflow in read_varlong()\n");
1584                         exit_cleanup(RERR_STREAMIO);
1585                 }
1586                 read_buf(f, u.b + min_bytes - 1, extra);
1587                 u.b[min_bytes + extra - 1] = CVAL(b2, 0) & (bit-1);
1588 #if SIZEOF_INT64 < 8
1589                 if (min_bytes + extra > 5 || u.b[4] || CVAL(u.b,3) & 0x80) {
1590                         rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1591                         exit_cleanup(RERR_UNSUPPORTED);
1592                 }
1593 #endif
1594         } else
1595                 u.b[min_bytes + extra - 1] = CVAL(b2, 0);
1596 #if SIZEOF_INT64 < 8
1597         u.x = IVAL(u.b,0);
1598 #elif CAREFUL_ALIGNMENT
1599         u.x = IVAL(u.b,0) | (((int64)IVAL(u.b,4))<<32);
1600 #endif
1601         return u.x;
1602 }
1603
1604 int64 read_longint(int f)
1605 {
1606 #if SIZEOF_INT64 >= 8
1607         char b[9];
1608 #endif
1609         int32 num = read_int(f);
1610
1611         if (num != (int32)0xffffffff)
1612                 return num;
1613
1614 #if SIZEOF_INT64 < 8
1615         rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1616         exit_cleanup(RERR_UNSUPPORTED);
1617 #else
1618         read_buf(f, b, 8);
1619         return IVAL(b,0) | (((int64)IVAL(b,4))<<32);
1620 #endif
1621 }
1622
1623 void read_buf(int f, char *buf, size_t len)
1624 {
1625         if (f != iobuf.in_fd) {
1626                 if (safe_read(f, buf, len) != len)
1627                         whine_about_eof(f); /* Doesn't return. */
1628                 goto batch_copy;
1629         }
1630
1631         if (!IN_MULTIPLEXED) {
1632                 memcpy(buf, perform_io(len, PIO_INPUT_AND_CONSUME), len);
1633                 total_data_read += len;
1634                 if (forward_flist_data)
1635                         write_buf(iobuf.out_fd, buf, len);
1636           batch_copy:
1637                 if (f == write_batch_monitor_in)
1638                         safe_write(batch_fd, buf, len);
1639                 return;
1640         }
1641
1642         while (1) {
1643                 char *data;
1644                 size_t siz;
1645
1646                 while (!iobuf.raw_input_ends_before)
1647                         read_a_msg();
1648
1649                 siz = MIN(len, iobuf.raw_input_ends_before - iobuf.in.pos);
1650                 data = perform_io(siz, PIO_INPUT_AND_CONSUME);
1651                 if (iobuf.in.pos == iobuf.raw_input_ends_before)
1652                         iobuf.raw_input_ends_before = 0;
1653
1654                 /* The bytes at the "data" pointer will survive long
1655                  * enough to make a copy, but not past future I/O. */
1656                 memcpy(buf, data, siz);
1657                 total_data_read += siz;
1658
1659                 if (forward_flist_data)
1660                         write_buf(iobuf.out_fd, buf, siz);
1661
1662                 if (f == write_batch_monitor_in)
1663                         safe_write(batch_fd, buf, siz);
1664
1665                 if ((len -= siz) == 0)
1666                         break;
1667                 buf += siz;
1668         }
1669 }
1670
1671 void read_sbuf(int f, char *buf, size_t len)
1672 {
1673         read_buf(f, buf, len);
1674         buf[len] = '\0';
1675 }
1676
1677 uchar read_byte(int f)
1678 {
1679         uchar c;
1680         read_buf(f, (char*)&c, 1);
1681         return c;
1682 }
1683
1684 int read_vstring(int f, char *buf, int bufsize)
1685 {
1686         int len = read_byte(f);
1687
1688         if (len & 0x80)
1689                 len = (len & ~0x80) * 0x100 + read_byte(f);
1690
1691         if (len >= bufsize) {
1692                 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
1693                         len, bufsize - 1);
1694                 return -1;
1695         }
1696
1697         if (len)
1698                 read_buf(f, buf, len);
1699         buf[len] = '\0';
1700         return len;
1701 }
1702
1703 /* Populate a sum_struct with values from the socket.  This is
1704  * called by both the sender and the receiver. */
1705 void read_sum_head(int f, struct sum_struct *sum)
1706 {
1707         int32 max_blength = protocol_version < 30 ? OLD_MAX_BLOCK_SIZE : MAX_BLOCK_SIZE;
1708         sum->count = read_int(f);
1709         if (sum->count < 0) {
1710                 rprintf(FERROR, "Invalid checksum count %ld [%s]\n",
1711                         (long)sum->count, who_am_i());
1712                 exit_cleanup(RERR_PROTOCOL);
1713         }
1714         sum->blength = read_int(f);
1715         if (sum->blength < 0 || sum->blength > max_blength) {
1716                 rprintf(FERROR, "Invalid block length %ld [%s]\n",
1717                         (long)sum->blength, who_am_i());
1718                 exit_cleanup(RERR_PROTOCOL);
1719         }
1720         sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
1721         if (sum->s2length < 0 || sum->s2length > MAX_DIGEST_LEN) {
1722                 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
1723                         sum->s2length, who_am_i());
1724                 exit_cleanup(RERR_PROTOCOL);
1725         }
1726         sum->remainder = read_int(f);
1727         if (sum->remainder < 0 || sum->remainder > sum->blength) {
1728                 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
1729                         (long)sum->remainder, who_am_i());
1730                 exit_cleanup(RERR_PROTOCOL);
1731         }
1732 }
1733
1734 /* Send the values from a sum_struct over the socket.  Set sum to
1735  * NULL if there are no checksums to send.  This is called by both
1736  * the generator and the sender. */
1737 void write_sum_head(int f, struct sum_struct *sum)
1738 {
1739         static struct sum_struct null_sum;
1740
1741         if (sum == NULL)
1742                 sum = &null_sum;
1743
1744         write_int(f, sum->count);
1745         write_int(f, sum->blength);
1746         if (protocol_version >= 27)
1747                 write_int(f, sum->s2length);
1748         write_int(f, sum->remainder);
1749 }
1750
1751 /* Sleep after writing to limit I/O bandwidth usage.
1752  *
1753  * @todo Rather than sleeping after each write, it might be better to
1754  * use some kind of averaging.  The current algorithm seems to always
1755  * use a bit less bandwidth than specified, because it doesn't make up
1756  * for slow periods.  But arguably this is a feature.  In addition, we
1757  * ought to take the time used to write the data into account.
1758  *
1759  * During some phases of big transfers (file FOO is uptodate) this is
1760  * called with a small bytes_written every time.  As the kernel has to
1761  * round small waits up to guarantee that we actually wait at least the
1762  * requested number of microseconds, this can become grossly inaccurate.
1763  * We therefore keep track of the bytes we've written over time and only
1764  * sleep when the accumulated delay is at least 1 tenth of a second. */
1765 static void sleep_for_bwlimit(int bytes_written)
1766 {
1767         static struct timeval prior_tv;
1768         static long total_written = 0;
1769         struct timeval tv, start_tv;
1770         long elapsed_usec, sleep_usec;
1771
1772 #define ONE_SEC 1000000L /* # of microseconds in a second */
1773
1774         total_written += bytes_written;
1775
1776         gettimeofday(&start_tv, NULL);
1777         if (prior_tv.tv_sec) {
1778                 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
1779                              + (start_tv.tv_usec - prior_tv.tv_usec);
1780                 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
1781                 if (total_written < 0)
1782                         total_written = 0;
1783         }
1784
1785         sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1786         if (sleep_usec < ONE_SEC / 10) {
1787                 prior_tv = start_tv;
1788                 return;
1789         }
1790
1791         tv.tv_sec  = sleep_usec / ONE_SEC;
1792         tv.tv_usec = sleep_usec % ONE_SEC;
1793         select(0, NULL, NULL, NULL, &tv);
1794
1795         gettimeofday(&prior_tv, NULL);
1796         elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1797                      + (prior_tv.tv_usec - start_tv.tv_usec);
1798         total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
1799 }
1800
1801 void io_flush(int flush_it_all)
1802 {
1803         if (iobuf.out.len > iobuf.out_empty_len) {
1804                 if (flush_it_all) /* FULL_FLUSH: flush everything in the output buffers */
1805                         perform_io(iobuf.out.size - iobuf.out_empty_len, PIO_NEED_OUTROOM);
1806                 else /* NORMAL_FLUSH: flush at least 1 byte */
1807                         perform_io(iobuf.out.size - iobuf.out.len + 1, PIO_NEED_OUTROOM);
1808         }
1809         if (iobuf.msg.len)
1810                 perform_io(iobuf.msg.size, PIO_NEED_MSGROOM);
1811 }
1812
1813 void write_shortint(int f, unsigned short x)
1814 {
1815         char b[2];
1816         b[0] = (char)x;
1817         b[1] = (char)(x >> 8);
1818         write_buf(f, b, 2);
1819 }
1820
1821 void write_int(int f, int32 x)
1822 {
1823         char b[4];
1824         SIVAL(b, 0, x);
1825         write_buf(f, b, 4);
1826 }
1827
1828 void write_varint(int f, int32 x)
1829 {
1830         char b[5];
1831         uchar bit;
1832         int cnt = 4;
1833
1834         SIVAL(b, 1, x);
1835
1836         while (cnt > 1 && b[cnt] == 0)
1837                 cnt--;
1838         bit = ((uchar)1<<(7-cnt+1));
1839         if (CVAL(b, cnt) >= bit) {
1840                 cnt++;
1841                 *b = ~(bit-1);
1842         } else if (cnt > 1)
1843                 *b = b[cnt] | ~(bit*2-1);
1844         else
1845                 *b = b[cnt];
1846
1847         write_buf(f, b, cnt);
1848 }
1849
1850 void write_varlong(int f, int64 x, uchar min_bytes)
1851 {
1852         char b[9];
1853         uchar bit;
1854         int cnt = 8;
1855
1856         SIVAL(b, 1, x);
1857 #if SIZEOF_INT64 >= 8
1858         SIVAL(b, 5, x >> 32);
1859 #else
1860         if (x <= 0x7FFFFFFF && x >= 0)
1861                 memset(b + 5, 0, 4);
1862         else {
1863                 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1864                 exit_cleanup(RERR_UNSUPPORTED);
1865         }
1866 #endif
1867
1868         while (cnt > min_bytes && b[cnt] == 0)
1869                 cnt--;
1870         bit = ((uchar)1<<(7-cnt+min_bytes));
1871         if (CVAL(b, cnt) >= bit) {
1872                 cnt++;
1873                 *b = ~(bit-1);
1874         } else if (cnt > min_bytes)
1875                 *b = b[cnt] | ~(bit*2-1);
1876         else
1877                 *b = b[cnt];
1878
1879         write_buf(f, b, cnt);
1880 }
1881
1882 /*
1883  * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1884  * 64-bit types on this platform.
1885  */
1886 void write_longint(int f, int64 x)
1887 {
1888         char b[12], * const s = b+4;
1889
1890         SIVAL(s, 0, x);
1891         if (x <= 0x7FFFFFFF && x >= 0) {
1892                 write_buf(f, s, 4);
1893                 return;
1894         }
1895
1896 #if SIZEOF_INT64 < 8
1897         rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1898         exit_cleanup(RERR_UNSUPPORTED);
1899 #else
1900         memset(b, 0xFF, 4);
1901         SIVAL(s, 4, x >> 32);
1902         write_buf(f, b, 12);
1903 #endif
1904 }
1905
1906 void write_buf(int f, const char *buf, size_t len)
1907 {
1908         size_t pos, siz;
1909
1910         if (f != iobuf.out_fd) {
1911                 safe_write(f, buf, len);
1912                 goto batch_copy;
1913         }
1914
1915         if (iobuf.out.len + len > iobuf.out.size)
1916                 perform_io(len, PIO_NEED_OUTROOM);
1917
1918         pos = iobuf.out.pos + iobuf.out.len; /* Must be set after any flushing. */
1919         if (pos >= iobuf.out.size)
1920                 pos -= iobuf.out.size;
1921
1922         /* Handle a split copy if we wrap around the end of the circular buffer. */
1923         if (pos >= iobuf.out.pos && (siz = iobuf.out.size - pos) < len) {
1924                 memcpy(iobuf.out.buf + pos, buf, siz);
1925                 memcpy(iobuf.out.buf, buf + siz, len - siz);
1926         } else
1927                 memcpy(iobuf.out.buf + pos, buf, len);
1928
1929         iobuf.out.len += len;
1930         total_data_written += len;
1931
1932   batch_copy:
1933         if (f == write_batch_monitor_out)
1934                 safe_write(batch_fd, buf, len);
1935 }
1936
1937 /* Write a string to the connection */
1938 void write_sbuf(int f, const char *buf)
1939 {
1940         write_buf(f, buf, strlen(buf));
1941 }
1942
1943 void write_byte(int f, uchar c)
1944 {
1945         write_buf(f, (char *)&c, 1);
1946 }
1947
1948 void write_vstring(int f, const char *str, int len)
1949 {
1950         uchar lenbuf[3], *lb = lenbuf;
1951
1952         if (len > 0x7F) {
1953                 if (len > 0x7FFF) {
1954                         rprintf(FERROR,
1955                                 "attempting to send over-long vstring (%d > %d)\n",
1956                                 len, 0x7FFF);
1957                         exit_cleanup(RERR_PROTOCOL);
1958                 }
1959                 *lb++ = len / 0x100 + 0x80;
1960         }
1961         *lb = len;
1962
1963         write_buf(f, (char*)lenbuf, lb - lenbuf + 1);
1964         if (len)
1965                 write_buf(f, str, len);
1966 }
1967
1968 /* Send a file-list index using a byte-reduction method. */
1969 void write_ndx(int f, int32 ndx)
1970 {
1971         static int32 prev_positive = -1, prev_negative = 1;
1972         int32 diff, cnt = 0;
1973         char b[6];
1974
1975         if (protocol_version < 30 || read_batch) {
1976                 write_int(f, ndx);
1977                 return;
1978         }
1979
1980         /* Send NDX_DONE as a single-byte 0 with no side effects.  Send
1981          * negative nums as a positive after sending a leading 0xFF. */
1982         if (ndx >= 0) {
1983                 diff = ndx - prev_positive;
1984                 prev_positive = ndx;
1985         } else if (ndx == NDX_DONE) {
1986                 *b = 0;
1987                 write_buf(f, b, 1);
1988                 return;
1989         } else {
1990                 b[cnt++] = (char)0xFF;
1991                 ndx = -ndx;
1992                 diff = ndx - prev_negative;
1993                 prev_negative = ndx;
1994         }
1995
1996         /* A diff of 1 - 253 is sent as a one-byte diff; a diff of 254 - 32767
1997          * or 0 is sent as a 0xFE + a two-byte diff; otherwise we send 0xFE
1998          * & all 4 bytes of the (non-negative) num with the high-bit set. */
1999         if (diff < 0xFE && diff > 0)
2000                 b[cnt++] = (char)diff;
2001         else if (diff < 0 || diff > 0x7FFF) {
2002                 b[cnt++] = (char)0xFE;
2003                 b[cnt++] = (char)((ndx >> 24) | 0x80);
2004                 b[cnt++] = (char)ndx;
2005                 b[cnt++] = (char)(ndx >> 8);
2006                 b[cnt++] = (char)(ndx >> 16);
2007         } else {
2008                 b[cnt++] = (char)0xFE;
2009                 b[cnt++] = (char)(diff >> 8);
2010                 b[cnt++] = (char)diff;
2011         }
2012         write_buf(f, b, cnt);
2013 }
2014
2015 /* Receive a file-list index using a byte-reduction method. */
2016 int32 read_ndx(int f)
2017 {
2018         static int32 prev_positive = -1, prev_negative = 1;
2019         int32 *prev_ptr, num;
2020         char b[4];
2021
2022         if (protocol_version < 30)
2023                 return read_int(f);
2024
2025         read_buf(f, b, 1);
2026         if (CVAL(b, 0) == 0xFF) {
2027                 read_buf(f, b, 1);
2028                 prev_ptr = &prev_negative;
2029         } else if (CVAL(b, 0) == 0)
2030                 return NDX_DONE;
2031         else
2032                 prev_ptr = &prev_positive;
2033         if (CVAL(b, 0) == 0xFE) {
2034                 read_buf(f, b, 2);
2035                 if (CVAL(b, 0) & 0x80) {
2036                         b[3] = CVAL(b, 0) & ~0x80;
2037                         b[0] = b[1];
2038                         read_buf(f, b+1, 2);
2039                         num = IVAL(b, 0);
2040                 } else
2041                         num = (UVAL(b,0)<<8) + UVAL(b,1) + *prev_ptr;
2042         } else
2043                 num = UVAL(b, 0) + *prev_ptr;
2044         *prev_ptr = num;
2045         if (prev_ptr == &prev_negative)
2046                 num = -num;
2047         return num;
2048 }
2049
2050 /* Read a line of up to bufsiz-1 characters into buf.  Strips
2051  * the (required) trailing newline and all carriage returns.
2052  * Returns 1 for success; 0 for I/O error or truncation. */
2053 int read_line_old(int fd, char *buf, size_t bufsiz)
2054 {
2055         bufsiz--; /* leave room for the null */
2056         while (bufsiz > 0) {
2057                 assert(fd != iobuf.in_fd);
2058                 if (safe_read(fd, buf, 1) == 0)
2059                         return 0;
2060                 if (*buf == '\0')
2061                         return 0;
2062                 if (*buf == '\n')
2063                         break;
2064                 if (*buf != '\r') {
2065                         buf++;
2066                         bufsiz--;
2067                 }
2068         }
2069         *buf = '\0';
2070         return bufsiz > 0;
2071 }
2072
2073 void io_printf(int fd, const char *format, ...)
2074 {
2075         va_list ap;
2076         char buf[BIGPATHBUFLEN];
2077         int len;
2078
2079         va_start(ap, format);
2080         len = vsnprintf(buf, sizeof buf, format, ap);
2081         va_end(ap);
2082
2083         if (len < 0)
2084                 exit_cleanup(RERR_STREAMIO);
2085
2086         if (len > (int)sizeof buf) {
2087                 rprintf(FERROR, "io_printf() was too long for the buffer.\n");
2088                 exit_cleanup(RERR_STREAMIO);
2089         }
2090
2091         write_sbuf(fd, buf);
2092 }
2093
2094 /* Setup for multiplexing a MSG_* stream with the data stream. */
2095 void io_start_multiplex_out(int fd)
2096 {
2097         io_flush(FULL_FLUSH);
2098
2099         if (msgs2stderr && DEBUG_GTE(IO, 2))
2100                 rprintf(FINFO, "[%s] io_start_multiplex_out(%d)\n", who_am_i(), fd);
2101
2102         iobuf.out_empty_len = 4; /* See also OUT_MULTIPLEXED */
2103         io_start_buffering_out(fd);
2104
2105         iobuf.raw_data_header_pos = iobuf.out.pos + iobuf.out.len;
2106         iobuf.out.len += 4;
2107 }
2108
2109 /* Setup for multiplexing a MSG_* stream with the data stream. */
2110 void io_start_multiplex_in(int fd)
2111 {
2112         if (msgs2stderr && DEBUG_GTE(IO, 2))
2113                 rprintf(FINFO, "[%s] io_start_multiplex_in(%d)\n", who_am_i(), fd);
2114
2115         iobuf.in_multiplexed = True; /* See also IN_MULTIPLEXED */
2116         io_start_buffering_in(fd);
2117 }
2118
2119 int io_end_multiplex_in(int mode)
2120 {
2121         int ret = iobuf.in_multiplexed ? iobuf.in_fd : -1;
2122
2123         if (msgs2stderr && DEBUG_GTE(IO, 2))
2124                 rprintf(FINFO, "[%s] io_end_multiplex_in(mode=%d)\n", who_am_i(), mode);
2125
2126         iobuf.in_multiplexed = False;
2127         if (mode == MPLX_SWITCHING)
2128                 iobuf.raw_input_ends_before = 0;
2129         else
2130                 assert(iobuf.raw_input_ends_before == 0);
2131         if (mode != MPLX_TO_BUFFERED)
2132                 io_end_buffering_in(mode);
2133
2134         return ret;
2135 }
2136
2137 int io_end_multiplex_out(int mode)
2138 {
2139         int ret = iobuf.out_empty_len ? iobuf.out_fd : -1;
2140
2141         if (msgs2stderr && DEBUG_GTE(IO, 2))
2142                 rprintf(FINFO, "[%s] io_end_multiplex_out(mode=%d)\n", who_am_i(), mode);
2143
2144         if (mode != MPLX_TO_BUFFERED)
2145                 io_end_buffering_out(mode);
2146         else
2147                 io_flush(FULL_FLUSH);
2148
2149         iobuf.out.len = 0;
2150         iobuf.out_empty_len = 0;
2151
2152         return ret;
2153 }
2154
2155 void start_write_batch(int fd)
2156 {
2157         /* Some communication has already taken place, but we don't
2158          * enable batch writing until here so that we can write a
2159          * canonical record of the communication even though the
2160          * actual communication so far depends on whether a daemon
2161          * is involved. */
2162         write_int(batch_fd, protocol_version);
2163         if (protocol_version >= 30)
2164                 write_byte(batch_fd, inc_recurse);
2165         write_int(batch_fd, checksum_seed);
2166
2167         if (am_sender)
2168                 write_batch_monitor_out = fd;
2169         else
2170                 write_batch_monitor_in = fd;
2171 }
2172
2173 void stop_write_batch(void)
2174 {
2175         write_batch_monitor_out = -1;
2176         write_batch_monitor_in = -1;
2177 }