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