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