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