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