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