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