Modified Files: glib/ChangeLog glib/glib.def glib/glib/giochannel.c
[platform/upstream/glib.git] / glib / giochannel.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * giochannel.c: IO Channel abstraction
5  * Copyright 1998 Owen Taylor
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library 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 GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20  * Boston, MA 02111-1307, USA.
21  */
22
23 /*
24  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
25  * file for a list of people on the GLib Team.  See the ChangeLog
26  * files for a list of changes.  These files are distributed with
27  * GLib at ftp://ftp.gtk.org/pub/gtk/. 
28  */
29
30 /* 
31  * MT safe
32  */
33
34 #include <string.h>
35 #include <errno.h>
36
37 #include "config.h"
38 #ifdef HAVE_UNISTD_H
39 #include <unistd.h>
40 #endif
41
42 #undef G_DISABLE_DEPRECATED
43
44 #include "glib.h"
45
46 #include "glibintl.h"
47
48 #define G_IO_NICE_BUF_SIZE      1024
49
50 static GIOError         g_io_error_get_from_g_error     (GIOStatus    status,
51                                                          GError      *err);
52 static void             g_io_channel_purge              (GIOChannel  *channel);
53 static GIOStatus        g_io_channel_fill_buffer        (GIOChannel  *channel,
54                                                          GError     **err);
55 static GIOStatus        g_io_channel_read_line_backend  (GIOChannel  *channel,
56                                                          gsize       *length,
57                                                          gsize       *terminator_pos,
58                                                          GError     **error);
59
60 void
61 g_io_channel_init (GIOChannel *channel)
62 {
63   channel->ref_count = 1;
64   channel->encoding = g_strdup ("UTF-8");
65   channel->line_term = NULL;
66   channel->buf_size = G_IO_NICE_BUF_SIZE;
67   channel->read_cd = (GIConv) -1;
68   channel->write_cd = (GIConv) -1;
69   channel->read_buf = NULL; /* Lazy allocate buffers */
70   channel->encoded_read_buf = NULL;
71   channel->write_buf = NULL;
72   channel->partial_write_buf[0] = '\0';
73   channel->use_buffer = TRUE;
74   channel->do_encode = FALSE;
75   channel->close_on_unref = FALSE;
76 }
77
78 void 
79 g_io_channel_ref (GIOChannel *channel)
80 {
81   g_return_if_fail (channel != NULL);
82
83   channel->ref_count++;
84 }
85
86 void 
87 g_io_channel_unref (GIOChannel *channel)
88 {
89   g_return_if_fail (channel != NULL);
90
91   channel->ref_count--;
92   if (channel->ref_count == 0)
93     {
94       if (channel->close_on_unref)
95         g_io_channel_close (channel);
96       else
97         g_io_channel_purge (channel);
98       g_free (channel->encoding);
99       if (channel->read_cd != (GIConv) -1)
100         g_iconv_close (channel->read_cd);
101       if (channel->write_cd != (GIConv) -1)
102         g_iconv_close (channel->write_cd);
103       g_free (channel->line_term);
104       if (channel->read_buf)
105         g_string_free (channel->read_buf, TRUE);
106       if (channel->write_buf)
107         g_string_free (channel->write_buf, TRUE);
108       if (channel->encoded_read_buf)
109         g_string_free (channel->encoded_read_buf, TRUE);
110       channel->funcs->io_free (channel);
111     }
112 }
113
114 static GIOError
115 g_io_error_get_from_g_error (GIOStatus status,
116                              GError *err)
117 {
118   switch (status)
119     {
120       case G_IO_STATUS_NORMAL:
121       case G_IO_STATUS_EOF:
122         return G_IO_ERROR_NONE;
123       case G_IO_STATUS_AGAIN:
124         return G_IO_ERROR_AGAIN;
125       case G_IO_STATUS_ERROR:
126         if (err->domain != G_IO_CHANNEL_ERROR)
127           return G_IO_ERROR_UNKNOWN;
128         switch (err->code)
129           {
130             case G_IO_CHANNEL_ERROR_INVAL:
131               return G_IO_ERROR_INVAL;
132             default:
133               return G_IO_ERROR_UNKNOWN;
134           }
135       default:
136         g_assert_not_reached ();
137         return G_IO_ERROR_UNKNOWN; /* Keep the compiler happy */
138     }
139 }
140
141 /**
142  * g_io_channel_read:
143  * @channel: a #GIOChannel. 
144  * @buf: a buffer to read the data into (which should be at least count bytes long).
145  * @count: the number of bytes to read from the #GIOChannel.
146  * @bytes_read: returns the number of bytes actually read. 
147  * 
148  * Reads data from a #GIOChannel. This function is depricated. New code should
149  * use g_io_channel_read_chars() instead.
150  * 
151  * Return value: %G_IO_ERROR_NONE if the operation was successful. 
152  **/
153 GIOError 
154 g_io_channel_read (GIOChannel *channel, 
155                    gchar      *buf, 
156                    gsize       count,
157                    gsize      *bytes_read)
158 {
159   GError *err = NULL;
160   GIOError error;
161   GIOStatus status;
162
163   g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
164   g_return_val_if_fail (bytes_read != NULL, G_IO_ERROR_UNKNOWN);
165
166   status = channel->funcs->io_read (channel, buf, count, bytes_read, &err);
167
168   error = g_io_error_get_from_g_error (status, err);
169
170   if (err)
171     g_error_free (err);
172
173   return error;
174 }
175
176 /**
177  * g_io_channel_write:
178  * @channel:  a #GIOChannel.
179  * @buf: the buffer containing the data to write. 
180  * @count: the number of bytes to write.
181  * @bytes_written:  the number of bytes actually written.
182  * 
183  * Writes data to a #GIOChannel. This function is depricated. New code should
184  * use g_io_channel_write_chars() instead.
185  * 
186  * Return value:  %G_IO_ERROR_NONE if the operation was successful.
187  **/
188 GIOError 
189 g_io_channel_write (GIOChannel  *channel, 
190                     const gchar *buf, 
191                     gsize        count,
192                     gsize       *bytes_written)
193 {
194   GError *err = NULL;
195   GIOError error;
196   GIOStatus status;
197
198   g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
199   g_return_val_if_fail (bytes_written != NULL, G_IO_ERROR_UNKNOWN);
200
201   status = channel->funcs->io_write (channel, buf, count, bytes_written, &err);
202
203   error = g_io_error_get_from_g_error (status, err);
204
205   if (err)
206     g_error_free (err);
207
208   return error;
209 }
210
211 /**
212  * g_io_channel_seek:
213  * @channel: a #GIOChannel. 
214  * @offset: an offset, in bytes, which is added to the position specified by @type
215  * @type: the position in the file, which can be %G_SEEK_CUR (the current
216  *        position), %G_SEEK_SET (the start of the file), or %G_SEEK_END (the end of the
217  *        file).
218  * 
219  * Sets the current position in the #GIOChannel, similar to the standard library
220  * function fseek(). This function is depricated. New code should
221  * use g_io_channel_seek_position() instead.
222  * 
223  * Return value: %G_IO_ERROR_NONE if the operation was successful.
224  **/
225 GIOError 
226 g_io_channel_seek  (GIOChannel   *channel,
227                     glong         offset, 
228                     GSeekType     type)
229 {
230   GError *err = NULL;
231   GIOError error;
232   GIOStatus status;
233
234   g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
235   g_return_val_if_fail (channel->is_seekable, G_IO_ERROR_UNKNOWN);
236
237   switch (type)
238     {
239       case G_SEEK_CUR:
240       case G_SEEK_SET:
241       case G_SEEK_END:
242         break;
243       default:
244         g_warning ("g_io_channel_seek: unknown seek type");
245         return G_IO_ERROR_UNKNOWN;
246     }
247
248   status = channel->funcs->io_seek (channel, offset, type, &err);
249
250   error = g_io_error_get_from_g_error (status, err);
251
252   if (err)
253     g_error_free (err);
254
255   return error;
256 }
257
258 /* The function g_io_channel_new_file() is prototyped in both
259  * giounix.c and giowin32.c, so we stick its documentation here.
260  */
261
262 /**
263  * g_io_channel_new_file:
264  * @filename: A string containing the name of a file.
265  * @mode: One of "r", "w", "a", "r+", "w+", "a+". These have
266  *        the same meaning as in fopen().
267  * @error: A location to return an error of type %G_IO_FILE_ERROR.
268  *
269  * Open a file @filename as a #GIOChannel using mode @mode. This
270  * channel will be closed when the last reference to it is dropped,
271  * so there is no need to call g_io_channel_close() (though doing
272  * so will not cause problems, as long as no attempt is made to
273  * access the channel after it is closed).
274  *
275  * Return value: A #GIOChannel on success, %NULL on failure.
276  **/
277
278 /**
279  * g_io_channel_close:
280  * @channel: A #GIOChannel
281  * 
282  * Close an IO channel. Any pending data to be written will be
283  * flushed, ignoring errors. The channel will not be freed until the
284  * last reference is dropped using g_io_channel_unref(). This
285  * function is deprecated: you should use g_io_channel_shutdown()
286  * instead.
287  **/
288 void
289 g_io_channel_close (GIOChannel *channel)
290 {
291   GError *err = NULL;
292   
293   g_return_if_fail (channel != NULL);
294
295   g_io_channel_purge (channel);
296
297   channel->funcs->io_close (channel, &err);
298
299   if (err)
300     { /* No way to return the error */
301       g_warning ("Error closing channel: %s", err->message);
302       g_error_free (err);
303     }
304   
305   channel->close_on_unref = FALSE; /* Because we already did */
306   channel->is_readable = FALSE;
307   channel->is_writeable = FALSE;
308   channel->is_seekable = FALSE;
309 }
310
311 /**
312  * g_io_channel_shutdown:
313  * @channel: a #GIOChannel
314  * @flush: if %TRUE, flush pending
315  * @err: location to store a #GIOChannelError
316  * 
317  * Close an IO channel. Any pending data to be written will be
318  * flushed. The channel will not be freed until the
319  * last reference is dropped using g_io_channel_unref().
320  *
321  * Return value:
322  **/
323 GIOStatus
324 g_io_channel_shutdown (GIOChannel *channel,
325                        gboolean    flush,
326                        GError    **err)
327 {
328   GIOStatus status, result;
329   GError *tmperr = NULL;
330   
331   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
332   g_return_val_if_fail (err == NULL || *err == NULL, G_IO_STATUS_ERROR);
333
334   if (flush && channel->write_buf && channel->write_buf->len > 0)
335     {
336       GIOFlags flags;
337       
338       /* Set the channel to blocking, to avoid a busy loop
339        */
340       flags = g_io_channel_get_flags (channel);
341       /* Ignore any errors here, they're irrelevant */
342       g_io_channel_set_flags (channel, flags & ~G_IO_FLAG_NONBLOCK, NULL);
343
344       result = g_io_channel_flush (channel, &tmperr);
345
346       if (channel->partial_write_buf[0] != '\0')
347         {
348           g_warning ("Partial character at end of write buffer not flushed.\n");
349           channel->partial_write_buf[0] = '\0';
350         }
351     }
352   else
353     result = G_IO_STATUS_NORMAL;
354
355   status = channel->funcs->io_close (channel, err);
356
357   channel->close_on_unref = FALSE; /* Because we already did */
358   channel->is_readable = FALSE;
359   channel->is_writeable = FALSE;
360   channel->is_seekable = FALSE;
361
362   if (status != G_IO_STATUS_NORMAL)
363     {
364       g_clear_error (&tmperr);
365       return status;
366     }
367   else if (result != G_IO_STATUS_NORMAL)
368     {
369       g_propagate_error (err, tmperr);
370       return result;
371     }
372   else
373     return G_IO_STATUS_NORMAL;
374 }
375
376 /* This function is used for the final flush on close or unref */
377 static void
378 g_io_channel_purge (GIOChannel *channel)
379 {
380   GError *err = NULL;
381   GIOStatus status;
382
383   g_return_if_fail (channel != NULL);
384
385   if (channel->write_buf && channel->write_buf->len > 0)
386     {
387       GIOFlags flags;
388       
389       /* Set the channel to blocking, to avoid a busy loop
390        */
391       flags = g_io_channel_get_flags (channel);
392       g_io_channel_set_flags (channel, flags & ~G_IO_FLAG_NONBLOCK, NULL);
393
394       status = g_io_channel_flush (channel, &err);
395
396       if (err)
397         { /* No way to return the error */
398           g_warning ("Error flushing string: %s", err->message);
399           g_error_free (err);
400         }
401     }
402
403   /* Flush these in case anyone tries to close without unrefing */
404
405   if (channel->read_buf)
406     g_string_truncate (channel->read_buf, 0);
407   if (channel->write_buf)
408     g_string_truncate (channel->write_buf, 0);
409   if (channel->do_encode)
410     {
411       if (channel->encoded_read_buf)
412         g_string_truncate (channel->encoded_read_buf, 0);
413
414       if (channel->partial_write_buf[0] != '\0')
415         {
416           g_warning ("Partial character at end of write buffer not flushed.\n");
417           channel->partial_write_buf[0] = '\0';
418         }
419     }
420 }
421
422 GSource *
423 g_io_create_watch (GIOChannel  *channel,
424                    GIOCondition condition)
425 {
426   g_return_val_if_fail (channel != NULL, NULL);
427
428   return channel->funcs->io_create_watch (channel, condition);
429 }
430
431 guint 
432 g_io_add_watch_full (GIOChannel    *channel,
433                      gint           priority,
434                      GIOCondition   condition,
435                      GIOFunc        func,
436                      gpointer       user_data,
437                      GDestroyNotify notify)
438 {
439   GSource *source;
440   guint id;
441   
442   g_return_val_if_fail (channel != NULL, 0);
443
444   source = g_io_create_watch (channel, condition);
445
446   if (priority != G_PRIORITY_DEFAULT)
447     g_source_set_priority (source, priority);
448   g_source_set_callback (source, (GSourceFunc)func, user_data, notify);
449
450   id = g_source_attach (source, NULL);
451   g_source_unref (source);
452
453   return id;
454 }
455
456 guint 
457 g_io_add_watch (GIOChannel    *channel,
458                 GIOCondition   condition,
459                 GIOFunc        func,
460                 gpointer       user_data)
461 {
462   return g_io_add_watch_full (channel, G_PRIORITY_DEFAULT, condition, func, user_data, NULL);
463 }
464
465 /**
466  * g_io_channel_get_buffer_condition:
467  * @channel: A #GIOChannel
468  *
469  * This function returns a #GIOCondition depending on the status of the
470  * internal buffers in the #GIOChannel. Only the flags %G_IO_IN and
471  * %G_IO_OUT will be set.
472  *
473  * Return value: A #GIOCondition
474  **/
475 GIOCondition
476 g_io_channel_get_buffer_condition (GIOChannel *channel)
477 {
478   GIOCondition condition = 0;
479
480   if ((channel->read_buf && (channel->read_buf->len > 0)) /* FIXME full chars how? */
481     || (channel->encoded_read_buf && (channel->encoded_read_buf->len > 0)))
482     condition &= G_IO_IN;
483
484   if (channel->write_buf && (channel->write_buf->len < channel->buf_size))
485     condition &= G_IO_OUT;
486
487   return condition;
488 }
489
490 /**
491  * g_io_channel_error_from_errno:
492  * @en: An errno error number, e.g. EINVAL
493  *
494  * Return value: A #GIOChannelError error number, e.g. %G_IO_CHANNEL_ERROR_INVAL
495  **/
496 GIOChannelError
497 g_io_channel_error_from_errno (gint en)
498 {
499 #ifdef EAGAIN
500   g_return_val_if_fail (en != EAGAIN, G_IO_CHANNEL_ERROR_FAILED);
501 #endif
502 #ifdef EINTR
503   g_return_val_if_fail (en != EINTR, G_IO_CHANNEL_ERROR_FAILED);
504 #endif
505
506   switch (en)
507     {
508 #ifdef EBADF
509     case EBADF:
510       g_warning("Invalid file descriptor.\n");
511       return G_IO_CHANNEL_ERROR_FAILED;
512 #endif
513
514 #ifdef EFAULT
515     case EFAULT:
516       g_warning("File descriptor outside valid address space.\n");
517       return G_IO_CHANNEL_ERROR_FAILED;
518 #endif
519
520 #ifdef EFBIG
521     case EFBIG:
522       return G_IO_CHANNEL_ERROR_FBIG;
523 #endif
524
525 #ifdef EINVAL
526     case EINVAL:
527       return G_IO_CHANNEL_ERROR_INVAL;
528 #endif
529
530 #ifdef EIO
531     case EIO:
532       return G_IO_CHANNEL_ERROR_IO;
533 #endif
534
535 #ifdef EISDIR
536     case EISDIR:
537       return G_IO_CHANNEL_ERROR_ISDIR;
538 #endif
539
540 #ifdef ENOSPC
541     case ENOSPC:
542       return G_IO_CHANNEL_ERROR_NOSPC;
543 #endif
544
545 #ifdef ENXIO
546     case ENXIO:
547       return G_IO_CHANNEL_ERROR_NXIO;
548 #endif
549
550 #ifdef EOVERFLOW
551     case EOVERFLOW:
552       return G_IO_CHANNEL_ERROR_OVERFLOW;
553 #endif
554
555 #ifdef EPIPE
556     case EPIPE:
557       return G_IO_CHANNEL_ERROR_PIPE;
558 #endif
559
560     default:
561       return G_IO_CHANNEL_ERROR_FAILED;
562     }
563 }
564
565 /**
566  * g_io_channel_set_buffer_size:
567  * @channel: a #GIOChannel
568  * @size: the size of the buffer. 0 == pick a good size
569  *
570  * Set the buffer size.
571  **/  
572 void
573 g_io_channel_set_buffer_size (GIOChannel        *channel,
574                               gsize              size)
575 {
576   g_return_if_fail (channel != NULL);
577
578   if (size == 0)
579     size = G_IO_NICE_BUF_SIZE;
580
581   if (size < 10) /* Needs to be larger than the widest char in any encoding */
582     size = 10;
583
584   channel->buf_size = size;
585 }
586
587 /**
588  * g_io_channel_get_buffer_size:
589  * @channel: a #GIOChannel
590  *
591  * Get the buffer size.
592  *
593  * Return value: the size of the buffer.
594  **/  
595 gsize
596 g_io_channel_get_buffer_size (GIOChannel        *channel)
597 {
598   g_return_val_if_fail (channel != NULL, 0);
599
600   return channel->buf_size;
601 }
602
603 /**
604  * g_io_channel_set_line_term:
605  * @channel: a #GIOChannel
606  * @line_term: The line termination string. Use %NULL for auto detect.
607  *
608  * This sets the string that #GIOChannel uses to determine
609  * where in the file a line break occurs.
610  **/
611 void
612 g_io_channel_set_line_term (GIOChannel  *channel,
613                             const gchar *line_term)
614 {
615   g_return_if_fail (channel != NULL);
616   g_return_if_fail (!line_term || line_term[0]); /* Disallow "" */
617   g_return_if_fail (!line_term || g_utf8_validate (line_term, -1, NULL));
618                    /* Require valid UTF-8 */
619
620   g_free (channel->line_term);
621   channel->line_term = g_strdup (line_term);
622 }
623
624 /**
625  * g_io_channel_get_line_term:
626  * @channel: a #GIOChannel
627  *
628  * This returns the string that #GIOChannel uses to determine
629  * where in the file a line break occurs. A value of %NULL
630  * indicates auto detection.
631  *
632  * Return value: The line termination string. This value
633  *   is owned by GLib and must not be freed.
634  **/
635 G_CONST_RETURN gchar*
636 g_io_channel_get_line_term (GIOChannel  *channel)
637 {
638   g_return_val_if_fail (channel != NULL, 0);
639
640   return channel->line_term;
641 }
642
643 /**
644  * g_io_channel_set_flags:
645  * @channel: a #GIOChannel
646  * @flags: the flags to set on the channel
647  * @error: A location to return an error of type #GIOChannelError
648  *
649  * Return value:
650  **/
651 GIOStatus
652 g_io_channel_set_flags (GIOChannel *channel,
653                         GIOFlags    flags,
654                         GError    **error)
655 {
656   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
657   g_return_val_if_fail ((error == NULL) || (*error == NULL),
658                         G_IO_STATUS_ERROR);
659
660   return (* channel->funcs->io_set_flags)(channel,
661                                           flags & G_IO_FLAG_SET_MASK,
662                                           error);
663 }
664
665 /**
666  * g_io_channel_get_flags:
667  * @channel: a #GIOChannel
668  *
669  * Gets the current flags for a #GIOChannel, including read-only
670  * flags such as %G_IO_FLAG_IS_READABLE.
671  *
672  * Return value: the flags which are set on the channel
673  **/
674 GIOFlags
675 g_io_channel_get_flags (GIOChannel *channel)
676 {
677   GIOFlags flags;
678
679   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
680
681   flags = (* channel->funcs->io_get_flags) (channel);
682
683   /* Cross implementation code */
684
685   if (channel->is_seekable)
686     flags |= G_IO_FLAG_IS_SEEKABLE;
687   if (channel->is_readable)
688     flags |= G_IO_FLAG_IS_READABLE;
689   if (channel->is_writeable)
690     flags |= G_IO_FLAG_IS_WRITEABLE;
691
692   return flags;
693 }
694
695 /**
696  * g_io_channel_seek_position:
697  * @channel: a #GIOChannel
698  * @offset: The offset in bytes from the position specified by @type
699  * @type: a #GSeekType. The type %G_SEEK_CUR is only allowed if
700  *        the channel has the default encoding or the
701  *        encoding %G_IO_CHANNEL_ENCODE_RAW for raw file access.
702  * @error: A location to return an error of type #GIOChannelError
703  *
704  * Replacement for g_io_channel_seek() with the new API.
705  *
706  * Return value:
707  **/
708 GIOStatus
709 g_io_channel_seek_position      (GIOChannel* channel,
710                                  glong       offset,
711                                  GSeekType   type,
712                                  GError    **error)
713 {
714   GIOStatus status;
715
716   /* For files, only one of the read and write buffers can contain data.
717    * For sockets, both can contain data.
718    */
719
720   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
721   g_return_val_if_fail ((error == NULL) || (*error == NULL),
722                         G_IO_STATUS_ERROR);
723   g_return_val_if_fail (channel->is_seekable, G_IO_STATUS_ERROR);
724
725   switch (type)
726     {
727       case G_SEEK_CUR: /* The user is seeking relative to the head of the buffer */
728         if (channel->use_buffer)
729           {
730             if (channel->encoded_read_buf && channel->encoded_read_buf->len > 0)
731               {
732                 g_warning ("Seek type G_SEEK_CUR not allowed for this"
733                   " channel's encoding.\n");
734                 return G_IO_STATUS_ERROR;
735               }
736           if (channel->read_buf)
737             offset -= channel->read_buf->len;
738           }
739         break;
740       case G_SEEK_SET:
741       case G_SEEK_END:
742         break;
743       default:
744         g_warning ("g_io_channel_seek_position: unknown seek type");
745         return G_IO_STATUS_ERROR;
746     }
747
748   if (channel->use_buffer)
749     {
750       status = g_io_channel_flush (channel, error);
751       if (status != G_IO_STATUS_NORMAL)
752         return status;
753     }
754
755   status = channel->funcs->io_seek (channel, offset, type, error);
756
757   if ((status == G_IO_STATUS_NORMAL) && (channel->use_buffer))
758     {
759       if (channel->read_buf)
760         g_string_truncate (channel->read_buf, 0);
761       if (channel->do_encode) /* Conversion state no longer matches position in file */
762         {
763           g_iconv (channel->read_cd, NULL, NULL, NULL, NULL);
764           g_iconv (channel->write_cd, NULL, NULL, NULL, NULL);
765           if (channel->encoded_read_buf)
766             g_string_truncate (channel->encoded_read_buf, 0);
767         }
768       if (channel->partial_write_buf[0] != '\0')
769         {
770           g_warning ("Partial character at end of write buffer not flushed.\n");
771           channel->partial_write_buf[0] = '\0';
772         }
773     }
774
775   return status;
776 }
777
778 /**
779  * g_io_channel_flush:
780  * @channel: a #GIOChannel
781  * @error: location to store an error of type #GIOChannelError
782  *
783  * Flush the write buffer for the GIOChannel.
784  *
785  * Return value: the status of the operation: One of
786  *   G_IO_CHANNEL_NORMAL, G_IO_CHANNEL_AGAIN, or
787  *   G_IO_CHANNEL_ERROR.
788  **/
789 GIOStatus
790 g_io_channel_flush (GIOChannel  *channel,
791                     GError     **error)
792 {
793   GIOStatus status;
794   gsize this_time = 1, bytes_written = 0;
795
796   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
797   g_return_val_if_fail ((error == NULL) || (*error == NULL), G_IO_STATUS_ERROR);
798
799   if (channel->write_buf && channel->write_buf->len > 0)
800     return G_IO_STATUS_NORMAL;
801
802   do
803     {
804       g_assert (this_time > 0);
805
806       status = channel->funcs->io_write (channel,
807                                       channel->write_buf->str + bytes_written,
808                                       channel->write_buf->len - bytes_written,
809                                       &this_time, error);
810       bytes_written += this_time;
811     }
812   while ((bytes_written < channel->write_buf->len)
813          && (status == G_IO_STATUS_NORMAL));
814
815   g_string_erase (channel->write_buf, 0, bytes_written);
816
817   return status;
818 }
819
820 /**
821  * g_io_channel_set_buffered:
822  * @channel: a #GIOChannel
823  * @buffered: whether to set the channel buffered or unbuffered
824  *
825  * The buffering state can only be set if the channel's encoding
826  * is %NULL. For any other encoding, the channel must be buffered.
827  *
828  * The default state of the channel is buffered.
829  **/
830 void
831 g_io_channel_set_buffered       (GIOChannel *channel,
832                                  gboolean    buffered)
833 {
834   g_return_if_fail (channel != NULL);
835
836   if (channel->encoding != NULL)
837     {
838       g_warning ("Need to have NULL encoding to set the buffering state of the "
839                  "channel.\n");
840       return;
841     }
842
843   g_return_if_fail (!channel->read_buf || channel->read_buf->len == 0);
844   g_return_if_fail (!channel->write_buf || channel->write_buf->len == 0);
845
846   channel->use_buffer = buffered;
847 }
848
849 /**
850  * g_io_channel_get_buffered:
851  * @channel: a #GIOChannel
852  *
853  * Return Value: the buffering state of the channel
854  **/
855 gboolean
856 g_io_channel_get_buffered       (GIOChannel *channel)
857 {
858   g_return_val_if_fail (channel != NULL, FALSE);
859
860   return channel->use_buffer;
861 }
862
863 /**
864  * g_io_channel_set_encoding:
865  * @channel: a #GIOChannel
866  * @encoding: the encoding type
867  * @error: location to store an error of type #GConvertError.
868  *
869  * Set the encoding for the input/output of the channel. The internal
870  * encoding is always UTF-8. The default encoding for the
871  * external file is UTF-8.
872  *
873  * The encoding %NULL is safe to use with binary data.
874  * Encodings other than %NULL must use a buffered channel.
875  * Encodings other than %NULL and UTF-8 cannot
876  * use g_io_channel_seek_position() with seek type %G_SEEK_CUR,
877  * and cannot mix reading and writing if the channel is
878  * a file without first doing a seek of type %G_SEEK_SET or
879  * %G_SEEK_END.
880  *
881  * The encoding can only be set under three conditions:
882  *
883  * 1. The channel was just created, and has not been written to
884  *    or read from yet.
885  *
886  * 2. The channel is a file, and the file pointer was just
887  *    repositioned by a call to g_io_channel_seek_position().
888  *    (This flushes all the internal buffers.)
889  *
890  * 3. The current encoding is %NULL or UTF-8.
891  *
892  * Return Value: %G_IO_STATUS_NORMAL if the encoding was succesfully set.
893  **/
894 GIOStatus
895 g_io_channel_set_encoding (GIOChannel   *channel,
896                            const gchar  *encoding,
897                            GError      **error)
898 {
899   GIConv read_cd, write_cd;
900   gboolean did_encode;
901
902   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
903   g_return_val_if_fail ((error == NULL) || (*error == NULL), G_IO_STATUS_ERROR);
904
905   /* Make sure the encoded buffers are empty */
906
907   g_return_val_if_fail (!channel->encoded_read_buf ||
908                         channel->encoded_read_buf->len == 0, G_IO_STATUS_ERROR);
909   g_return_val_if_fail (channel->partial_write_buf[0] == '\0', G_IO_STATUS_ERROR);
910
911   if (!channel->use_buffer)
912     {
913       g_warning ("Need to set the channel buffered before setting the encoding.\n");
914       g_warning ("Assuming this is what you meant and acting accordingly.\n");
915
916       channel->use_buffer = TRUE;
917     }
918
919   did_encode = channel->do_encode;
920
921   if (!encoding || strcmp (encoding, "UTF8") == 0 || strcmp (encoding, "UTF-8") == 0)
922     {
923       channel->do_encode = FALSE;
924       read_cd = write_cd = (GIConv) -1;
925     }
926   else
927     {
928       gint err = 0;
929       const gchar *from_enc = NULL, *to_enc = NULL;
930
931       if (channel->is_readable)
932         {
933           read_cd = g_iconv_open ("UTF-8", encoding);
934
935           if (read_cd == (GIConv) -1)
936             {
937               err = errno;
938               from_enc = "UTF-8";
939               to_enc = encoding;
940             }
941         }
942       else
943         read_cd = (GIConv) -1;
944
945       if (channel->is_writeable && err == 0)
946         {
947           write_cd = g_iconv_open (encoding, "UTF-8");
948
949           if (write_cd == (GIConv) -1)
950             {
951               err = errno;
952               from_enc = encoding;
953               to_enc = "UTF-8";
954             }
955         }
956       else
957         write_cd = (GIConv) -1;
958
959       if (err != 0)
960         {
961           g_assert (from_enc);
962           g_assert (to_enc);
963
964           if (err == EINVAL)
965             g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
966                          _("Conversion from character set `%s' to `%s' is not supported"),
967                          from_enc, to_enc);
968           else
969             g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
970                          _("Could not open converter from `%s' to `%s': %s"),
971                          from_enc, to_enc, strerror (errno));
972
973           if (read_cd != (GIConv) -1)
974             g_iconv_close (read_cd);
975           if (write_cd != (GIConv) -1)
976             g_iconv_close (write_cd);
977
978           return G_IO_STATUS_ERROR;
979         }
980
981       channel->do_encode = TRUE;
982     }
983
984   /* The encoding is ok, so set the fields in channel */
985
986   if (channel->read_cd != (GIConv) -1)
987     g_iconv_close (channel->read_cd);
988   if (channel->write_cd != (GIConv) -1)
989     g_iconv_close (channel->write_cd);
990
991   channel->read_cd = read_cd;
992   channel->write_cd = write_cd;
993
994   g_free (channel->encoding);
995   channel->encoding = g_strdup (encoding);
996
997   return G_IO_STATUS_NORMAL;
998 }
999
1000 /**
1001  * g_io_channel_get_encoding:
1002  * @channel: a #GIOChannel
1003  *
1004  * Get the encoding for the input/output of the channel. The internal
1005  * encoding is always UTF-8. The encoding %G_IO_CHANNEL_ENCODE_RAW
1006  * disables encoding and turns off internal buffering. Both
1007  * %G_IO_CHANNEL_ENCODE_RAW and the default (no encoding, but buffered)
1008  * are safe to use with binary data.
1009  *
1010  * Return value: A string containing the encoding, this string is
1011  *   owned by GLib and must not be freed.
1012  **/
1013 G_CONST_RETURN gchar*
1014 g_io_channel_get_encoding (GIOChannel      *channel)
1015 {
1016   g_return_val_if_fail (channel != NULL, NULL);
1017
1018   return channel->encoding;
1019 }
1020
1021 static GIOStatus
1022 g_io_channel_fill_buffer (GIOChannel *channel,
1023                           GError    **err)
1024 {
1025   gsize read_size, cur_len, oldlen;
1026   GIOStatus status;
1027
1028   if (channel->is_seekable && channel->write_buf && channel->write_buf->len > 0)
1029     {
1030       status = g_io_channel_flush (channel, err);
1031       if (status != G_IO_STATUS_NORMAL)
1032         return status;
1033     }
1034   if (channel->is_seekable && channel->partial_write_buf[0] != '\0')
1035     {
1036       g_warning ("Partial character at end of write buffer not flushed.\n");
1037       channel->partial_write_buf[0] = '\0';
1038     }
1039
1040   if (!channel->read_buf)
1041     channel->read_buf = g_string_sized_new (channel->buf_size);
1042
1043   cur_len = channel->read_buf->len;
1044
1045   g_string_set_size (channel->read_buf, channel->read_buf->len + channel->buf_size);
1046
1047   status = channel->funcs->io_read (channel, channel->read_buf->str + cur_len,
1048                                     channel->buf_size, &read_size, err);
1049
1050   g_assert ((status == G_IO_STATUS_NORMAL) || (read_size == 0));
1051
1052   g_string_truncate (channel->read_buf, read_size + cur_len);
1053
1054   if ((status != G_IO_STATUS_NORMAL)
1055     && ((status != G_IO_STATUS_EOF) || (channel->read_buf->len == 0)))
1056     return status;
1057
1058   g_assert (channel->read_buf->len > 0);
1059
1060   if (channel->encoded_read_buf)
1061     oldlen = channel->encoded_read_buf->len;
1062   else
1063     oldlen = 0;
1064
1065   if (channel->do_encode)
1066     {
1067       size_t errnum, inbytes_left, outbytes_left;
1068       gchar *inbuf, *outbuf;
1069
1070       if (!channel->encoded_read_buf)
1071         channel->encoded_read_buf = g_string_sized_new (channel->buf_size);
1072
1073 reencode:
1074
1075       inbytes_left = channel->read_buf->len;
1076       outbytes_left = MIN (channel->buf_size / 4,
1077                            channel->encoded_read_buf->allocated_len
1078                            - channel->encoded_read_buf->len);
1079
1080       g_string_set_size (channel->encoded_read_buf,
1081                          channel->encoded_read_buf->len + outbytes_left);
1082
1083       inbuf = channel->read_buf->str;
1084       outbuf = channel->encoded_read_buf->str + channel->encoded_read_buf->len
1085                - outbytes_left;
1086
1087       errnum = g_iconv (channel->read_cd, &inbuf, &inbytes_left,
1088                         &outbuf, &outbytes_left);
1089
1090       g_string_erase (channel->read_buf, 0,
1091                       channel->read_buf->len - inbytes_left);
1092       g_string_truncate (channel->encoded_read_buf,
1093                          channel->encoded_read_buf->len - outbytes_left);
1094
1095       if (errnum == (size_t) -1)
1096         {
1097           switch (errno)
1098             {
1099               case EINVAL:
1100                 if ((oldlen == channel->encoded_read_buf->len)
1101                   && (status == G_IO_STATUS_EOF))
1102                   status = G_IO_STATUS_EOF;
1103                 else
1104                   status = G_IO_STATUS_NORMAL;
1105                 break;
1106               case E2BIG:
1107                 goto reencode;
1108               case EILSEQ:
1109                 if (oldlen < channel->encoded_read_buf->len)
1110                   status = G_IO_STATUS_NORMAL;
1111                 else
1112                   {
1113                     g_set_error (err, G_CONVERT_ERROR,
1114                       G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1115                       _("Invalid byte sequence in conversion input"));
1116                     return G_IO_STATUS_ERROR;
1117                   }
1118                 break;
1119               default:
1120                 g_set_error (err, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1121                   _("Error during conversion: %s"), strerror (errno));
1122                 return G_IO_STATUS_ERROR;
1123             }
1124         }
1125       g_assert ((status != G_IO_STATUS_NORMAL)
1126                || (channel->encoded_read_buf->len > 0));
1127     }
1128   else if (channel->encoding) /* UTF-8 */
1129     {
1130       gchar *nextchar, *lastchar;
1131
1132       nextchar = channel->read_buf->str;
1133       lastchar = channel->read_buf->str + channel->read_buf->len;
1134
1135       while (nextchar < lastchar)
1136         {
1137           gunichar val_char;
1138
1139           val_char = g_utf8_get_char_validated (nextchar, lastchar - nextchar);
1140
1141           switch (val_char)
1142             {
1143               case -2:
1144                 /* stop, leave partial character in buffer */
1145                 lastchar = nextchar;
1146                 break;
1147               case -1:
1148                 if (oldlen > channel->encoded_read_buf->len)
1149                   status = G_IO_STATUS_NORMAL;
1150                 else
1151                   {
1152                     g_set_error (err, G_CONVERT_ERROR,
1153                       G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1154                       _("Invalid byte sequence in conversion input"));
1155                     status = G_IO_STATUS_ERROR;
1156                   }
1157                 lastchar = nextchar;
1158                 break;
1159               default:
1160                 nextchar = g_utf8_next_char (nextchar);
1161                 break;
1162             }
1163         }
1164
1165       if (lastchar > channel->read_buf->str)
1166         {
1167           gint copy_len = lastchar - channel->read_buf->str;
1168
1169           if (!channel->encoded_read_buf)
1170             channel->encoded_read_buf = g_string_sized_new (channel->buf_size);
1171
1172           g_string_append_len (channel->encoded_read_buf, channel->read_buf->str,
1173                                copy_len);
1174           g_string_erase (channel->read_buf, 0, copy_len);
1175         }
1176     }
1177
1178   return status;
1179 }
1180
1181 /**
1182  * g_io_channel_read_line:
1183  * @channel: a #GIOChannel
1184  * @str_return: The line read from the #GIOChannel, not including the
1185  *              line terminator. This data should be freed with g_free()
1186  *              when no longer needed. This
1187  *              is a null terminated string. If a @length of zero is
1188  *              returned, this will be %NULL instead.
1189  * @length: location to store length of the read data, or %NULL
1190  * @terminator_pos: location to store position of line terminator, or %NULL
1191  * @error: A location to return an error of type #GConvertError
1192  *         or #GIOChannelError
1193  *
1194  * Read a line, not including the terminating character(s),
1195  * from a #GIOChannel into a newly allocated string.
1196  * @length will contain allocated memory if the return
1197  * is %G_IO_STATUS_NORMAL.
1198  *
1199  * Return value: a newly allocated string. Free this string
1200  *   with g_free() when you are done with it.
1201  **/
1202 GIOStatus
1203 g_io_channel_read_line (GIOChannel *channel,
1204                         gchar     **str_return,
1205                         gsize      *length,
1206                         gsize      *terminator_pos,
1207                         GError    **error)
1208 {
1209   GIOStatus status;
1210   
1211   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1212   g_return_val_if_fail (str_return != NULL, G_IO_STATUS_ERROR);
1213   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1214                         G_IO_STATUS_ERROR);
1215   g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1216
1217   status = g_io_channel_read_line_backend (channel, length, terminator_pos, error);
1218
1219   if (status == G_IO_STATUS_NORMAL)
1220     {
1221       GString *use_buf;
1222
1223       if (channel->do_encode)
1224         use_buf = channel->encoded_read_buf;
1225       else
1226         use_buf = channel->read_buf;
1227
1228       g_assert (use_buf);
1229
1230       *str_return = g_strndup (use_buf->str, *length);
1231       g_string_erase (use_buf, 0, *length);
1232     }
1233   else
1234     *str_return = NULL;
1235   
1236   return status;
1237 }
1238
1239 /**
1240  * g_io_channel_read_line_string:
1241  * @channel: a #GIOChannel
1242  * @buffer: a #GString into which the line will be written.
1243  *          If @buffer already contains data, the new data will
1244  *          be appended to it.
1245  * @terminator_pos: location to store position of line terminator, or %NULL
1246  * @error: a location to store an error of type #GConvertError
1247  *         or #GIOChannelError
1248  *
1249  * Read a line from a #GIOChannel, using a #GString as a buffer.
1250  *
1251  * Return value:
1252  **/
1253 GIOStatus
1254 g_io_channel_read_line_string (GIOChannel *channel,
1255                                GString    *buffer,
1256                                gsize      *terminator_pos,
1257                                GError    **error)
1258 {
1259   gsize length;
1260   GIOStatus status;
1261
1262   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1263   g_return_val_if_fail (buffer != NULL, G_IO_STATUS_ERROR);
1264   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1265                         G_IO_STATUS_ERROR);
1266   g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1267
1268   if (buffer->len > 0)
1269     g_string_truncate (buffer, 0); /* clear out the buffer */
1270
1271   status = g_io_channel_read_line_backend (channel, &length, terminator_pos, error);
1272
1273   if (status == G_IO_STATUS_NORMAL)
1274     {
1275       GString *use_buf;
1276
1277       if (channel->do_encode)
1278         use_buf = channel->encoded_read_buf;
1279       else
1280         use_buf = channel->read_buf;
1281
1282       g_assert (use_buf);
1283
1284       g_string_append_len (buffer, use_buf->str, length);
1285       g_string_erase (use_buf, 0, length);
1286     }
1287
1288   return status;
1289 }
1290
1291
1292 static GIOStatus
1293 g_io_channel_read_line_backend  (GIOChannel *channel,
1294                                  gsize      *length,
1295                                  gsize      *terminator_pos,
1296                                  GError    **error)
1297 {
1298   GIOStatus status;
1299   gsize checked_to, line_term_len, line_length, got_term_len;
1300   GString *use_buf;
1301   gboolean first_time = TRUE;
1302
1303   if (!channel->use_buffer)
1304     {
1305       /* Can't do a raw read in read_line */
1306       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1307                    _("Can't do a raw read in g_io_channel_read_line_string"));
1308       return G_IO_STATUS_ERROR;
1309     }
1310
1311   if (channel->encoding)
1312     {
1313       if (!channel->encoded_read_buf)
1314         channel->encoded_read_buf = g_string_sized_new (channel->buf_size);
1315       use_buf = channel->encoded_read_buf;
1316     }
1317   else
1318     {
1319       if (!channel->read_buf)
1320         channel->read_buf = g_string_sized_new (channel->buf_size);
1321       use_buf = channel->read_buf;
1322     }
1323
1324   status = G_IO_STATUS_NORMAL;
1325
1326   if (channel->line_term)
1327     line_term_len = strlen (channel->line_term);
1328   else
1329     line_term_len = 3;
1330     /* This value used for setting checked_to, it's the longest of the four
1331      * we autodetect for.
1332      */
1333
1334   checked_to = 0;
1335
1336   while (TRUE)
1337     {
1338       gchar *nextchar, *lastchar;
1339
1340       if (!first_time || (use_buf->len == 0))
1341         {
1342 read_again:
1343           status = g_io_channel_fill_buffer (channel, error);
1344           switch (status)
1345             {
1346               case G_IO_STATUS_NORMAL:
1347                 if (use_buf->len == 0)
1348                   /* Can happen when using conversion and only read
1349                    * part of a character
1350                    */
1351                   {
1352                     first_time = FALSE;
1353                     continue;
1354                   }
1355                 break;
1356               case G_IO_STATUS_EOF:
1357                 if (use_buf->len == 0)
1358                   {
1359                     *length = 0;
1360
1361                     if (channel->do_encode && channel->read_buf->len != 0)
1362                       /* using GIConv conversion, unconverted chars */
1363                       {
1364                         g_set_error (error, G_CONVERT_ERROR,
1365                                      G_CONVERT_ERROR_PARTIAL_INPUT,
1366                                      "Leftover unconverted data in read buffer");
1367                         return G_IO_STATUS_ERROR;
1368                       }
1369                     else
1370                       return G_IO_STATUS_EOF;
1371                   }
1372                 break;
1373               default:
1374                 *length = 0;
1375                 return status;
1376             }
1377         }
1378
1379       g_assert (use_buf->len > 0);
1380
1381       first_time = FALSE;
1382
1383       lastchar = use_buf->str + strlen (use_buf->str);
1384
1385       for (nextchar = use_buf->str + checked_to; nextchar < lastchar;
1386            channel->encoding ? nextchar = g_utf8_next_char (nextchar) : nextchar++)
1387         {
1388           if (channel->line_term)
1389             {
1390               if (strncmp (channel->line_term, nextchar, line_term_len) == 0)
1391                 {
1392                   line_length = nextchar - use_buf->str;
1393                   got_term_len = line_term_len;
1394                   goto done;
1395                 }
1396             }
1397           else /* auto detect */
1398             {
1399               switch (*nextchar)
1400                 {
1401                   case '\n': /* unix */
1402                     line_length = nextchar - use_buf->str;
1403                     got_term_len = 1;
1404                     goto done;
1405                   case '\r': /* Warning: do not use with sockets */
1406                     line_length = nextchar - use_buf->str;
1407                     if ((nextchar == lastchar - 1) && (status != G_IO_STATUS_EOF)
1408                        && (lastchar == use_buf->str + use_buf->len))
1409                       goto read_again; /* Try to read more data */
1410                     if ((nextchar < lastchar - 1) && (*(nextchar + 1) == '\n')) /* dos */
1411                       got_term_len = 2;
1412                     else /* mac */
1413                       got_term_len = 1;
1414                     goto done;
1415                   case '\xe2': /* Unicode paragraph separator */
1416                     if (strncmp ("\xe2\x80\xa9", nextchar, 3) == 0)
1417                       {
1418                         line_length = nextchar - use_buf->str;
1419                         got_term_len = 3;
1420                         goto done;
1421                       }
1422                     break;
1423                   default: /* no match */
1424                     break;
1425                 }
1426             }
1427         }
1428
1429       g_assert (nextchar == lastchar); /* Valid UTF-8, didn't overshoot */
1430
1431       /* Also terminate on '\0' */
1432
1433       line_length = lastchar - use_buf->str;
1434       if (line_length < use_buf->len)
1435         {
1436           got_term_len = 0;
1437           break;
1438         }
1439
1440       /* Check for EOF */
1441
1442       if (status == G_IO_STATUS_EOF)
1443         {
1444           if (channel->encoding && channel->read_buf->len > 0)
1445             {
1446               g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1447                            "Channel terminates in a partial character");
1448               return G_IO_STATUS_ERROR;
1449             }
1450           line_length = use_buf->len;
1451           got_term_len = 0;
1452           break;
1453         }
1454
1455       if (use_buf->len > line_term_len - 1)
1456         checked_to = use_buf->len - (line_term_len - 1);
1457       else
1458         checked_to = 0;
1459     }
1460
1461 done:
1462
1463   if (terminator_pos)
1464     *terminator_pos = line_length;
1465
1466   *length = line_length + got_term_len;
1467
1468   return G_IO_STATUS_NORMAL;
1469 }
1470
1471 /**
1472  * g_io_channel_read_to_end:
1473  * @channel: a #GIOChannel
1474  * @str_return: Location to store a pointer to a string holding
1475  *              the remaining data in the #GIOChannel. This data should
1476  *              be freed with g_free() when no longer needed. This
1477  *              data is terminated by an extra null, but there may be other
1478  *              nulls in the intervening data.
1479  * @length: Location to store length of the data
1480  * @error: A location to return an error of type #GConvertError
1481  *         or #GIOChannelError
1482  *
1483  * Read all the remaining data from the file. Parameters as
1484  * for g_io_channel_read_line.
1485  *
1486  * Return value: One of #G_IO_STATUS_EOF or #G_IO_STATUS_PARTIAL_CHARS
1487  *               on success
1488  **/
1489 GIOStatus
1490 g_io_channel_read_to_end (GIOChannel    *channel,
1491                           gchar        **str_return,
1492                           gsize         *length,
1493                           GError       **error)
1494 {
1495   GIOStatus status;
1496   GString **use_buf;
1497     
1498   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1499   g_return_val_if_fail (str_return != NULL, G_IO_STATUS_ERROR);
1500   g_return_val_if_fail (length != NULL, G_IO_STATUS_ERROR);
1501   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1502     G_IO_STATUS_ERROR);
1503   g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1504
1505   *str_return = NULL;
1506   *length = 0;
1507
1508   if (!channel->use_buffer)
1509     {
1510       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1511                    _("Can't do a raw read in g_io_channel_read_to_end"));
1512       return G_IO_STATUS_ERROR;
1513     }
1514
1515   do
1516     status = g_io_channel_fill_buffer (channel, error);
1517   while (status == G_IO_STATUS_NORMAL);
1518
1519   if (status != G_IO_STATUS_EOF)
1520     return status;
1521
1522   if (channel->encoding)
1523     {
1524       if (channel->read_buf->len > 0)
1525         {
1526           g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1527                        "Channel terminates in a partial character");
1528           return G_IO_STATUS_ERROR;
1529         }
1530
1531       if (!channel->encoded_read_buf)
1532         {
1533           if (length)
1534             *length = 0;
1535           if (str_return)
1536             *str_return = g_strdup ("");
1537         }
1538
1539       use_buf = &channel->encoded_read_buf;
1540     }
1541   else
1542     use_buf = &channel->read_buf;
1543
1544   g_assert (*use_buf); /* Created by fill_buffer if it didn't previously exist */
1545
1546   if (length)
1547     *length = (*use_buf)->len;
1548
1549   if (str_return)
1550     *str_return = g_string_free (*use_buf, FALSE);
1551   else
1552     g_string_free (*use_buf, TRUE);
1553   
1554   *use_buf = NULL;
1555
1556   return G_IO_STATUS_NORMAL;
1557 }
1558
1559 /**
1560  * g_io_channel_read_chars:
1561  * @channel: a #GIOChannel
1562  * @buf: a buffer to read data into
1563  * @count: the size of the buffer. Note that the buffer may
1564  *         not be complelely filled even if there is data
1565  *         in the buffer if the remaining data is not a
1566  *         complete character.
1567  * @bytes_read: The number of bytes read.
1568  * @error: A location to return an error of type #GConvertError
1569  *         or #GIOChannelError.
1570  *
1571  * Replacement for g_io_channel_read() with the new API.
1572  *
1573  * Return value:
1574  **/
1575 GIOStatus
1576 g_io_channel_read_chars (GIOChannel     *channel,
1577                          gchar          *buf,
1578                          gsize           count,
1579                          gsize          *bytes_read,
1580                          GError        **error)
1581 {
1582   GIOStatus status;
1583   GString *use_buf;
1584
1585   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1586   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1587                         G_IO_STATUS_ERROR);
1588   g_return_val_if_fail (bytes_read != NULL, G_IO_STATUS_ERROR);
1589   g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1590
1591   if (count == 0)
1592     {
1593       *bytes_read = 0;
1594       return G_IO_STATUS_NORMAL;
1595     }
1596   g_return_val_if_fail (buf != NULL, G_IO_STATUS_ERROR);
1597
1598   if (!channel->use_buffer)
1599     {
1600       g_assert (!channel->read_buf || channel->read_buf->len == 0);
1601
1602       return channel->funcs->io_read (channel, buf, count, bytes_read, error);
1603     }
1604
1605   if (channel->encoding)
1606     {
1607       if (!channel->encoded_read_buf)
1608         channel->encoded_read_buf = g_string_sized_new (channel->buf_size);
1609       use_buf = channel->encoded_read_buf;
1610     }
1611   else
1612     {
1613       if (!channel->read_buf)
1614         channel->read_buf = g_string_sized_new (channel->buf_size);
1615       use_buf = channel->read_buf;
1616     }
1617
1618   status = G_IO_STATUS_NORMAL;
1619
1620   while (use_buf->len < MAX (count, 6) && status == G_IO_STATUS_NORMAL)
1621     /* Be sure to read in at least one full UTF-8 character
1622      * (max length 6)
1623      */
1624     status = g_io_channel_fill_buffer (channel, error);
1625
1626   switch (status)
1627     {
1628     case G_IO_STATUS_NORMAL:
1629       g_assert (use_buf->len > 0);
1630       break;
1631     case G_IO_STATUS_EOF:
1632       if (use_buf->len == 0)
1633         {
1634           *bytes_read = 0;
1635
1636           if (channel->encoding && channel->read_buf->len != 0)
1637             {
1638               g_set_error (error, G_CONVERT_ERROR,
1639                            G_CONVERT_ERROR_PARTIAL_INPUT,
1640                            "Leftover unconverted data in read buffer");
1641               return G_IO_STATUS_ERROR;
1642             }
1643           else
1644             return G_IO_STATUS_EOF;
1645         }
1646       break;
1647     case G_IO_STATUS_AGAIN:
1648       if (use_buf->len > 0)
1649         break; /* return what we have */
1650       else
1651         {
1652           *bytes_read = 0;
1653           return G_IO_STATUS_AGAIN;
1654         }
1655     default:
1656       *bytes_read = 0;
1657       return status;
1658     }
1659
1660   *bytes_read = MIN (count, use_buf->len);
1661
1662   if (channel->encoding && *bytes_read > 0)
1663     /* Don't validate for NULL encoding, binary safe */
1664     {
1665       gchar *nextchar, *prevchar = NULL;
1666
1667       nextchar = use_buf->str;
1668
1669       while (nextchar < use_buf->str + *bytes_read)
1670         {
1671           prevchar = nextchar;
1672           nextchar = g_utf8_next_char (nextchar);
1673         }
1674
1675       if (nextchar > use_buf->str + *bytes_read)
1676         *bytes_read = prevchar - use_buf->str;
1677
1678       g_assert (*bytes_read > 0 || count < 6);
1679     }
1680
1681   memcpy (buf, use_buf->str, *bytes_read);
1682   g_string_erase (use_buf, 0, *bytes_read);
1683
1684   return G_IO_STATUS_NORMAL;
1685 }
1686
1687 /**
1688  * g_io_channel_write_chars:
1689  * @channel: a #GIOChannel
1690  * @buf: a buffer to write data from
1691  * @count: the size of the buffer. If -1, the buffer
1692  *         is taken to be a nul terminated string.
1693  * @bytes_written: The number of bytes written. This can be nonzero
1694  *                 even if the return value is not %G_IO_STATUS_NORMAL.
1695  * @error: A location to return an error of type #GConvertError
1696  *         or #GIOChannelError
1697  *
1698  * Replacement for g_io_channel_write() with the new API.
1699  *
1700  * Return value:
1701  **/
1702 GIOStatus
1703 g_io_channel_write_chars (GIOChannel    *channel,
1704                           const gchar   *buf,
1705                           gssize         count,
1706                           gsize         *bytes_written,
1707                           GError       **error)
1708 {
1709   GIOStatus status;
1710
1711   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1712   g_return_val_if_fail (bytes_written != NULL, G_IO_STATUS_ERROR);
1713   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1714                         G_IO_STATUS_ERROR);
1715   g_return_val_if_fail (channel->is_writeable, G_IO_STATUS_ERROR);
1716
1717   if ((count < 0) && buf)
1718     count = strlen (buf);
1719   
1720   if (count == 0)
1721     return G_IO_STATUS_NORMAL;
1722
1723   g_return_val_if_fail (buf != NULL, G_IO_STATUS_ERROR);
1724   g_return_val_if_fail (count > 0, G_IO_STATUS_ERROR);
1725
1726   /* Raw write case */
1727
1728   if (!channel->use_buffer)
1729     {
1730       g_assert (!channel->write_buf || channel->write_buf->len == 0);
1731       g_assert (channel->partial_write_buf[0] == '\0');
1732       return channel->funcs->io_write (channel, buf, count, bytes_written, error);
1733     }
1734
1735   /* General case */
1736
1737   if (channel->is_seekable && ((channel->read_buf && channel->read_buf->len > 0)
1738     || (channel->encoded_read_buf && channel->encoded_read_buf->len > 0)))
1739     {
1740       if (channel->encoded_read_buf && channel->encoded_read_buf->len > 0)
1741         {
1742           g_warning("Mixed reading and writing not allowed on encoded files");
1743           return G_IO_STATUS_ERROR;
1744         }
1745       status = g_io_channel_seek_position (channel, 0, G_SEEK_CUR, error);
1746       if (status != G_IO_STATUS_NORMAL)
1747         return status;
1748     }
1749
1750   if (!channel->write_buf)
1751     channel->write_buf = g_string_sized_new (channel->buf_size);
1752
1753   if (!channel->do_encode)
1754     {
1755       guint copy_bytes;
1756
1757       if (channel->encoding)
1758         { 
1759           const gchar *badchar;
1760
1761           if (channel->partial_write_buf[0] != '\0')
1762             {
1763               guint partial_chars = strlen (channel->partial_write_buf);
1764               guint chars_in_buf = MIN (6, partial_chars + count);
1765               gint skip;
1766
1767               memcpy (channel->partial_write_buf + partial_chars, buf,
1768                 chars_in_buf - partial_chars);
1769
1770               g_utf8_validate (channel->partial_write_buf, chars_in_buf, &badchar);
1771
1772               if (badchar < channel->partial_write_buf + partial_chars)
1773                 {
1774                   gunichar try_char;
1775                   gsize left_len = chars_in_buf;
1776
1777                   g_assert (badchar == channel->partial_write_buf);
1778
1779                   try_char = g_utf8_get_char_validated (badchar, left_len);
1780
1781                   switch (try_char)
1782                     {
1783                       case -2:
1784                         g_assert (chars_in_buf < 6);
1785                         channel->partial_write_buf[chars_in_buf] = '\0';
1786                         *bytes_written = count;
1787                         return G_IO_STATUS_NORMAL;
1788                       case -1:
1789                         g_set_error (error, G_CONVERT_ERROR,
1790                                      G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1791                                      "Illegal UTF-8 sequence");
1792                         *bytes_written = 0;
1793                         return G_IO_STATUS_ERROR;
1794                       default:
1795                         g_assert_not_reached ();
1796                         return G_IO_STATUS_ERROR; /* keep the compiler happy */
1797                     }
1798                 }
1799
1800               skip = badchar - (channel->partial_write_buf + partial_chars);
1801
1802               buf += skip;
1803               copy_bytes = count - skip;
1804
1805               g_string_append_len (channel->write_buf, channel->partial_write_buf,
1806                                   badchar - channel->partial_write_buf);
1807               channel->partial_write_buf[0] = '\0';
1808             }
1809           else
1810             copy_bytes = count;
1811
1812           if (!g_utf8_validate (buf, copy_bytes, &badchar))
1813             {
1814               gunichar try_char;
1815               gsize left_len = buf + copy_bytes - badchar;
1816
1817               try_char = g_utf8_get_char_validated (badchar, left_len);
1818
1819               switch (try_char)
1820                 {
1821                   case -2:
1822                     g_assert (left_len < 6);
1823                     break;
1824                   case -1:
1825                     g_set_error (error, G_CONVERT_ERROR,
1826                                  G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1827                                  "Illegal UTF-8 sequence");
1828                     *bytes_written = count - copy_bytes;
1829                     return G_IO_STATUS_ERROR;
1830                   default:
1831                     g_assert_not_reached ();
1832                     return G_IO_STATUS_ERROR; /* Don't confunse the compiler */
1833                 }
1834
1835               g_string_append (channel->write_buf, channel->partial_write_buf);
1836               memcpy (channel->partial_write_buf, badchar, left_len);
1837               channel->partial_write_buf[left_len] = '\0';
1838               copy_bytes = count - left_len;
1839             }
1840           else
1841             {
1842               g_string_append (channel->write_buf, channel->partial_write_buf);
1843               channel->partial_write_buf[0] = '\0';
1844               copy_bytes = count;
1845             }
1846         }
1847       else
1848         {
1849           copy_bytes = count;
1850           g_assert (channel->partial_write_buf[0] == '\0');
1851         }
1852
1853       while (copy_bytes > channel->write_buf->allocated_len - channel->write_buf->len)
1854         {
1855           gsize wrote_bytes;
1856
1857           if (channel->write_buf->len > 0)
1858             {
1859               status = channel->funcs->io_write (channel, channel->write_buf->str,
1860                                                  channel->write_buf->len, &wrote_bytes,
1861                                                  error);
1862               g_string_erase (channel->write_buf, 0, wrote_bytes);
1863             }
1864           else
1865             {
1866               status = channel->funcs->io_write (channel, buf, copy_bytes, &wrote_bytes,
1867                                                  error);
1868               copy_bytes -= wrote_bytes;
1869               buf += wrote_bytes;
1870             }
1871
1872           if (status != G_IO_STATUS_NORMAL)
1873             {
1874               *bytes_written = count - copy_bytes;
1875               if (channel->partial_write_buf[0] != '\0')
1876                 {
1877                   *bytes_written -= strlen (channel->partial_write_buf);
1878                   channel->partial_write_buf[0] = '\0';
1879                 }
1880               return status;
1881             }
1882         }
1883
1884       g_string_append_len (channel->write_buf, buf, copy_bytes);
1885       *bytes_written = count;
1886     }
1887   else
1888     {
1889       gsize bytes_to_go = count, buf_space, err;
1890       gchar *outbuf;
1891       gsize oldlen = channel->write_buf->len;
1892
1893       if (channel->partial_write_buf[0] != '\0')
1894         {
1895           gsize partial_chars = strlen (channel->partial_write_buf);
1896           gsize partial_buf_size = MIN (6, partial_chars + count);
1897           guint chars_in_buf = partial_buf_size;
1898           gchar *inbuf;
1899
1900           g_assert (partial_chars < 6);
1901
1902           memcpy (channel->partial_write_buf + partial_chars, buf,
1903             chars_in_buf - partial_chars);
1904           inbuf = channel->partial_write_buf;
1905 redo:
1906           buf_space = MIN (channel->buf_size / 4, channel->write_buf->allocated_len
1907                            - channel->write_buf->len);
1908           g_string_set_size (channel->write_buf, channel->write_buf->len
1909                              + buf_space);
1910           outbuf = channel->write_buf->str + channel->write_buf->len - buf_space;
1911
1912           err = g_iconv (channel->write_cd, &inbuf, &partial_buf_size,
1913                          &outbuf, &buf_space);
1914
1915           g_string_truncate (channel->write_buf, channel->write_buf->len - buf_space);
1916
1917           if (err == (size_t) -1)
1918             {
1919               if (errno == E2BIG)
1920                 goto redo;
1921
1922               if (errno == EINVAL)
1923                 {
1924                   if (chars_in_buf == partial_buf_size)
1925                     {
1926                       /* Didn't convert anything */
1927
1928                       g_assert (chars_in_buf < 6); /* More of the same character */
1929                       g_assert (chars_in_buf == count + partial_chars);
1930
1931                       channel->partial_write_buf[chars_in_buf] = '\0';
1932                       *bytes_written = count;
1933                       return G_IO_STATUS_NORMAL;
1934                     }
1935
1936                   g_assert (chars_in_buf - partial_buf_size > partial_chars);
1937                   /* Converted the character of which a part was sitting in
1938                    * the partial character buffer before the write.
1939                    */
1940                 }
1941               else
1942                 {
1943                   switch (errno)
1944                     {
1945                       case EINVAL:
1946                       case E2BIG:
1947                         g_assert_not_reached ();
1948                       case EILSEQ:
1949                         g_set_error (error, G_CONVERT_ERROR,
1950                           G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1951                           _("Invalid byte sequence in conversion input"));
1952                       default:
1953                         g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1954                           _("Error during conversion: %s"), strerror (errno));
1955                     }
1956
1957                   g_string_truncate (channel->write_buf, oldlen);
1958                   *bytes_written = 0;
1959                   channel->partial_write_buf[partial_chars] = '\0';
1960
1961                   return G_IO_STATUS_ERROR;
1962                 }
1963             }
1964
1965           *bytes_written = (chars_in_buf - partial_buf_size) - partial_chars;
1966           buf += *bytes_written;
1967           bytes_to_go -= *bytes_written;
1968           channel->partial_write_buf[0] = '\0';
1969         }
1970
1971       do
1972         {
1973           buf_space = MIN (channel->write_buf->allocated_len
1974                            - channel->write_buf->len, channel->buf_size / 4);
1975
1976           g_string_set_size (channel->write_buf, channel->write_buf->len + buf_space);
1977           outbuf = channel->write_buf->str + channel->write_buf->len - buf_space;
1978     
1979           err = g_iconv (channel->write_cd, (gchar**) &buf, &bytes_to_go,
1980                          &outbuf, &buf_space);
1981
1982           g_string_truncate (channel->write_buf, channel->write_buf->len - buf_space);
1983           *bytes_written = count - bytes_to_go;
1984
1985           if (err == (size_t) -1)
1986             {
1987               switch (errno)
1988                 {
1989                   case EINVAL:
1990                     {
1991                       gint bytes_left = count - *bytes_written;
1992
1993                       g_assert (bytes_left < 6);
1994
1995                       memcpy (channel->partial_write_buf, buf, bytes_left);
1996                       channel->partial_write_buf[bytes_left] = '\0';
1997                     }
1998                     *bytes_written = count;
1999
2000                     return G_IO_STATUS_NORMAL;
2001                   case E2BIG:
2002                     {
2003                       gsize wrote_bytes;
2004
2005                       status = channel->funcs->io_write (channel,
2006                         channel->write_buf->str, channel->write_buf->len,
2007                         &wrote_bytes, error);
2008                       g_string_erase (channel->write_buf, 0, wrote_bytes);
2009
2010                       if (status != G_IO_STATUS_NORMAL)
2011                         return status;
2012                     }
2013                     continue;
2014                   case EILSEQ:
2015                     g_set_error (error, G_CONVERT_ERROR,
2016                       G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
2017                       _("Invalid byte sequence in conversion input"));
2018                     return G_IO_STATUS_ERROR;
2019                   default:
2020                     g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
2021                       _("Error during conversion: %s"), strerror (errno));
2022                     return G_IO_STATUS_ERROR;
2023                 }
2024
2025             }
2026         }
2027       while (bytes_to_go > 0);
2028     }
2029
2030   if (channel->write_buf->len > channel->buf_size)
2031     {
2032       gsize wrote_bytes;
2033
2034       status = channel->funcs->io_write (channel, channel->write_buf->str,
2035                                          channel->write_buf->len, &wrote_bytes, error);
2036
2037       if (wrote_bytes > 0)
2038         g_string_erase (channel->write_buf, 0, wrote_bytes);
2039
2040       return status;
2041     }
2042   else
2043     return G_IO_STATUS_NORMAL;
2044 }
2045
2046 /**
2047  * g_io_channel_error_quark:
2048  *
2049  * Return value: The quark used as %G_IO_CHANNEL_ERROR
2050  **/
2051 GQuark
2052 g_io_channel_error_quark (void)
2053 {
2054   static GQuark q = 0;
2055   if (q == 0)
2056     q = g_quark_from_static_string ("g-io-channel-error-quark");
2057
2058   return q;
2059 }