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