Use the latest F_*() accessors.
[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>
7 * Copyright (C) 2003, 2004, 2005, 2006 Wayne Davison
d62bcc17 8 *
880da007
MP
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 2 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
WD
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
880da007 22 */
720b47f2 23
0f78b815
WD
24/* Rsync provides its own multiplexing system, which is used to send
25 * stderr and stdout over a single socket.
87ee2481
MP
26 *
27 * For historical reasons this is off during the start of the
28 * connection, but it's switched on quite early using
0f78b815 29 * io_start_multiplex_out() and io_start_multiplex_in(). */
720b47f2 30
720b47f2
AT
31#include "rsync.h"
32
880da007 33/** If no timeout is specified then use a 60 second select timeout */
8cd9fd4e
AT
34#define SELECT_TIMEOUT 60
35
7a55d06e 36extern int bwlimit;
71e58630 37extern size_t bwlimit_writemax;
6ba9279f 38extern int io_timeout;
cdf236aa 39extern int allowed_lull;
d17e1dd2
WD
40extern int am_server;
41extern int am_daemon;
42extern int am_sender;
98f8c9a5 43extern int am_generator;
e626b29e 44extern int eol_nulls;
3b0a30eb 45extern int read_batch;
188fed95 46extern int csum_length;
b9f592fb
WD
47extern int checksum_seed;
48extern int protocol_version;
47c11975 49extern int remove_source_files;
cdf236aa 50extern int preserve_hard_links;
d19320fd 51extern char *filesfrom_host;
a800434a 52extern struct stats stats;
cdf236aa 53extern struct file_list *the_file_list;
720b47f2 54
a86179f4 55const char phase_unknown[] = "unknown";
9e2409ab 56int ignore_timeout = 0;
b9f592fb 57int batch_fd = -1;
b0ad5429 58int batch_gen_fd = -1;
805edf9d 59
cb2e1f18 60/* Ignore an EOF error if non-zero. See whine_about_eof(). */
574c2500 61int kluge_around_eof = 0;
7a55d06e 62
d17e1dd2
WD
63int msg_fd_in = -1;
64int msg_fd_out = -1;
cdf236aa
WD
65int sock_f_in = -1;
66int sock_f_out = -1;
7a55d06e 67
1f75bb10
WD
68static int io_multiplexing_out;
69static int io_multiplexing_in;
3b0a30eb
WD
70static time_t last_io_in;
71static time_t last_io_out;
1f75bb10
WD
72static int no_flush;
73
b9f592fb
WD
74static int write_batch_monitor_in = -1;
75static int write_batch_monitor_out = -1;
76
56014c8c
WD
77static int io_filesfrom_f_in = -1;
78static int io_filesfrom_f_out = -1;
79static char io_filesfrom_buf[2048];
80static char *io_filesfrom_bp;
81static char io_filesfrom_lastchar;
82static int io_filesfrom_buflen;
954bbed8 83static int defer_forwarding_messages = 0;
3b0a30eb 84static int select_timeout = SELECT_TIMEOUT;
d6081c82
WD
85static int active_filecnt = 0;
86static OFF_T active_bytecnt = 0;
720b47f2 87
482f48cc
WD
88static char int_byte_cnt[256] = {
89 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 00 - 0F */
90 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 10 - 1F */
91 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 20 - 2F */
92 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 30 - 3F */
93 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 40 - 4F */
94 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 50 - 5F */
95 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 60 - 6F */
96 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 70 - 7F */
97 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, /* 80 - 8F */
98 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, /* 90 - 9F */
99 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, /* A0 - AF */
100 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, /* B0 - BF */
101 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, /* C0 - CF */
102 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, /* D0 - DF */
103 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, /* E0 - EF */
104 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, /* F0 - FF */
105};
106
9dd891bb 107static void read_loop(int fd, char *buf, size_t len);
ff41a59f 108
c6816b94
WD
109struct flist_ndx_item {
110 struct flist_ndx_item *next;
111 int ndx;
d17e1dd2
WD
112};
113
c6816b94
WD
114struct flist_ndx_list {
115 struct flist_ndx_item *head, *tail;
116};
117
cdf236aa 118static struct flist_ndx_list redo_list, hlink_list;
d17e1dd2 119
08c88178
WD
120struct msg_list_item {
121 struct msg_list_item *next;
d17e1dd2 122 int len;
954bbed8 123 char buf[1];
d17e1dd2
WD
124};
125
08c88178
WD
126struct msg_list {
127 struct msg_list_item *head, *tail;
128};
129
954bbed8 130static struct msg_list msg2genr, msg2sndr;
d17e1dd2 131
c6816b94 132static void flist_ndx_push(struct flist_ndx_list *lp, int ndx)
d17e1dd2 133{
c6816b94
WD
134 struct flist_ndx_item *item;
135
136 if (!(item = new(struct flist_ndx_item)))
137 out_of_memory("flist_ndx_push");
138 item->next = NULL;
139 item->ndx = ndx;
140 if (lp->tail)
141 lp->tail->next = item;
d17e1dd2 142 else
c6816b94
WD
143 lp->head = item;
144 lp->tail = item;
145}
146
147static int flist_ndx_pop(struct flist_ndx_list *lp)
148{
149 struct flist_ndx_item *next;
150 int ndx;
151
152 if (!lp->head)
153 return -1;
154
155 ndx = lp->head->ndx;
156 next = lp->head->next;
157 free(lp->head);
158 lp->head = next;
159 if (!next)
160 lp->tail = NULL;
161
162 return ndx;
d17e1dd2
WD
163}
164
8d9dc9f9
AT
165static void check_timeout(void)
166{
167 time_t t;
90ba34e2 168
9e2409ab 169 if (!io_timeout || ignore_timeout)
d17e1dd2 170 return;
8d9dc9f9 171
3b0a30eb
WD
172 if (!last_io_in) {
173 last_io_in = time(NULL);
8d9dc9f9
AT
174 return;
175 }
176
177 t = time(NULL);
178
3b0a30eb 179 if (t - last_io_in >= io_timeout) {
0adb99b9 180 if (!am_server && !am_daemon) {
4ccfd96c 181 rprintf(FERROR, "io timeout after %d seconds -- exiting\n",
3b0a30eb 182 (int)(t-last_io_in));
0adb99b9 183 }
65417579 184 exit_cleanup(RERR_TIMEOUT);
8d9dc9f9
AT
185 }
186}
187
1f75bb10
WD
188/* Note the fds used for the main socket (which might really be a pipe
189 * for a local transfer, but we can ignore that). */
190void io_set_sock_fds(int f_in, int f_out)
191{
192 sock_f_in = f_in;
193 sock_f_out = f_out;
194}
195
3b0a30eb
WD
196void set_io_timeout(int secs)
197{
198 io_timeout = secs;
199
200 if (!io_timeout || io_timeout > SELECT_TIMEOUT)
201 select_timeout = SELECT_TIMEOUT;
202 else
203 select_timeout = io_timeout;
204
205 allowed_lull = read_batch ? 0 : (io_timeout + 1) / 2;
206}
207
98f8c9a5
WD
208/* Setup the fd used to receive MSG_* messages. Only needed during the
209 * early stages of being a local sender (up through the sending of the
210 * file list) or when we're the generator (to fetch the messages from
211 * the receiver). */
d17e1dd2
WD
212void set_msg_fd_in(int fd)
213{
214 msg_fd_in = fd;
215}
216
98f8c9a5
WD
217/* Setup the fd used to send our MSG_* messages. Only needed when
218 * we're the receiver (to send our messages to the generator). */
d17e1dd2
WD
219void set_msg_fd_out(int fd)
220{
221 msg_fd_out = fd;
222 set_nonblocking(msg_fd_out);
223}
224
225/* Add a message to the pending MSG_* list. */
4a19c3b2 226static void msg_list_add(struct msg_list *lst, int code, const char *buf, int len)
554e0a8d 227{
954bbed8
WD
228 struct msg_list_item *m;
229 int sz = len + 4 + sizeof m[0] - 1;
d17e1dd2 230
954bbed8 231 if (!(m = (struct msg_list_item *)new_array(char, sz)))
c6816b94 232 out_of_memory("msg_list_add");
954bbed8
WD
233 m->next = NULL;
234 m->len = len + 4;
235 SIVAL(m->buf, 0, ((code+MPLEX_BASE)<<24) | len);
236 memcpy(m->buf + 4, buf, len);
237 if (lst->tail)
238 lst->tail->next = m;
d17e1dd2 239 else
954bbed8
WD
240 lst->head = m;
241 lst->tail = m;
554e0a8d
AT
242}
243
98f8c9a5
WD
244/* Read a message from the MSG_* fd and handle it. This is called either
245 * during the early stages of being a local sender (up through the sending
246 * of the file list) or when we're the generator (to fetch the messages
247 * from the receiver). */
d17e1dd2 248static void read_msg_fd(void)
554e0a8d 249{
f9c6b3e7 250 char buf[2048];
06ce139f 251 size_t n;
d17e1dd2 252 int fd = msg_fd_in;
ff41a59f
AT
253 int tag, len;
254
00bdf899 255 /* Temporarily disable msg_fd_in. This is needed to avoid looping back
af436313 256 * to this routine from writefd_unbuffered(). */
d17e1dd2 257 msg_fd_in = -1;
554e0a8d 258
ff41a59f
AT
259 read_loop(fd, buf, 4);
260 tag = IVAL(buf, 0);
261
262 len = tag & 0xFFFFFF;
d17e1dd2 263 tag = (tag >> 24) - MPLEX_BASE;
ff41a59f 264
d17e1dd2
WD
265 switch (tag) {
266 case MSG_DONE:
98f8c9a5 267 if (len != 0 || !am_generator) {
13c7bcbb 268 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
d17e1dd2 269 exit_cleanup(RERR_STREAMIO);
13c7bcbb 270 }
c6816b94 271 flist_ndx_push(&redo_list, -1);
d17e1dd2
WD
272 break;
273 case MSG_REDO:
98f8c9a5 274 if (len != 4 || !am_generator) {
13c7bcbb 275 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
d17e1dd2 276 exit_cleanup(RERR_STREAMIO);
13c7bcbb 277 }
d17e1dd2 278 read_loop(fd, buf, 4);
47c11975 279 if (remove_source_files)
d6081c82 280 decrement_active_files(IVAL(buf,0));
c6816b94 281 flist_ndx_push(&redo_list, IVAL(buf,0));
d17e1dd2 282 break;
0d67e00a
WD
283 case MSG_DELETED:
284 if (len >= (int)sizeof buf || !am_generator) {
285 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
286 exit_cleanup(RERR_STREAMIO);
287 }
288 read_loop(fd, buf, len);
12ccc73a 289 send_msg(MSG_DELETED, buf, len);
0d67e00a 290 break;
9981c27e
WD
291 case MSG_SUCCESS:
292 if (len != 4 || !am_generator) {
293 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
294 exit_cleanup(RERR_STREAMIO);
295 }
296 read_loop(fd, buf, len);
47c11975 297 if (remove_source_files) {
d6081c82 298 decrement_active_files(IVAL(buf,0));
12ccc73a 299 send_msg(MSG_SUCCESS, buf, len);
d6081c82 300 }
cdf236aa
WD
301 if (preserve_hard_links)
302 flist_ndx_push(&hlink_list, IVAL(buf,0));
9981c27e 303 break;
72f2d1b3
WD
304 case MSG_SOCKERR:
305 if (!am_generator) {
306 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
307 exit_cleanup(RERR_STREAMIO);
308 }
309 close_multiplexing_out();
310 /* FALL THROUGH */
d17e1dd2
WD
311 case MSG_INFO:
312 case MSG_ERROR:
313 case MSG_LOG:
314 while (len) {
315 n = len;
316 if (n >= sizeof buf)
317 n = sizeof buf - 1;
318 read_loop(fd, buf, n);
54b0dfa0 319 rwrite((enum logcode)tag, buf, n);
d17e1dd2
WD
320 len -= n;
321 }
322 break;
323 default:
f8b9da1a
WD
324 rprintf(FERROR, "unknown message %d:%d [%s]\n",
325 tag, len, who_am_i());
d17e1dd2
WD
326 exit_cleanup(RERR_STREAMIO);
327 }
328
329 msg_fd_in = fd;
330}
331
d6081c82 332/* This is used by the generator to limit how many file transfers can
47c11975 333 * be active at once when --remove-source-files is specified. Without
d6081c82
WD
334 * this, sender-side deletions were mostly happening at the end. */
335void increment_active_files(int ndx, int itemizing, enum logcode code)
336{
337 /* TODO: tune these limits? */
5b986297 338 while (active_filecnt >= (active_bytecnt >= 128*1024 ? 10 : 50)) {
d6081c82
WD
339 if (hlink_list.head)
340 check_for_finished_hlinks(itemizing, code);
341 read_msg_fd();
342 }
343
344 active_filecnt++;
112d728f 345 active_bytecnt += F_LENGTH(the_file_list->files[ndx]);
d6081c82
WD
346}
347
348void decrement_active_files(int ndx)
349{
350 active_filecnt--;
112d728f 351 active_bytecnt -= F_LENGTH(the_file_list->files[ndx]);
d6081c82
WD
352}
353
d17e1dd2
WD
354/* Try to push messages off the list onto the wire. If we leave with more
355 * to do, return 0. On error, return -1. If everything flushed, return 1.
f9c6b3e7 356 * This is only active in the receiver. */
954bbed8 357static int msg2genr_flush(int flush_it_all)
d17e1dd2
WD
358{
359 static int written = 0;
360 struct timeval tv;
361 fd_set fds;
362
363 if (msg_fd_out < 0)
364 return -1;
365
954bbed8
WD
366 while (msg2genr.head) {
367 struct msg_list_item *m = msg2genr.head;
368 int n = write(msg_fd_out, m->buf + written, m->len - written);
d17e1dd2
WD
369 if (n < 0) {
370 if (errno == EINTR)
371 continue;
372 if (errno != EWOULDBLOCK && errno != EAGAIN)
373 return -1;
374 if (!flush_it_all)
375 return 0;
376 FD_ZERO(&fds);
377 FD_SET(msg_fd_out, &fds);
e626b29e 378 tv.tv_sec = select_timeout;
d17e1dd2
WD
379 tv.tv_usec = 0;
380 if (!select(msg_fd_out+1, NULL, &fds, NULL, &tv))
381 check_timeout();
954bbed8
WD
382 } else if ((written += n) == m->len) {
383 msg2genr.head = m->next;
384 if (!msg2genr.head)
385 msg2genr.tail = NULL;
386 free(m);
d17e1dd2
WD
387 written = 0;
388 }
554e0a8d 389 }
d17e1dd2
WD
390 return 1;
391}
392
4a19c3b2 393int send_msg(enum msgcode code, const char *buf, int len)
37f35d89
WD
394{
395 if (msg_fd_out < 0) {
12ccc73a
WD
396 if (!defer_forwarding_messages)
397 return io_multiplex_write(code, buf, len);
398 if (!io_multiplexing_out)
399 return 0;
400 msg_list_add(&msg2sndr, code, buf, len);
401 return 1;
37f35d89 402 }
954bbed8
WD
403 msg_list_add(&msg2genr, code, buf, len);
404 msg2genr_flush(NORMAL_FLUSH);
12ccc73a 405 return 1;
37f35d89
WD
406}
407
155d9206
WD
408void send_msg_int(enum msgcode code, int num)
409{
410 char numbuf[4];
411 SIVAL(numbuf, 0, num);
412 send_msg(code, numbuf, 4);
413}
414
cdf236aa 415int get_redo_num(int itemizing, enum logcode code)
d17e1dd2 416{
cdf236aa
WD
417 while (1) {
418 if (hlink_list.head)
419 check_for_finished_hlinks(itemizing, code);
420 if (redo_list.head)
421 break;
d17e1dd2 422 read_msg_fd();
c6816b94 423 }
554e0a8d 424
c6816b94 425 return flist_ndx_pop(&redo_list);
554e0a8d
AT
426}
427
cdf236aa
WD
428int get_hlink_num(void)
429{
430 return flist_ndx_pop(&hlink_list);
431}
432
56014c8c
WD
433/**
434 * When we're the receiver and we have a local --files-from list of names
435 * that needs to be sent over the socket to the sender, we have to do two
436 * things at the same time: send the sender a list of what files we're
437 * processing and read the incoming file+info list from the sender. We do
438 * this by augmenting the read_timeout() function to copy this data. It
439 * uses the io_filesfrom_buf to read a block of data from f_in (when it is
440 * ready, since it might be a pipe) and then blast it out f_out (when it
441 * is ready to receive more data).
442 */
443void io_set_filesfrom_fds(int f_in, int f_out)
444{
445 io_filesfrom_f_in = f_in;
446 io_filesfrom_f_out = f_out;
447 io_filesfrom_bp = io_filesfrom_buf;
448 io_filesfrom_lastchar = '\0';
449 io_filesfrom_buflen = 0;
450}
720b47f2 451
cb2e1f18
WD
452/* It's almost always an error to get an EOF when we're trying to read from the
453 * network, because the protocol is (for the most part) self-terminating.
880da007 454 *
cb2e1f18
WD
455 * There is one case for the receiver when it is at the end of the transfer
456 * (hanging around reading any keep-alive packets that might come its way): if
457 * the sender dies before the generator's kill-signal comes through, we can end
458 * up here needing to loop until the kill-signal arrives. In this situation,
459 * kluge_around_eof will be < 0.
460 *
461 * There is another case for older protocol versions (< 24) where the module
462 * listing was not terminated, so we must ignore an EOF error in that case and
463 * exit. In this situation, kluge_around_eof will be > 0. */
1f75bb10 464static void whine_about_eof(int fd)
7a55d06e 465{
574c2500 466 if (kluge_around_eof && fd == sock_f_in) {
55bb7fff 467 int i;
574c2500
WD
468 if (kluge_around_eof > 0)
469 exit_cleanup(0);
55bb7fff
WD
470 /* If we're still here after 10 seconds, exit with an error. */
471 for (i = 10*1000/20; i--; )
574c2500
WD
472 msleep(20);
473 }
3151cbae 474
00bdf899 475 rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
dca68b0a
WD
476 "(%.0f bytes received so far) [%s]\n",
477 (double)stats.total_read, who_am_i());
00bdf899
WD
478
479 exit_cleanup(RERR_STREAMIO);
7a55d06e 480}
720b47f2 481
880da007 482/**
6ed6d7f5 483 * Read from a socket with I/O timeout. return the number of bytes
c3563c46
MP
484 * read. If no bytes can be read then exit, never return a number <= 0.
485 *
8886f8d0
MP
486 * TODO: If the remote shell connection fails, then current versions
487 * actually report an "unexpected EOF" error here. Since it's a
488 * fairly common mistake to try to use rsh when ssh is required, we
489 * should trap that: if we fail to read any data at all, we should
490 * give a better explanation. We can tell whether the connection has
491 * started by looking e.g. at whether the remote version is known yet.
c3563c46 492 */
3151cbae 493static int read_timeout(int fd, char *buf, size_t len)
8d9dc9f9 494{
d8aeda1e 495 int n, cnt = 0;
4c36ddbe 496
d17e1dd2 497 io_flush(NORMAL_FLUSH);
ea2111d1 498
d8aeda1e 499 while (cnt == 0) {
7a55d06e 500 /* until we manage to read *something* */
56014c8c 501 fd_set r_fds, w_fds;
4c36ddbe 502 struct timeval tv;
1ea087a7 503 int maxfd = fd;
a57873b7 504 int count;
4c36ddbe 505
56014c8c 506 FD_ZERO(&r_fds);
a7026ba9 507 FD_ZERO(&w_fds);
56014c8c 508 FD_SET(fd, &r_fds);
954bbed8 509 if (msg2genr.head) {
4033b80b 510 FD_SET(msg_fd_out, &w_fds);
1ea087a7
WD
511 if (msg_fd_out > maxfd)
512 maxfd = msg_fd_out;
56014c8c 513 }
3309507d 514 if (io_filesfrom_f_out >= 0) {
56014c8c
WD
515 int new_fd;
516 if (io_filesfrom_buflen == 0) {
3309507d 517 if (io_filesfrom_f_in >= 0) {
56014c8c
WD
518 FD_SET(io_filesfrom_f_in, &r_fds);
519 new_fd = io_filesfrom_f_in;
520 } else {
521 io_filesfrom_f_out = -1;
522 new_fd = -1;
523 }
524 } else {
56014c8c
WD
525 FD_SET(io_filesfrom_f_out, &w_fds);
526 new_fd = io_filesfrom_f_out;
527 }
1ea087a7
WD
528 if (new_fd > maxfd)
529 maxfd = new_fd;
554e0a8d
AT
530 }
531
e626b29e 532 tv.tv_sec = select_timeout;
4c36ddbe
AT
533 tv.tv_usec = 0;
534
554e0a8d
AT
535 errno = 0;
536
a7026ba9 537 count = select(maxfd + 1, &r_fds, &w_fds, NULL, &tv);
a57873b7 538
a57873b7 539 if (count <= 0) {
f89b9368 540 if (errno == EBADF)
554e0a8d 541 exit_cleanup(RERR_SOCKETIO);
bd717af8 542 check_timeout();
4c36ddbe
AT
543 continue;
544 }
545
954bbed8
WD
546 if (msg2genr.head && FD_ISSET(msg_fd_out, &w_fds))
547 msg2genr_flush(NORMAL_FLUSH);
554e0a8d 548
3309507d 549 if (io_filesfrom_f_out >= 0) {
56014c8c
WD
550 if (io_filesfrom_buflen) {
551 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
552 int l = write(io_filesfrom_f_out,
553 io_filesfrom_bp,
554 io_filesfrom_buflen);
555 if (l > 0) {
556 if (!(io_filesfrom_buflen -= l))
557 io_filesfrom_bp = io_filesfrom_buf;
558 else
559 io_filesfrom_bp += l;
560 } else {
561 /* XXX should we complain? */
562 io_filesfrom_f_out = -1;
563 }
564 }
3309507d 565 } else if (io_filesfrom_f_in >= 0) {
56014c8c
WD
566 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
567 int l = read(io_filesfrom_f_in,
568 io_filesfrom_buf,
569 sizeof io_filesfrom_buf);
570 if (l <= 0) {
571 /* Send end-of-file marker */
572 io_filesfrom_buf[0] = '\0';
573 io_filesfrom_buf[1] = '\0';
574 io_filesfrom_buflen = io_filesfrom_lastchar? 2 : 1;
575 io_filesfrom_f_in = -1;
576 } else {
56014c8c
WD
577 if (!eol_nulls) {
578 char *s = io_filesfrom_buf + l;
579 /* Transform CR and/or LF into '\0' */
580 while (s-- > io_filesfrom_buf) {
581 if (*s == '\n' || *s == '\r')
582 *s = '\0';
583 }
584 }
585 if (!io_filesfrom_lastchar) {
586 /* Last buf ended with a '\0', so don't
587 * let this buf start with one. */
588 while (l && !*io_filesfrom_bp)
589 io_filesfrom_bp++, l--;
590 }
591 if (!l)
592 io_filesfrom_bp = io_filesfrom_buf;
593 else {
594 char *f = io_filesfrom_bp;
595 char *t = f;
596 char *eob = f + l;
597 /* Eliminate any multi-'\0' runs. */
598 while (f != eob) {
599 if (!(*t++ = *f++)) {
600 while (f != eob && !*f)
601 f++, l--;
602 }
603 }
604 io_filesfrom_lastchar = f[-1];
605 }
606 io_filesfrom_buflen = l;
607 }
608 }
609 }
610 }
611
f89b9368
WD
612 if (!FD_ISSET(fd, &r_fds))
613 continue;
554e0a8d 614
4c36ddbe
AT
615 n = read(fd, buf, len);
616
1ea087a7
WD
617 if (n <= 0) {
618 if (n == 0)
1f75bb10 619 whine_about_eof(fd); /* Doesn't return. */
d62bcc17
WD
620 if (errno == EINTR || errno == EWOULDBLOCK
621 || errno == EAGAIN)
7a55d06e 622 continue;
1f75bb10
WD
623
624 /* Don't write errors on a dead socket. */
72f2d1b3 625 if (fd == sock_f_in) {
7f459268 626 close_multiplexing_out();
72f2d1b3
WD
627 rsyserr(FSOCKERR, errno, "read error");
628 } else
629 rsyserr(FERROR, errno, "read error");
1f75bb10 630 exit_cleanup(RERR_STREAMIO);
8d9dc9f9 631 }
00bdf899
WD
632
633 buf += n;
634 len -= n;
d8aeda1e 635 cnt += n;
1f75bb10 636
3b0a30eb
WD
637 if (fd == sock_f_in && io_timeout)
638 last_io_in = time(NULL);
4c36ddbe 639 }
8d9dc9f9 640
d8aeda1e 641 return cnt;
4c36ddbe 642}
8d9dc9f9 643
56014c8c
WD
644/**
645 * Read a line into the "fname" buffer (which must be at least MAXPATHLEN
646 * characters long).
647 */
648int read_filesfrom_line(int fd, char *fname)
649{
650 char ch, *s, *eob = fname + MAXPATHLEN - 1;
651 int cnt;
d19320fd 652 int reading_remotely = filesfrom_host != NULL;
56014c8c
WD
653 int nulls = eol_nulls || reading_remotely;
654
655 start:
656 s = fname;
657 while (1) {
658 cnt = read(fd, &ch, 1);
659 if (cnt < 0 && (errno == EWOULDBLOCK
660 || errno == EINTR || errno == EAGAIN)) {
661 struct timeval tv;
6c850772
WD
662 fd_set r_fds, e_fds;
663 FD_ZERO(&r_fds);
664 FD_SET(fd, &r_fds);
665 FD_ZERO(&e_fds);
666 FD_SET(fd, &e_fds);
e626b29e 667 tv.tv_sec = select_timeout;
56014c8c 668 tv.tv_usec = 0;
6c850772 669 if (!select(fd+1, &r_fds, NULL, &e_fds, &tv))
56014c8c 670 check_timeout();
6c850772
WD
671 if (FD_ISSET(fd, &e_fds)) {
672 rsyserr(FINFO, errno,
673 "select exception on fd %d", fd);
674 }
56014c8c
WD
675 continue;
676 }
677 if (cnt != 1)
678 break;
679 if (nulls? !ch : (ch == '\r' || ch == '\n')) {
680 /* Skip empty lines if reading locally. */
681 if (!reading_remotely && s == fname)
682 continue;
683 break;
684 }
685 if (s < eob)
686 *s++ = ch;
687 }
688 *s = '\0';
7a55d06e 689
6b45fcf1
WD
690 /* Dump comments. */
691 if (*fname == '#' || *fname == ';')
56014c8c
WD
692 goto start;
693
694 return s - fname;
695}
7a55d06e 696
1f75bb10
WD
697static char *iobuf_out;
698static int iobuf_out_cnt;
699
700void io_start_buffering_out(void)
701{
702 if (iobuf_out)
703 return;
704 if (!(iobuf_out = new_array(char, IO_BUFFER_SIZE)))
705 out_of_memory("io_start_buffering_out");
706 iobuf_out_cnt = 0;
707}
708
1f75bb10
WD
709static char *iobuf_in;
710static size_t iobuf_in_siz;
711
712void io_start_buffering_in(void)
713{
714 if (iobuf_in)
715 return;
716 iobuf_in_siz = 2 * IO_BUFFER_SIZE;
717 if (!(iobuf_in = new_array(char, iobuf_in_siz)))
718 out_of_memory("io_start_buffering_in");
719}
720
1f75bb10
WD
721void io_end_buffering(void)
722{
723 io_flush(NORMAL_FLUSH);
724 if (!io_multiplexing_out) {
725 free(iobuf_out);
726 iobuf_out = NULL;
727 }
728}
729
626bec8e
WD
730void maybe_flush_socket(void)
731{
3b0a30eb 732 if (iobuf_out && iobuf_out_cnt && time(NULL) - last_io_out >= 5)
626bec8e
WD
733 io_flush(NORMAL_FLUSH);
734}
735
cdf236aa 736void maybe_send_keepalive(void)
9e2409ab 737{
3b0a30eb 738 if (time(NULL) - last_io_out >= allowed_lull) {
9e2409ab 739 if (!iobuf_out || !iobuf_out_cnt) {
3221f451
WD
740 if (protocol_version < 29)
741 return; /* there's nothing we can do */
cdf236aa 742 write_int(sock_f_out, the_file_list->count);
9e2409ab
WD
743 write_shortint(sock_f_out, ITEM_IS_NEW);
744 }
745 if (iobuf_out)
746 io_flush(NORMAL_FLUSH);
747 }
748}
749
880da007
MP
750/**
751 * Continue trying to read len bytes - don't return until len has been
752 * read.
753 **/
3151cbae 754static void read_loop(int fd, char *buf, size_t len)
4c36ddbe
AT
755{
756 while (len) {
757 int n = read_timeout(fd, buf, len);
758
759 buf += n;
760 len -= n;
8d9dc9f9
AT
761 }
762}
763
7a55d06e
MP
764/**
765 * Read from the file descriptor handling multiplexing - return number
766 * of bytes read.
d62bcc17
WD
767 *
768 * Never returns <= 0.
7a55d06e 769 */
c399d22a 770static int readfd_unbuffered(int fd, char *buf, size_t len)
8d9dc9f9 771{
6fe25398 772 static size_t remaining;
1f75bb10 773 static size_t iobuf_in_ndx;
f2a4853c 774 size_t msg_bytes;
d8aeda1e 775 int tag, cnt = 0;
33544bf4 776 char line[BIGPATHBUFLEN];
8d9dc9f9 777
1f75bb10 778 if (!iobuf_in || fd != sock_f_in)
4c36ddbe 779 return read_timeout(fd, buf, len);
8d9dc9f9 780
76c21947 781 if (!io_multiplexing_in && remaining == 0) {
1f75bb10
WD
782 remaining = read_timeout(fd, iobuf_in, iobuf_in_siz);
783 iobuf_in_ndx = 0;
76c21947
WD
784 }
785
d8aeda1e 786 while (cnt == 0) {
8d9dc9f9
AT
787 if (remaining) {
788 len = MIN(len, remaining);
1f75bb10
WD
789 memcpy(buf, iobuf_in + iobuf_in_ndx, len);
790 iobuf_in_ndx += len;
8d9dc9f9 791 remaining -= len;
d8aeda1e 792 cnt = len;
76c21947 793 break;
8d9dc9f9
AT
794 }
795
909ce14f 796 read_loop(fd, line, 4);
ff41a59f 797 tag = IVAL(line, 0);
679e7657 798
f2a4853c 799 msg_bytes = tag & 0xFFFFFF;
d17e1dd2 800 tag = (tag >> 24) - MPLEX_BASE;
8d9dc9f9 801
d17e1dd2
WD
802 switch (tag) {
803 case MSG_DATA:
f2a4853c 804 if (msg_bytes > iobuf_in_siz) {
1f75bb10 805 if (!(iobuf_in = realloc_array(iobuf_in, char,
f2a4853c 806 msg_bytes)))
c399d22a 807 out_of_memory("readfd_unbuffered");
f2a4853c 808 iobuf_in_siz = msg_bytes;
76c21947 809 }
f2a4853c
WD
810 read_loop(fd, iobuf_in, msg_bytes);
811 remaining = msg_bytes;
1f75bb10 812 iobuf_in_ndx = 0;
d17e1dd2 813 break;
0d67e00a 814 case MSG_DELETED:
f2a4853c
WD
815 if (msg_bytes >= sizeof line)
816 goto overflow;
817 read_loop(fd, line, msg_bytes);
0d67e00a 818 /* A directory name was sent with the trailing null */
f2a4853c 819 if (msg_bytes > 0 && !line[msg_bytes-1])
0d67e00a 820 log_delete(line, S_IFDIR);
12bda6f7
WD
821 else {
822 line[msg_bytes] = '\0';
0d67e00a 823 log_delete(line, S_IFREG);
12bda6f7 824 }
0d67e00a 825 break;
9981c27e 826 case MSG_SUCCESS:
f2a4853c 827 if (msg_bytes != 4) {
cdf236aa 828 rprintf(FERROR, "invalid multi-message %d:%ld [%s]\n",
f2a4853c 829 tag, (long)msg_bytes, who_am_i());
9981c27e
WD
830 exit_cleanup(RERR_STREAMIO);
831 }
f2a4853c 832 read_loop(fd, line, msg_bytes);
9981c27e 833 successful_send(IVAL(line, 0));
9981c27e 834 break;
d17e1dd2
WD
835 case MSG_INFO:
836 case MSG_ERROR:
f2a4853c
WD
837 if (msg_bytes >= sizeof line) {
838 overflow:
bd9fca47 839 rprintf(FERROR,
cdf236aa 840 "multiplexing overflow %d:%ld [%s]\n",
f2a4853c 841 tag, (long)msg_bytes, who_am_i());
d17e1dd2
WD
842 exit_cleanup(RERR_STREAMIO);
843 }
f2a4853c
WD
844 read_loop(fd, line, msg_bytes);
845 rwrite((enum logcode)tag, line, msg_bytes);
d17e1dd2
WD
846 break;
847 default:
cdf236aa
WD
848 rprintf(FERROR, "unexpected tag %d [%s]\n",
849 tag, who_am_i());
65417579 850 exit_cleanup(RERR_STREAMIO);
8d9dc9f9 851 }
8d9dc9f9
AT
852 }
853
76c21947 854 if (remaining == 0)
d17e1dd2 855 io_flush(NORMAL_FLUSH);
76c21947 856
d8aeda1e 857 return cnt;
8d9dc9f9
AT
858}
859
880da007
MP
860/**
861 * Do a buffered read from @p fd. Don't return until all @p n bytes
862 * have been read. If all @p n can't be read then exit with an
863 * error.
864 **/
3151cbae 865static void readfd(int fd, char *buffer, size_t N)
720b47f2 866{
d8aeda1e 867 int cnt;
d62bcc17 868 size_t total = 0;
3151cbae 869
6ba9279f 870 while (total < N) {
d8aeda1e
WD
871 cnt = readfd_unbuffered(fd, buffer + total, N-total);
872 total += cnt;
7f28dbee 873 }
1b7c47cb 874
b9f592fb
WD
875 if (fd == write_batch_monitor_in) {
876 if ((size_t)write(batch_fd, buffer, total) != total)
877 exit_cleanup(RERR_FILEIO);
878 }
1f75bb10
WD
879
880 if (fd == sock_f_in)
881 stats.total_read += total;
720b47f2
AT
882}
883
3a993aa4 884unsigned short read_shortint(int f)
9361f839 885{
482f48cc
WD
886 char b[2];
887 readfd(f, b, 2);
888 return (UVAL(b, 1) << 8) + UVAL(b, 0);
9361f839
WD
889}
890
b7922338 891int32 read_int(int f)
720b47f2 892{
4c36ddbe 893 char b[4];
d8aeda1e 894 int32 num;
d730b113 895
482f48cc
WD
896 readfd(f, b, 4);
897 num = IVAL(b, 0);
898#if SIZEOF_INT32 > 4
899 if (num & (int32)0x80000000)
900 num |= ~(int32)0xffffffff;
901#endif
d8aeda1e 902 return num;
720b47f2
AT
903}
904
71c46176 905int64 read_longint(int f)
3a6a366f 906{
d8aeda1e 907 int64 num;
482f48cc
WD
908 char b[9];
909
910 if (protocol_version < 30) {
911 num = read_int(f);
71c46176 912
482f48cc
WD
913 if ((int32)num != (int32)0xffffffff)
914 return num;
71c46176 915
031fa9ad 916#if SIZEOF_INT64 < 8
482f48cc
WD
917 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
918 exit_cleanup(RERR_UNSUPPORTED);
031fa9ad 919#else
482f48cc
WD
920 readfd(f, b, 8);
921 num = IVAL(b,0) | (((int64)IVAL(b,4))<<32);
031fa9ad 922#endif
482f48cc
WD
923 } else {
924 int cnt;
925 readfd(f, b, 3);
926 cnt = int_byte_cnt[CVAL(b, 0)];
4ea4acf1
WD
927#if SIZEOF_INT64 < 8
928 if (cnt > 5 || (cnt == 5 && (CVAL(b,0)&0x3F || CVAL(b,1)&0x80))) {
929 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
930 exit_cleanup(RERR_UNSUPPORTED);
931 }
932#endif
482f48cc
WD
933 if (cnt > 3)
934 readfd(f, b + 3, cnt - 3);
935 switch (cnt) {
936 case 3:
937 num = NVAL3(b, 0);
938 break;
939 case 4:
940 num = NVAL4(b, 0x80);
941 break;
942 case 5:
943 num = NVAL5(b, 0xC0);
944 break;
4ea4acf1 945#if SIZEOF_INT64 >= 8
482f48cc
WD
946 case 6:
947 num = NVAL6(b, 0xE0);
948 break;
949 case 7:
950 num = NVAL7(b, 0xF0);
951 break;
952 case 8:
953 num = NVAL8(b, 0xF8);
954 break;
955 case 9:
956 num = NVAL8(b+1, 0);
957 break;
4ea4acf1 958#endif
482f48cc 959 default:
4ea4acf1 960 exit_cleanup(RERR_PROTOCOL); /* impossible... */
482f48cc
WD
961 }
962 }
71c46176 963
d8aeda1e 964 return num;
3a6a366f
AT
965}
966
4a19c3b2 967void read_buf(int f, char *buf, size_t len)
720b47f2 968{
4c36ddbe 969 readfd(f,buf,len);
720b47f2
AT
970}
971
4a19c3b2 972void read_sbuf(int f, char *buf, size_t len)
575f2fca 973{
93095cbe 974 readfd(f, buf, len);
af436313 975 buf[len] = '\0';
575f2fca
AT
976}
977
9361f839 978uchar read_byte(int f)
182dca5c 979{
9361f839 980 uchar c;
93095cbe 981 readfd(f, (char *)&c, 1);
4c36ddbe 982 return c;
182dca5c 983}
720b47f2 984
46e99b09
WD
985int read_vstring(int f, char *buf, int bufsize)
986{
987 int len = read_byte(f);
988
989 if (len & 0x80)
990 len = (len & ~0x80) * 0x100 + read_byte(f);
991
992 if (len >= bufsize) {
993 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
994 len, bufsize - 1);
9a6ed83f 995 return -1;
46e99b09
WD
996 }
997
998 if (len)
999 readfd(f, buf, len);
1000 buf[len] = '\0';
1001 return len;
1002}
1003
188fed95
WD
1004/* Populate a sum_struct with values from the socket. This is
1005 * called by both the sender and the receiver. */
1006void read_sum_head(int f, struct sum_struct *sum)
1007{
1008 sum->count = read_int(f);
c638caa6
WD
1009 if (sum->count < 0) {
1010 rprintf(FERROR, "Invalid checksum count %ld [%s]\n",
1011 (long)sum->count, who_am_i());
1012 exit_cleanup(RERR_PROTOCOL);
1013 }
188fed95
WD
1014 sum->blength = read_int(f);
1015 if (sum->blength < 0 || sum->blength > MAX_BLOCK_SIZE) {
cdf236aa
WD
1016 rprintf(FERROR, "Invalid block length %ld [%s]\n",
1017 (long)sum->blength, who_am_i());
188fed95
WD
1018 exit_cleanup(RERR_PROTOCOL);
1019 }
1020 sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
1021 if (sum->s2length < 0 || sum->s2length > MD4_SUM_LENGTH) {
cdf236aa
WD
1022 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
1023 sum->s2length, who_am_i());
188fed95
WD
1024 exit_cleanup(RERR_PROTOCOL);
1025 }
1026 sum->remainder = read_int(f);
1027 if (sum->remainder < 0 || sum->remainder > sum->blength) {
cdf236aa
WD
1028 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
1029 (long)sum->remainder, who_am_i());
188fed95
WD
1030 exit_cleanup(RERR_PROTOCOL);
1031 }
1032}
1033
c207d7ec
WD
1034/* Send the values from a sum_struct over the socket. Set sum to
1035 * NULL if there are no checksums to send. This is called by both
1036 * the generator and the sender. */
1037void write_sum_head(int f, struct sum_struct *sum)
1038{
1039 static struct sum_struct null_sum;
1040
1041 if (sum == NULL)
1042 sum = &null_sum;
1043
1044 write_int(f, sum->count);
1045 write_int(f, sum->blength);
1046 if (protocol_version >= 27)
1047 write_int(f, sum->s2length);
1048 write_int(f, sum->remainder);
1049}
1050
08571358
MP
1051/**
1052 * Sleep after writing to limit I/O bandwidth usage.
1053 *
1054 * @todo Rather than sleeping after each write, it might be better to
1055 * use some kind of averaging. The current algorithm seems to always
1056 * use a bit less bandwidth than specified, because it doesn't make up
1057 * for slow periods. But arguably this is a feature. In addition, we
1058 * ought to take the time used to write the data into account.
71e58630
WD
1059 *
1060 * During some phases of big transfers (file FOO is uptodate) this is
1061 * called with a small bytes_written every time. As the kernel has to
1062 * round small waits up to guarantee that we actually wait at least the
1063 * requested number of microseconds, this can become grossly inaccurate.
1064 * We therefore keep track of the bytes we've written over time and only
1065 * sleep when the accumulated delay is at least 1 tenth of a second.
08571358
MP
1066 **/
1067static void sleep_for_bwlimit(int bytes_written)
1068{
71e58630 1069 static struct timeval prior_tv;
0f78b815 1070 static long total_written = 0;
71e58630
WD
1071 struct timeval tv, start_tv;
1072 long elapsed_usec, sleep_usec;
1073
1074#define ONE_SEC 1000000L /* # of microseconds in a second */
08571358 1075
9a0cfff5 1076 if (!bwlimit_writemax)
08571358 1077 return;
e681e820 1078
0f78b815 1079 total_written += bytes_written;
71e58630
WD
1080
1081 gettimeofday(&start_tv, NULL);
1082 if (prior_tv.tv_sec) {
1083 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
1084 + (start_tv.tv_usec - prior_tv.tv_usec);
1085 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
1086 if (total_written < 0)
1087 total_written = 0;
1088 }
3151cbae 1089
71e58630
WD
1090 sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1091 if (sleep_usec < ONE_SEC / 10) {
1092 prior_tv = start_tv;
1093 return;
1094 }
08571358 1095
71e58630
WD
1096 tv.tv_sec = sleep_usec / ONE_SEC;
1097 tv.tv_usec = sleep_usec % ONE_SEC;
98b332ed 1098 select(0, NULL, NULL, NULL, &tv);
71e58630
WD
1099
1100 gettimeofday(&prior_tv, NULL);
1101 elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1102 + (prior_tv.tv_usec - start_tv.tv_usec);
1103 total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
08571358
MP
1104}
1105
1f75bb10 1106/* Write len bytes to the file descriptor fd, looping as necessary to get
0fb2fc4a 1107 * the job done and also (in certain circumstances) reading any data on
af436313 1108 * msg_fd_in to avoid deadlock.
880da007
MP
1109 *
1110 * This function underlies the multiplexing system. The body of the
1f75bb10 1111 * application never calls this function directly. */
4a19c3b2 1112static void writefd_unbuffered(int fd, const char *buf, size_t len)
720b47f2 1113{
1ea087a7 1114 size_t n, total = 0;
6c850772 1115 fd_set w_fds, r_fds, e_fds;
d8aeda1e 1116 int maxfd, count, cnt, using_r_fds;
7d51b837 1117 int defer_save = defer_forwarding_messages;
8d9dc9f9 1118 struct timeval tv;
720b47f2 1119
e44f9a12
AT
1120 no_flush++;
1121
4c36ddbe 1122 while (total < len) {
8d9dc9f9 1123 FD_ZERO(&w_fds);
6c850772
WD
1124 FD_SET(fd, &w_fds);
1125 FD_ZERO(&e_fds);
1126 FD_SET(fd, &e_fds);
1ea087a7 1127 maxfd = fd;
4c36ddbe 1128
954bbed8 1129 if (msg_fd_in >= 0) {
56014c8c 1130 FD_ZERO(&r_fds);
6c850772 1131 FD_SET(msg_fd_in, &r_fds);
1ea087a7
WD
1132 if (msg_fd_in > maxfd)
1133 maxfd = msg_fd_in;
3eeac9bc
WD
1134 using_r_fds = 1;
1135 } else
1136 using_r_fds = 0;
8d9dc9f9 1137
e626b29e 1138 tv.tv_sec = select_timeout;
8d9dc9f9 1139 tv.tv_usec = 0;
4c36ddbe 1140
554e0a8d 1141 errno = 0;
3eeac9bc 1142 count = select(maxfd + 1, using_r_fds ? &r_fds : NULL,
6c850772 1143 &w_fds, &e_fds, &tv);
4c36ddbe
AT
1144
1145 if (count <= 0) {
1ea087a7 1146 if (count < 0 && errno == EBADF)
554e0a8d 1147 exit_cleanup(RERR_SOCKETIO);
bd717af8 1148 check_timeout();
8d9dc9f9
AT
1149 continue;
1150 }
4c36ddbe 1151
6c850772
WD
1152 if (FD_ISSET(fd, &e_fds)) {
1153 rsyserr(FINFO, errno,
1154 "select exception on fd %d", fd);
1155 }
1156
3eeac9bc 1157 if (using_r_fds && FD_ISSET(msg_fd_in, &r_fds))
d17e1dd2 1158 read_msg_fd();
554e0a8d 1159
9a6ed83f 1160 if (!FD_ISSET(fd, &w_fds))
1ea087a7 1161 continue;
4c36ddbe 1162
1ea087a7 1163 n = len - total;
9a0cfff5 1164 if (bwlimit_writemax && n > bwlimit_writemax)
1ea087a7 1165 n = bwlimit_writemax;
d8aeda1e 1166 cnt = write(fd, buf + total, n);
1ea087a7 1167
d8aeda1e
WD
1168 if (cnt <= 0) {
1169 if (cnt < 0) {
3309507d
WD
1170 if (errno == EINTR)
1171 continue;
1172 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1173 msleep(1);
1174 continue;
1175 }
f0359dd0
AT
1176 }
1177
1ea087a7 1178 /* Don't try to write errors back across the stream. */
1f75bb10 1179 if (fd == sock_f_out)
7f459268 1180 close_multiplexing_out();
1ea087a7 1181 rsyserr(FERROR, errno,
b88c2e8f
WD
1182 "writefd_unbuffered failed to write %ld bytes [%s]",
1183 (long)len, who_am_i());
d1b31da7
WD
1184 /* If the other side is sending us error messages, try
1185 * to grab any messages they sent before they died. */
7f459268 1186 while (fd == sock_f_out && io_multiplexing_in) {
3b0a30eb 1187 set_io_timeout(30);
9e2409ab 1188 ignore_timeout = 0;
d1b31da7
WD
1189 readfd_unbuffered(sock_f_in, io_filesfrom_buf,
1190 sizeof io_filesfrom_buf);
1191 }
1ea087a7
WD
1192 exit_cleanup(RERR_STREAMIO);
1193 }
4c36ddbe 1194
d8aeda1e 1195 total += cnt;
954bbed8 1196 defer_forwarding_messages = 1;
a800434a 1197
1f75bb10 1198 if (fd == sock_f_out) {
626bec8e 1199 if (io_timeout || am_generator)
3b0a30eb 1200 last_io_out = time(NULL);
d8aeda1e 1201 sleep_for_bwlimit(cnt);
1f75bb10 1202 }
4c36ddbe 1203 }
e44f9a12 1204
7d51b837 1205 defer_forwarding_messages = defer_save;
e44f9a12 1206 no_flush--;
720b47f2
AT
1207}
1208
7d51b837
WD
1209static void msg2sndr_flush(void)
1210{
1211 if (defer_forwarding_messages)
1212 return;
1213
a7704777 1214 while (msg2sndr.head && io_multiplexing_out) {
7d51b837
WD
1215 struct msg_list_item *m = msg2sndr.head;
1216 if (!(msg2sndr.head = m->next))
1217 msg2sndr.tail = NULL;
12ccc73a 1218 stats.total_written += m->len;
7d51b837 1219 defer_forwarding_messages = 1;
12ccc73a 1220 writefd_unbuffered(sock_f_out, m->buf, m->len);
7d51b837
WD
1221 defer_forwarding_messages = 0;
1222 free(m);
1223 }
1224}
1225
880da007
MP
1226/**
1227 * Write an message to a multiplexed stream. If this fails then rsync
1228 * exits.
1229 **/
4a19c3b2 1230static void mplex_write(enum msgcode code, const char *buf, size_t len)
ff41a59f 1231{
12bda6f7 1232 char buffer[1024];
06ce139f 1233 size_t n = len;
8d9dc9f9 1234
ff41a59f
AT
1235 SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
1236
c399d22a 1237 if (n > sizeof buffer - 4)
12bda6f7
WD
1238 n = 0;
1239 else
1240 memcpy(buffer + 4, buf, n);
ff41a59f 1241
1f75bb10 1242 writefd_unbuffered(sock_f_out, buffer, n+4);
ff41a59f
AT
1243
1244 len -= n;
1245 buf += n;
1246
7d51b837
WD
1247 if (len) {
1248 defer_forwarding_messages = 1;
1f75bb10 1249 writefd_unbuffered(sock_f_out, buf, len);
7d51b837
WD
1250 defer_forwarding_messages = 0;
1251 msg2sndr_flush();
1252 }
d6dead6b
AT
1253}
1254
d17e1dd2 1255void io_flush(int flush_it_all)
d6dead6b 1256{
954bbed8 1257 msg2genr_flush(flush_it_all);
7d51b837 1258 msg2sndr_flush();
90ba34e2 1259
1f75bb10 1260 if (!iobuf_out_cnt || no_flush)
d17e1dd2 1261 return;
8d9dc9f9 1262
d17e1dd2 1263 if (io_multiplexing_out)
1f75bb10 1264 mplex_write(MSG_DATA, iobuf_out, iobuf_out_cnt);
d17e1dd2 1265 else
1f75bb10
WD
1266 writefd_unbuffered(sock_f_out, iobuf_out, iobuf_out_cnt);
1267 iobuf_out_cnt = 0;
8d9dc9f9
AT
1268}
1269
4a19c3b2 1270static void writefd(int fd, const char *buf, size_t len)
d6dead6b 1271{
4033b80b
WD
1272 if (fd == msg_fd_out) {
1273 rprintf(FERROR, "Internal error: wrong write used in receiver.\n");
1274 exit_cleanup(RERR_PROTOCOL);
1275 }
90ba34e2 1276
1f75bb10
WD
1277 if (fd == sock_f_out)
1278 stats.total_written += len;
1279
b9f592fb
WD
1280 if (fd == write_batch_monitor_out) {
1281 if ((size_t)write(batch_fd, buf, len) != len)
1282 exit_cleanup(RERR_FILEIO);
1283 }
1284
1f75bb10 1285 if (!iobuf_out || fd != sock_f_out) {
4c36ddbe
AT
1286 writefd_unbuffered(fd, buf, len);
1287 return;
1288 }
d6dead6b
AT
1289
1290 while (len) {
1f75bb10 1291 int n = MIN((int)len, IO_BUFFER_SIZE - iobuf_out_cnt);
d6dead6b 1292 if (n > 0) {
1f75bb10 1293 memcpy(iobuf_out+iobuf_out_cnt, buf, n);
d6dead6b
AT
1294 buf += n;
1295 len -= n;
1f75bb10 1296 iobuf_out_cnt += n;
d6dead6b 1297 }
3151cbae 1298
1f75bb10 1299 if (iobuf_out_cnt == IO_BUFFER_SIZE)
d17e1dd2 1300 io_flush(NORMAL_FLUSH);
d6dead6b 1301 }
d6dead6b 1302}
720b47f2 1303
3a993aa4 1304void write_shortint(int f, unsigned short x)
9361f839 1305{
3a993aa4
WD
1306 char b[2];
1307 b[0] = (char)x;
1308 b[1] = (char)(x >> 8);
1309 writefd(f, b, 2);
9361f839
WD
1310}
1311
482f48cc 1312void write_int(int f, int32 x)
720b47f2 1313{
8d9dc9f9 1314 char b[4];
482f48cc
WD
1315 SIVAL(b, 0, x);
1316 writefd(f, b, 4);
720b47f2
AT
1317}
1318
7a24c346
MP
1319/*
1320 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1321 * 64-bit types on this platform.
1322 */
71c46176 1323void write_longint(int f, int64 x)
3a6a366f 1324{
482f48cc 1325 char b[12];
3a6a366f 1326
482f48cc
WD
1327#if SIZEOF_INT64 < 8
1328 if (x < 0 || x > 0x7FFFFFFF) {
1329 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1330 exit_cleanup(RERR_UNSUPPORTED);
3a6a366f 1331 }
482f48cc 1332#endif
3a6a366f 1333
482f48cc
WD
1334 if (protocol_version < 30) {
1335 char * const s = b+4;
1336 SIVAL(s, 0, x);
031fa9ad 1337#if SIZEOF_INT64 < 8
482f48cc 1338 writefd(f, s, 4);
031fa9ad 1339#else
482f48cc
WD
1340 if (x <= 0x7FFFFFFF && x >= 0) {
1341 writefd(f, s, 4);
1342 return;
1343 }
3a6a366f 1344
482f48cc
WD
1345 memset(b, 0xFF, 4);
1346 SIVAL(s, 4, x >> 32);
1347 writefd(f, b, 12);
1348 } else if (x < 0) {
1349 goto all_bits;
031fa9ad 1350#endif
482f48cc 1351 } else if (x < ((int32)1<<(3*8-1))) {
3a993aa4
WD
1352 b[0] = (char)(x >> 16);
1353 b[1] = (char)(x >> 8);
1354 b[2] = (char)x;
482f48cc
WD
1355 writefd(f, b, 3);
1356 } else if (x < ((int64)1<<(4*8-2))) {
3a993aa4
WD
1357 b[0] = (char)((x >> 24) | 0x80);
1358 b[1] = (char)(x >> 16);
1359 b[2] = (char)(x >> 8);
1360 b[3] = (char)x;
482f48cc 1361 writefd(f, b, 4);
4ea4acf1
WD
1362#if SIZEOF_INT64 < 8
1363 } else {
1364 b[0] = 0xC0;
1365 b[1] = (char)(x >> 24);
1366 b[2] = (char)(x >> 16);
1367 b[3] = (char)(x >> 8);
1368 b[4] = (char)x;
1369 writefd(f, b, 5);
1370 }
1371#else
482f48cc 1372 } else if (x < ((int64)1<<(5*8-3))) {
3a993aa4
WD
1373 b[0] = (char)((x >> 32) | 0xC0);
1374 b[1] = (char)(x >> 24);
1375 b[2] = (char)(x >> 16);
1376 b[3] = (char)(x >> 8);
1377 b[4] = (char)x;
482f48cc 1378 writefd(f, b, 5);
482f48cc 1379 } else if (x < ((int64)1<<(6*8-4))) {
3a993aa4
WD
1380 b[0] = (char)((x >> 40) | 0xE0);
1381 b[1] = (char)(x >> 32);
1382 b[2] = (char)(x >> 24);
1383 b[3] = (char)(x >> 16);
1384 b[4] = (char)(x >> 8);
1385 b[5] = (char)x;
482f48cc
WD
1386 writefd(f, b, 6);
1387 } else if (x < ((int64)1<<(7*8-5))) {
3a993aa4
WD
1388 b[0] = (char)((x >> 48) | 0xF0);
1389 b[1] = (char)(x >> 40);
1390 b[2] = (char)(x >> 32);
1391 b[3] = (char)(x >> 24);
1392 b[4] = (char)(x >> 16);
1393 b[5] = (char)(x >> 8);
1394 b[6] = (char)x;
482f48cc
WD
1395 writefd(f, b, 7);
1396 } else if (x < ((int64)1<<(8*8-6))) {
3a993aa4
WD
1397 b[0] = (char)((x >> 56) | 0xF8);
1398 b[1] = (char)(x >> 48);
1399 b[2] = (char)(x >> 40);
1400 b[3] = (char)(x >> 32);
1401 b[4] = (char)(x >> 24);
1402 b[5] = (char)(x >> 16);
1403 b[6] = (char)(x >> 8);
1404 b[7] = (char)x;
482f48cc
WD
1405 writefd(f, b, 8);
1406 } else {
1407 all_bits:
3a993aa4
WD
1408 b[0] = (char)0xFC;
1409 b[1] = (char)(x >> 56);
1410 b[2] = (char)(x >> 48);
1411 b[3] = (char)(x >> 40);
1412 b[4] = (char)(x >> 32);
1413 b[5] = (char)(x >> 24);
1414 b[6] = (char)(x >> 16);
1415 b[7] = (char)(x >> 8);
1416 b[8] = (char)x;
482f48cc 1417 writefd(f, b, 9);
482f48cc 1418 }
4ea4acf1 1419#endif
3a6a366f
AT
1420}
1421
4a19c3b2 1422void write_buf(int f, const char *buf, size_t len)
720b47f2 1423{
4c36ddbe 1424 writefd(f,buf,len);
720b47f2
AT
1425}
1426
880da007 1427/** Write a string to the connection */
4a19c3b2 1428void write_sbuf(int f, const char *buf)
f0fca04e 1429{
93095cbe 1430 writefd(f, buf, strlen(buf));
f0fca04e
AT
1431}
1432
9361f839 1433void write_byte(int f, uchar c)
182dca5c 1434{
93095cbe 1435 writefd(f, (char *)&c, 1);
182dca5c
AT
1436}
1437
4a19c3b2 1438void write_vstring(int f, const char *str, int len)
46e99b09
WD
1439{
1440 uchar lenbuf[3], *lb = lenbuf;
1441
1442 if (len > 0x7F) {
1443 if (len > 0x7FFF) {
1444 rprintf(FERROR,
1445 "attempting to send over-long vstring (%d > %d)\n",
1446 len, 0x7FFF);
1447 exit_cleanup(RERR_PROTOCOL);
1448 }
1449 *lb++ = len / 0x100 + 0x80;
1450 }
1451 *lb = len;
1452
1453 writefd(f, (char*)lenbuf, lb - lenbuf + 1);
1454 if (len)
1455 writefd(f, str, len);
1456}
1457
914cc65c 1458/**
6ed6d7f5
WD
1459 * Read a line of up to @p maxlen characters into @p buf (not counting
1460 * the trailing null). Strips the (required) trailing newline and all
1461 * carriage returns.
914cc65c 1462 *
6ed6d7f5 1463 * @return 1 for success; 0 for I/O error or truncation.
914cc65c 1464 **/
9dd891bb 1465int read_line(int f, char *buf, size_t maxlen)
f0fca04e
AT
1466{
1467 while (maxlen) {
528bfcd7 1468 buf[0] = 0;
f0fca04e 1469 read_buf(f, buf, 1);
914cc65c
MP
1470 if (buf[0] == 0)
1471 return 0;
6ed6d7f5 1472 if (buf[0] == '\n')
f0fca04e 1473 break;
f0fca04e
AT
1474 if (buf[0] != '\r') {
1475 buf++;
1476 maxlen--;
1477 }
1478 }
6ed6d7f5
WD
1479 *buf = '\0';
1480 return maxlen > 0;
f0fca04e
AT
1481}
1482
f0fca04e
AT
1483void io_printf(int fd, const char *format, ...)
1484{
d62bcc17 1485 va_list ap;
33544bf4 1486 char buf[BIGPATHBUFLEN];
f0fca04e 1487 int len;
3151cbae 1488
f0fca04e 1489 va_start(ap, format);
3151cbae 1490 len = vsnprintf(buf, sizeof buf, format, ap);
f0fca04e
AT
1491 va_end(ap);
1492
f89b9368
WD
1493 if (len < 0)
1494 exit_cleanup(RERR_STREAMIO);
f0fca04e 1495
33544bf4
WD
1496 if (len > (int)sizeof buf) {
1497 rprintf(FERROR, "io_printf() was too long for the buffer.\n");
1498 exit_cleanup(RERR_STREAMIO);
1499 }
1500
f0fca04e
AT
1501 write_sbuf(fd, buf);
1502}
8d9dc9f9 1503
d17e1dd2 1504/** Setup for multiplexing a MSG_* stream with the data stream. */
1f75bb10 1505void io_start_multiplex_out(void)
8d9dc9f9 1506{
d17e1dd2 1507 io_flush(NORMAL_FLUSH);
1f75bb10 1508 io_start_buffering_out();
8d9dc9f9
AT
1509 io_multiplexing_out = 1;
1510}
1511
d17e1dd2 1512/** Setup for multiplexing a MSG_* stream with the data stream. */
1f75bb10 1513void io_start_multiplex_in(void)
8d9dc9f9 1514{
d17e1dd2 1515 io_flush(NORMAL_FLUSH);
1f75bb10 1516 io_start_buffering_in();
8d9dc9f9
AT
1517 io_multiplexing_in = 1;
1518}
1519
d17e1dd2 1520/** Write an message to the multiplexed data stream. */
4a19c3b2 1521int io_multiplex_write(enum msgcode code, const char *buf, size_t len)
8d9dc9f9 1522{
f89b9368
WD
1523 if (!io_multiplexing_out)
1524 return 0;
8d9dc9f9 1525
d17e1dd2 1526 io_flush(NORMAL_FLUSH);
1b7c47cb 1527 stats.total_written += (len+4);
1f75bb10 1528 mplex_write(code, buf, len);
8d9dc9f9
AT
1529 return 1;
1530}
1531
7f459268
WD
1532void close_multiplexing_in(void)
1533{
1534 io_multiplexing_in = 0;
1535}
1536
d17e1dd2 1537/** Stop output multiplexing. */
7f459268 1538void close_multiplexing_out(void)
554e0a8d
AT
1539{
1540 io_multiplexing_out = 0;
1541}
1542
b9f592fb
WD
1543void start_write_batch(int fd)
1544{
741d6544
WD
1545 write_stream_flags(batch_fd);
1546
b9f592fb
WD
1547 /* Some communication has already taken place, but we don't
1548 * enable batch writing until here so that we can write a
1549 * canonical record of the communication even though the
1550 * actual communication so far depends on whether a daemon
1551 * is involved. */
1552 write_int(batch_fd, protocol_version);
1553 write_int(batch_fd, checksum_seed);
b9f592fb
WD
1554
1555 if (am_sender)
1556 write_batch_monitor_out = fd;
1557 else
1558 write_batch_monitor_in = fd;
1559}
1560
1561void stop_write_batch(void)
1562{
1563 write_batch_monitor_out = -1;
1564 write_batch_monitor_in = -1;
1565}