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