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