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