- My use of readfd_unbuffered() in read_msg_fd() really needed to be
[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 void readfd(int fd, char *buffer, size_t N);
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(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(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(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(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(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(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(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 || flist_forward_from >= 0)
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(FULL_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         flist_forward_from = -1;
822         io_flush(FULL_FLUSH);
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 /* Do a buffered read from fd.  Don't return until all N bytes have
951  * been read.  If all N can't be read then exit with an error. */
952 static void readfd(int fd, char *buffer, size_t N)
953 {
954         int  cnt;
955         size_t total = 0;
956
957         while (total < N) {
958                 cnt = readfd_unbuffered(fd, buffer + total, N-total);
959                 total += cnt;
960         }
961
962         if (fd == write_batch_monitor_in) {
963                 if ((size_t)write(batch_fd, buffer, total) != total)
964                         exit_cleanup(RERR_FILEIO);
965         }
966
967         if (fd == flist_forward_from)
968                 writefd(iobuf_f_out, buffer, total);
969
970         if (fd == sock_f_in)
971                 stats.total_read += total;
972 }
973
974 unsigned short read_shortint(int f)
975 {
976         char b[2];
977         readfd(f, b, 2);
978         return (UVAL(b, 1) << 8) + UVAL(b, 0);
979 }
980
981 int32 read_int(int f)
982 {
983         char b[4];
984         int32 num;
985
986         readfd(f, b, 4);
987         num = IVAL(b, 0);
988 #if SIZEOF_INT32 > 4
989         if (num & (int32)0x80000000)
990                 num |= ~(int32)0xffffffff;
991 #endif
992         return num;
993 }
994
995 int64 read_longint(int f)
996 {
997         int64 num;
998         char b[9];
999
1000         if (protocol_version < 30) {
1001                 num = read_int(f);
1002
1003                 if ((int32)num != (int32)0xffffffff)
1004                         return num;
1005
1006 #if SIZEOF_INT64 < 8
1007                 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1008                 exit_cleanup(RERR_UNSUPPORTED);
1009 #else
1010                 readfd(f, b, 8);
1011                 num = IVAL(b,0) | (((int64)IVAL(b,4))<<32);
1012 #endif
1013         } else {
1014                 int cnt;
1015                 readfd(f, b, 3);
1016                 cnt = int_byte_cnt[CVAL(b, 0) / 4];
1017 #if SIZEOF_INT64 < 8
1018                 if (cnt > 5 || (cnt == 5 && (CVAL(b,0)&0x3F || CVAL(b,1)&0x80))) {
1019                         rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1020                         exit_cleanup(RERR_UNSUPPORTED);
1021                 }
1022 #endif
1023                 if (cnt > 3)
1024                         readfd(f, b + 3, cnt - 3);
1025                 switch (cnt) {
1026                 case 3:
1027                         num = NVAL3(b, 0);
1028                         break;
1029                 case 4:
1030                         num = NVAL4(b, 0x80);
1031                         break;
1032                 case 5:
1033                         num = NVAL5(b, 0xC0);
1034                         break;
1035 #if SIZEOF_INT64 >= 8
1036                 case 6:
1037                         num = NVAL6(b, 0xE0);
1038                         break;
1039                 case 7:
1040                         num = NVAL7(b, 0xF0);
1041                         break;
1042                 case 8:
1043                         num = NVAL8(b, 0xF8);
1044                         break;
1045                 case 9:
1046                         num = NVAL8(b+1, 0);
1047                         break;
1048 #endif
1049                 default:
1050                         exit_cleanup(RERR_PROTOCOL); /* impossible... */
1051                 }
1052         }
1053
1054         return num;
1055 }
1056
1057 void read_buf(int f, char *buf, size_t len)
1058 {
1059         readfd(f,buf,len);
1060 }
1061
1062 void read_sbuf(int f, char *buf, size_t len)
1063 {
1064         readfd(f, buf, len);
1065         buf[len] = '\0';
1066 }
1067
1068 uchar read_byte(int f)
1069 {
1070         uchar c;
1071         readfd(f, (char *)&c, 1);
1072         return c;
1073 }
1074
1075 int read_vstring(int f, char *buf, int bufsize)
1076 {
1077         int len = read_byte(f);
1078
1079         if (len & 0x80)
1080                 len = (len & ~0x80) * 0x100 + read_byte(f);
1081
1082         if (len >= bufsize) {
1083                 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
1084                         len, bufsize - 1);
1085                 return -1;
1086         }
1087
1088         if (len)
1089                 readfd(f, buf, len);
1090         buf[len] = '\0';
1091         return len;
1092 }
1093
1094 /* Populate a sum_struct with values from the socket.  This is
1095  * called by both the sender and the receiver. */
1096 void read_sum_head(int f, struct sum_struct *sum)
1097 {
1098         sum->count = read_int(f);
1099         if (sum->count < 0) {
1100                 rprintf(FERROR, "Invalid checksum count %ld [%s]\n",
1101                         (long)sum->count, who_am_i());
1102                 exit_cleanup(RERR_PROTOCOL);
1103         }
1104         sum->blength = read_int(f);
1105         if (sum->blength < 0 || sum->blength > MAX_BLOCK_SIZE) {
1106                 rprintf(FERROR, "Invalid block length %ld [%s]\n",
1107                         (long)sum->blength, who_am_i());
1108                 exit_cleanup(RERR_PROTOCOL);
1109         }
1110         sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
1111         if (sum->s2length < 0 || sum->s2length > MD4_SUM_LENGTH) {
1112                 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
1113                         sum->s2length, who_am_i());
1114                 exit_cleanup(RERR_PROTOCOL);
1115         }
1116         sum->remainder = read_int(f);
1117         if (sum->remainder < 0 || sum->remainder > sum->blength) {
1118                 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
1119                         (long)sum->remainder, who_am_i());
1120                 exit_cleanup(RERR_PROTOCOL);
1121         }
1122 }
1123
1124 /* Send the values from a sum_struct over the socket.  Set sum to
1125  * NULL if there are no checksums to send.  This is called by both
1126  * the generator and the sender. */
1127 void write_sum_head(int f, struct sum_struct *sum)
1128 {
1129         static struct sum_struct null_sum;
1130
1131         if (sum == NULL)
1132                 sum = &null_sum;
1133
1134         write_int(f, sum->count);
1135         write_int(f, sum->blength);
1136         if (protocol_version >= 27)
1137                 write_int(f, sum->s2length);
1138         write_int(f, sum->remainder);
1139 }
1140
1141 /**
1142  * Sleep after writing to limit I/O bandwidth usage.
1143  *
1144  * @todo Rather than sleeping after each write, it might be better to
1145  * use some kind of averaging.  The current algorithm seems to always
1146  * use a bit less bandwidth than specified, because it doesn't make up
1147  * for slow periods.  But arguably this is a feature.  In addition, we
1148  * ought to take the time used to write the data into account.
1149  *
1150  * During some phases of big transfers (file FOO is uptodate) this is
1151  * called with a small bytes_written every time.  As the kernel has to
1152  * round small waits up to guarantee that we actually wait at least the
1153  * requested number of microseconds, this can become grossly inaccurate.
1154  * We therefore keep track of the bytes we've written over time and only
1155  * sleep when the accumulated delay is at least 1 tenth of a second.
1156  **/
1157 static void sleep_for_bwlimit(int bytes_written)
1158 {
1159         static struct timeval prior_tv;
1160         static long total_written = 0;
1161         struct timeval tv, start_tv;
1162         long elapsed_usec, sleep_usec;
1163
1164 #define ONE_SEC 1000000L /* # of microseconds in a second */
1165
1166         if (!bwlimit_writemax)
1167                 return;
1168
1169         total_written += bytes_written;
1170
1171         gettimeofday(&start_tv, NULL);
1172         if (prior_tv.tv_sec) {
1173                 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
1174                              + (start_tv.tv_usec - prior_tv.tv_usec);
1175                 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
1176                 if (total_written < 0)
1177                         total_written = 0;
1178         }
1179
1180         sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1181         if (sleep_usec < ONE_SEC / 10) {
1182                 prior_tv = start_tv;
1183                 return;
1184         }
1185
1186         tv.tv_sec  = sleep_usec / ONE_SEC;
1187         tv.tv_usec = sleep_usec % ONE_SEC;
1188         select(0, NULL, NULL, NULL, &tv);
1189
1190         gettimeofday(&prior_tv, NULL);
1191         elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1192                      + (prior_tv.tv_usec - start_tv.tv_usec);
1193         total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
1194 }
1195
1196 /* Write len bytes to the file descriptor fd, looping as necessary to get
1197  * the job done and also (in certain circumstances) reading any data on
1198  * msg_fd_in to avoid deadlock.
1199  *
1200  * This function underlies the multiplexing system.  The body of the
1201  * application never calls this function directly. */
1202 static void writefd_unbuffered(int fd, const char *buf, size_t len)
1203 {
1204         size_t n, total = 0;
1205         fd_set w_fds, r_fds, e_fds;
1206         int maxfd, count, cnt, using_r_fds;
1207         int defer_save = defer_forwarding_messages;
1208         struct timeval tv;
1209
1210         no_flush++;
1211
1212         while (total < len) {
1213                 FD_ZERO(&w_fds);
1214                 FD_SET(fd, &w_fds);
1215                 FD_ZERO(&e_fds);
1216                 FD_SET(fd, &e_fds);
1217                 maxfd = fd;
1218
1219                 if (msg_fd_in >= 0) {
1220                         FD_ZERO(&r_fds);
1221                         FD_SET(msg_fd_in, &r_fds);
1222                         if (msg_fd_in > maxfd)
1223                                 maxfd = msg_fd_in;
1224                         using_r_fds = 1;
1225                 } else
1226                         using_r_fds = 0;
1227
1228                 tv.tv_sec = select_timeout;
1229                 tv.tv_usec = 0;
1230
1231                 errno = 0;
1232                 count = select(maxfd + 1, using_r_fds ? &r_fds : NULL,
1233                                &w_fds, &e_fds, &tv);
1234
1235                 if (count <= 0) {
1236                         if (count < 0 && errno == EBADF)
1237                                 exit_cleanup(RERR_SOCKETIO);
1238                         check_timeout();
1239                         continue;
1240                 }
1241
1242                 if (FD_ISSET(fd, &e_fds)) {
1243                         rsyserr(FINFO, errno,
1244                                 "select exception on fd %d", fd);
1245                 }
1246
1247                 if (using_r_fds && FD_ISSET(msg_fd_in, &r_fds))
1248                         read_msg_fd();
1249
1250                 if (!FD_ISSET(fd, &w_fds))
1251                         continue;
1252
1253                 n = len - total;
1254                 if (bwlimit_writemax && n > bwlimit_writemax)
1255                         n = bwlimit_writemax;
1256                 cnt = write(fd, buf + total, n);
1257
1258                 if (cnt <= 0) {
1259                         if (cnt < 0) {
1260                                 if (errno == EINTR)
1261                                         continue;
1262                                 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1263                                         msleep(1);
1264                                         continue;
1265                                 }
1266                         }
1267
1268                         /* Don't try to write errors back across the stream. */
1269                         if (fd == sock_f_out)
1270                                 io_end_multiplex_out();
1271                         rsyserr(FERROR, errno,
1272                                 "writefd_unbuffered failed to write %ld bytes [%s]",
1273                                 (long)len, who_am_i());
1274                         /* If the other side is sending us error messages, try
1275                          * to grab any messages they sent before they died. */
1276                         while (fd == sock_f_out && io_multiplexing_in) {
1277                                 set_io_timeout(30);
1278                                 ignore_timeout = 0;
1279                                 readfd_unbuffered(sock_f_in, io_filesfrom_buf,
1280                                                   sizeof io_filesfrom_buf);
1281                         }
1282                         exit_cleanup(RERR_STREAMIO);
1283                 }
1284
1285                 total += cnt;
1286                 defer_forwarding_messages = 1;
1287
1288                 if (fd == sock_f_out) {
1289                         if (io_timeout || am_generator)
1290                                 last_io_out = time(NULL);
1291                         sleep_for_bwlimit(cnt);
1292                 }
1293         }
1294
1295         defer_forwarding_messages = defer_save;
1296         no_flush--;
1297 }
1298
1299 static void msg2sndr_flush(void)
1300 {
1301         if (defer_forwarding_messages)
1302                 return;
1303
1304         while (msg2sndr.head && io_multiplexing_out) {
1305                 struct msg_list_item *m = msg2sndr.head;
1306                 if (!(msg2sndr.head = m->next))
1307                         msg2sndr.tail = NULL;
1308                 stats.total_written += m->len;
1309                 defer_forwarding_messages = 1;
1310                 writefd_unbuffered(sock_f_out, m->buf, m->len);
1311                 defer_forwarding_messages = 0;
1312                 free(m);
1313         }
1314 }
1315
1316 /**
1317  * Write an message to a multiplexed stream. If this fails then rsync
1318  * exits.
1319  **/
1320 static void mplex_write(enum msgcode code, const char *buf, size_t len)
1321 {
1322         char buffer[1024];
1323         size_t n = len;
1324
1325         SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
1326
1327         if (n > sizeof buffer - 4)
1328                 n = 0;
1329         else
1330                 memcpy(buffer + 4, buf, n);
1331
1332         writefd_unbuffered(sock_f_out, buffer, n+4);
1333
1334         len -= n;
1335         buf += n;
1336
1337         if (len) {
1338                 defer_forwarding_messages = 1;
1339                 writefd_unbuffered(sock_f_out, buf, len);
1340                 defer_forwarding_messages = 0;
1341                 msg2sndr_flush();
1342         }
1343 }
1344
1345 void io_flush(int flush_it_all)
1346 {
1347         if (flush_it_all) {
1348                 msg2genr_flush();
1349                 msg2sndr_flush();
1350         }
1351
1352         if (!iobuf_out_cnt || no_flush)
1353                 return;
1354
1355         if (io_multiplexing_out)
1356                 mplex_write(MSG_DATA, iobuf_out, iobuf_out_cnt);
1357         else
1358                 writefd_unbuffered(iobuf_f_out, iobuf_out, iobuf_out_cnt);
1359         iobuf_out_cnt = 0;
1360 }
1361
1362 static void writefd(int fd, const char *buf, size_t len)
1363 {
1364         if (fd == sock_f_out)
1365                 stats.total_written += len;
1366
1367         if (fd == write_batch_monitor_out) {
1368                 if ((size_t)write(batch_fd, buf, len) != len)
1369                         exit_cleanup(RERR_FILEIO);
1370         }
1371
1372         if (!iobuf_out || fd != iobuf_f_out) {
1373                 writefd_unbuffered(fd, buf, len);
1374                 return;
1375         }
1376
1377         while (len) {
1378                 int n = MIN((int)len, IO_BUFFER_SIZE - iobuf_out_cnt);
1379                 if (n > 0) {
1380                         memcpy(iobuf_out+iobuf_out_cnt, buf, n);
1381                         buf += n;
1382                         len -= n;
1383                         iobuf_out_cnt += n;
1384                 }
1385
1386                 if (iobuf_out_cnt == IO_BUFFER_SIZE)
1387                         io_flush(NORMAL_FLUSH);
1388         }
1389 }
1390
1391 void write_shortint(int f, unsigned short x)
1392 {
1393         char b[2];
1394         b[0] = (char)x;
1395         b[1] = (char)(x >> 8);
1396         writefd(f, b, 2);
1397 }
1398
1399 void write_int(int f, int32 x)
1400 {
1401         char b[4];
1402         SIVAL(b, 0, x);
1403         writefd(f, b, 4);
1404 }
1405
1406 /*
1407  * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1408  * 64-bit types on this platform.
1409  */
1410 void write_longint(int f, int64 x)
1411 {
1412         char b[12];
1413
1414 #if SIZEOF_INT64 < 8
1415         if (x < 0 || x > 0x7FFFFFFF) {
1416                 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1417                 exit_cleanup(RERR_UNSUPPORTED);
1418         }
1419 #endif
1420
1421         if (protocol_version < 30) {
1422                 char * const s = b+4;
1423                 SIVAL(s, 0, x);
1424 #if SIZEOF_INT64 < 8
1425                 writefd(f, s, 4);
1426 #else
1427                 if (x <= 0x7FFFFFFF && x >= 0) {
1428                         writefd(f, s, 4);
1429                         return;
1430                 }
1431
1432                 memset(b, 0xFF, 4);
1433                 SIVAL(s, 4, x >> 32);
1434                 writefd(f, b, 12);
1435         } else if (x < 0) {
1436                 goto all_bits;
1437 #endif
1438         } else if (x < ((int32)1<<(3*8-1))) {
1439                 b[0] = (char)(x >> 16);
1440                 b[1] = (char)(x >> 8);
1441                 b[2] = (char)x;
1442                 writefd(f, b, 3);
1443         } else if (x < ((int64)1<<(4*8-2))) {
1444                 b[0] = (char)((x >> 24) | 0x80);
1445                 b[1] = (char)(x >> 16);
1446                 b[2] = (char)(x >> 8);
1447                 b[3] = (char)x;
1448                 writefd(f, b, 4);
1449 #if SIZEOF_INT64 < 8
1450         } else {
1451                 b[0] = 0xC0;
1452                 b[1] = (char)(x >> 24);
1453                 b[2] = (char)(x >> 16);
1454                 b[3] = (char)(x >> 8);
1455                 b[4] = (char)x;
1456                 writefd(f, b, 5);
1457         }
1458 #else
1459         } else if (x < ((int64)1<<(5*8-3))) {
1460                 b[0] = (char)((x >> 32) | 0xC0);
1461                 b[1] = (char)(x >> 24);
1462                 b[2] = (char)(x >> 16);
1463                 b[3] = (char)(x >> 8);
1464                 b[4] = (char)x;
1465                 writefd(f, b, 5);
1466         } else if (x < ((int64)1<<(6*8-4))) {
1467                 b[0] = (char)((x >> 40) | 0xE0);
1468                 b[1] = (char)(x >> 32);
1469                 b[2] = (char)(x >> 24);
1470                 b[3] = (char)(x >> 16);
1471                 b[4] = (char)(x >> 8);
1472                 b[5] = (char)x;
1473                 writefd(f, b, 6);
1474         } else if (x < ((int64)1<<(7*8-5))) {
1475                 b[0] = (char)((x >> 48) | 0xF0);
1476                 b[1] = (char)(x >> 40);
1477                 b[2] = (char)(x >> 32);
1478                 b[3] = (char)(x >> 24);
1479                 b[4] = (char)(x >> 16);
1480                 b[5] = (char)(x >> 8);
1481                 b[6] = (char)x;
1482                 writefd(f, b, 7);
1483         } else if (x < ((int64)1<<(8*8-6))) {
1484                 b[0] = (char)((x >> 56) | 0xF8);
1485                 b[1] = (char)(x >> 48);
1486                 b[2] = (char)(x >> 40);
1487                 b[3] = (char)(x >> 32);
1488                 b[4] = (char)(x >> 24);
1489                 b[5] = (char)(x >> 16);
1490                 b[6] = (char)(x >> 8);
1491                 b[7] = (char)x;
1492                 writefd(f, b, 8);
1493         } else {
1494           all_bits:
1495                 b[0] = (char)0xFC;
1496                 b[1] = (char)(x >> 56);
1497                 b[2] = (char)(x >> 48);
1498                 b[3] = (char)(x >> 40);
1499                 b[4] = (char)(x >> 32);
1500                 b[5] = (char)(x >> 24);
1501                 b[6] = (char)(x >> 16);
1502                 b[7] = (char)(x >> 8);
1503                 b[8] = (char)x;
1504                 writefd(f, b, 9);
1505         }
1506 #endif
1507 }
1508
1509 void write_buf(int f, const char *buf, size_t len)
1510 {
1511         writefd(f,buf,len);
1512 }
1513
1514 /** Write a string to the connection */
1515 void write_sbuf(int f, const char *buf)
1516 {
1517         writefd(f, buf, strlen(buf));
1518 }
1519
1520 void write_byte(int f, uchar c)
1521 {
1522         writefd(f, (char *)&c, 1);
1523 }
1524
1525 void write_vstring(int f, const char *str, int len)
1526 {
1527         uchar lenbuf[3], *lb = lenbuf;
1528
1529         if (len > 0x7F) {
1530                 if (len > 0x7FFF) {
1531                         rprintf(FERROR,
1532                                 "attempting to send over-long vstring (%d > %d)\n",
1533                                 len, 0x7FFF);
1534                         exit_cleanup(RERR_PROTOCOL);
1535                 }
1536                 *lb++ = len / 0x100 + 0x80;
1537         }
1538         *lb = len;
1539
1540         writefd(f, (char*)lenbuf, lb - lenbuf + 1);
1541         if (len)
1542                 writefd(f, str, len);
1543 }
1544
1545 /* Send a file-list index using a byte-reduction method. */
1546 void write_ndx(int f, int32 ndx)
1547 {
1548         static int32 prev_positive = -1, prev_negative = 1;
1549         int32 diff, cnt = 0;
1550         char b[6];
1551
1552         if (protocol_version < 30 || read_batch) {
1553                 write_int(f, ndx);
1554                 return;
1555         }
1556
1557         /* Send NDX_DONE as a single-byte 0 with no side effects.  Send
1558          * negative nums as a positive after sending a leading 0xFF. */
1559         if (ndx >= 0) {
1560                 diff = ndx - prev_positive;
1561                 prev_positive = ndx;
1562         } else if (ndx == NDX_DONE) {
1563                 *b = 0;
1564                 writefd(f, b, 1);
1565                 return;
1566         } else {
1567                 b[cnt++] = (char)0xFF;
1568                 ndx = -ndx;
1569                 diff = ndx - prev_negative;
1570                 prev_negative = ndx;
1571         }
1572
1573         /* A diff of 1 - 253 is sent as a one-byte diff; a diff of 254 - 32767
1574          * or 0 is sent as a 0xFE + a two-byte diff; otherwise we send 0xFE
1575          * & all 4 bytes of the (non-negative) num with the high-bit set. */
1576         if (diff < 0xFE && diff > 0)
1577                 b[cnt++] = (char)diff;
1578         else if (diff < 0 || diff > 0x7FFF) {
1579                 b[cnt++] = (char)0xFE;
1580                 b[cnt++] = (char)((ndx >> 24) | 0x80);
1581                 b[cnt++] = (char)(ndx >> 16);
1582                 b[cnt++] = (char)(ndx >> 8);
1583                 b[cnt++] = (char)ndx;
1584         } else {
1585                 b[cnt++] = (char)0xFE;
1586                 b[cnt++] = (char)(diff >> 8);
1587                 b[cnt++] = (char)diff;
1588         }
1589         writefd(f, b, cnt);
1590 }
1591
1592 /* Receive a file-list index using a byte-reduction method. */
1593 int32 read_ndx(int f)
1594 {
1595         static int32 prev_positive = -1, prev_negative = 1;
1596         int32 *prev_ptr, num;
1597         char b[4];
1598
1599         if (protocol_version < 30)
1600                 return read_int(f);
1601
1602         readfd(f, b, 1);
1603         if (CVAL(b, 0) == 0xFF) {
1604                 readfd(f, b, 1);
1605                 prev_ptr = &prev_negative;
1606         } else if (CVAL(b, 0) == 0)
1607                 return NDX_DONE;
1608         else
1609                 prev_ptr = &prev_positive;
1610         if (CVAL(b, 0) == 0xFE) {
1611                 readfd(f, b, 2);
1612                 if (CVAL(b, 0) & 0x80) {
1613                         readfd(f, b+2, 2);
1614                         num = NVAL4(b, 0x80);
1615                 } else
1616                         num = NVAL2(b, 0) + *prev_ptr;
1617         } else
1618                 num = CVAL(b, 0) + *prev_ptr;
1619         *prev_ptr = num;
1620         if (prev_ptr == &prev_negative)
1621                 num = -num;
1622         return num;
1623 }
1624
1625 /**
1626  * Read a line of up to @p maxlen characters into @p buf (not counting
1627  * the trailing null).  Strips the (required) trailing newline and all
1628  * carriage returns.
1629  *
1630  * @return 1 for success; 0 for I/O error or truncation.
1631  **/
1632 int read_line(int f, char *buf, size_t maxlen)
1633 {
1634         while (maxlen) {
1635                 buf[0] = 0;
1636                 read_buf(f, buf, 1);
1637                 if (buf[0] == 0)
1638                         return 0;
1639                 if (buf[0] == '\n')
1640                         break;
1641                 if (buf[0] != '\r') {
1642                         buf++;
1643                         maxlen--;
1644                 }
1645         }
1646         *buf = '\0';
1647         return maxlen > 0;
1648 }
1649
1650 void io_printf(int fd, const char *format, ...)
1651 {
1652         va_list ap;
1653         char buf[BIGPATHBUFLEN];
1654         int len;
1655
1656         va_start(ap, format);
1657         len = vsnprintf(buf, sizeof buf, format, ap);
1658         va_end(ap);
1659
1660         if (len < 0)
1661                 exit_cleanup(RERR_STREAMIO);
1662
1663         if (len > (int)sizeof buf) {
1664                 rprintf(FERROR, "io_printf() was too long for the buffer.\n");
1665                 exit_cleanup(RERR_STREAMIO);
1666         }
1667
1668         write_sbuf(fd, buf);
1669 }
1670
1671 /** Setup for multiplexing a MSG_* stream with the data stream. */
1672 void io_start_multiplex_out(void)
1673 {
1674         io_flush(NORMAL_FLUSH);
1675         io_start_buffering_out(sock_f_out);
1676         io_multiplexing_out = 1;
1677 }
1678
1679 /** Setup for multiplexing a MSG_* stream with the data stream. */
1680 void io_start_multiplex_in(void)
1681 {
1682         io_flush(NORMAL_FLUSH);
1683         io_start_buffering_in(sock_f_in);
1684         io_multiplexing_in = 1;
1685 }
1686
1687 /** Write an message to the multiplexed data stream. */
1688 int io_multiplex_write(enum msgcode code, const char *buf, size_t len)
1689 {
1690         if (!io_multiplexing_out)
1691                 return 0;
1692         io_flush(NORMAL_FLUSH);
1693         stats.total_written += (len+4);
1694         mplex_write(code, buf, len);
1695         return 1;
1696 }
1697
1698 void io_end_multiplex_in(void)
1699 {
1700         io_multiplexing_in = 0;
1701         io_end_buffering_in();
1702 }
1703
1704 /** Stop output multiplexing. */
1705 void io_end_multiplex_out(void)
1706 {
1707         io_multiplexing_out = 0;
1708         io_end_buffering_out();
1709 }
1710
1711 void start_write_batch(int fd)
1712 {
1713         /* Some communication has already taken place, but we don't
1714          * enable batch writing until here so that we can write a
1715          * canonical record of the communication even though the
1716          * actual communication so far depends on whether a daemon
1717          * is involved. */
1718         write_int(batch_fd, protocol_version);
1719         write_int(batch_fd, checksum_seed);
1720
1721         if (am_sender)
1722                 write_batch_monitor_out = fd;
1723         else
1724                 write_batch_monitor_in = fd;
1725 }
1726
1727 void stop_write_batch(void)
1728 {
1729         write_batch_monitor_out = -1;
1730         write_batch_monitor_in = -1;
1731 }