ba71098d415e855489e4e2332899a25f652ba79a
[rsync/rsync.git] / io.c
1 /* -*- c-file-style: "linux" -*-
2  *
3  * Copyright (C) 1996-2001 by Andrew Tridgell
4  * Copyright (C) Paul Mackerras 1996
5  * Copyright (C) 2001, 2002 by Martin Pool <mbp@samba.org>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20  */
21
22 /**
23  * @file io.c
24  *
25  * Socket and pipe I/O utilities used in rsync.
26  *
27  * rsync provides its own multiplexing system, which is used to send
28  * stderr and stdout over a single socket.  We need this because
29  * stdout normally carries the binary data stream, and stderr all our
30  * error messages.
31  *
32  * For historical reasons this is off during the start of the
33  * connection, but it's switched on quite early using
34  * io_start_multiplex_out() and io_start_multiplex_in().
35  **/
36
37 #include "rsync.h"
38
39 /** If no timeout is specified then use a 60 second select timeout */
40 #define SELECT_TIMEOUT 60
41
42 extern int bwlimit;
43 extern size_t bwlimit_writemax;
44 extern int verbose;
45 extern int io_timeout;
46 extern int allowed_lull;
47 extern int am_server;
48 extern int am_daemon;
49 extern int am_sender;
50 extern int am_generator;
51 extern int eol_nulls;
52 extern int read_batch;
53 extern int csum_length;
54 extern int checksum_seed;
55 extern int protocol_version;
56 extern int remove_sent_files;
57 extern int preserve_hard_links;
58 extern char *filesfrom_host;
59 extern struct stats stats;
60 extern struct file_list *the_file_list;
61
62 const char phase_unknown[] = "unknown";
63 int ignore_timeout = 0;
64 int batch_fd = -1;
65 int batch_gen_fd = -1;
66
67 /**
68  * The connection might be dropped at some point; perhaps because the
69  * remote instance crashed.  Just giving the offset on the stream is
70  * not very helpful.  So instead we try to make io_phase_name point to
71  * something useful.
72  *
73  * For buffered/multiplexed I/O these names will be somewhat
74  * approximate; perhaps for ease of support we would rather make the
75  * buffer always flush when a single application-level I/O finishes.
76  *
77  * @todo Perhaps we want some simple stack functionality, but there's
78  * no need to overdo it.
79  **/
80 const char *io_write_phase = phase_unknown;
81 const char *io_read_phase = phase_unknown;
82
83 /* Ignore an EOF error if non-zero. See whine_about_eof(). */
84 int kluge_around_eof = 0;
85
86 int msg_fd_in = -1;
87 int msg_fd_out = -1;
88 int sock_f_in = -1;
89 int sock_f_out = -1;
90
91 static int io_multiplexing_out;
92 static int io_multiplexing_in;
93 static time_t last_io_in;
94 static time_t last_io_out;
95 static int no_flush;
96
97 static int write_batch_monitor_in = -1;
98 static int write_batch_monitor_out = -1;
99
100 static int io_filesfrom_f_in = -1;
101 static int io_filesfrom_f_out = -1;
102 static char io_filesfrom_buf[2048];
103 static char *io_filesfrom_bp;
104 static char io_filesfrom_lastchar;
105 static int io_filesfrom_buflen;
106 static size_t contiguous_write_len = 0;
107 static int select_timeout = SELECT_TIMEOUT;
108
109 static void read_loop(int fd, char *buf, size_t len);
110
111 struct flist_ndx_item {
112         struct flist_ndx_item *next;
113         int ndx;
114 };
115
116 struct flist_ndx_list {
117         struct flist_ndx_item *head, *tail;
118 };
119
120 static struct flist_ndx_list redo_list, hlink_list;
121
122 struct msg_list_item {
123         struct msg_list_item *next;
124         char *buf;
125         int len;
126 };
127
128 struct msg_list {
129         struct msg_list_item *head, *tail;
130 };
131
132 static struct msg_list msg_list;
133
134 static void flist_ndx_push(struct flist_ndx_list *lp, int ndx)
135 {
136         struct flist_ndx_item *item;
137
138         if (!(item = new(struct flist_ndx_item)))
139                 out_of_memory("flist_ndx_push");
140         item->next = NULL;
141         item->ndx = ndx;
142         if (lp->tail)
143                 lp->tail->next = item;
144         else
145                 lp->head = item;
146         lp->tail = item;
147 }
148
149 static int flist_ndx_pop(struct flist_ndx_list *lp)
150 {
151         struct flist_ndx_item *next;
152         int ndx;
153
154         if (!lp->head)
155                 return -1;
156
157         ndx = lp->head->ndx;
158         next = lp->head->next;
159         free(lp->head);
160         lp->head = next;
161         if (!next)
162                 lp->tail = NULL;
163
164         return ndx;
165 }
166
167 static void check_timeout(void)
168 {
169         time_t t;
170
171         if (!io_timeout || ignore_timeout)
172                 return;
173
174         if (!last_io_in) {
175                 last_io_in = time(NULL);
176                 return;
177         }
178
179         t = time(NULL);
180
181         if (t - last_io_in >= io_timeout) {
182                 if (!am_server && !am_daemon) {
183                         rprintf(FERROR, "io timeout after %d seconds -- exiting\n",
184                                 (int)(t-last_io_in));
185                 }
186                 exit_cleanup(RERR_TIMEOUT);
187         }
188 }
189
190 /* Note the fds used for the main socket (which might really be a pipe
191  * for a local transfer, but we can ignore that). */
192 void io_set_sock_fds(int f_in, int f_out)
193 {
194         sock_f_in = f_in;
195         sock_f_out = f_out;
196 }
197
198 void set_io_timeout(int secs)
199 {
200         io_timeout = secs;
201
202         if (!io_timeout || io_timeout > SELECT_TIMEOUT)
203                 select_timeout = SELECT_TIMEOUT;
204         else
205                 select_timeout = io_timeout;
206
207         allowed_lull = read_batch ? 0 : (io_timeout + 1) / 2;
208 }
209
210 /* Setup the fd used to receive MSG_* messages.  Only needed during the
211  * early stages of being a local sender (up through the sending of the
212  * file list) or when we're the generator (to fetch the messages from
213  * the receiver). */
214 void set_msg_fd_in(int fd)
215 {
216         msg_fd_in = fd;
217 }
218
219 /* Setup the fd used to send our MSG_* messages.  Only needed when
220  * we're the receiver (to send our messages to the generator). */
221 void set_msg_fd_out(int fd)
222 {
223         msg_fd_out = fd;
224         set_nonblocking(msg_fd_out);
225 }
226
227 /* Add a message to the pending MSG_* list. */
228 static void msg_list_add(int code, char *buf, int len)
229 {
230         struct msg_list_item *ml;
231
232         if (!(ml = new(struct msg_list_item)))
233                 out_of_memory("msg_list_add");
234         ml->next = NULL;
235         if (!(ml->buf = new_array(char, len+4)))
236                 out_of_memory("msg_list_add");
237         SIVAL(ml->buf, 0, ((code+MPLEX_BASE)<<24) | len);
238         memcpy(ml->buf+4, buf, len);
239         ml->len = len+4;
240         if (msg_list.tail)
241                 msg_list.tail->next = ml;
242         else
243                 msg_list.head = ml;
244         msg_list.tail = ml;
245 }
246
247 /* Read a message from the MSG_* fd and handle it.  This is called either
248  * during the early stages of being a local sender (up through the sending
249  * of the file list) or when we're the generator (to fetch the messages
250  * from the receiver). */
251 static void read_msg_fd(void)
252 {
253         char buf[2048];
254         size_t n;
255         int fd = msg_fd_in;
256         int tag, len;
257
258         /* Temporarily disable msg_fd_in.  This is needed to avoid looping back
259          * to this routine from writefd_unbuffered(). */
260         msg_fd_in = -1;
261
262         read_loop(fd, buf, 4);
263         tag = IVAL(buf, 0);
264
265         len = tag & 0xFFFFFF;
266         tag = (tag >> 24) - MPLEX_BASE;
267
268         switch (tag) {
269         case MSG_DONE:
270                 if (len != 0 || !am_generator) {
271                         rprintf(FERROR, "invalid message %d:%d\n", tag, len);
272                         exit_cleanup(RERR_STREAMIO);
273                 }
274                 flist_ndx_push(&redo_list, -1);
275                 break;
276         case MSG_REDO:
277                 if (len != 4 || !am_generator) {
278                         rprintf(FERROR, "invalid message %d:%d\n", tag, len);
279                         exit_cleanup(RERR_STREAMIO);
280                 }
281                 read_loop(fd, buf, 4);
282                 flist_ndx_push(&redo_list, IVAL(buf,0));
283                 break;
284         case MSG_DELETED:
285                 if (len >= (int)sizeof buf || !am_generator) {
286                         rprintf(FERROR, "invalid message %d:%d\n", tag, len);
287                         exit_cleanup(RERR_STREAMIO);
288                 }
289                 read_loop(fd, buf, len);
290                 io_multiplex_write(MSG_DELETED, buf, len);
291                 break;
292         case MSG_SUCCESS:
293                 if (len != 4 || !am_generator) {
294                         rprintf(FERROR, "invalid message %d:%d\n", tag, len);
295                         exit_cleanup(RERR_STREAMIO);
296                 }
297                 read_loop(fd, buf, len);
298                 if (remove_sent_files)
299                         io_multiplex_write(MSG_SUCCESS, buf, len);
300                 if (preserve_hard_links)
301                         flist_ndx_push(&hlink_list, IVAL(buf,0));
302                 break;
303         case MSG_INFO:
304         case MSG_ERROR:
305         case MSG_LOG:
306                 while (len) {
307                         n = len;
308                         if (n >= sizeof buf)
309                                 n = sizeof buf - 1;
310                         read_loop(fd, buf, n);
311                         rwrite((enum logcode)tag, buf, n);
312                         len -= n;
313                 }
314                 break;
315         default:
316                 rprintf(FERROR, "unknown message %d:%d\n", tag, len);
317                 exit_cleanup(RERR_STREAMIO);
318         }
319
320         msg_fd_in = fd;
321 }
322
323 /* Try to push messages off the list onto the wire.  If we leave with more
324  * to do, return 0.  On error, return -1.  If everything flushed, return 1.
325  * This is only active in the receiver. */
326 static int msg_list_flush(int flush_it_all)
327 {
328         static int written = 0;
329         struct timeval tv;
330         fd_set fds;
331
332         if (msg_fd_out < 0)
333                 return -1;
334
335         while (msg_list.head) {
336                 struct msg_list_item *ml = msg_list.head;
337                 int n = write(msg_fd_out, ml->buf + written, ml->len - written);
338                 if (n < 0) {
339                         if (errno == EINTR)
340                                 continue;
341                         if (errno != EWOULDBLOCK && errno != EAGAIN)
342                                 return -1;
343                         if (!flush_it_all)
344                                 return 0;
345                         FD_ZERO(&fds);
346                         FD_SET(msg_fd_out, &fds);
347                         tv.tv_sec = select_timeout;
348                         tv.tv_usec = 0;
349                         if (!select(msg_fd_out+1, NULL, &fds, NULL, &tv))
350                                 check_timeout();
351                 } else if ((written += n) == ml->len) {
352                         free(ml->buf);
353                         msg_list.head = ml->next;
354                         if (!msg_list.head)
355                                 msg_list.tail = NULL;
356                         free(ml);
357                         written = 0;
358                 }
359         }
360         return 1;
361 }
362
363 void send_msg(enum msgcode code, char *buf, int len)
364 {
365         if (msg_fd_out < 0) {
366                 io_multiplex_write(code, buf, len);
367                 return;
368         }
369         msg_list_add(code, buf, len);
370         msg_list_flush(NORMAL_FLUSH);
371 }
372
373 int get_redo_num(int itemizing, enum logcode code)
374 {
375         while (1) {
376                 if (hlink_list.head)
377                         check_for_finished_hlinks(itemizing, code);
378                 if (redo_list.head)
379                         break;
380                 read_msg_fd();
381         }
382
383         return flist_ndx_pop(&redo_list);
384 }
385
386 int get_hlink_num(void)
387 {
388         return flist_ndx_pop(&hlink_list);
389 }
390
391 /**
392  * When we're the receiver and we have a local --files-from list of names
393  * that needs to be sent over the socket to the sender, we have to do two
394  * things at the same time: send the sender a list of what files we're
395  * processing and read the incoming file+info list from the sender.  We do
396  * this by augmenting the read_timeout() function to copy this data.  It
397  * uses the io_filesfrom_buf to read a block of data from f_in (when it is
398  * ready, since it might be a pipe) and then blast it out f_out (when it
399  * is ready to receive more data).
400  */
401 void io_set_filesfrom_fds(int f_in, int f_out)
402 {
403         io_filesfrom_f_in = f_in;
404         io_filesfrom_f_out = f_out;
405         io_filesfrom_bp = io_filesfrom_buf;
406         io_filesfrom_lastchar = '\0';
407         io_filesfrom_buflen = 0;
408 }
409
410 /* It's almost always an error to get an EOF when we're trying to read from the
411  * network, because the protocol is (for the most part) self-terminating.
412  *
413  * There is one case for the receiver when it is at the end of the transfer
414  * (hanging around reading any keep-alive packets that might come its way): if
415  * the sender dies before the generator's kill-signal comes through, we can end
416  * up here needing to loop until the kill-signal arrives.  In this situation,
417  * kluge_around_eof will be < 0.
418  *
419  * There is another case for older protocol versions (< 24) where the module
420  * listing was not terminated, so we must ignore an EOF error in that case and
421  * exit.  In this situation, kluge_around_eof will be > 0. */
422 static void whine_about_eof(int fd)
423 {
424         if (kluge_around_eof && fd == sock_f_in) {
425                 int i;
426                 if (kluge_around_eof > 0)
427                         exit_cleanup(0);
428                 /* If we're still here after 10 seconds, exit with an error. */
429                 for (i = 10*1000/20; i--; )
430                         msleep(20);
431         }
432
433         rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
434                 "(%.0f bytes received so far) [%s]\n",
435                 (double)stats.total_read, who_am_i());
436
437         exit_cleanup(RERR_STREAMIO);
438 }
439
440 /**
441  * Read from a socket with I/O timeout. return the number of bytes
442  * read. If no bytes can be read then exit, never return a number <= 0.
443  *
444  * TODO: If the remote shell connection fails, then current versions
445  * actually report an "unexpected EOF" error here.  Since it's a
446  * fairly common mistake to try to use rsh when ssh is required, we
447  * should trap that: if we fail to read any data at all, we should
448  * give a better explanation.  We can tell whether the connection has
449  * started by looking e.g. at whether the remote version is known yet.
450  */
451 static int read_timeout(int fd, char *buf, size_t len)
452 {
453         int n, cnt = 0;
454
455         io_flush(NORMAL_FLUSH);
456
457         while (cnt == 0) {
458                 /* until we manage to read *something* */
459                 fd_set r_fds, w_fds;
460                 struct timeval tv;
461                 int maxfd = fd;
462                 int count;
463
464                 FD_ZERO(&r_fds);
465                 FD_ZERO(&w_fds);
466                 FD_SET(fd, &r_fds);
467                 if (msg_list.head) {
468                         FD_SET(msg_fd_out, &w_fds);
469                         if (msg_fd_out > maxfd)
470                                 maxfd = msg_fd_out;
471                 }
472                 if (io_filesfrom_f_out >= 0) {
473                         int new_fd;
474                         if (io_filesfrom_buflen == 0) {
475                                 if (io_filesfrom_f_in >= 0) {
476                                         FD_SET(io_filesfrom_f_in, &r_fds);
477                                         new_fd = io_filesfrom_f_in;
478                                 } else {
479                                         io_filesfrom_f_out = -1;
480                                         new_fd = -1;
481                                 }
482                         } else {
483                                 FD_SET(io_filesfrom_f_out, &w_fds);
484                                 new_fd = io_filesfrom_f_out;
485                         }
486                         if (new_fd > maxfd)
487                                 maxfd = new_fd;
488                 }
489
490                 tv.tv_sec = select_timeout;
491                 tv.tv_usec = 0;
492
493                 errno = 0;
494
495                 count = select(maxfd + 1, &r_fds, &w_fds, NULL, &tv);
496
497                 if (count <= 0) {
498                         if (errno == EBADF)
499                                 exit_cleanup(RERR_SOCKETIO);
500                         check_timeout();
501                         continue;
502                 }
503
504                 if (msg_list.head && FD_ISSET(msg_fd_out, &w_fds))
505                         msg_list_flush(NORMAL_FLUSH);
506
507                 if (io_filesfrom_f_out >= 0) {
508                         if (io_filesfrom_buflen) {
509                                 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
510                                         int l = write(io_filesfrom_f_out,
511                                                       io_filesfrom_bp,
512                                                       io_filesfrom_buflen);
513                                         if (l > 0) {
514                                                 if (!(io_filesfrom_buflen -= l))
515                                                         io_filesfrom_bp = io_filesfrom_buf;
516                                                 else
517                                                         io_filesfrom_bp += l;
518                                         } else {
519                                                 /* XXX should we complain? */
520                                                 io_filesfrom_f_out = -1;
521                                         }
522                                 }
523                         } else if (io_filesfrom_f_in >= 0) {
524                                 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
525                                         int l = read(io_filesfrom_f_in,
526                                                      io_filesfrom_buf,
527                                                      sizeof io_filesfrom_buf);
528                                         if (l <= 0) {
529                                                 /* Send end-of-file marker */
530                                                 io_filesfrom_buf[0] = '\0';
531                                                 io_filesfrom_buf[1] = '\0';
532                                                 io_filesfrom_buflen = io_filesfrom_lastchar? 2 : 1;
533                                                 io_filesfrom_f_in = -1;
534                                         } else {
535                                                 if (!eol_nulls) {
536                                                         char *s = io_filesfrom_buf + l;
537                                                         /* Transform CR and/or LF into '\0' */
538                                                         while (s-- > io_filesfrom_buf) {
539                                                                 if (*s == '\n' || *s == '\r')
540                                                                         *s = '\0';
541                                                         }
542                                                 }
543                                                 if (!io_filesfrom_lastchar) {
544                                                         /* Last buf ended with a '\0', so don't
545                                                          * let this buf start with one. */
546                                                         while (l && !*io_filesfrom_bp)
547                                                                 io_filesfrom_bp++, l--;
548                                                 }
549                                                 if (!l)
550                                                         io_filesfrom_bp = io_filesfrom_buf;
551                                                 else {
552                                                         char *f = io_filesfrom_bp;
553                                                         char *t = f;
554                                                         char *eob = f + l;
555                                                         /* Eliminate any multi-'\0' runs. */
556                                                         while (f != eob) {
557                                                                 if (!(*t++ = *f++)) {
558                                                                         while (f != eob && !*f)
559                                                                                 f++, l--;
560                                                                 }
561                                                         }
562                                                         io_filesfrom_lastchar = f[-1];
563                                                 }
564                                                 io_filesfrom_buflen = l;
565                                         }
566                                 }
567                         }
568                 }
569
570                 if (!FD_ISSET(fd, &r_fds))
571                         continue;
572
573                 n = read(fd, buf, len);
574
575                 if (n <= 0) {
576                         if (n == 0)
577                                 whine_about_eof(fd); /* Doesn't return. */
578                         if (errno == EINTR || errno == EWOULDBLOCK
579                             || errno == EAGAIN)
580                                 continue;
581
582                         /* Don't write errors on a dead socket. */
583                         if (fd == sock_f_in)
584                                 close_multiplexing_out();
585                         rsyserr(FERROR, errno, "read error");
586                         exit_cleanup(RERR_STREAMIO);
587                 }
588
589                 buf += n;
590                 len -= n;
591                 cnt += n;
592
593                 if (fd == sock_f_in && io_timeout)
594                         last_io_in = time(NULL);
595         }
596
597         return cnt;
598 }
599
600 /**
601  * Read a line into the "fname" buffer (which must be at least MAXPATHLEN
602  * characters long).
603  */
604 int read_filesfrom_line(int fd, char *fname)
605 {
606         char ch, *s, *eob = fname + MAXPATHLEN - 1;
607         int cnt;
608         int reading_remotely = filesfrom_host != NULL;
609         int nulls = eol_nulls || reading_remotely;
610
611   start:
612         s = fname;
613         while (1) {
614                 cnt = read(fd, &ch, 1);
615                 if (cnt < 0 && (errno == EWOULDBLOCK
616                   || errno == EINTR || errno == EAGAIN)) {
617                         struct timeval tv;
618                         fd_set fds;
619                         FD_ZERO(&fds);
620                         FD_SET(fd, &fds);
621                         tv.tv_sec = select_timeout;
622                         tv.tv_usec = 0;
623                         if (!select(fd+1, &fds, NULL, NULL, &tv))
624                                 check_timeout();
625                         continue;
626                 }
627                 if (cnt != 1)
628                         break;
629                 if (nulls? !ch : (ch == '\r' || ch == '\n')) {
630                         /* Skip empty lines if reading locally. */
631                         if (!reading_remotely && s == fname)
632                                 continue;
633                         break;
634                 }
635                 if (s < eob)
636                         *s++ = ch;
637         }
638         *s = '\0';
639
640         /* Dump comments. */
641         if (*fname == '#' || *fname == ';')
642                 goto start;
643
644         return s - fname;
645 }
646
647 static char *iobuf_out;
648 static int iobuf_out_cnt;
649
650 void io_start_buffering_out(void)
651 {
652         if (iobuf_out)
653                 return;
654         if (!(iobuf_out = new_array(char, IO_BUFFER_SIZE)))
655                 out_of_memory("io_start_buffering_out");
656         iobuf_out_cnt = 0;
657 }
658
659 static char *iobuf_in;
660 static size_t iobuf_in_siz;
661
662 void io_start_buffering_in(void)
663 {
664         if (iobuf_in)
665                 return;
666         iobuf_in_siz = 2 * IO_BUFFER_SIZE;
667         if (!(iobuf_in = new_array(char, iobuf_in_siz)))
668                 out_of_memory("io_start_buffering_in");
669 }
670
671 void io_end_buffering(void)
672 {
673         io_flush(NORMAL_FLUSH);
674         if (!io_multiplexing_out) {
675                 free(iobuf_out);
676                 iobuf_out = NULL;
677         }
678 }
679
680 void maybe_flush_socket(void)
681 {
682         if (iobuf_out && iobuf_out_cnt && time(NULL) - last_io_out >= 5)
683                 io_flush(NORMAL_FLUSH);
684 }
685
686 void maybe_send_keepalive(void)
687 {
688         if (time(NULL) - last_io_out >= allowed_lull) {
689                 if (!iobuf_out || !iobuf_out_cnt) {
690                         if (protocol_version < 29)
691                                 return; /* there's nothing we can do */
692                         write_int(sock_f_out, the_file_list->count);
693                         write_shortint(sock_f_out, ITEM_IS_NEW);
694                 }
695                 if (iobuf_out)
696                         io_flush(NORMAL_FLUSH);
697         }
698 }
699
700 /**
701  * Continue trying to read len bytes - don't return until len has been
702  * read.
703  **/
704 static void read_loop(int fd, char *buf, size_t len)
705 {
706         while (len) {
707                 int n = read_timeout(fd, buf, len);
708
709                 buf += n;
710                 len -= n;
711         }
712 }
713
714 /**
715  * Read from the file descriptor handling multiplexing - return number
716  * of bytes read.
717  *
718  * Never returns <= 0.
719  */
720 static int readfd_unbuffered(int fd, char *buf, size_t len)
721 {
722         static size_t remaining;
723         static size_t iobuf_in_ndx;
724         size_t msg_bytes;
725         int tag, cnt = 0;
726         char line[BIGPATHBUFLEN];
727
728         if (!iobuf_in || fd != sock_f_in)
729                 return read_timeout(fd, buf, len);
730
731         if (!io_multiplexing_in && remaining == 0) {
732                 remaining = read_timeout(fd, iobuf_in, iobuf_in_siz);
733                 iobuf_in_ndx = 0;
734         }
735
736         while (cnt == 0) {
737                 if (remaining) {
738                         len = MIN(len, remaining);
739                         memcpy(buf, iobuf_in + iobuf_in_ndx, len);
740                         iobuf_in_ndx += len;
741                         remaining -= len;
742                         cnt = len;
743                         break;
744                 }
745
746                 read_loop(fd, line, 4);
747                 tag = IVAL(line, 0);
748
749                 msg_bytes = tag & 0xFFFFFF;
750                 tag = (tag >> 24) - MPLEX_BASE;
751
752                 switch (tag) {
753                 case MSG_DATA:
754                         if (msg_bytes > iobuf_in_siz) {
755                                 if (!(iobuf_in = realloc_array(iobuf_in, char,
756                                                                msg_bytes)))
757                                         out_of_memory("readfd_unbuffered");
758                                 iobuf_in_siz = msg_bytes;
759                         }
760                         read_loop(fd, iobuf_in, msg_bytes);
761                         remaining = msg_bytes;
762                         iobuf_in_ndx = 0;
763                         break;
764                 case MSG_DELETED:
765                         if (msg_bytes >= sizeof line)
766                                 goto overflow;
767                         read_loop(fd, line, msg_bytes);
768                         line[msg_bytes] = '\0';
769                         /* A directory name was sent with the trailing null */
770                         if (msg_bytes > 0 && !line[msg_bytes-1])
771                                 log_delete(line, S_IFDIR);
772                         else
773                                 log_delete(line, S_IFREG);
774                         break;
775                 case MSG_SUCCESS:
776                         if (msg_bytes != 4) {
777                                 rprintf(FERROR, "invalid multi-message %d:%ld [%s]\n",
778                                         tag, (long)msg_bytes, who_am_i());
779                                 exit_cleanup(RERR_STREAMIO);
780                         }
781                         read_loop(fd, line, msg_bytes);
782                         successful_send(IVAL(line, 0));
783                         break;
784                 case MSG_INFO:
785                 case MSG_ERROR:
786                         if (msg_bytes >= sizeof line) {
787                             overflow:
788                                 rprintf(FERROR,
789                                         "multiplexing overflow %d:%ld [%s]\n",
790                                         tag, (long)msg_bytes, who_am_i());
791                                 exit_cleanup(RERR_STREAMIO);
792                         }
793                         read_loop(fd, line, msg_bytes);
794                         rwrite((enum logcode)tag, line, msg_bytes);
795                         break;
796                 default:
797                         rprintf(FERROR, "unexpected tag %d [%s]\n",
798                                 tag, who_am_i());
799                         exit_cleanup(RERR_STREAMIO);
800                 }
801         }
802
803         if (remaining == 0)
804                 io_flush(NORMAL_FLUSH);
805
806         return cnt;
807 }
808
809 /**
810  * Do a buffered read from @p fd.  Don't return until all @p n bytes
811  * have been read.  If all @p n can't be read then exit with an
812  * error.
813  **/
814 static void readfd(int fd, char *buffer, size_t N)
815 {
816         int  cnt;
817         size_t total = 0;
818
819         while (total < N) {
820                 cnt = readfd_unbuffered(fd, buffer + total, N-total);
821                 total += cnt;
822         }
823
824         if (fd == write_batch_monitor_in) {
825                 if ((size_t)write(batch_fd, buffer, total) != total)
826                         exit_cleanup(RERR_FILEIO);
827         }
828
829         if (fd == sock_f_in)
830                 stats.total_read += total;
831 }
832
833 int read_shortint(int f)
834 {
835         uchar b[2];
836         readfd(f, (char *)b, 2);
837         return (b[1] << 8) + b[0];
838 }
839
840 int32 read_int(int f)
841 {
842         char b[4];
843         int32 num;
844
845         readfd(f,b,4);
846         num = IVAL(b,0);
847         if (num == (int32)0xffffffff)
848                 return -1;
849         return num;
850 }
851
852 int64 read_longint(int f)
853 {
854         int64 num;
855         char b[8];
856         num = read_int(f);
857
858         if ((int32)num != (int32)0xffffffff)
859                 return num;
860
861 #if SIZEOF_INT64 < 8
862         rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
863         exit_cleanup(RERR_UNSUPPORTED);
864 #else
865         readfd(f,b,8);
866         num = IVAL(b,0) | (((int64)IVAL(b,4))<<32);
867 #endif
868
869         return num;
870 }
871
872 void read_buf(int f,char *buf,size_t len)
873 {
874         readfd(f,buf,len);
875 }
876
877 void read_sbuf(int f,char *buf,size_t len)
878 {
879         readfd(f, buf, len);
880         buf[len] = '\0';
881 }
882
883 uchar read_byte(int f)
884 {
885         uchar c;
886         readfd(f, (char *)&c, 1);
887         return c;
888 }
889
890 int read_vstring(int f, char *buf, int bufsize)
891 {
892         int len = read_byte(f);
893
894         if (len & 0x80)
895                 len = (len & ~0x80) * 0x100 + read_byte(f);
896
897         if (len >= bufsize) {
898                 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
899                         len, bufsize - 1);
900                 return -1;
901         }
902
903         if (len)
904                 readfd(f, buf, len);
905         buf[len] = '\0';
906         return len;
907 }
908
909 /* Populate a sum_struct with values from the socket.  This is
910  * called by both the sender and the receiver. */
911 void read_sum_head(int f, struct sum_struct *sum)
912 {
913         sum->count = read_int(f);
914         sum->blength = read_int(f);
915         if (sum->blength < 0 || sum->blength > MAX_BLOCK_SIZE) {
916                 rprintf(FERROR, "Invalid block length %ld [%s]\n",
917                         (long)sum->blength, who_am_i());
918                 exit_cleanup(RERR_PROTOCOL);
919         }
920         sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
921         if (sum->s2length < 0 || sum->s2length > MD4_SUM_LENGTH) {
922                 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
923                         sum->s2length, who_am_i());
924                 exit_cleanup(RERR_PROTOCOL);
925         }
926         sum->remainder = read_int(f);
927         if (sum->remainder < 0 || sum->remainder > sum->blength) {
928                 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
929                         (long)sum->remainder, who_am_i());
930                 exit_cleanup(RERR_PROTOCOL);
931         }
932 }
933
934 /* Send the values from a sum_struct over the socket.  Set sum to
935  * NULL if there are no checksums to send.  This is called by both
936  * the generator and the sender. */
937 void write_sum_head(int f, struct sum_struct *sum)
938 {
939         static struct sum_struct null_sum;
940
941         if (sum == NULL)
942                 sum = &null_sum;
943
944         write_int(f, sum->count);
945         write_int(f, sum->blength);
946         if (protocol_version >= 27)
947                 write_int(f, sum->s2length);
948         write_int(f, sum->remainder);
949 }
950
951 /**
952  * Sleep after writing to limit I/O bandwidth usage.
953  *
954  * @todo Rather than sleeping after each write, it might be better to
955  * use some kind of averaging.  The current algorithm seems to always
956  * use a bit less bandwidth than specified, because it doesn't make up
957  * for slow periods.  But arguably this is a feature.  In addition, we
958  * ought to take the time used to write the data into account.
959  *
960  * During some phases of big transfers (file FOO is uptodate) this is
961  * called with a small bytes_written every time.  As the kernel has to
962  * round small waits up to guarantee that we actually wait at least the
963  * requested number of microseconds, this can become grossly inaccurate.
964  * We therefore keep track of the bytes we've written over time and only
965  * sleep when the accumulated delay is at least 1 tenth of a second.
966  **/
967 static void sleep_for_bwlimit(int bytes_written)
968 {
969         static struct timeval prior_tv;
970         static long total_written = 0; 
971         struct timeval tv, start_tv;
972         long elapsed_usec, sleep_usec;
973
974 #define ONE_SEC 1000000L /* # of microseconds in a second */
975
976         if (!bwlimit)
977                 return;
978
979         total_written += bytes_written; 
980
981         gettimeofday(&start_tv, NULL);
982         if (prior_tv.tv_sec) {
983                 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
984                              + (start_tv.tv_usec - prior_tv.tv_usec);
985                 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
986                 if (total_written < 0)
987                         total_written = 0;
988         }
989
990         sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
991         if (sleep_usec < ONE_SEC / 10) {
992                 prior_tv = start_tv;
993                 return;
994         }
995
996         tv.tv_sec  = sleep_usec / ONE_SEC;
997         tv.tv_usec = sleep_usec % ONE_SEC;
998         select(0, NULL, NULL, NULL, &tv);
999
1000         gettimeofday(&prior_tv, NULL);
1001         elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1002                      + (prior_tv.tv_usec - start_tv.tv_usec);
1003         total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
1004 }
1005
1006 /* Write len bytes to the file descriptor fd, looping as necessary to get
1007  * the job done and also (in certain circumstances) reading any data on
1008  * msg_fd_in to avoid deadlock.
1009  *
1010  * This function underlies the multiplexing system.  The body of the
1011  * application never calls this function directly. */
1012 static void writefd_unbuffered(int fd,char *buf,size_t len)
1013 {
1014         size_t n, total = 0;
1015         fd_set w_fds, r_fds;
1016         int maxfd, count, cnt, using_r_fds;
1017         struct timeval tv;
1018
1019         no_flush++;
1020
1021         while (total < len) {
1022                 FD_ZERO(&w_fds);
1023                 FD_SET(fd,&w_fds);
1024                 maxfd = fd;
1025
1026                 if (msg_fd_in >= 0 && len-total >= contiguous_write_len) {
1027                         FD_ZERO(&r_fds);
1028                         FD_SET(msg_fd_in,&r_fds);
1029                         if (msg_fd_in > maxfd)
1030                                 maxfd = msg_fd_in;
1031                         using_r_fds = 1;
1032                 } else
1033                         using_r_fds = 0;
1034
1035                 tv.tv_sec = select_timeout;
1036                 tv.tv_usec = 0;
1037
1038                 errno = 0;
1039                 count = select(maxfd + 1, using_r_fds ? &r_fds : NULL,
1040                                &w_fds, NULL, &tv);
1041
1042                 if (count <= 0) {
1043                         if (count < 0 && errno == EBADF)
1044                                 exit_cleanup(RERR_SOCKETIO);
1045                         check_timeout();
1046                         continue;
1047                 }
1048
1049                 if (using_r_fds && FD_ISSET(msg_fd_in, &r_fds))
1050                         read_msg_fd();
1051
1052                 if (!FD_ISSET(fd, &w_fds))
1053                         continue;
1054
1055                 n = len - total;
1056                 if (bwlimit && n > bwlimit_writemax)
1057                         n = bwlimit_writemax;
1058                 cnt = write(fd, buf + total, n);
1059
1060                 if (cnt <= 0) {
1061                         if (cnt < 0) {
1062                                 if (errno == EINTR)
1063                                         continue;
1064                                 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1065                                         msleep(1);
1066                                         continue;
1067                                 }
1068                         }
1069
1070                         /* Don't try to write errors back across the stream. */
1071                         if (fd == sock_f_out)
1072                                 close_multiplexing_out();
1073                         rsyserr(FERROR, errno,
1074                                 "writefd_unbuffered failed to write %ld bytes: phase \"%s\" [%s]",
1075                                 (long)len, io_write_phase, who_am_i());
1076                         /* If the other side is sending us error messages, try
1077                          * to grab any messages they sent before they died. */
1078                         while (fd == sock_f_out && io_multiplexing_in) {
1079                                 set_io_timeout(30);
1080                                 ignore_timeout = 0;
1081                                 readfd_unbuffered(sock_f_in, io_filesfrom_buf,
1082                                                   sizeof io_filesfrom_buf);
1083                         }
1084                         exit_cleanup(RERR_STREAMIO);
1085                 }
1086
1087                 total += cnt;
1088
1089                 if (fd == sock_f_out) {
1090                         if (io_timeout || am_generator)
1091                                 last_io_out = time(NULL);
1092                         sleep_for_bwlimit(cnt);
1093                 }
1094         }
1095
1096         no_flush--;
1097 }
1098
1099 /**
1100  * Write an message to a multiplexed stream. If this fails then rsync
1101  * exits.
1102  **/
1103 static void mplex_write(enum msgcode code, char *buf, size_t len)
1104 {
1105         char buffer[BIGPATHBUFLEN];
1106         size_t n = len;
1107
1108         SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
1109
1110         /* When the generator reads messages from the msg_fd_in pipe, it can
1111          * cause output to occur down the socket.  Setting contiguous_write_len
1112          * prevents the reading of msg_fd_in once we actually start to write
1113          * this sequence of data (though we might read it before the start). */
1114         if (am_generator && msg_fd_in >= 0)
1115                 contiguous_write_len = len + 4;
1116
1117         if (n > sizeof buffer - 4)
1118                 n = sizeof buffer - 4;
1119
1120         memcpy(&buffer[4], buf, n);
1121         writefd_unbuffered(sock_f_out, buffer, n+4);
1122
1123         len -= n;
1124         buf += n;
1125
1126         if (len)
1127                 writefd_unbuffered(sock_f_out, buf, len);
1128
1129         if (am_generator && msg_fd_in >= 0)
1130                 contiguous_write_len = 0;
1131 }
1132
1133 void io_flush(int flush_it_all)
1134 {
1135         msg_list_flush(flush_it_all);
1136
1137         if (!iobuf_out_cnt || no_flush)
1138                 return;
1139
1140         if (io_multiplexing_out)
1141                 mplex_write(MSG_DATA, iobuf_out, iobuf_out_cnt);
1142         else
1143                 writefd_unbuffered(sock_f_out, iobuf_out, iobuf_out_cnt);
1144         iobuf_out_cnt = 0;
1145 }
1146
1147 static void writefd(int fd,char *buf,size_t len)
1148 {
1149         if (fd == msg_fd_out) {
1150                 rprintf(FERROR, "Internal error: wrong write used in receiver.\n");
1151                 exit_cleanup(RERR_PROTOCOL);
1152         }
1153
1154         if (fd == sock_f_out)
1155                 stats.total_written += len;
1156
1157         if (fd == write_batch_monitor_out) {
1158                 if ((size_t)write(batch_fd, buf, len) != len)
1159                         exit_cleanup(RERR_FILEIO);
1160         }
1161
1162         if (!iobuf_out || fd != sock_f_out) {
1163                 writefd_unbuffered(fd, buf, len);
1164                 return;
1165         }
1166
1167         while (len) {
1168                 int n = MIN((int)len, IO_BUFFER_SIZE - iobuf_out_cnt);
1169                 if (n > 0) {
1170                         memcpy(iobuf_out+iobuf_out_cnt, buf, n);
1171                         buf += n;
1172                         len -= n;
1173                         iobuf_out_cnt += n;
1174                 }
1175
1176                 if (iobuf_out_cnt == IO_BUFFER_SIZE)
1177                         io_flush(NORMAL_FLUSH);
1178         }
1179 }
1180
1181 void write_shortint(int f, int x)
1182 {
1183         uchar b[2];
1184         b[0] = x;
1185         b[1] = x >> 8;
1186         writefd(f, (char *)b, 2);
1187 }
1188
1189 void write_int(int f,int32 x)
1190 {
1191         char b[4];
1192         SIVAL(b,0,x);
1193         writefd(f,b,4);
1194 }
1195
1196 void write_int_named(int f, int32 x, const char *phase)
1197 {
1198         io_write_phase = phase;
1199         write_int(f, x);
1200         io_write_phase = phase_unknown;
1201 }
1202
1203 /*
1204  * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1205  * 64-bit types on this platform.
1206  */
1207 void write_longint(int f, int64 x)
1208 {
1209         char b[8];
1210
1211         if (x <= 0x7FFFFFFF) {
1212                 write_int(f, (int)x);
1213                 return;
1214         }
1215
1216 #if SIZEOF_INT64 < 8
1217         rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1218         exit_cleanup(RERR_UNSUPPORTED);
1219 #else
1220         write_int(f, (int32)0xFFFFFFFF);
1221         SIVAL(b,0,(x&0xFFFFFFFF));
1222         SIVAL(b,4,((x>>32)&0xFFFFFFFF));
1223
1224         writefd(f,b,8);
1225 #endif
1226 }
1227
1228 void write_buf(int f,char *buf,size_t len)
1229 {
1230         writefd(f,buf,len);
1231 }
1232
1233 /** Write a string to the connection */
1234 void write_sbuf(int f, char *buf)
1235 {
1236         writefd(f, buf, strlen(buf));
1237 }
1238
1239 void write_byte(int f, uchar c)
1240 {
1241         writefd(f, (char *)&c, 1);
1242 }
1243
1244 void write_vstring(int f, char *str, int len)
1245 {
1246         uchar lenbuf[3], *lb = lenbuf;
1247
1248         if (len > 0x7F) {
1249                 if (len > 0x7FFF) {
1250                         rprintf(FERROR,
1251                                 "attempting to send over-long vstring (%d > %d)\n",
1252                                 len, 0x7FFF);
1253                         exit_cleanup(RERR_PROTOCOL);
1254                 }
1255                 *lb++ = len / 0x100 + 0x80;
1256         }
1257         *lb = len;
1258
1259         writefd(f, (char*)lenbuf, lb - lenbuf + 1);
1260         if (len)
1261                 writefd(f, str, len);
1262 }
1263
1264 /**
1265  * Read a line of up to @p maxlen characters into @p buf (not counting
1266  * the trailing null).  Strips the (required) trailing newline and all
1267  * carriage returns.
1268  *
1269  * @return 1 for success; 0 for I/O error or truncation.
1270  **/
1271 int read_line(int f, char *buf, size_t maxlen)
1272 {
1273         while (maxlen) {
1274                 buf[0] = 0;
1275                 read_buf(f, buf, 1);
1276                 if (buf[0] == 0)
1277                         return 0;
1278                 if (buf[0] == '\n')
1279                         break;
1280                 if (buf[0] != '\r') {
1281                         buf++;
1282                         maxlen--;
1283                 }
1284         }
1285         *buf = '\0';
1286         return maxlen > 0;
1287 }
1288
1289 void io_printf(int fd, const char *format, ...)
1290 {
1291         va_list ap;
1292         char buf[BIGPATHBUFLEN];
1293         int len;
1294
1295         va_start(ap, format);
1296         len = vsnprintf(buf, sizeof buf, format, ap);
1297         va_end(ap);
1298
1299         if (len < 0)
1300                 exit_cleanup(RERR_STREAMIO);
1301
1302         if (len > (int)sizeof buf) {
1303                 rprintf(FERROR, "io_printf() was too long for the buffer.\n");
1304                 exit_cleanup(RERR_STREAMIO);
1305         }
1306
1307         write_sbuf(fd, buf);
1308 }
1309
1310 /** Setup for multiplexing a MSG_* stream with the data stream. */
1311 void io_start_multiplex_out(void)
1312 {
1313         io_flush(NORMAL_FLUSH);
1314         io_start_buffering_out();
1315         io_multiplexing_out = 1;
1316 }
1317
1318 /** Setup for multiplexing a MSG_* stream with the data stream. */
1319 void io_start_multiplex_in(void)
1320 {
1321         io_flush(NORMAL_FLUSH);
1322         io_start_buffering_in();
1323         io_multiplexing_in = 1;
1324 }
1325
1326 /** Write an message to the multiplexed data stream. */
1327 int io_multiplex_write(enum msgcode code, char *buf, size_t len)
1328 {
1329         if (!io_multiplexing_out)
1330                 return 0;
1331
1332         io_flush(NORMAL_FLUSH);
1333         stats.total_written += (len+4);
1334         mplex_write(code, buf, len);
1335         return 1;
1336 }
1337
1338 void close_multiplexing_in(void)
1339 {
1340         io_multiplexing_in = 0;
1341 }
1342
1343 /** Stop output multiplexing. */
1344 void close_multiplexing_out(void)
1345 {
1346         io_multiplexing_out = 0;
1347 }
1348
1349 void start_write_batch(int fd)
1350 {
1351         write_stream_flags(batch_fd);
1352
1353         /* Some communication has already taken place, but we don't
1354          * enable batch writing until here so that we can write a
1355          * canonical record of the communication even though the
1356          * actual communication so far depends on whether a daemon
1357          * is involved. */
1358         write_int(batch_fd, protocol_version);
1359         write_int(batch_fd, checksum_seed);
1360
1361         if (am_sender)
1362                 write_batch_monitor_out = fd;
1363         else
1364                 write_batch_monitor_in = fd;
1365 }
1366
1367 void stop_write_batch(void)
1368 {
1369         write_batch_monitor_out = -1;
1370         write_batch_monitor_in = -1;
1371 }