Mention the log-file.diff.
[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);
c638caa6
WD
951 if (sum->count < 0) {
952 rprintf(FERROR, "Invalid checksum count %ld [%s]\n",
953 (long)sum->count, who_am_i());
954 exit_cleanup(RERR_PROTOCOL);
955 }
188fed95
WD
956 sum->blength = read_int(f);
957 if (sum->blength < 0 || sum->blength > MAX_BLOCK_SIZE) {
cdf236aa
WD
958 rprintf(FERROR, "Invalid block length %ld [%s]\n",
959 (long)sum->blength, who_am_i());
188fed95
WD
960 exit_cleanup(RERR_PROTOCOL);
961 }
962 sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
963 if (sum->s2length < 0 || sum->s2length > MD4_SUM_LENGTH) {
cdf236aa
WD
964 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
965 sum->s2length, who_am_i());
188fed95
WD
966 exit_cleanup(RERR_PROTOCOL);
967 }
968 sum->remainder = read_int(f);
969 if (sum->remainder < 0 || sum->remainder > sum->blength) {
cdf236aa
WD
970 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
971 (long)sum->remainder, who_am_i());
188fed95
WD
972 exit_cleanup(RERR_PROTOCOL);
973 }
974}
975
c207d7ec
WD
976/* Send the values from a sum_struct over the socket. Set sum to
977 * NULL if there are no checksums to send. This is called by both
978 * the generator and the sender. */
979void write_sum_head(int f, struct sum_struct *sum)
980{
981 static struct sum_struct null_sum;
982
983 if (sum == NULL)
984 sum = &null_sum;
985
986 write_int(f, sum->count);
987 write_int(f, sum->blength);
988 if (protocol_version >= 27)
989 write_int(f, sum->s2length);
990 write_int(f, sum->remainder);
991}
992
08571358
MP
993/**
994 * Sleep after writing to limit I/O bandwidth usage.
995 *
996 * @todo Rather than sleeping after each write, it might be better to
997 * use some kind of averaging. The current algorithm seems to always
998 * use a bit less bandwidth than specified, because it doesn't make up
999 * for slow periods. But arguably this is a feature. In addition, we
1000 * ought to take the time used to write the data into account.
71e58630
WD
1001 *
1002 * During some phases of big transfers (file FOO is uptodate) this is
1003 * called with a small bytes_written every time. As the kernel has to
1004 * round small waits up to guarantee that we actually wait at least the
1005 * requested number of microseconds, this can become grossly inaccurate.
1006 * We therefore keep track of the bytes we've written over time and only
1007 * sleep when the accumulated delay is at least 1 tenth of a second.
08571358
MP
1008 **/
1009static void sleep_for_bwlimit(int bytes_written)
1010{
71e58630
WD
1011 static struct timeval prior_tv;
1012 static long total_written = 0;
1013 struct timeval tv, start_tv;
1014 long elapsed_usec, sleep_usec;
1015
1016#define ONE_SEC 1000000L /* # of microseconds in a second */
08571358 1017
9a0cfff5 1018 if (!bwlimit_writemax)
08571358 1019 return;
e681e820 1020
71e58630
WD
1021 total_written += bytes_written;
1022
1023 gettimeofday(&start_tv, NULL);
1024 if (prior_tv.tv_sec) {
1025 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
1026 + (start_tv.tv_usec - prior_tv.tv_usec);
1027 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
1028 if (total_written < 0)
1029 total_written = 0;
1030 }
3151cbae 1031
71e58630
WD
1032 sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1033 if (sleep_usec < ONE_SEC / 10) {
1034 prior_tv = start_tv;
1035 return;
1036 }
08571358 1037
71e58630
WD
1038 tv.tv_sec = sleep_usec / ONE_SEC;
1039 tv.tv_usec = sleep_usec % ONE_SEC;
98b332ed 1040 select(0, NULL, NULL, NULL, &tv);
71e58630
WD
1041
1042 gettimeofday(&prior_tv, NULL);
1043 elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1044 + (prior_tv.tv_usec - start_tv.tv_usec);
1045 total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
08571358
MP
1046}
1047
1f75bb10 1048/* Write len bytes to the file descriptor fd, looping as necessary to get
0fb2fc4a 1049 * the job done and also (in certain circumstances) reading any data on
af436313 1050 * msg_fd_in to avoid deadlock.
880da007
MP
1051 *
1052 * This function underlies the multiplexing system. The body of the
1f75bb10 1053 * application never calls this function directly. */
9dd891bb 1054static void writefd_unbuffered(int fd,char *buf,size_t len)
720b47f2 1055{
1ea087a7 1056 size_t n, total = 0;
8d9dc9f9 1057 fd_set w_fds, r_fds;
d8aeda1e 1058 int maxfd, count, cnt, using_r_fds;
8d9dc9f9 1059 struct timeval tv;
720b47f2 1060
e44f9a12
AT
1061 no_flush++;
1062
4c36ddbe 1063 while (total < len) {
8d9dc9f9 1064 FD_ZERO(&w_fds);
8d9dc9f9 1065 FD_SET(fd,&w_fds);
1ea087a7 1066 maxfd = fd;
4c36ddbe 1067
af436313 1068 if (msg_fd_in >= 0 && len-total >= contiguous_write_len) {
56014c8c 1069 FD_ZERO(&r_fds);
d17e1dd2 1070 FD_SET(msg_fd_in,&r_fds);
1ea087a7
WD
1071 if (msg_fd_in > maxfd)
1072 maxfd = msg_fd_in;
3eeac9bc
WD
1073 using_r_fds = 1;
1074 } else
1075 using_r_fds = 0;
8d9dc9f9 1076
e626b29e 1077 tv.tv_sec = select_timeout;
8d9dc9f9 1078 tv.tv_usec = 0;
4c36ddbe 1079
554e0a8d 1080 errno = 0;
3eeac9bc 1081 count = select(maxfd + 1, using_r_fds ? &r_fds : NULL,
d17e1dd2 1082 &w_fds, NULL, &tv);
4c36ddbe
AT
1083
1084 if (count <= 0) {
1ea087a7 1085 if (count < 0 && errno == EBADF)
554e0a8d 1086 exit_cleanup(RERR_SOCKETIO);
bd717af8 1087 check_timeout();
8d9dc9f9
AT
1088 continue;
1089 }
4c36ddbe 1090
3eeac9bc 1091 if (using_r_fds && FD_ISSET(msg_fd_in, &r_fds))
d17e1dd2 1092 read_msg_fd();
554e0a8d 1093
9a6ed83f 1094 if (!FD_ISSET(fd, &w_fds))
1ea087a7 1095 continue;
4c36ddbe 1096
1ea087a7 1097 n = len - total;
9a0cfff5 1098 if (bwlimit_writemax && n > bwlimit_writemax)
1ea087a7 1099 n = bwlimit_writemax;
d8aeda1e 1100 cnt = write(fd, buf + total, n);
1ea087a7 1101
d8aeda1e
WD
1102 if (cnt <= 0) {
1103 if (cnt < 0) {
3309507d
WD
1104 if (errno == EINTR)
1105 continue;
1106 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1107 msleep(1);
1108 continue;
1109 }
f0359dd0
AT
1110 }
1111
1ea087a7 1112 /* Don't try to write errors back across the stream. */
1f75bb10 1113 if (fd == sock_f_out)
7f459268 1114 close_multiplexing_out();
1ea087a7 1115 rsyserr(FERROR, errno,
dca68b0a
WD
1116 "writefd_unbuffered failed to write %ld bytes: phase \"%s\" [%s]",
1117 (long)len, io_write_phase, who_am_i());
d1b31da7
WD
1118 /* If the other side is sending us error messages, try
1119 * to grab any messages they sent before they died. */
7f459268 1120 while (fd == sock_f_out && io_multiplexing_in) {
3b0a30eb 1121 set_io_timeout(30);
9e2409ab 1122 ignore_timeout = 0;
d1b31da7
WD
1123 readfd_unbuffered(sock_f_in, io_filesfrom_buf,
1124 sizeof io_filesfrom_buf);
1125 }
1ea087a7
WD
1126 exit_cleanup(RERR_STREAMIO);
1127 }
4c36ddbe 1128
d8aeda1e 1129 total += cnt;
a800434a 1130
1f75bb10 1131 if (fd == sock_f_out) {
626bec8e 1132 if (io_timeout || am_generator)
3b0a30eb 1133 last_io_out = time(NULL);
d8aeda1e 1134 sleep_for_bwlimit(cnt);
1f75bb10 1135 }
4c36ddbe 1136 }
e44f9a12
AT
1137
1138 no_flush--;
720b47f2
AT
1139}
1140
880da007
MP
1141/**
1142 * Write an message to a multiplexed stream. If this fails then rsync
1143 * exits.
1144 **/
1f75bb10 1145static void mplex_write(enum msgcode code, char *buf, size_t len)
ff41a59f 1146{
12bda6f7 1147 char buffer[1024];
06ce139f 1148 size_t n = len;
8d9dc9f9 1149
ff41a59f
AT
1150 SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
1151
af436313
WD
1152 /* When the generator reads messages from the msg_fd_in pipe, it can
1153 * cause output to occur down the socket. Setting contiguous_write_len
1154 * prevents the reading of msg_fd_in once we actually start to write
1155 * this sequence of data (though we might read it before the start). */
1156 if (am_generator && msg_fd_in >= 0)
1157 contiguous_write_len = len + 4;
1158
c399d22a 1159 if (n > sizeof buffer - 4)
12bda6f7
WD
1160 n = 0;
1161 else
1162 memcpy(buffer + 4, buf, n);
ff41a59f 1163
1f75bb10 1164 writefd_unbuffered(sock_f_out, buffer, n+4);
ff41a59f
AT
1165
1166 len -= n;
1167 buf += n;
1168
1ea087a7 1169 if (len)
1f75bb10 1170 writefd_unbuffered(sock_f_out, buf, len);
af436313
WD
1171
1172 if (am_generator && msg_fd_in >= 0)
1173 contiguous_write_len = 0;
d6dead6b
AT
1174}
1175
d17e1dd2 1176void io_flush(int flush_it_all)
d6dead6b 1177{
37f35d89 1178 msg_list_flush(flush_it_all);
90ba34e2 1179
1f75bb10 1180 if (!iobuf_out_cnt || no_flush)
d17e1dd2 1181 return;
8d9dc9f9 1182
d17e1dd2 1183 if (io_multiplexing_out)
1f75bb10 1184 mplex_write(MSG_DATA, iobuf_out, iobuf_out_cnt);
d17e1dd2 1185 else
1f75bb10
WD
1186 writefd_unbuffered(sock_f_out, iobuf_out, iobuf_out_cnt);
1187 iobuf_out_cnt = 0;
8d9dc9f9
AT
1188}
1189
9dd891bb 1190static void writefd(int fd,char *buf,size_t len)
d6dead6b 1191{
4033b80b
WD
1192 if (fd == msg_fd_out) {
1193 rprintf(FERROR, "Internal error: wrong write used in receiver.\n");
1194 exit_cleanup(RERR_PROTOCOL);
1195 }
90ba34e2 1196
1f75bb10
WD
1197 if (fd == sock_f_out)
1198 stats.total_written += len;
1199
b9f592fb
WD
1200 if (fd == write_batch_monitor_out) {
1201 if ((size_t)write(batch_fd, buf, len) != len)
1202 exit_cleanup(RERR_FILEIO);
1203 }
1204
1f75bb10 1205 if (!iobuf_out || fd != sock_f_out) {
4c36ddbe
AT
1206 writefd_unbuffered(fd, buf, len);
1207 return;
1208 }
d6dead6b
AT
1209
1210 while (len) {
1f75bb10 1211 int n = MIN((int)len, IO_BUFFER_SIZE - iobuf_out_cnt);
d6dead6b 1212 if (n > 0) {
1f75bb10 1213 memcpy(iobuf_out+iobuf_out_cnt, buf, n);
d6dead6b
AT
1214 buf += n;
1215 len -= n;
1f75bb10 1216 iobuf_out_cnt += n;
d6dead6b 1217 }
3151cbae 1218
1f75bb10 1219 if (iobuf_out_cnt == IO_BUFFER_SIZE)
d17e1dd2 1220 io_flush(NORMAL_FLUSH);
d6dead6b 1221 }
d6dead6b 1222}
720b47f2 1223
0d67e00a 1224void write_shortint(int f, int x)
9361f839
WD
1225{
1226 uchar b[2];
1227 b[0] = x;
1228 b[1] = x >> 8;
1229 writefd(f, (char *)b, 2);
1230}
1231
b7922338 1232void write_int(int f,int32 x)
720b47f2 1233{
8d9dc9f9
AT
1234 char b[4];
1235 SIVAL(b,0,x);
4c36ddbe 1236 writefd(f,b,4);
720b47f2
AT
1237}
1238
805edf9d
MP
1239void write_int_named(int f, int32 x, const char *phase)
1240{
1241 io_write_phase = phase;
1242 write_int(f, x);
1243 io_write_phase = phase_unknown;
1244}
1245
7a24c346
MP
1246/*
1247 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1248 * 64-bit types on this platform.
1249 */
71c46176 1250void write_longint(int f, int64 x)
3a6a366f 1251{
3a6a366f 1252 char b[8];
3a6a366f 1253
91c4da3f 1254 if (x <= 0x7FFFFFFF) {
3a6a366f
AT
1255 write_int(f, (int)x);
1256 return;
1257 }
1258
031fa9ad
WD
1259#if SIZEOF_INT64 < 8
1260 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1261 exit_cleanup(RERR_UNSUPPORTED);
1262#else
8de330a3 1263 write_int(f, (int32)0xFFFFFFFF);
3a6a366f
AT
1264 SIVAL(b,0,(x&0xFFFFFFFF));
1265 SIVAL(b,4,((x>>32)&0xFFFFFFFF));
1266
4c36ddbe 1267 writefd(f,b,8);
031fa9ad 1268#endif
3a6a366f
AT
1269}
1270
9dd891bb 1271void write_buf(int f,char *buf,size_t len)
720b47f2 1272{
4c36ddbe 1273 writefd(f,buf,len);
720b47f2
AT
1274}
1275
880da007 1276/** Write a string to the connection */
cf338ab1 1277void write_sbuf(int f, char *buf)
f0fca04e 1278{
93095cbe 1279 writefd(f, buf, strlen(buf));
f0fca04e
AT
1280}
1281
9361f839 1282void write_byte(int f, uchar c)
182dca5c 1283{
93095cbe 1284 writefd(f, (char *)&c, 1);
182dca5c
AT
1285}
1286
46e99b09
WD
1287void write_vstring(int f, char *str, int len)
1288{
1289 uchar lenbuf[3], *lb = lenbuf;
1290
1291 if (len > 0x7F) {
1292 if (len > 0x7FFF) {
1293 rprintf(FERROR,
1294 "attempting to send over-long vstring (%d > %d)\n",
1295 len, 0x7FFF);
1296 exit_cleanup(RERR_PROTOCOL);
1297 }
1298 *lb++ = len / 0x100 + 0x80;
1299 }
1300 *lb = len;
1301
1302 writefd(f, (char*)lenbuf, lb - lenbuf + 1);
1303 if (len)
1304 writefd(f, str, len);
1305}
1306
914cc65c 1307/**
6ed6d7f5
WD
1308 * Read a line of up to @p maxlen characters into @p buf (not counting
1309 * the trailing null). Strips the (required) trailing newline and all
1310 * carriage returns.
914cc65c 1311 *
6ed6d7f5 1312 * @return 1 for success; 0 for I/O error or truncation.
914cc65c 1313 **/
9dd891bb 1314int read_line(int f, char *buf, size_t maxlen)
f0fca04e
AT
1315{
1316 while (maxlen) {
528bfcd7 1317 buf[0] = 0;
f0fca04e 1318 read_buf(f, buf, 1);
914cc65c
MP
1319 if (buf[0] == 0)
1320 return 0;
6ed6d7f5 1321 if (buf[0] == '\n')
f0fca04e 1322 break;
f0fca04e
AT
1323 if (buf[0] != '\r') {
1324 buf++;
1325 maxlen--;
1326 }
1327 }
6ed6d7f5
WD
1328 *buf = '\0';
1329 return maxlen > 0;
f0fca04e
AT
1330}
1331
f0fca04e
AT
1332void io_printf(int fd, const char *format, ...)
1333{
d62bcc17 1334 va_list ap;
33544bf4 1335 char buf[BIGPATHBUFLEN];
f0fca04e 1336 int len;
3151cbae 1337
f0fca04e 1338 va_start(ap, format);
3151cbae 1339 len = vsnprintf(buf, sizeof buf, format, ap);
f0fca04e
AT
1340 va_end(ap);
1341
f89b9368
WD
1342 if (len < 0)
1343 exit_cleanup(RERR_STREAMIO);
f0fca04e 1344
33544bf4
WD
1345 if (len > (int)sizeof buf) {
1346 rprintf(FERROR, "io_printf() was too long for the buffer.\n");
1347 exit_cleanup(RERR_STREAMIO);
1348 }
1349
f0fca04e
AT
1350 write_sbuf(fd, buf);
1351}
8d9dc9f9 1352
d17e1dd2 1353/** Setup for multiplexing a MSG_* stream with the data stream. */
1f75bb10 1354void io_start_multiplex_out(void)
8d9dc9f9 1355{
d17e1dd2 1356 io_flush(NORMAL_FLUSH);
1f75bb10 1357 io_start_buffering_out();
8d9dc9f9
AT
1358 io_multiplexing_out = 1;
1359}
1360
d17e1dd2 1361/** Setup for multiplexing a MSG_* stream with the data stream. */
1f75bb10 1362void io_start_multiplex_in(void)
8d9dc9f9 1363{
d17e1dd2 1364 io_flush(NORMAL_FLUSH);
1f75bb10 1365 io_start_buffering_in();
8d9dc9f9
AT
1366 io_multiplexing_in = 1;
1367}
1368
d17e1dd2
WD
1369/** Write an message to the multiplexed data stream. */
1370int io_multiplex_write(enum msgcode code, char *buf, size_t len)
8d9dc9f9 1371{
f89b9368
WD
1372 if (!io_multiplexing_out)
1373 return 0;
8d9dc9f9 1374
d17e1dd2 1375 io_flush(NORMAL_FLUSH);
1b7c47cb 1376 stats.total_written += (len+4);
1f75bb10 1377 mplex_write(code, buf, len);
8d9dc9f9
AT
1378 return 1;
1379}
1380
7f459268
WD
1381void close_multiplexing_in(void)
1382{
1383 io_multiplexing_in = 0;
1384}
1385
d17e1dd2 1386/** Stop output multiplexing. */
7f459268 1387void close_multiplexing_out(void)
554e0a8d
AT
1388{
1389 io_multiplexing_out = 0;
1390}
1391
b9f592fb
WD
1392void start_write_batch(int fd)
1393{
741d6544
WD
1394 write_stream_flags(batch_fd);
1395
b9f592fb
WD
1396 /* Some communication has already taken place, but we don't
1397 * enable batch writing until here so that we can write a
1398 * canonical record of the communication even though the
1399 * actual communication so far depends on whether a daemon
1400 * is involved. */
1401 write_int(batch_fd, protocol_version);
1402 write_int(batch_fd, checksum_seed);
b9f592fb
WD
1403
1404 if (am_sender)
1405 write_batch_monitor_out = fd;
1406 else
1407 write_batch_monitor_in = fd;
1408}
1409
1410void stop_write_batch(void)
1411{
1412 write_batch_monitor_out = -1;
1413 write_batch_monitor_in = -1;
1414}