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