When using --iconv, if a server-side receiver can't convert a filename,
[rsync/rsync.git] / io.c
1 /*
2  * Socket and pipe I/O utilities used in rsync.
3  *
4  * Copyright (C) 1996-2001 Andrew Tridgell
5  * Copyright (C) 1996 Paul Mackerras
6  * Copyright (C) 2001, 2002 Martin Pool <mbp@samba.org>
7  * Copyright (C) 2003-2008 Wayne Davison
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 3 of the License, or
12  * (at your option) any later version.
13  *
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.
18  *
19  * You should have received a copy of the GNU General Public License along
20  * with this program; if not, visit the http://fsf.org website.
21  */
22
23 /* Rsync provides its own multiplexing system, which is used to send
24  * stderr and stdout over a single socket.
25  *
26  * For historical reasons this is off during the start of the
27  * connection, but it's switched on quite early using
28  * io_start_multiplex_out() and io_start_multiplex_in(). */
29
30 #include "rsync.h"
31 #include "ifuncs.h"
32
33 /** If no timeout is specified then use a 60 second select timeout */
34 #define SELECT_TIMEOUT 60
35
36 extern int bwlimit;
37 extern size_t bwlimit_writemax;
38 extern int io_timeout;
39 extern int allowed_lull;
40 extern int am_server;
41 extern int am_daemon;
42 extern int am_sender;
43 extern int am_generator;
44 extern int inc_recurse;
45 extern int io_error;
46 extern int eol_nulls;
47 extern int flist_eof;
48 extern int list_only;
49 extern int read_batch;
50 extern int csum_length;
51 extern int protect_args;
52 extern int checksum_seed;
53 extern int protocol_version;
54 extern int remove_source_files;
55 extern int preserve_hard_links;
56 extern struct stats stats;
57 extern struct file_list *cur_flist;
58 #ifdef ICONV_OPTION
59 extern int filesfrom_convert;
60 extern iconv_t ic_send, ic_recv;
61 #endif
62
63 const char phase_unknown[] = "unknown";
64 int ignore_timeout = 0;
65 int batch_fd = -1;
66 int msgdone_cnt = 0;
67 int check_for_io_err = 0;
68
69 /* Ignore an EOF error if non-zero. See whine_about_eof(). */
70 int kluge_around_eof = 0;
71
72 int msg_fd_in = -1;
73 int msg_fd_out = -1;
74 int sock_f_in = -1;
75 int sock_f_out = -1;
76
77 static int iobuf_f_in = -1;
78 static char *iobuf_in;
79 static size_t iobuf_in_siz;
80 static size_t iobuf_in_ndx;
81 static size_t iobuf_in_remaining;
82
83 static int iobuf_f_out = -1;
84 static char *iobuf_out;
85 static int iobuf_out_cnt;
86
87 int flist_forward_from = -1;
88
89 static int io_multiplexing_out;
90 static int io_multiplexing_in;
91 static time_t last_io_in;
92 static time_t last_io_out;
93 static int no_flush;
94
95 static int write_batch_monitor_in = -1;
96 static int write_batch_monitor_out = -1;
97
98 static int io_filesfrom_f_in = -1;
99 static int io_filesfrom_f_out = -1;
100 static xbuf ff_buf = EMPTY_XBUF;
101 static char ff_lastchar;
102 #ifdef ICONV_OPTION
103 static xbuf iconv_buf = EMPTY_XBUF;
104 #endif
105 static int defer_forwarding_messages = 0, defer_forwarding_keep = 0;
106 static int select_timeout = SELECT_TIMEOUT;
107 static int active_filecnt = 0;
108 static OFF_T active_bytecnt = 0;
109 static int first_message = 1;
110
111 static 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 */
116 };
117
118 #define REMOTE_OPTION_ERROR "rsync: on remote machine: -"
119 #define REMOTE_OPTION_ERROR2 ": unknown option"
120
121 enum festatus { FES_SUCCESS, FES_REDO, FES_NO_SEND };
122
123 static void readfd(int fd, char *buffer, size_t N);
124 static void writefd(int fd, const char *buf, size_t len);
125 static void writefd_unbuffered(int fd, const char *buf, size_t len);
126 static void mplex_write(int fd, enum msgcode code, const char *buf, size_t len, int convert);
127
128 struct flist_ndx_item {
129         struct flist_ndx_item *next;
130         int ndx;
131 };
132
133 struct flist_ndx_list {
134         struct flist_ndx_item *head, *tail;
135 };
136
137 static struct flist_ndx_list redo_list, hlink_list;
138
139 struct msg_list_item {
140         struct msg_list_item *next;
141         char convert;
142         char buf[1];
143 };
144
145 struct msg_list {
146         struct msg_list_item *head, *tail;
147 };
148
149 static struct msg_list msg_queue;
150
151 static void flist_ndx_push(struct flist_ndx_list *lp, int ndx)
152 {
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;
161         else
162                 lp->head = item;
163         lp->tail = item;
164 }
165
166 static 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;
182 }
183
184 static 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);
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];
205                         if (F_IS_HLINKED(file)) {
206                                 flist_ndx_push(&hlink_list, ndx);
207                                 flist->in_progress++;
208                         }
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
221 static void check_timeout(void)
222 {
223         time_t t;
224
225         if (!io_timeout || ignore_timeout)
226                 return;
227
228         if (!last_io_in) {
229                 last_io_in = time(NULL);
230                 return;
231         }
232
233         t = time(NULL);
234
235         if (t - last_io_in >= io_timeout) {
236                 if (!am_server && !am_daemon) {
237                         rprintf(FERROR, "io timeout after %d seconds -- exiting\n",
238                                 (int)(t-last_io_in));
239                 }
240                 exit_cleanup(RERR_TIMEOUT);
241         }
242 }
243
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). */
246 void 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
252 void 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
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). */
268 void set_msg_fd_in(int fd)
269 {
270         msg_fd_in = fd;
271 }
272
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). */
275 void 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. */
282 static void msg_list_add(struct msg_list *lst, int code, const char *buf, int len, int convert)
283 {
284         struct msg_list_item *m;
285         int sz = len + 4 + sizeof m[0] - 1;
286
287         if (!(m = (struct msg_list_item *)new_array(char, sz)))
288                 out_of_memory("msg_list_add");
289         m->next = NULL;
290         m->convert = convert;
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;
295         else
296                 lst->head = m;
297         lst->tail = m;
298 }
299
300 static void msg_flush(void)
301 {
302         if (am_generator) {
303                 while (msg_queue.head && io_multiplexing_out) {
304                         struct msg_list_item *m = msg_queue.head;
305                         int len = IVAL(m->buf, 0) & 0xFFFFFF;
306                         int tag = *((uchar*)m->buf+3) - MPLEX_BASE;
307                         if (!(msg_queue.head = m->next))
308                                 msg_queue.tail = NULL;
309                         stats.total_written += len + 4;
310                         defer_forwarding_messages++;
311                         mplex_write(sock_f_out, tag, m->buf + 4, len, m->convert);
312                         defer_forwarding_messages--;
313                         free(m);
314                 }
315         } else {
316                 while (msg_queue.head) {
317                         struct msg_list_item *m = msg_queue.head;
318                         int len = IVAL(m->buf, 0) & 0xFFFFFF;
319                         int tag = *((uchar*)m->buf+3) - MPLEX_BASE;
320                         if (!(msg_queue.head = m->next))
321                                 msg_queue.tail = NULL;
322                         defer_forwarding_messages++;
323                         mplex_write(msg_fd_out, tag, m->buf + 4, len, m->convert);
324                         defer_forwarding_messages--;
325                         free(m);
326                 }
327         }
328 }
329
330 static 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,
356                     "*** Try using \"--old-d\" if remote rsync is <= 2.6.3 ***\n");
357         }
358 }
359
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). */
364 static void read_msg_fd(void)
365 {
366         char buf[2048];
367         size_t n;
368         struct file_list *flist;
369         int fd = msg_fd_in;
370         int tag, len;
371
372         /* Temporarily disable msg_fd_in.  This is needed to avoid looping back
373          * to this routine from writefd_unbuffered(). */
374         no_flush++;
375         msg_fd_in = -1;
376         defer_forwarding_messages++;
377
378         readfd(fd, buf, 4);
379         tag = IVAL(buf, 0);
380
381         len = tag & 0xFFFFFF;
382         tag = (tag >> 24) - MPLEX_BASE;
383
384         check_for_io_err = 0;
385
386         switch (tag) {
387         case MSG_DONE:
388                 if (len < 0 || len > 1 || !am_generator) {
389                   invalid_msg:
390                         rprintf(FERROR, "invalid message %d:%d [%s%s]\n",
391                                 tag, len, who_am_i(),
392                                 inc_recurse ? "/inc" : "");
393                         exit_cleanup(RERR_STREAMIO);
394                 }
395                 if (len) {
396                         readfd(fd, buf, len);
397                         stats.total_read = read_varlong(fd, 3);
398                 }
399                 msgdone_cnt++;
400                 break;
401         case MSG_REDO:
402                 if (len != 4 || !am_generator)
403                         goto invalid_msg;
404                 readfd(fd, buf, 4);
405                 got_flist_entry_status(FES_REDO, buf);
406                 break;
407         case MSG_FLIST:
408                 if (len != 4 || !am_generator || !inc_recurse)
409                         goto invalid_msg;
410                 readfd(fd, buf, 4);
411                 /* Read extra file list from receiver. */
412                 assert(iobuf_in != NULL);
413                 assert(iobuf_f_in == fd);
414                 if (verbose > 3) {
415                         rprintf(FINFO, "[%s] receiving flist for dir %d\n",
416                                 who_am_i(), IVAL(buf,0));
417                 }
418                 flist = recv_file_list(fd);
419                 flist->parent_ndx = IVAL(buf,0);
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;
423 #ifdef SUPPORT_HARD_LINKS
424                 if (preserve_hard_links)
425                         match_hard_links(flist);
426 #endif
427                 break;
428         case MSG_FLIST_EOF:
429                 if (len != 0 || !am_generator || !inc_recurse)
430                         goto invalid_msg;
431                 flist_eof = 1;
432                 break;
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;
439         case MSG_DELETED:
440                 if (len >= (int)sizeof buf || !am_generator)
441                         goto invalid_msg;
442                 readfd(fd, buf, len);
443                 send_msg(MSG_DELETED, buf, len, 1);
444                 break;
445         case MSG_SUCCESS:
446                 if (len != 4 || !am_generator)
447                         goto invalid_msg;
448                 readfd(fd, buf, 4);
449                 got_flist_entry_status(FES_SUCCESS, buf);
450                 break;
451         case MSG_NO_SEND:
452                 if (len != 4 || !am_generator)
453                         goto invalid_msg;
454                 readfd(fd, buf, 4);
455                 got_flist_entry_status(FES_NO_SEND, buf);
456                 break;
457         case MSG_ERROR_SOCKET:
458         case MSG_ERROR_UTF8:
459         case MSG_CLIENT:
460                 if (!am_generator)
461                         goto invalid_msg;
462                 if (tag == MSG_ERROR_SOCKET)
463                         io_end_multiplex_out();
464                 /* FALL THROUGH */
465         case MSG_INFO:
466         case MSG_ERROR:
467         case MSG_ERROR_XFER:
468         case MSG_WARNING:
469         case MSG_LOG:
470                 while (len) {
471                         n = len;
472                         if (n >= sizeof buf)
473                                 n = sizeof buf - 1;
474                         readfd(fd, buf, n);
475                         rwrite((enum logcode)tag, buf, n, !am_generator);
476                         len -= n;
477                 }
478                 break;
479         default:
480                 rprintf(FERROR, "unknown message %d:%d [%s]\n",
481                         tag, len, who_am_i());
482                 exit_cleanup(RERR_STREAMIO);
483         }
484
485         no_flush--;
486         msg_fd_in = fd;
487         if (!--defer_forwarding_messages && !no_flush)
488                 msg_flush();
489 }
490
491 /* This is used by the generator to limit how many file transfers can
492  * be active at once when --remove-source-files is specified.  Without
493  * this, sender-side deletions were mostly happening at the end. */
494 void increment_active_files(int ndx, int itemizing, enum logcode code)
495 {
496         /* TODO: tune these limits? */
497         while (active_filecnt >= (active_bytecnt >= 128*1024 ? 10 : 50)) {
498                 check_for_finished_files(itemizing, code, 0);
499                 if (iobuf_out_cnt)
500                         io_flush(NORMAL_FLUSH);
501                 else
502                         read_msg_fd();
503         }
504
505         active_filecnt++;
506         active_bytecnt += F_LENGTH(cur_flist->files[ndx - cur_flist->ndx_start]);
507 }
508
509 /* Write an message to a multiplexed stream. If this fails, rsync exits. */
510 static void mplex_write(int fd, enum msgcode code, const char *buf, size_t len, int convert)
511 {
512         char buffer[BIGPATHBUFLEN]; /* Oversized for use by iconv code. */
513         size_t n = len;
514
515 #ifdef ICONV_OPTION
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);
523
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(). */
536         else
537                 memcpy(buffer + 4, buf, n);
538
539         SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
540
541         defer_forwarding_keep = 1; /* defer_forwarding_messages++ on return */
542         writefd_unbuffered(fd, buffer, n+4);
543         defer_forwarding_keep = 0;
544
545         if (len > n)
546                 writefd_unbuffered(fd, buf+n, len-n);
547
548         if (!--defer_forwarding_messages && !no_flush)
549                 msg_flush();
550 }
551
552 int send_msg(enum msgcode code, const char *buf, int len, int convert)
553 {
554         if (msg_fd_out < 0) {
555                 if (!defer_forwarding_messages)
556                         return io_multiplex_write(code, buf, len, convert);
557                 if (!io_multiplexing_out)
558                         return 0;
559                 msg_list_add(&msg_queue, code, buf, len, convert);
560                 return 1;
561         }
562         if (flist_forward_from >= 0)
563                 msg_list_add(&msg_queue, code, buf, len, convert);
564         else
565                 mplex_write(msg_fd_out, code, buf, len, convert);
566         return 1;
567 }
568
569 void send_msg_int(enum msgcode code, int num)
570 {
571         char numbuf[4];
572         SIVAL(numbuf, 0, num);
573         send_msg(code, numbuf, 4, 0);
574 }
575
576 void wait_for_receiver(void)
577 {
578         if (iobuf_out_cnt)
579                 io_flush(NORMAL_FLUSH);
580         else
581                 read_msg_fd();
582 }
583
584 int get_redo_num(void)
585 {
586         return flist_ndx_pop(&redo_list);
587 }
588
589 int get_hlink_num(void)
590 {
591         return flist_ndx_pop(&hlink_list);
592 }
593
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
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).
603  */
604 void 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;
608         alloc_xbuf(&ff_buf, 2048);
609 #ifdef ICONV_OPTION
610         if (protect_args)
611                 alloc_xbuf(&iconv_buf, 1024);
612 #endif
613 }
614
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.
617  *
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. */
627 static void whine_about_eof(int fd)
628 {
629         if (kluge_around_eof && fd == sock_f_in) {
630                 int i;
631                 if (kluge_around_eof > 0)
632                         exit_cleanup(0);
633                 /* If we're still here after 10 seconds, exit with an error. */
634                 for (i = 10*1000/20; i--; )
635                         msleep(20);
636         }
637
638         rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
639                 "(%.0f bytes received so far) [%s]\n",
640                 (double)stats.total_read, who_am_i());
641
642         exit_cleanup(RERR_STREAMIO);
643 }
644
645 /**
646  * Read from a socket with I/O timeout. return the number of bytes
647  * read. If no bytes can be read then exit, never return a number <= 0.
648  *
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.
655  */
656 static int read_timeout(int fd, char *buf, size_t len)
657 {
658         int n, cnt = 0;
659
660         io_flush(FULL_FLUSH);
661
662         while (cnt == 0) {
663                 /* until we manage to read *something* */
664                 fd_set r_fds, w_fds;
665                 struct timeval tv;
666                 int maxfd = fd;
667                 int count;
668
669                 FD_ZERO(&r_fds);
670                 FD_ZERO(&w_fds);
671                 FD_SET(fd, &r_fds);
672                 if (io_filesfrom_f_out >= 0) {
673                         int new_fd;
674                         if (ff_buf.len == 0) {
675                                 if (io_filesfrom_f_in >= 0) {
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 {
683                                 FD_SET(io_filesfrom_f_out, &w_fds);
684                                 new_fd = io_filesfrom_f_out;
685                         }
686                         if (new_fd > maxfd)
687                                 maxfd = new_fd;
688                 }
689
690                 tv.tv_sec = select_timeout;
691                 tv.tv_usec = 0;
692
693                 errno = 0;
694
695                 count = select(maxfd + 1, &r_fds, &w_fds, NULL, &tv);
696
697                 if (count <= 0) {
698                         if (errno == EBADF) {
699                                 defer_forwarding_messages = 0;
700                                 exit_cleanup(RERR_SOCKETIO);
701                         }
702                         check_timeout();
703                         continue;
704                 }
705
706                 if (io_filesfrom_f_out >= 0) {
707                         if (ff_buf.len) {
708                                 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
709                                         int l = write(io_filesfrom_f_out,
710                                                       ff_buf.buf + ff_buf.pos,
711                                                       ff_buf.len);
712                                         if (l > 0) {
713                                                 if (!(ff_buf.len -= l))
714                                                         ff_buf.pos = 0;
715                                                 else
716                                                         ff_buf.pos += l;
717                                         } else if (errno != EINTR) {
718                                                 /* XXX should we complain? */
719                                                 io_filesfrom_f_out = -1;
720                                         }
721                                 }
722                         } else if (io_filesfrom_f_in >= 0) {
723                                 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
724 #ifdef ICONV_OPTION
725                                         xbuf *ibuf = filesfrom_convert ? &iconv_buf : &ff_buf;
726 #else
727                                         xbuf *ibuf = &ff_buf;
728 #endif
729                                         int l = read(io_filesfrom_f_in, ibuf->buf, ibuf->size);
730                                         if (l <= 0) {
731                                                 if (l == 0 || errno != EINTR) {
732                                                         /* Send end-of-file marker */
733                                                         memcpy(ff_buf.buf, "\0\0", 2);
734                                                         ff_buf.len = ff_lastchar? 2 : 1;
735                                                         ff_buf.pos = 0;
736                                                         io_filesfrom_f_in = -1;
737                                                 }
738                                         } else {
739 #ifdef ICONV_OPTION
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                                                 }
747 #endif
748                                                 if (!eol_nulls) {
749                                                         char *s = ff_buf.buf + l;
750                                                         /* Transform CR and/or LF into '\0' */
751                                                         while (s-- > ff_buf.buf) {
752                                                                 if (*s == '\n' || *s == '\r')
753                                                                         *s = '\0';
754                                                         }
755                                                 }
756                                                 if (!ff_lastchar) {
757                                                         /* Last buf ended with a '\0', so don't
758                                                          * let this buf start with one. */
759                                                         while (l && ff_buf.buf[ff_buf.pos] == '\0')
760                                                                 ff_buf.pos++, l--;
761                                                 }
762                                                 if (!l)
763                                                         ff_buf.pos = 0;
764                                                 else {
765                                                         char *f = ff_buf.buf + ff_buf.pos;
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                                                         }
775                                                         ff_lastchar = f[-1];
776                                                 }
777                                                 ff_buf.len = l;
778                                         }
779                                 }
780                         }
781                 }
782
783                 if (!FD_ISSET(fd, &r_fds))
784                         continue;
785
786                 n = read(fd, buf, len);
787
788                 if (n <= 0) {
789                         if (n == 0)
790                                 whine_about_eof(fd); /* Doesn't return. */
791                         if (errno == EINTR || errno == EWOULDBLOCK
792                             || errno == EAGAIN)
793                                 continue;
794
795                         /* Don't write errors on a dead socket. */
796                         if (fd == sock_f_in) {
797                                 io_end_multiplex_out();
798                                 rsyserr(FERROR_SOCKET, errno, "read error");
799                         } else
800                                 rsyserr(FERROR, errno, "read error");
801                         exit_cleanup(RERR_STREAMIO);
802                 }
803
804                 buf += n;
805                 len -= n;
806                 cnt += n;
807
808                 if (fd == sock_f_in && io_timeout)
809                         last_io_in = time(NULL);
810         }
811
812         return cnt;
813 }
814
815 /* Read a line into the "buf" buffer. */
816 int read_line(int fd, char *buf, size_t bufsiz, int flags)
817 {
818         char ch, *s, *eob;
819         int cnt;
820
821 #ifdef ICONV_OPTION
822         if (flags & RL_CONVERT && iconv_buf.size < bufsiz)
823                 realloc_xbuf(&iconv_buf, bufsiz + 1024);
824 #endif
825
826   start:
827 #ifdef ICONV_OPTION
828         s = flags & RL_CONVERT ? iconv_buf.buf : buf;
829 #else
830         s = buf;
831 #endif
832         eob = s + bufsiz - 1;
833         while (1) {
834                 cnt = read(fd, &ch, 1);
835                 if (cnt < 0 && (errno == EWOULDBLOCK
836                   || errno == EINTR || errno == EAGAIN)) {
837                         struct timeval tv;
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);
843                         tv.tv_sec = select_timeout;
844                         tv.tv_usec = 0;
845                         if (!select(fd+1, &r_fds, NULL, &e_fds, &tv))
846                                 check_timeout();
847                         /*if (FD_ISSET(fd, &e_fds))
848                                 rprintf(FINFO, "select exception on fd %d\n", fd); */
849                         continue;
850                 }
851                 if (cnt != 1)
852                         break;
853                 if (flags & RL_EOL_NULLS ? ch == '\0' : (ch == '\r' || ch == '\n')) {
854                         /* Skip empty lines if dumping comments. */
855                         if (flags & RL_DUMP_COMMENTS && s == buf)
856                                 continue;
857                         break;
858                 }
859                 if (s < eob)
860                         *s++ = ch;
861         }
862         *s = '\0';
863
864         if (flags & RL_DUMP_COMMENTS && (*buf == '#' || *buf == ';'))
865                 goto start;
866
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
880         return s - buf;
881 }
882
883 void 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)
885 {
886         int maxargs = MAX_ARGS;
887         int dot_pos = 0;
888         int argc = 0;
889         char **argv, *p;
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
895
896         if (!(argv = new_array(char *, maxargs)))
897                 out_of_memory("read_args");
898         if (mod_name && !protect_args)
899                 argv[argc++] = "rsyncd";
900
901         while (1) {
902                 if (read_line(f_in, buf, bufsiz, rl_flags) == 0)
903                         break;
904
905                 if (argc == maxargs-1) {
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         }
928         argv[argc] = NULL;
929
930         glob_expand(NULL, NULL, NULL, NULL);
931
932         *argc_p = argc;
933         *argv_p = argv;
934 }
935
936 int io_start_buffering_out(int f_out)
937 {
938         if (iobuf_out) {
939                 assert(f_out == iobuf_f_out);
940                 return 0;
941         }
942         if (!(iobuf_out = new_array(char, IO_BUFFER_SIZE)))
943                 out_of_memory("io_start_buffering_out");
944         iobuf_out_cnt = 0;
945         iobuf_f_out = f_out;
946         return 1;
947 }
948
949 int io_start_buffering_in(int f_in)
950 {
951         if (iobuf_in) {
952                 assert(f_in == iobuf_f_in);
953                 return 0;
954         }
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");
958         iobuf_f_in = f_in;
959         return 1;
960 }
961
962 void io_end_buffering_in(void)
963 {
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
973 void 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;
981 }
982
983 void maybe_flush_socket(int important)
984 {
985         if (iobuf_out && iobuf_out_cnt
986          && (important || time(NULL) - last_io_out >= 5))
987                 io_flush(NORMAL_FLUSH);
988 }
989
990 void maybe_send_keepalive(void)
991 {
992         if (time(NULL) - last_io_out >= allowed_lull) {
993                 if (!iobuf_out || !iobuf_out_cnt) {
994                         if (protocol_version < 29)
995                                 return; /* there's nothing we can do */
996                         if (protocol_version >= 30)
997                                 send_msg(MSG_NOOP, "", 0, 0);
998                         else {
999                                 write_int(sock_f_out, cur_flist->used);
1000                                 write_shortint(sock_f_out, ITEM_IS_NEW);
1001                         }
1002                 }
1003                 if (iobuf_out)
1004                         io_flush(NORMAL_FLUSH);
1005         }
1006 }
1007
1008 void 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
1015 void stop_flist_forward()
1016 {
1017         flist_forward_from = -1;
1018         io_flush(FULL_FLUSH);
1019 }
1020
1021 /**
1022  * Continue trying to read len bytes - don't return until len has been
1023  * read.
1024  **/
1025 static void read_loop(int fd, char *buf, size_t len)
1026 {
1027         while (len) {
1028                 int n = read_timeout(fd, buf, len);
1029
1030                 buf += n;
1031                 len -= n;
1032         }
1033 }
1034
1035 /**
1036  * Read from the file descriptor handling multiplexing - return number
1037  * of bytes read.
1038  *
1039  * Never returns <= 0.
1040  */
1041 static int readfd_unbuffered(int fd, char *buf, size_t len)
1042 {
1043         size_t msg_bytes;
1044         int tag, cnt = 0;
1045         char line[BIGPATHBUFLEN];
1046
1047         if (!iobuf_in || fd != iobuf_f_in)
1048                 return read_timeout(fd, buf, len);
1049
1050         if (!io_multiplexing_in && iobuf_in_remaining == 0) {
1051                 iobuf_in_remaining = read_timeout(fd, iobuf_in, iobuf_in_siz);
1052                 iobuf_in_ndx = 0;
1053         }
1054
1055         while (cnt == 0) {
1056                 if (iobuf_in_remaining) {
1057                         len = MIN(len, iobuf_in_remaining);
1058                         memcpy(buf, iobuf_in + iobuf_in_ndx, len);
1059                         iobuf_in_ndx += len;
1060                         iobuf_in_remaining -= len;
1061                         cnt = len;
1062                         break;
1063                 }
1064
1065                 read_loop(fd, line, 4);
1066                 tag = IVAL(line, 0);
1067
1068                 msg_bytes = tag & 0xFFFFFF;
1069                 tag = (tag >> 24) - MPLEX_BASE;
1070
1071                 check_for_io_err = 0;
1072
1073                 switch (tag) {
1074                 case MSG_DATA:
1075                         if (msg_bytes > iobuf_in_siz) {
1076                                 if (!(iobuf_in = realloc_array(iobuf_in, char,
1077                                                                msg_bytes)))
1078                                         out_of_memory("readfd_unbuffered");
1079                                 iobuf_in_siz = msg_bytes;
1080                         }
1081                         read_loop(fd, iobuf_in, msg_bytes);
1082                         iobuf_in_remaining = msg_bytes;
1083                         iobuf_in_ndx = 0;
1084                         break;
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);
1093                         send_msg_int(MSG_IO_ERROR, IVAL(line, 0));
1094                         io_error |= IVAL(line, 0);
1095                         break;
1096                 case MSG_DELETED:
1097                         if (msg_bytes >= sizeof line)
1098                                 goto overflow;
1099 #ifdef ICONV_OPTION
1100                         if (ic_recv != (iconv_t)-1) {
1101                                 xbuf outbuf, inbuf;
1102                                 char ibuf[512];
1103                                 int add_null = 0;
1104                                 int pos = 0;
1105
1106                                 INIT_CONST_XBUF(outbuf, line);
1107                                 INIT_XBUF(inbuf, ibuf, 0, -1);
1108
1109                                 while (msg_bytes) {
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';
1125                                 }
1126                                 msg_bytes = outbuf.len;
1127                         } else
1128 #endif
1129                                 read_loop(fd, line, msg_bytes);
1130                         /* A directory name was sent with the trailing null */
1131                         if (msg_bytes > 0 && !line[msg_bytes-1])
1132                                 log_delete(line, S_IFDIR);
1133                         else {
1134                                 line[msg_bytes] = '\0';
1135                                 log_delete(line, S_IFREG);
1136                         }
1137                         break;
1138                 case MSG_SUCCESS:
1139                         if (msg_bytes != 4) {
1140                           invalid_msg:
1141                                 rprintf(FERROR, "invalid multi-message %d:%ld [%s]\n",
1142                                         tag, (long)msg_bytes, who_am_i());
1143                                 exit_cleanup(RERR_STREAMIO);
1144                         }
1145                         read_loop(fd, line, msg_bytes);
1146                         successful_send(IVAL(line, 0));
1147                         break;
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;
1154                 case MSG_INFO:
1155                 case MSG_ERROR:
1156                 case MSG_ERROR_XFER:
1157                 case MSG_WARNING:
1158                         if (msg_bytes >= sizeof line) {
1159                             overflow:
1160                                 rprintf(FERROR,
1161                                         "multiplexing overflow %d:%ld [%s]\n",
1162                                         tag, (long)msg_bytes, who_am_i());
1163                                 exit_cleanup(RERR_STREAMIO);
1164                         }
1165                         read_loop(fd, line, msg_bytes);
1166                         rwrite((enum logcode)tag, line, msg_bytes, 1);
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                         }
1174                         break;
1175                 default:
1176                         rprintf(FERROR, "unexpected tag %d [%s]\n",
1177                                 tag, who_am_i());
1178                         exit_cleanup(RERR_STREAMIO);
1179                 }
1180         }
1181
1182         if (iobuf_in_remaining == 0)
1183                 io_flush(NORMAL_FLUSH);
1184
1185         return cnt;
1186 }
1187
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. */
1190 static void readfd(int fd, char *buffer, size_t N)
1191 {
1192         int  cnt;
1193         size_t total = 0;
1194
1195         while (total < N) {
1196                 cnt = readfd_unbuffered(fd, buffer + total, N-total);
1197                 total += cnt;
1198         }
1199
1200         if (fd == write_batch_monitor_in) {
1201                 if ((size_t)write(batch_fd, buffer, total) != total)
1202                         exit_cleanup(RERR_FILEIO);
1203         }
1204
1205         if (fd == flist_forward_from)
1206                 writefd(iobuf_f_out, buffer, total);
1207
1208         if (fd == sock_f_in)
1209                 stats.total_read += total;
1210 }
1211
1212 unsigned short read_shortint(int f)
1213 {
1214         char b[2];
1215         readfd(f, b, 2);
1216         return (UVAL(b, 1) << 8) + UVAL(b, 0);
1217 }
1218
1219 int32 read_int(int f)
1220 {
1221         char b[4];
1222         int32 num;
1223
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
1230         return num;
1231 }
1232
1233 int32 read_varint(int f)
1234 {
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 }
1264
1265 int64 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;
1273
1274 #if SIZEOF_INT64 < 8
1275         memset(u.b, 0, 8);
1276 #else
1277         u.x = 0;
1278 #endif
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);
1290 #if SIZEOF_INT64 < 8
1291                 if (min_bytes + extra > 5 || u.b[4] || CVAL(u.b,3) & 0x80) {
1292                         rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1293                         exit_cleanup(RERR_UNSUPPORTED);
1294                 }
1295 #endif
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
1306 int64 read_longint(int f)
1307 {
1308 #if SIZEOF_INT64 >= 8
1309         char b[9];
1310 #endif
1311         int32 num = read_int(f);
1312
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
1323 }
1324
1325 void read_buf(int f, char *buf, size_t len)
1326 {
1327         readfd(f,buf,len);
1328 }
1329
1330 void read_sbuf(int f, char *buf, size_t len)
1331 {
1332         readfd(f, buf, len);
1333         buf[len] = '\0';
1334 }
1335
1336 uchar read_byte(int f)
1337 {
1338         uchar c;
1339         readfd(f, (char *)&c, 1);
1340         return c;
1341 }
1342
1343 int 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);
1353                 return -1;
1354         }
1355
1356         if (len)
1357                 readfd(f, buf, len);
1358         buf[len] = '\0';
1359         return len;
1360 }
1361
1362 /* Populate a sum_struct with values from the socket.  This is
1363  * called by both the sender and the receiver. */
1364 void read_sum_head(int f, struct sum_struct *sum)
1365 {
1366         int32 max_blength = protocol_version < 30 ? OLD_MAX_BLOCK_SIZE : MAX_BLOCK_SIZE;
1367         sum->count = read_int(f);
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         }
1373         sum->blength = read_int(f);
1374         if (sum->blength < 0 || sum->blength > max_blength) {
1375                 rprintf(FERROR, "Invalid block length %ld [%s]\n",
1376                         (long)sum->blength, who_am_i());
1377                 exit_cleanup(RERR_PROTOCOL);
1378         }
1379         sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
1380         if (sum->s2length < 0 || sum->s2length > MAX_DIGEST_LEN) {
1381                 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
1382                         sum->s2length, who_am_i());
1383                 exit_cleanup(RERR_PROTOCOL);
1384         }
1385         sum->remainder = read_int(f);
1386         if (sum->remainder < 0 || sum->remainder > sum->blength) {
1387                 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
1388                         (long)sum->remainder, who_am_i());
1389                 exit_cleanup(RERR_PROTOCOL);
1390         }
1391 }
1392
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. */
1396 void 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
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.
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.
1425  **/
1426 static void sleep_for_bwlimit(int bytes_written)
1427 {
1428         static struct timeval prior_tv;
1429         static long total_written = 0;
1430         struct timeval tv, start_tv;
1431         long elapsed_usec, sleep_usec;
1432
1433 #define ONE_SEC 1000000L /* # of microseconds in a second */
1434
1435         if (!bwlimit_writemax)
1436                 return;
1437
1438         total_written += bytes_written;
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         }
1448
1449         sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1450         if (sleep_usec < ONE_SEC / 10) {
1451                 prior_tv = start_tv;
1452                 return;
1453         }
1454
1455         tv.tv_sec  = sleep_usec / ONE_SEC;
1456         tv.tv_usec = sleep_usec % ONE_SEC;
1457         select(0, NULL, NULL, NULL, &tv);
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);
1463 }
1464
1465 /* Write len bytes to the file descriptor fd, looping as necessary to get
1466  * the job done and also (in certain circumstances) reading any data on
1467  * msg_fd_in to avoid deadlock.
1468  *
1469  * This function underlies the multiplexing system.  The body of the
1470  * application never calls this function directly. */
1471 static void writefd_unbuffered(int fd, const char *buf, size_t len)
1472 {
1473         size_t n, total = 0;
1474         fd_set w_fds, r_fds, e_fds;
1475         int maxfd, count, cnt, using_r_fds;
1476         int defer_inc = 0;
1477         struct timeval tv;
1478
1479         if (no_flush++)
1480                 defer_forwarding_messages++, defer_inc++;
1481
1482         while (total < len) {
1483                 FD_ZERO(&w_fds);
1484                 FD_SET(fd, &w_fds);
1485                 FD_ZERO(&e_fds);
1486                 FD_SET(fd, &e_fds);
1487                 maxfd = fd;
1488
1489                 if (msg_fd_in >= 0) {
1490                         FD_ZERO(&r_fds);
1491                         FD_SET(msg_fd_in, &r_fds);
1492                         if (msg_fd_in > maxfd)
1493                                 maxfd = msg_fd_in;
1494                         using_r_fds = 1;
1495                 } else
1496                         using_r_fds = 0;
1497
1498                 tv.tv_sec = select_timeout;
1499                 tv.tv_usec = 0;
1500
1501                 errno = 0;
1502                 count = select(maxfd + 1, using_r_fds ? &r_fds : NULL,
1503                                &w_fds, &e_fds, &tv);
1504
1505                 if (count <= 0) {
1506                         if (count < 0 && errno == EBADF)
1507                                 exit_cleanup(RERR_SOCKETIO);
1508                         check_timeout();
1509                         continue;
1510                 }
1511
1512                 /*if (FD_ISSET(fd, &e_fds))
1513                         rprintf(FINFO, "select exception on fd %d\n", fd); */
1514
1515                 if (using_r_fds && FD_ISSET(msg_fd_in, &r_fds))
1516                         read_msg_fd();
1517
1518                 if (!FD_ISSET(fd, &w_fds))
1519                         continue;
1520
1521                 n = len - total;
1522                 if (bwlimit_writemax && n > bwlimit_writemax)
1523                         n = bwlimit_writemax;
1524                 cnt = write(fd, buf + total, n);
1525
1526                 if (cnt <= 0) {
1527                         if (cnt < 0) {
1528                                 if (errno == EINTR)
1529                                         continue;
1530                                 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1531                                         msleep(1);
1532                                         continue;
1533                                 }
1534                         }
1535
1536                         /* Don't try to write errors back across the stream. */
1537                         if (fd == sock_f_out)
1538                                 io_end_multiplex_out();
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);
1542                         rsyserr(FERROR, errno,
1543                                 "writefd_unbuffered failed to write %ld bytes [%s]",
1544                                 (long)len, who_am_i());
1545                         /* If the other side is sending us error messages, try
1546                          * to grab any messages they sent before they died. */
1547                         while (!am_server && fd == sock_f_out && io_multiplexing_in) {
1548                                 char buf[1024];
1549                                 set_io_timeout(30);
1550                                 ignore_timeout = 0;
1551                                 readfd_unbuffered(sock_f_in, buf, sizeof buf);
1552                         }
1553                         exit_cleanup(RERR_STREAMIO);
1554                 }
1555
1556                 total += cnt;
1557                 defer_forwarding_messages++, defer_inc++;
1558
1559                 if (fd == sock_f_out) {
1560                         if (io_timeout || am_generator)
1561                                 last_io_out = time(NULL);
1562                         sleep_for_bwlimit(cnt);
1563                 }
1564         }
1565
1566         no_flush--;
1567         defer_inc -= defer_forwarding_keep;
1568         if (!(defer_forwarding_messages -= defer_inc) && !no_flush)
1569                 msg_flush();
1570 }
1571
1572 void io_flush(int flush_it_all)
1573 {
1574         if (!iobuf_out_cnt || no_flush)
1575                 return;
1576
1577         if (io_multiplexing_out)
1578                 mplex_write(sock_f_out, MSG_DATA, iobuf_out, iobuf_out_cnt, 0);
1579         else
1580                 writefd_unbuffered(iobuf_f_out, iobuf_out, iobuf_out_cnt);
1581         iobuf_out_cnt = 0;
1582
1583         if (flush_it_all && !defer_forwarding_messages)
1584                 msg_flush();
1585 }
1586
1587 static void writefd(int fd, const char *buf, size_t len)
1588 {
1589         if (fd == sock_f_out)
1590                 stats.total_written += len;
1591
1592         if (fd == write_batch_monitor_out) {
1593                 if ((size_t)write(batch_fd, buf, len) != len)
1594                         exit_cleanup(RERR_FILEIO);
1595         }
1596
1597         if (!iobuf_out || fd != iobuf_f_out) {
1598                 writefd_unbuffered(fd, buf, len);
1599                 return;
1600         }
1601
1602         while (len) {
1603                 int n = MIN((int)len, IO_BUFFER_SIZE - iobuf_out_cnt);
1604                 if (n > 0) {
1605                         memcpy(iobuf_out+iobuf_out_cnt, buf, n);
1606                         buf += n;
1607                         len -= n;
1608                         iobuf_out_cnt += n;
1609                 }
1610
1611                 if (iobuf_out_cnt == IO_BUFFER_SIZE)
1612                         io_flush(NORMAL_FLUSH);
1613         }
1614 }
1615
1616 void write_shortint(int f, unsigned short x)
1617 {
1618         char b[2];
1619         b[0] = (char)x;
1620         b[1] = (char)(x >> 8);
1621         writefd(f, b, 2);
1622 }
1623
1624 void write_int(int f, int32 x)
1625 {
1626         char b[4];
1627         SIVAL(b, 0, x);
1628         writefd(f, b, 4);
1629 }
1630
1631 void write_varint(int f, int32 x)
1632 {
1633         char b[5];
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);
1651 }
1652
1653 void write_varlong(int f, int64 x, uchar min_bytes)
1654 {
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);
1683 }
1684
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  */
1689 void write_longint(int f, int64 x)
1690 {
1691         char b[12], * const s = b+4;
1692
1693         SIVAL(s, 0, x);
1694         if (x <= 0x7FFFFFFF && x >= 0) {
1695                 writefd(f, s, 4);
1696                 return;
1697         }
1698
1699 #if SIZEOF_INT64 < 8
1700         rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1701         exit_cleanup(RERR_UNSUPPORTED);
1702 #else
1703         memset(b, 0xFF, 4);
1704         SIVAL(s, 4, x >> 32);
1705         writefd(f, b, 12);
1706 #endif
1707 }
1708
1709 void write_buf(int f, const char *buf, size_t len)
1710 {
1711         writefd(f,buf,len);
1712 }
1713
1714 /** Write a string to the connection */
1715 void write_sbuf(int f, const char *buf)
1716 {
1717         writefd(f, buf, strlen(buf));
1718 }
1719
1720 void write_byte(int f, uchar c)
1721 {
1722         writefd(f, (char *)&c, 1);
1723 }
1724
1725 void write_vstring(int f, const char *str, int len)
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
1745 /* Send a file-list index using a byte-reduction method. */
1746 void 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);
1781                 b[cnt++] = (char)ndx;
1782                 b[cnt++] = (char)(ndx >> 8);
1783                 b[cnt++] = (char)(ndx >> 16);
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. */
1793 int32 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) {
1813                         b[3] = CVAL(b, 0) & ~0x80;
1814                         b[0] = b[1];
1815                         readfd(f, b+1, 2);
1816                         num = IVAL(b, 0);
1817                 } else
1818                         num = (UVAL(b,0)<<8) + UVAL(b,1) + *prev_ptr;
1819         } else
1820                 num = UVAL(b, 0) + *prev_ptr;
1821         *prev_ptr = num;
1822         if (prev_ptr == &prev_negative)
1823                 num = -num;
1824         return num;
1825 }
1826
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. */
1830 int read_line_old(int f, char *buf, size_t bufsiz)
1831 {
1832         bufsiz--; /* leave room for the null */
1833         while (bufsiz > 0) {
1834                 buf[0] = 0;
1835                 read_buf(f, buf, 1);
1836                 if (buf[0] == 0)
1837                         return 0;
1838                 if (buf[0] == '\n')
1839                         break;
1840                 if (buf[0] != '\r') {
1841                         buf++;
1842                         bufsiz--;
1843                 }
1844         }
1845         *buf = '\0';
1846         return bufsiz > 0;
1847 }
1848
1849 void io_printf(int fd, const char *format, ...)
1850 {
1851         va_list ap;
1852         char buf[BIGPATHBUFLEN];
1853         int len;
1854
1855         va_start(ap, format);
1856         len = vsnprintf(buf, sizeof buf, format, ap);
1857         va_end(ap);
1858
1859         if (len < 0)
1860                 exit_cleanup(RERR_STREAMIO);
1861
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
1867         write_sbuf(fd, buf);
1868 }
1869
1870 /** Setup for multiplexing a MSG_* stream with the data stream. */
1871 void io_start_multiplex_out(void)
1872 {
1873         io_flush(NORMAL_FLUSH);
1874         io_start_buffering_out(sock_f_out);
1875         io_multiplexing_out = 1;
1876 }
1877
1878 /** Setup for multiplexing a MSG_* stream with the data stream. */
1879 void io_start_multiplex_in(void)
1880 {
1881         io_flush(NORMAL_FLUSH);
1882         io_start_buffering_in(sock_f_in);
1883         io_multiplexing_in = 1;
1884 }
1885
1886 /** Write an message to the multiplexed data stream. */
1887 int io_multiplex_write(enum msgcode code, const char *buf, size_t len, int convert)
1888 {
1889         if (!io_multiplexing_out)
1890                 return 0;
1891         io_flush(NORMAL_FLUSH);
1892         stats.total_written += (len+4);
1893         mplex_write(sock_f_out, code, buf, len, convert);
1894         return 1;
1895 }
1896
1897 void io_end_multiplex_in(void)
1898 {
1899         io_multiplexing_in = 0;
1900         io_end_buffering_in();
1901 }
1902
1903 /** Stop output multiplexing. */
1904 void io_end_multiplex_out(void)
1905 {
1906         io_multiplexing_out = 0;
1907         io_end_buffering_out();
1908 }
1909
1910 void 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);
1918         if (protocol_version >= 30)
1919                 write_byte(batch_fd, inc_recurse);
1920         write_int(batch_fd, checksum_seed);
1921
1922         if (am_sender)
1923                 write_batch_monitor_out = fd;
1924         else
1925                 write_batch_monitor_in = fd;
1926 }
1927
1928 void stop_write_batch(void)
1929 {
1930         write_batch_monitor_out = -1;
1931         write_batch_monitor_in = -1;
1932 }