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