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