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