Some name tweaks.
[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 const char phase_unknown[] = "unknown";
56
57 /**
58  * The connection might be dropped at some point; perhaps because the
59  * remote instance crashed.  Just giving the offset on the stream is
60  * not very helpful.  So instead we try to make io_phase_name point to
61  * something useful.
62  *
63  * For buffered/multiplexed IO these names will be somewhat
64  * approximate; perhaps for ease of support we would rather make the
65  * buffer always flush when a single application-level IO finishes.
66  *
67  * @todo Perhaps we want some simple stack functionality, but there's
68  * no need to overdo it.
69  **/
70 const char *io_write_phase = phase_unknown;
71 const char *io_read_phase = phase_unknown;
72
73 /** Ignore EOF errors while reading a module listing if the remote
74     version is 24 or less. */
75 int kludge_around_eof = False;
76
77
78 static int io_error_fd = -1;
79 static int io_filesfrom_f_in = -1;
80 static int io_filesfrom_f_out = -1;
81 static char io_filesfrom_buf[2048];
82 static char *io_filesfrom_bp;
83 static char io_filesfrom_lastchar;
84 static int io_filesfrom_buflen;
85
86 static void read_loop(int fd, char *buf, size_t len);
87
88 static void check_timeout(void)
89 {
90         extern int am_server, am_daemon;
91         time_t t;
92
93         err_list_push();
94
95         if (!io_timeout) return;
96
97         if (!last_io) {
98                 last_io = time(NULL);
99                 return;
100         }
101
102         t = time(NULL);
103
104         if (last_io && io_timeout && (t-last_io) >= io_timeout) {
105                 if (!am_server && !am_daemon) {
106                         rprintf(FERROR,"io timeout after %d seconds - exiting\n", 
107                                 (int)(t-last_io));
108                 }
109                 exit_cleanup(RERR_TIMEOUT);
110         }
111 }
112
113 /** Setup the fd used to propagate errors */
114 void io_set_error_fd(int fd)
115 {
116         io_error_fd = fd;
117 }
118
119 /** Read some data from the error fd and write it to the write log code */
120 static void read_error_fd(void)
121 {
122         char buf[200];
123         size_t n;
124         int fd = io_error_fd;
125         int tag, len;
126
127         /* io_error_fd is temporarily disabled -- is this meant to
128          * prevent indefinite recursion? */
129         io_error_fd = -1;
130
131         read_loop(fd, buf, 4);
132         tag = IVAL(buf, 0);
133
134         len = tag & 0xFFFFFF;
135         tag = tag >> 24;
136         tag -= MPLEX_BASE;
137
138         while (len) {
139                 n = len;
140                 if (n > (sizeof buf - 1))
141                         n = sizeof buf - 1;
142                 read_loop(fd, buf, n);
143                 rwrite((enum logcode)tag, buf, n);
144                 len -= n;
145         }
146
147         io_error_fd = fd;
148 }
149
150 /**
151  * When we're the receiver and we have a local --files-from list of names
152  * that needs to be sent over the socket to the sender, we have to do two
153  * things at the same time: send the sender a list of what files we're
154  * processing and read the incoming file+info list from the sender.  We do
155  * this by augmenting the read_timeout() function to copy this data.  It
156  * uses the io_filesfrom_buf to read a block of data from f_in (when it is
157  * ready, since it might be a pipe) and then blast it out f_out (when it
158  * is ready to receive more data).
159  */
160 void io_set_filesfrom_fds(int f_in, int f_out)
161 {
162         io_filesfrom_f_in = f_in;
163         io_filesfrom_f_out = f_out;
164         io_filesfrom_bp = io_filesfrom_buf;
165         io_filesfrom_lastchar = '\0';
166         io_filesfrom_buflen = 0;
167 }
168
169 /**
170  * It's almost always an error to get an EOF when we're trying to read
171  * from the network, because the protocol is self-terminating.
172  *
173  * However, there is one unfortunate cases where it is not, which is
174  * rsync <2.4.6 sending a list of modules on a server, since the list
175  * is terminated by closing the socket. So, for the section of the
176  * program where that is a problem (start_socket_client),
177  * kludge_around_eof is True and we just exit.
178  */
179 static void whine_about_eof(void)
180 {
181         if (kludge_around_eof)
182                 exit_cleanup(0);
183         else {
184                 rprintf(FERROR,
185                         "%s: connection unexpectedly closed "
186                         "(%.0f bytes read so far)\n",
187                         RSYNC_NAME, (double)stats.total_read);
188
189                 exit_cleanup(RERR_STREAMIO);
190         }
191 }
192
193
194 static void die_from_readerr(int err)
195 {
196         /* this prevents us trying to write errors on a dead socket */
197         io_multiplexing_close();
198
199         rprintf(FERROR, "%s: read error: %s\n",
200                 RSYNC_NAME, strerror(err));
201         exit_cleanup(RERR_STREAMIO);
202 }
203
204
205 /**
206  * Read from a socket with IO timeout. return the number of bytes
207  * read. If no bytes can be read then exit, never return a number <= 0.
208  *
209  * TODO: If the remote shell connection fails, then current versions
210  * actually report an "unexpected EOF" error here.  Since it's a
211  * fairly common mistake to try to use rsh when ssh is required, we
212  * should trap that: if we fail to read any data at all, we should
213  * give a better explanation.  We can tell whether the connection has
214  * started by looking e.g. at whether the remote version is known yet.
215  */
216 static int read_timeout(int fd, char *buf, size_t len)
217 {
218         int n, ret=0;
219
220         io_flush();
221
222         while (ret == 0) {
223                 /* until we manage to read *something* */
224                 fd_set r_fds, w_fds;
225                 struct timeval tv;
226                 int fd_count = fd+1;
227                 int count;
228
229                 FD_ZERO(&r_fds);
230                 FD_SET(fd, &r_fds);
231                 if (io_error_fd != -1) {
232                         FD_SET(io_error_fd, &r_fds);
233                         if (io_error_fd >= fd_count) fd_count = io_error_fd+1;
234                 }
235                 if (io_filesfrom_f_out != -1) {
236                         int new_fd;
237                         if (io_filesfrom_buflen == 0) {
238                                 if (io_filesfrom_f_in != -1) {
239                                         FD_SET(io_filesfrom_f_in, &r_fds);
240                                         new_fd = io_filesfrom_f_in;
241                                 } else {
242                                         io_filesfrom_f_out = -1;
243                                         new_fd = -1;
244                                 }
245                         } else {
246                                 FD_ZERO(&w_fds);
247                                 FD_SET(io_filesfrom_f_out, &w_fds);
248                                 new_fd = io_filesfrom_f_out;
249                         }
250                         if (new_fd >= fd_count) fd_count = new_fd+1;
251                 }
252
253                 tv.tv_sec = io_timeout?io_timeout:SELECT_TIMEOUT;
254                 tv.tv_usec = 0;
255
256                 errno = 0;
257
258                 count = select(fd_count, &r_fds,
259                                io_filesfrom_buflen? &w_fds : NULL,
260                                NULL, &tv);
261
262                 if (count == 0) {
263                         check_timeout();
264                 }
265
266                 if (count <= 0) {
267                         if (errno == EBADF) {
268                                 exit_cleanup(RERR_SOCKETIO);
269                         }
270                         continue;
271                 }
272
273                 if (io_error_fd != -1 && FD_ISSET(io_error_fd, &r_fds)) {
274                         read_error_fd();
275                 }
276
277                 if (io_filesfrom_f_out != -1) {
278                         if (io_filesfrom_buflen) {
279                                 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
280                                         int l = write(io_filesfrom_f_out,
281                                                       io_filesfrom_bp,
282                                                       io_filesfrom_buflen);
283                                         if (l > 0) {
284                                                 if (!(io_filesfrom_buflen -= l))
285                                                         io_filesfrom_bp = io_filesfrom_buf;
286                                                 else
287                                                         io_filesfrom_bp += l;
288                                         } else {
289                                                 /* XXX should we complain? */
290                                                 io_filesfrom_f_out = -1;
291                                         }
292                                 }
293                         } else if (io_filesfrom_f_in != -1) {
294                                 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
295                                         int l = read(io_filesfrom_f_in,
296                                                      io_filesfrom_buf,
297                                                      sizeof io_filesfrom_buf);
298                                         if (l <= 0) {
299                                                 /* Send end-of-file marker */
300                                                 io_filesfrom_buf[0] = '\0';
301                                                 io_filesfrom_buf[1] = '\0';
302                                                 io_filesfrom_buflen = io_filesfrom_lastchar? 2 : 1;
303                                                 io_filesfrom_f_in = -1;
304                                         } else {
305                                                 extern int eol_nulls;
306                                                 if (!eol_nulls) {
307                                                         char *s = io_filesfrom_buf + l;
308                                                         /* Transform CR and/or LF into '\0' */
309                                                         while (s-- > io_filesfrom_buf) {
310                                                                 if (*s == '\n' || *s == '\r')
311                                                                         *s = '\0';
312                                                         }
313                                                 }
314                                                 if (!io_filesfrom_lastchar) {
315                                                         /* Last buf ended with a '\0', so don't
316                                                          * let this buf start with one. */
317                                                         while (l && !*io_filesfrom_bp)
318                                                                 io_filesfrom_bp++, l--;
319                                                 }
320                                                 if (!l)
321                                                         io_filesfrom_bp = io_filesfrom_buf;
322                                                 else {
323                                                         char *f = io_filesfrom_bp;
324                                                         char *t = f;
325                                                         char *eob = f + l;
326                                                         /* Eliminate any multi-'\0' runs. */
327                                                         while (f != eob) {
328                                                                 if (!(*t++ = *f++)) {
329                                                                         while (f != eob && !*f)
330                                                                                 f++, l--;
331                                                                 }
332                                                         }
333                                                         io_filesfrom_lastchar = f[-1];
334                                                 }
335                                                 io_filesfrom_buflen = l;
336                                         }
337                                 }
338                         }
339                 }
340
341                 if (!FD_ISSET(fd, &r_fds)) continue;
342
343                 n = read(fd, buf, len);
344
345                 if (n > 0) {
346                         buf += n;
347                         len -= n;
348                         ret += n;
349                         if (io_timeout)
350                                 last_io = time(NULL);
351                         continue;
352                 } else if (n == 0) {
353                         whine_about_eof();
354                         return -1; /* doesn't return */
355                 } else if (n == -1) {
356                         if (errno == EINTR || errno == EWOULDBLOCK ||
357                             errno == EAGAIN) 
358                                 continue;
359                         die_from_readerr(errno);
360                 }
361         }
362
363         return ret;
364 }
365
366 /**
367  * Read a line into the "fname" buffer (which must be at least MAXPATHLEN
368  * characters long).
369  */
370 int read_filesfrom_line(int fd, char *fname)
371 {
372         char ch, *s, *eob = fname + MAXPATHLEN - 1;
373         int cnt;
374         extern int io_timeout;
375         extern int eol_nulls;
376         extern char *remote_filesfrom_file;
377         int reading_remotely = remote_filesfrom_file != NULL;
378         int nulls = eol_nulls || reading_remotely;
379
380   start:
381         s = fname;
382         while (1) {
383                 cnt = read(fd, &ch, 1);
384                 if (cnt < 0 && (errno == EWOULDBLOCK
385                   || errno == EINTR || errno == EAGAIN)) {
386                         struct timeval tv;
387                         fd_set fds;
388                         FD_ZERO(&fds);
389                         FD_SET(fd, &fds);
390                         tv.tv_sec = io_timeout? io_timeout : SELECT_TIMEOUT;
391                         tv.tv_usec = 0;
392                         if (!select(fd+1, &fds, NULL, NULL, &tv))
393                                 check_timeout();
394                         continue;
395                 }
396                 if (cnt != 1)
397                         break;
398                 if (nulls? !ch : (ch == '\r' || ch == '\n')) {
399                         /* Skip empty lines if reading locally. */
400                         if (!reading_remotely && s == fname)
401                                 continue;
402                         break;
403                 }
404                 if (s < eob)
405                         *s++ = ch;
406         }
407         *s = '\0';
408
409         /* Dump comments. */
410         if (*fname == '#' || *fname == ';')
411                 goto start;
412
413         return s - fname;
414 }
415
416
417 /**
418  * Continue trying to read len bytes - don't return until len has been
419  * read.
420  **/
421 static void read_loop(int fd, char *buf, size_t len)
422 {
423         while (len) {
424                 int n = read_timeout(fd, buf, len);
425
426                 buf += n;
427                 len -= n;
428         }
429 }
430
431
432 /**
433  * Read from the file descriptor handling multiplexing - return number
434  * of bytes read.
435  * 
436  * Never returns <= 0. 
437  */
438 static int read_unbuffered(int fd, char *buf, size_t len)
439 {
440         static size_t remaining;
441         int tag, ret = 0;
442         char line[1024];
443
444         if (!io_multiplexing_in || fd != multiplex_in_fd)
445                 return read_timeout(fd, buf, len);
446
447         while (ret == 0) {
448                 if (remaining) {
449                         len = MIN(len, remaining);
450                         read_loop(fd, buf, len);
451                         remaining -= len;
452                         ret = len;
453                         continue;
454                 }
455
456                 read_loop(fd, line, 4);
457                 tag = IVAL(line, 0);
458
459                 remaining = tag & 0xFFFFFF;
460                 tag = tag >> 24;
461
462                 if (tag == MPLEX_BASE)
463                         continue;
464
465                 tag -= MPLEX_BASE;
466
467                 if (tag != FERROR && tag != FINFO) {
468                         rprintf(FERROR, "unexpected tag %d\n", tag);
469                         exit_cleanup(RERR_STREAMIO);
470                 }
471
472                 if (remaining > sizeof line - 1) {
473                         rprintf(FERROR, "multiplexing overflow %ld\n\n",
474                                 (long)remaining);
475                         exit_cleanup(RERR_STREAMIO);
476                 }
477
478                 read_loop(fd, line, remaining);
479                 line[remaining] = 0;
480
481                 rprintf((enum logcode) tag, "%s", line);
482                 remaining = 0;
483         }
484
485         return ret;
486 }
487
488
489
490 /**
491  * Do a buffered read from @p fd.  Don't return until all @p n bytes
492  * have been read.  If all @p n can't be read then exit with an
493  * error.
494  **/
495 static void readfd(int fd, char *buffer, size_t N)
496 {
497         int  ret;
498         size_t total=0;  
499
500         while (total < N) {
501                 io_flush();
502
503                 ret = read_unbuffered(fd, buffer + total, N-total);
504                 total += ret;
505         }
506
507         stats.total_read += total;
508 }
509
510
511 int32 read_int(int f)
512 {
513         char b[4];
514         int32 ret;
515
516         readfd(f,b,4);
517         ret = IVAL(b,0);
518         if (ret == (int32)0xffffffff) return -1;
519         return ret;
520 }
521
522 int64 read_longint(int f)
523 {
524         int64 ret;
525         char b[8];
526         ret = read_int(f);
527
528         if ((int32)ret != (int32)0xffffffff) {
529                 return ret;
530         }
531
532 #ifdef NO_INT64
533         rprintf(FERROR,"Integer overflow - attempted 64 bit offset\n");
534         exit_cleanup(RERR_UNSUPPORTED);
535 #else
536         readfd(f,b,8);
537         ret = IVAL(b,0) | (((int64)IVAL(b,4))<<32);
538 #endif
539
540         return ret;
541 }
542
543 void read_buf(int f,char *buf,size_t len)
544 {
545         readfd(f,buf,len);
546 }
547
548 void read_sbuf(int f,char *buf,size_t len)
549 {
550         read_buf(f,buf,len);
551         buf[len] = 0;
552 }
553
554 unsigned char read_byte(int f)
555 {
556         unsigned char c;
557         read_buf(f, (char *)&c, 1);
558         return c;
559 }
560
561
562 /**
563  * Sleep after writing to limit I/O bandwidth usage.
564  *
565  * @todo Rather than sleeping after each write, it might be better to
566  * use some kind of averaging.  The current algorithm seems to always
567  * use a bit less bandwidth than specified, because it doesn't make up
568  * for slow periods.  But arguably this is a feature.  In addition, we
569  * ought to take the time used to write the data into account.
570  **/
571 static void sleep_for_bwlimit(int bytes_written)
572 {
573         struct timeval tv;
574
575         if (!bwlimit)
576                 return;
577
578         assert(bytes_written > 0);
579         assert(bwlimit > 0);
580
581         tv.tv_usec = bytes_written * 1000 / bwlimit;
582         tv.tv_sec  = tv.tv_usec / 1000000;
583         tv.tv_usec = tv.tv_usec % 1000000;
584
585         select(0, NULL, NULL, NULL, &tv);
586 }
587
588
589 /**
590  * Write len bytes to the file descriptor @p fd.
591  *
592  * This function underlies the multiplexing system.  The body of the
593  * application never calls this function directly.
594  **/
595 static void writefd_unbuffered(int fd,char *buf,size_t len)
596 {
597         size_t total = 0;
598         fd_set w_fds, r_fds;
599         int fd_count, count;
600         struct timeval tv;
601
602         err_list_push();
603
604         no_flush++;
605
606         while (total < len) {
607                 FD_ZERO(&w_fds);
608                 FD_SET(fd,&w_fds);
609                 fd_count = fd;
610
611                 if (io_error_fd != -1) {
612                         FD_ZERO(&r_fds);
613                         FD_SET(io_error_fd,&r_fds);
614                         if (io_error_fd > fd_count) 
615                                 fd_count = io_error_fd;
616                 }
617
618                 tv.tv_sec = io_timeout?io_timeout:SELECT_TIMEOUT;
619                 tv.tv_usec = 0;
620
621                 errno = 0;
622
623                 count = select(fd_count+1,
624                                io_error_fd != -1?&r_fds:NULL,
625                                &w_fds,NULL,
626                                &tv);
627
628                 if (count == 0) {
629                         check_timeout();
630                 }
631
632                 if (count <= 0) {
633                         if (errno == EBADF) {
634                                 exit_cleanup(RERR_SOCKETIO);
635                         }
636                         continue;
637                 }
638
639                 if (io_error_fd != -1 && FD_ISSET(io_error_fd, &r_fds)) {
640                         read_error_fd();
641                 }
642
643                 if (FD_ISSET(fd, &w_fds)) {
644                         int ret;
645                         size_t n = len-total;
646                         ret = write(fd,buf+total,n);
647
648                         if (ret == -1 && errno == EINTR) {
649                                 continue;
650                         }
651
652                         if (ret == -1 && 
653                             (errno == EWOULDBLOCK || errno == EAGAIN)) {
654                                 msleep(1);
655                                 continue;
656                         }
657
658                         if (ret <= 0) {
659                                 /* Don't try to write errors back
660                                  * across the stream */
661                                 io_multiplexing_close();
662                                 rprintf(FERROR, RSYNC_NAME
663                                         ": writefd_unbuffered failed to write %ld bytes: phase \"%s\": %s\n",
664                                         (long) len, io_write_phase, 
665                                         strerror(errno));
666                                 exit_cleanup(RERR_STREAMIO);
667                         }
668
669                         sleep_for_bwlimit(ret);
670  
671                         total += ret;
672
673                         if (io_timeout)
674                                 last_io = time(NULL);
675                 }
676         }
677
678         no_flush--;
679 }
680
681
682 static char *io_buffer;
683 static int io_buffer_count;
684
685 void io_start_buffering(int fd)
686 {
687         if (io_buffer) return;
688         multiplex_out_fd = fd;
689         io_buffer = new_array(char, IO_BUFFER_SIZE);
690         if (!io_buffer) out_of_memory("writefd");
691         io_buffer_count = 0;
692 }
693
694 /**
695  * Write an message to a multiplexed stream. If this fails then rsync
696  * exits.
697  **/
698 static void mplex_write(int fd, enum logcode code, char *buf, size_t len)
699 {
700         char buffer[4096];
701         size_t n = len;
702
703         SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
704
705         if (n > (sizeof buffer - 4)) {
706                 n = sizeof buffer - 4;
707         }
708
709         memcpy(&buffer[4], buf, n);
710         writefd_unbuffered(fd, buffer, n+4);
711
712         len -= n;
713         buf += n;
714
715         if (len) {
716                 writefd_unbuffered(fd, buf, len);
717         }
718 }
719
720
721 void io_flush(void)
722 {
723         int fd = multiplex_out_fd;
724
725         err_list_push();
726
727         if (!io_buffer_count || no_flush) return;
728
729         if (io_multiplexing_out) {
730                 mplex_write(fd, FNONE, io_buffer, io_buffer_count);
731         } else {
732                 writefd_unbuffered(fd, io_buffer, io_buffer_count);
733         }
734         io_buffer_count = 0;
735 }
736
737
738 void io_end_buffering(void)
739 {
740         io_flush();
741         if (!io_multiplexing_out) {
742                 free(io_buffer);
743                 io_buffer = NULL;
744         }
745 }
746
747 static void writefd(int fd,char *buf,size_t len)
748 {
749         stats.total_written += len;
750
751         err_list_push();
752
753         if (!io_buffer || fd != multiplex_out_fd) {
754                 writefd_unbuffered(fd, buf, len);
755                 return;
756         }
757
758         while (len) {
759                 int n = MIN((int) len, IO_BUFFER_SIZE-io_buffer_count);
760                 if (n > 0) {
761                         memcpy(io_buffer+io_buffer_count, buf, n);
762                         buf += n;
763                         len -= n;
764                         io_buffer_count += n;
765                 }
766
767                 if (io_buffer_count == IO_BUFFER_SIZE) io_flush();
768         }
769 }
770
771
772 void write_int(int f,int32 x)
773 {
774         char b[4];
775         SIVAL(b,0,x);
776         writefd(f,b,4);
777 }
778
779
780 void write_int_named(int f, int32 x, const char *phase)
781 {
782         io_write_phase = phase;
783         write_int(f, x);
784         io_write_phase = phase_unknown;
785 }
786
787
788 /*
789  * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
790  * 64-bit types on this platform.
791  */
792 void write_longint(int f, int64 x)
793 {
794         char b[8];
795
796         if (x <= 0x7FFFFFFF) {
797                 write_int(f, (int)x);
798                 return;
799         }
800
801 #ifdef NO_INT64
802         rprintf(FERROR,"Integer overflow - attempted 64 bit offset\n");
803         exit_cleanup(RERR_UNSUPPORTED);
804 #else
805         write_int(f, (int32)0xFFFFFFFF);
806         SIVAL(b,0,(x&0xFFFFFFFF));
807         SIVAL(b,4,((x>>32)&0xFFFFFFFF));
808
809         writefd(f,b,8);
810 #endif
811 }
812
813 void write_buf(int f,char *buf,size_t len)
814 {
815         writefd(f,buf,len);
816 }
817
818 /** Write a string to the connection */
819 static void write_sbuf(int f,char *buf)
820 {
821         write_buf(f, buf, strlen(buf));
822 }
823
824
825 void write_byte(int f,unsigned char c)
826 {
827         write_buf(f,(char *)&c,1);
828 }
829
830
831
832 /**
833  * Read a line of up to @p maxlen characters into @p buf.  Does not
834  * contain a trailing newline or carriage return.
835  *
836  * @return 1 for success; 0 for io error or truncation.
837  **/
838 int read_line(int f, char *buf, size_t maxlen)
839 {
840         while (maxlen) {
841                 buf[0] = 0;
842                 read_buf(f, buf, 1);
843                 if (buf[0] == 0)
844                         return 0;
845                 if (buf[0] == '\n') {
846                         buf[0] = 0;
847                         break;
848                 }
849                 if (buf[0] != '\r') {
850                         buf++;
851                         maxlen--;
852                 }
853         }
854         if (maxlen == 0) {
855                 *buf = 0;
856                 return 0;
857         }
858
859         return 1;
860 }
861
862
863 void io_printf(int fd, const char *format, ...)
864 {
865         va_list ap;  
866         char buf[1024];
867         int len;
868
869         va_start(ap, format);
870         len = vsnprintf(buf, sizeof buf, format, ap);
871         va_end(ap);
872
873         if (len < 0) exit_cleanup(RERR_STREAMIO);
874
875         write_sbuf(fd, buf);
876 }
877
878
879 /** Setup for multiplexing an error stream with the data stream */
880 void io_start_multiplex_out(int fd)
881 {
882         multiplex_out_fd = fd;
883         io_flush();
884         io_start_buffering(fd);
885         io_multiplexing_out = 1;
886 }
887
888 /** Setup for multiplexing an error stream with the data stream */
889 void io_start_multiplex_in(int fd)
890 {
891         multiplex_in_fd = fd;
892         io_flush();
893         io_multiplexing_in = 1;
894 }
895
896 /** Write an message to the multiplexed error stream */
897 int io_multiplex_write(enum logcode code, char *buf, size_t len)
898 {
899         if (!io_multiplexing_out) return 0;
900
901         io_flush();
902         stats.total_written += (len+4);
903         mplex_write(multiplex_out_fd, code, buf, len);
904         return 1;
905 }
906
907 /** Stop output multiplexing */
908 void io_multiplexing_close(void)
909 {
910         io_multiplexing_out = 0;
911 }
912