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