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