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