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