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