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