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