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