Factor out bwlimit sleep code from writefd_unbuffered into its own function.
[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 IO 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 static int io_multiplexing_out;
43 static int io_multiplexing_in;
44 static int multiplex_in_fd;
45 static int multiplex_out_fd;
46 static time_t last_io;
47 static int no_flush;
48
49 extern int bwlimit;
50 extern int verbose;
51 extern int io_timeout;
52 extern struct stats stats;
53
54
55 /** Ignore EOF errors while reading a module listing if the remote
56     version is 24 or less. */
57 int kludge_around_eof = False;
58
59
60 static int io_error_fd = -1;
61
62 static void read_loop(int fd, char *buf, size_t len);
63
64 static void check_timeout(void)
65 {
66         extern int am_server, am_daemon;
67         time_t t;
68
69         err_list_push();
70         
71         if (!io_timeout) return;
72
73         if (!last_io) {
74                 last_io = time(NULL);
75                 return;
76         }
77
78         t = time(NULL);
79
80         if (last_io && io_timeout && (t-last_io) >= io_timeout) {
81                 if (!am_server && !am_daemon) {
82                         rprintf(FERROR,"io timeout after %d seconds - exiting\n", 
83                                 (int)(t-last_io));
84                 }
85                 exit_cleanup(RERR_TIMEOUT);
86         }
87 }
88
89 /** Setup the fd used to propogate errors */
90 void io_set_error_fd(int fd)
91 {
92         io_error_fd = fd;
93 }
94
95 /** Read some data from the error fd and write it to the write log code */
96 static void read_error_fd(void)
97 {
98         char buf[200];
99         size_t n;
100         int fd = io_error_fd;
101         int tag, len;
102
103         /* io_error_fd is temporarily disabled -- is this meant to
104          * prevent indefinite recursion? */
105         io_error_fd = -1;
106
107         read_loop(fd, buf, 4);
108         tag = IVAL(buf, 0);
109
110         len = tag & 0xFFFFFF;
111         tag = tag >> 24;
112         tag -= MPLEX_BASE;
113
114         while (len) {
115                 n = len;
116                 if (n > (sizeof(buf)-1))
117                         n = sizeof(buf)-1;
118                 read_loop(fd, buf, n);
119                 rwrite((enum logcode)tag, buf, n);
120                 len -= n;
121         }
122
123         io_error_fd = fd;
124 }
125
126
127 /**
128  * It's almost always an error to get an EOF when we're trying to read
129  * from the network, because the protocol is self-terminating.
130  *
131  * However, there is one unfortunate cases where it is not, which is
132  * rsync <2.4.6 sending a list of modules on a server, since the list
133  * is terminated by closing the socket. So, for the section of the
134  * program where that is a problem (start_socket_client),
135  * kludge_around_eof is True and we just exit.
136  */
137 static void whine_about_eof (void)
138 {
139         if (kludge_around_eof)
140                 exit_cleanup (0);
141         else {
142                 rprintf (FERROR,
143                          "%s: connection unexpectedly closed "
144                          "(%.0f bytes read so far)\n",
145                          RSYNC_NAME, (double)stats.total_read);
146         
147                 exit_cleanup (RERR_STREAMIO);
148         }
149 }
150
151
152 static void die_from_readerr (int err)
153 {
154         /* this prevents us trying to write errors on a dead socket */
155         io_multiplexing_close();
156                                 
157         rprintf(FERROR, "%s: read error: %s\n",
158                 RSYNC_NAME, strerror (err));
159         exit_cleanup(RERR_STREAMIO);
160 }
161
162
163 /**
164  * Read from a socket with IO timeout. return the number of bytes
165  * read. If no bytes can be read then exit, never return a number <= 0.
166  *
167  * TODO: If the remote shell connection fails, then current versions
168  * actually report an "unexpected EOF" error here.  Since it's a
169  * fairly common mistake to try to use rsh when ssh is required, we
170  * should trap that: if we fail to read any data at all, we should
171  * give a better explanation.  We can tell whether the connection has
172  * started by looking e.g. at whether the remote version is known yet.
173  */
174 static int read_timeout (int fd, char *buf, size_t len)
175 {
176         int n, ret=0;
177
178         io_flush();
179
180         while (ret == 0) {
181                 /* until we manage to read *something* */
182                 fd_set fds;
183                 struct timeval tv;
184                 int fd_count = fd+1;
185                 int count;
186
187                 FD_ZERO(&fds);
188                 FD_SET(fd, &fds);
189                 if (io_error_fd != -1) {
190                         FD_SET(io_error_fd, &fds);
191                         if (io_error_fd > fd) fd_count = io_error_fd+1;
192                 }
193
194                 tv.tv_sec = io_timeout?io_timeout:SELECT_TIMEOUT;
195                 tv.tv_usec = 0;
196
197                 errno = 0;
198
199                 count = select(fd_count, &fds, NULL, NULL, &tv);
200
201                 if (count == 0) {
202                         check_timeout();
203                 }
204
205                 if (count <= 0) {
206                         if (errno == EBADF) {
207                                 exit_cleanup(RERR_SOCKETIO);
208                         }
209                         continue;
210                 }
211
212                 if (io_error_fd != -1 && FD_ISSET(io_error_fd, &fds)) {
213                         read_error_fd();
214                 }
215
216                 if (!FD_ISSET(fd, &fds)) continue;
217
218                 n = read(fd, buf, len);
219
220                 if (n > 0) {
221                         buf += n;
222                         len -= n;
223                         ret += n;
224                         if (io_timeout)
225                                 last_io = time(NULL);
226                         continue;
227                 } else if (n == 0) {
228                         whine_about_eof ();
229                         return -1; /* doesn't return */
230                 } else if (n == -1) {
231                         if (errno == EINTR || errno == EWOULDBLOCK ||
232                             errno == EAGAIN) 
233                                 continue;
234                         else
235                                 die_from_readerr (errno);
236                 }
237         }
238
239         return ret;
240 }
241
242
243
244
245 /**
246  * Continue trying to read len bytes - don't return until len has been
247  * read.
248  **/
249 static void read_loop (int fd, char *buf, size_t len)
250 {
251         while (len) {
252                 int n = read_timeout(fd, buf, len);
253
254                 buf += n;
255                 len -= n;
256         }
257 }
258
259
260 /**
261  * Read from the file descriptor handling multiplexing - return number
262  * of bytes read.
263  * 
264  * Never returns <= 0. 
265  */
266 static int read_unbuffered(int fd, char *buf, size_t len)
267 {
268         static size_t remaining;
269         int tag, ret = 0;
270         char line[1024];
271
272         if (!io_multiplexing_in || fd != multiplex_in_fd)
273                 return read_timeout(fd, buf, len);
274
275         while (ret == 0) {
276                 if (remaining) {
277                         len = MIN(len, remaining);
278                         read_loop(fd, buf, len);
279                         remaining -= len;
280                         ret = len;
281                         continue;
282                 }
283
284                 read_loop(fd, line, 4);
285                 tag = IVAL(line, 0);
286
287                 remaining = tag & 0xFFFFFF;
288                 tag = tag >> 24;
289
290                 if (tag == MPLEX_BASE)
291                         continue;
292
293                 tag -= MPLEX_BASE;
294
295                 if (tag != FERROR && tag != FINFO) {
296                         rprintf(FERROR, "unexpected tag %d\n", tag);
297                         exit_cleanup(RERR_STREAMIO);
298                 }
299
300                 if (remaining > sizeof(line) - 1) {
301                         rprintf(FERROR, "multiplexing overflow %d\n\n",
302                                 remaining);
303                         exit_cleanup(RERR_STREAMIO);
304                 }
305
306                 read_loop(fd, line, remaining);
307                 line[remaining] = 0;
308
309                 rprintf((enum logcode) tag, "%s", line);
310                 remaining = 0;
311         }
312
313         return ret;
314 }
315
316
317
318 /**
319  * Do a buffered read from @p fd.  Don't return until all @p n bytes
320  * have been read.  If all @p n can't be read then exit with an
321  * error.
322  **/
323 static void readfd (int fd, char *buffer, size_t N)
324 {
325         int  ret;
326         size_t total=0;  
327         
328         while (total < N) {
329                 io_flush();
330
331                 ret = read_unbuffered (fd, buffer + total, N-total);
332                 total += ret;
333         }
334
335         stats.total_read += total;
336 }
337
338
339 int32 read_int(int f)
340 {
341         char b[4];
342         int32 ret;
343
344         readfd(f,b,4);
345         ret = IVAL(b,0);
346         if (ret == (int32)0xffffffff) return -1;
347         return ret;
348 }
349
350 int64 read_longint(int f)
351 {
352         extern int remote_version;
353         int64 ret;
354         char b[8];
355         ret = read_int(f);
356
357         if ((int32)ret != (int32)0xffffffff) {
358                 return ret;
359         }
360
361 #ifdef NO_INT64
362         rprintf(FERROR,"Integer overflow - attempted 64 bit offset\n");
363         exit_cleanup(RERR_UNSUPPORTED);
364 #else
365         if (remote_version >= 16) {
366                 readfd(f,b,8);
367                 ret = IVAL(b,0) | (((int64)IVAL(b,4))<<32);
368         }
369 #endif
370
371         return ret;
372 }
373
374 void read_buf(int f,char *buf,size_t len)
375 {
376         readfd(f,buf,len);
377 }
378
379 void read_sbuf(int f,char *buf,size_t len)
380 {
381         read_buf (f,buf,len);
382         buf[len] = 0;
383 }
384
385 unsigned char read_byte(int f)
386 {
387         unsigned char c;
388         read_buf (f, (char *)&c, 1);
389         return c;
390 }
391
392
393 /**
394  * Sleep after writing to limit I/O bandwidth usage.
395  *
396  * @todo Rather than sleeping after each write, it might be better to
397  * use some kind of averaging.  The current algorithm seems to always
398  * use a bit less bandwidth than specified, because it doesn't make up
399  * for slow periods.  But arguably this is a feature.  In addition, we
400  * ought to take the time used to write the data into account.
401  **/
402 static void sleep_for_bwlimit(int bytes_written)
403 {
404         struct timeval tv;
405
406         if (!bwlimit)
407                 return;
408         
409         tv.tv_sec = 0;
410         tv.tv_usec = bytes_written * 1000 / bwlimit;
411
412         while (tv.tv_usec > 1000000) {
413                 tv.tv_sec++;
414                 tv.tv_usec -= 1000000;
415         }
416         select(0, NULL, NULL, NULL, tv);
417 }
418
419
420 /**
421  * Write len bytes to the file descriptor @p fd.
422  *
423  * This function underlies the multiplexing system.  The body of the
424  * application never calls this function directly.
425  **/
426 static void writefd_unbuffered(int fd,char *buf,size_t len)
427 {
428         size_t total = 0;
429         fd_set w_fds, r_fds;
430         int fd_count, count;
431         struct timeval tv;
432
433         err_list_push();
434
435         no_flush++;
436
437         while (total < len) {
438                 FD_ZERO(&w_fds);
439                 FD_ZERO(&r_fds);
440                 FD_SET(fd,&w_fds);
441                 fd_count = fd;
442
443                 if (io_error_fd != -1) {
444                         FD_SET(io_error_fd,&r_fds);
445                         if (io_error_fd > fd_count) 
446                                 fd_count = io_error_fd;
447                 }
448
449                 tv.tv_sec = io_timeout?io_timeout:SELECT_TIMEOUT;
450                 tv.tv_usec = 0;
451
452                 errno = 0;
453
454                 count = select(fd_count+1,
455                                io_error_fd != -1?&r_fds:NULL,
456                                &w_fds,NULL,
457                                &tv);
458
459                 if (count == 0) {
460                         check_timeout();
461                 }
462
463                 if (count <= 0) {
464                         if (errno == EBADF) {
465                                 exit_cleanup(RERR_SOCKETIO);
466                         }
467                         continue;
468                 }
469
470                 if (io_error_fd != -1 && FD_ISSET(io_error_fd, &r_fds)) {
471                         read_error_fd();
472                 }
473
474                 if (FD_ISSET(fd, &w_fds)) {
475                         int ret;
476                         size_t n = len-total;
477                         ret = write(fd,buf+total,n);
478
479                         if (ret == -1 && errno == EINTR) {
480                                 continue;
481                         }
482
483                         if (ret == -1 && 
484                             (errno == EWOULDBLOCK || errno == EAGAIN)) {
485                                 msleep(1);
486                                 continue;
487                         }
488
489                         if (ret <= 0) {
490                                 /* Don't try to write errors back
491                                  * across the stream */
492                                 io_multiplexing_close();
493                                 rprintf(FERROR, RSYNC_NAME
494                                         ": writefd_unbuffered failed to write %ld bytes: %s\n",
495                                         (long) len, 
496                                         strerror(errno));
497                                 exit_cleanup(RERR_STREAMIO);
498                         }
499
500                         sleep_for_bwlimit(ret);
501  
502                         total += ret;
503
504                         if (io_timeout)
505                                 last_io = time(NULL);
506                 }
507         }
508
509         no_flush--;
510 }
511
512
513 static char *io_buffer;
514 static int io_buffer_count;
515
516 void io_start_buffering(int fd)
517 {
518         if (io_buffer) return;
519         multiplex_out_fd = fd;
520         io_buffer = (char *)malloc(IO_BUFFER_SIZE);
521         if (!io_buffer) out_of_memory("writefd");
522         io_buffer_count = 0;
523 }
524
525 /**
526  * Write an message to a multiplexed stream. If this fails then rsync
527  * exits.
528  **/
529 static void mplex_write(int fd, enum logcode code, char *buf, size_t len)
530 {
531         char buffer[4096];
532         size_t n = len;
533
534         SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
535
536         if (n > (sizeof(buffer)-4)) {
537                 n = sizeof(buffer)-4;
538         }
539
540         memcpy(&buffer[4], buf, n);
541         writefd_unbuffered(fd, buffer, n+4);
542
543         len -= n;
544         buf += n;
545
546         if (len) {
547                 writefd_unbuffered(fd, buf, len);
548         }
549 }
550
551
552 void io_flush(void)
553 {
554         int fd = multiplex_out_fd;
555
556         err_list_push();
557
558         if (!io_buffer_count || no_flush) return;
559
560         if (io_multiplexing_out) {
561                 mplex_write(fd, FNONE, io_buffer, io_buffer_count);
562         } else {
563                 writefd_unbuffered(fd, io_buffer, io_buffer_count);
564         }
565         io_buffer_count = 0;
566 }
567
568
569 void io_end_buffering(void)
570 {
571         io_flush();
572         if (!io_multiplexing_out) {
573                 free(io_buffer);
574                 io_buffer = NULL;
575         }
576 }
577
578 static void writefd(int fd,char *buf,size_t len)
579 {
580         stats.total_written += len;
581
582         err_list_push();
583
584         if (!io_buffer || fd != multiplex_out_fd) {
585                 writefd_unbuffered(fd, buf, len);
586                 return;
587         }
588
589         while (len) {
590                 int n = MIN((int) len, IO_BUFFER_SIZE-io_buffer_count);
591                 if (n > 0) {
592                         memcpy(io_buffer+io_buffer_count, buf, n);
593                         buf += n;
594                         len -= n;
595                         io_buffer_count += n;
596                 }
597                 
598                 if (io_buffer_count == IO_BUFFER_SIZE) io_flush();
599         }
600 }
601
602
603 void write_int(int f,int32 x)
604 {
605         char b[4];
606         SIVAL(b,0,x);
607         writefd(f,b,4);
608 }
609
610
611 /*
612  * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
613  * 64-bit types on this platform.
614  */
615 void write_longint(int f, int64 x)
616 {
617         extern int remote_version;
618         char b[8];
619
620         if (remote_version < 16 || x <= 0x7FFFFFFF) {
621                 write_int(f, (int)x);
622                 return;
623         }
624
625         write_int(f, (int32)0xFFFFFFFF);
626         SIVAL(b,0,(x&0xFFFFFFFF));
627         SIVAL(b,4,((x>>32)&0xFFFFFFFF));
628
629         writefd(f,b,8);
630 }
631
632 void write_buf(int f,char *buf,size_t len)
633 {
634         writefd(f,buf,len);
635 }
636
637 /** Write a string to the connection */
638 static void write_sbuf(int f,char *buf)
639 {
640         write_buf(f, buf, strlen(buf));
641 }
642
643
644 void write_byte(int f,unsigned char c)
645 {
646         write_buf(f,(char *)&c,1);
647 }
648
649
650
651 /**
652  * Read a line of up to @p maxlen characters into @p buf.  Does not
653  * contain a trailing newline or carriage return.
654  *
655  * @return 1 for success; 0 for io error or truncation.
656  **/
657 int read_line(int f, char *buf, size_t maxlen)
658 {
659         while (maxlen) {
660                 buf[0] = 0;
661                 read_buf(f, buf, 1);
662                 if (buf[0] == 0)
663                         return 0;
664                 if (buf[0] == '\n') {
665                         buf[0] = 0;
666                         break;
667                 }
668                 if (buf[0] != '\r') {
669                         buf++;
670                         maxlen--;
671                 }
672         }
673         if (maxlen == 0) {
674                 *buf = 0;
675                 return 0;
676         }
677
678         return 1;
679 }
680
681
682 void io_printf(int fd, const char *format, ...)
683 {
684         va_list ap;  
685         char buf[1024];
686         int len;
687         
688         va_start(ap, format);
689         len = vsnprintf(buf, sizeof(buf), format, ap);
690         va_end(ap);
691
692         if (len < 0) exit_cleanup(RERR_STREAMIO);
693
694         write_sbuf(fd, buf);
695 }
696
697
698 /** Setup for multiplexing an error stream with the data stream */
699 void io_start_multiplex_out(int fd)
700 {
701         multiplex_out_fd = fd;
702         io_flush();
703         io_start_buffering(fd);
704         io_multiplexing_out = 1;
705 }
706
707 /** Setup for multiplexing an error stream with the data stream */
708 void io_start_multiplex_in(int fd)
709 {
710         multiplex_in_fd = fd;
711         io_flush();
712         io_multiplexing_in = 1;
713 }
714
715 /** Write an message to the multiplexed error stream */
716 int io_multiplex_write(enum logcode code, char *buf, size_t len)
717 {
718         if (!io_multiplexing_out) return 0;
719
720         io_flush();
721         stats.total_written += (len+4);
722         mplex_write(multiplex_out_fd, code, buf, len);
723         return 1;
724 }
725
726 /** Stop output multiplexing */
727 void io_multiplexing_close(void)
728 {
729         io_multiplexing_out = 0;
730 }
731