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