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