Matthias Classen's patch to give g_io_channel_flush() the correct sense
[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->encoding)
481     {
482       if (channel->encoded_read_buf && (channel->encoded_read_buf->len > 0))
483         condition |= G_IO_IN; /* Only return if we have full characters */
484     }
485   else
486     {
487       if (channel->read_buf && (channel->read_buf->len > 0))
488         condition |= G_IO_IN;
489     }
490
491   if (channel->write_buf && (channel->write_buf->len < channel->buf_size))
492     condition |= G_IO_OUT;
493
494   return condition;
495 }
496
497 /**
498  * g_io_channel_error_from_errno:
499  * @en: An errno error number, e.g. EINVAL
500  *
501  * Return value: A #GIOChannelError error number, e.g. %G_IO_CHANNEL_ERROR_INVAL
502  **/
503 GIOChannelError
504 g_io_channel_error_from_errno (gint en)
505 {
506 #ifdef EAGAIN
507   g_return_val_if_fail (en != EAGAIN, G_IO_CHANNEL_ERROR_FAILED);
508 #endif
509 #ifdef EINTR
510   g_return_val_if_fail (en != EINTR, G_IO_CHANNEL_ERROR_FAILED);
511 #endif
512
513   switch (en)
514     {
515 #ifdef EBADF
516     case EBADF:
517       g_warning("Invalid file descriptor.\n");
518       return G_IO_CHANNEL_ERROR_FAILED;
519 #endif
520
521 #ifdef EFAULT
522     case EFAULT:
523       g_warning("File descriptor outside valid address space.\n");
524       return G_IO_CHANNEL_ERROR_FAILED;
525 #endif
526
527 #ifdef EFBIG
528     case EFBIG:
529       return G_IO_CHANNEL_ERROR_FBIG;
530 #endif
531
532 #ifdef EINVAL
533     case EINVAL:
534       return G_IO_CHANNEL_ERROR_INVAL;
535 #endif
536
537 #ifdef EIO
538     case EIO:
539       return G_IO_CHANNEL_ERROR_IO;
540 #endif
541
542 #ifdef EISDIR
543     case EISDIR:
544       return G_IO_CHANNEL_ERROR_ISDIR;
545 #endif
546
547 #ifdef ENOSPC
548     case ENOSPC:
549       return G_IO_CHANNEL_ERROR_NOSPC;
550 #endif
551
552 #ifdef ENXIO
553     case ENXIO:
554       return G_IO_CHANNEL_ERROR_NXIO;
555 #endif
556
557 #ifdef EOVERFLOW
558     case EOVERFLOW:
559       return G_IO_CHANNEL_ERROR_OVERFLOW;
560 #endif
561
562 #ifdef EPIPE
563     case EPIPE:
564       return G_IO_CHANNEL_ERROR_PIPE;
565 #endif
566
567     default:
568       return G_IO_CHANNEL_ERROR_FAILED;
569     }
570 }
571
572 /**
573  * g_io_channel_set_buffer_size:
574  * @channel: a #GIOChannel
575  * @size: the size of the buffer. 0 == pick a good size
576  *
577  * Set the buffer size.
578  **/  
579 void
580 g_io_channel_set_buffer_size (GIOChannel        *channel,
581                               gsize              size)
582 {
583   g_return_if_fail (channel != NULL);
584
585   if (size == 0)
586     size = G_IO_NICE_BUF_SIZE;
587
588   if (size < 10) /* Needs to be larger than the widest char in any encoding */
589     size = 10;
590
591   channel->buf_size = size;
592 }
593
594 /**
595  * g_io_channel_get_buffer_size:
596  * @channel: a #GIOChannel
597  *
598  * Get the buffer size.
599  *
600  * Return value: the size of the buffer.
601  **/  
602 gsize
603 g_io_channel_get_buffer_size (GIOChannel        *channel)
604 {
605   g_return_val_if_fail (channel != NULL, 0);
606
607   return channel->buf_size;
608 }
609
610 /**
611  * g_io_channel_set_line_term:
612  * @channel: a #GIOChannel
613  * @line_term: The line termination string. Use %NULL for auto detect.
614  *
615  * This sets the string that #GIOChannel uses to determine
616  * where in the file a line break occurs.
617  **/
618 void
619 g_io_channel_set_line_term (GIOChannel  *channel,
620                             const gchar *line_term)
621 {
622   g_return_if_fail (channel != NULL);
623   g_return_if_fail (!line_term || line_term[0]); /* Disallow "" */
624   g_return_if_fail (!line_term || g_utf8_validate (line_term, -1, NULL));
625                    /* Require valid UTF-8 */
626
627   g_free (channel->line_term);
628   channel->line_term = g_strdup (line_term);
629 }
630
631 /**
632  * g_io_channel_get_line_term:
633  * @channel: a #GIOChannel
634  *
635  * This returns the string that #GIOChannel uses to determine
636  * where in the file a line break occurs. A value of %NULL
637  * indicates auto detection.
638  *
639  * Return value: The line termination string. This value
640  *   is owned by GLib and must not be freed.
641  **/
642 G_CONST_RETURN gchar*
643 g_io_channel_get_line_term (GIOChannel  *channel)
644 {
645   g_return_val_if_fail (channel != NULL, 0);
646
647   return channel->line_term;
648 }
649
650 /**
651  * g_io_channel_set_flags:
652  * @channel: a #GIOChannel
653  * @flags: the flags to set on the channel
654  * @error: A location to return an error of type #GIOChannelError
655  *
656  * Return value:
657  **/
658 GIOStatus
659 g_io_channel_set_flags (GIOChannel *channel,
660                         GIOFlags    flags,
661                         GError    **error)
662 {
663   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
664   g_return_val_if_fail ((error == NULL) || (*error == NULL),
665                         G_IO_STATUS_ERROR);
666
667   return (* channel->funcs->io_set_flags)(channel,
668                                           flags & G_IO_FLAG_SET_MASK,
669                                           error);
670 }
671
672 /**
673  * g_io_channel_get_flags:
674  * @channel: a #GIOChannel
675  *
676  * Gets the current flags for a #GIOChannel, including read-only
677  * flags such as %G_IO_FLAG_IS_READABLE.
678  *
679  * Return value: the flags which are set on the channel
680  **/
681 GIOFlags
682 g_io_channel_get_flags (GIOChannel *channel)
683 {
684   GIOFlags flags;
685
686   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
687
688   flags = (* channel->funcs->io_get_flags) (channel);
689
690   /* Cross implementation code */
691
692   if (channel->is_seekable)
693     flags |= G_IO_FLAG_IS_SEEKABLE;
694   if (channel->is_readable)
695     flags |= G_IO_FLAG_IS_READABLE;
696   if (channel->is_writeable)
697     flags |= G_IO_FLAG_IS_WRITEABLE;
698
699   return flags;
700 }
701
702 /**
703  * g_io_channel_seek_position:
704  * @channel: a #GIOChannel
705  * @offset: The offset in bytes from the position specified by @type
706  * @type: a #GSeekType. The type %G_SEEK_CUR is only allowed if
707  *        the channel has the default encoding or the
708  *        encoding %G_IO_CHANNEL_ENCODE_RAW for raw file access.
709  * @error: A location to return an error of type #GIOChannelError
710  *
711  * Replacement for g_io_channel_seek() with the new API.
712  *
713  * Return value:
714  **/
715 GIOStatus
716 g_io_channel_seek_position      (GIOChannel* channel,
717                                  glong       offset,
718                                  GSeekType   type,
719                                  GError    **error)
720 {
721   GIOStatus status;
722
723   /* For files, only one of the read and write buffers can contain data.
724    * For sockets, both can contain data.
725    */
726
727   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
728   g_return_val_if_fail ((error == NULL) || (*error == NULL),
729                         G_IO_STATUS_ERROR);
730   g_return_val_if_fail (channel->is_seekable, G_IO_STATUS_ERROR);
731
732   switch (type)
733     {
734       case G_SEEK_CUR: /* The user is seeking relative to the head of the buffer */
735         if (channel->use_buffer)
736           {
737             if (channel->do_encode && channel->encoded_read_buf
738                 && channel->encoded_read_buf->len > 0)
739               {
740                 g_warning ("Seek type G_SEEK_CUR not allowed for this"
741                   " channel's encoding.\n");
742                 return G_IO_STATUS_ERROR;
743               }
744           if (channel->read_buf)
745             offset -= channel->read_buf->len;
746           if (channel->encoded_read_buf)
747             {
748               g_assert (channel->encoded_read_buf->len == 0 && !channel->do_encode);
749
750               /* If there's anything here, it's because the encoding is UTF-8,
751                * so we can just subtract the buffer length, the same as for
752                * the unencoded data.
753                */
754
755               offset -= channel->encoded_read_buf->len;
756             }
757           }
758         break;
759       case G_SEEK_SET:
760       case G_SEEK_END:
761         break;
762       default:
763         g_warning ("g_io_channel_seek_position: unknown seek type");
764         return G_IO_STATUS_ERROR;
765     }
766
767   if (channel->use_buffer)
768     {
769       status = g_io_channel_flush (channel, error);
770       if (status != G_IO_STATUS_NORMAL)
771         return status;
772     }
773
774   status = channel->funcs->io_seek (channel, offset, type, error);
775
776   if ((status == G_IO_STATUS_NORMAL) && (channel->use_buffer))
777     {
778       if (channel->read_buf)
779         g_string_truncate (channel->read_buf, 0);
780
781       /* Conversion state no longer matches position in file */
782       if (channel->read_cd != (GIConv) -1)
783         g_iconv (channel->read_cd, NULL, NULL, NULL, NULL);
784       if (channel->write_cd != (GIConv) -1)
785         g_iconv (channel->write_cd, NULL, NULL, NULL, NULL);
786
787       if (channel->encoded_read_buf)
788         {
789           g_assert (channel->encoded_read_buf->len == 0 || !channel->do_encode);
790           g_string_truncate (channel->encoded_read_buf, 0);
791         }
792
793       if (channel->partial_write_buf[0] != '\0')
794         {
795           g_warning ("Partial character at end of write buffer not flushed.\n");
796           channel->partial_write_buf[0] = '\0';
797         }
798     }
799
800   return status;
801 }
802
803 /**
804  * g_io_channel_flush:
805  * @channel: a #GIOChannel
806  * @error: location to store an error of type #GIOChannelError
807  *
808  * Flush the write buffer for the GIOChannel.
809  *
810  * Return value: the status of the operation: One of
811  *   G_IO_CHANNEL_NORMAL, G_IO_CHANNEL_AGAIN, or
812  *   G_IO_CHANNEL_ERROR.
813  **/
814 GIOStatus
815 g_io_channel_flush (GIOChannel  *channel,
816                     GError     **error)
817 {
818   GIOStatus status;
819   gsize this_time = 1, bytes_written = 0;
820
821   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
822   g_return_val_if_fail ((error == NULL) || (*error == NULL), G_IO_STATUS_ERROR);
823
824   if (channel->write_buf == NULL || channel->write_buf->len == 0)
825     return G_IO_STATUS_NORMAL;
826
827   do
828     {
829       g_assert (this_time > 0);
830
831       status = channel->funcs->io_write (channel,
832                                       channel->write_buf->str + bytes_written,
833                                       channel->write_buf->len - bytes_written,
834                                       &this_time, error);
835       bytes_written += this_time;
836     }
837   while ((bytes_written < channel->write_buf->len)
838          && (status == G_IO_STATUS_NORMAL));
839
840   g_string_erase (channel->write_buf, 0, bytes_written);
841
842   return status;
843 }
844
845 /**
846  * g_io_channel_set_buffered:
847  * @channel: a #GIOChannel
848  * @buffered: whether to set the channel buffered or unbuffered
849  *
850  * The buffering state can only be set if the channel's encoding
851  * is %NULL. For any other encoding, the channel must be buffered.
852  *
853  * The default state of the channel is buffered.
854  **/
855 void
856 g_io_channel_set_buffered       (GIOChannel *channel,
857                                  gboolean    buffered)
858 {
859   g_return_if_fail (channel != NULL);
860
861   if (channel->encoding != NULL)
862     {
863       g_warning ("Need to have NULL encoding to set the buffering state of the "
864                  "channel.\n");
865       return;
866     }
867
868   g_return_if_fail (!channel->read_buf || channel->read_buf->len == 0);
869   g_return_if_fail (!channel->write_buf || channel->write_buf->len == 0);
870
871   channel->use_buffer = buffered;
872 }
873
874 /**
875  * g_io_channel_get_buffered:
876  * @channel: a #GIOChannel
877  *
878  * Return Value: the buffering state of the channel
879  **/
880 gboolean
881 g_io_channel_get_buffered       (GIOChannel *channel)
882 {
883   g_return_val_if_fail (channel != NULL, FALSE);
884
885   return channel->use_buffer;
886 }
887
888 /**
889  * g_io_channel_set_encoding:
890  * @channel: a #GIOChannel
891  * @encoding: the encoding type
892  * @error: location to store an error of type #GConvertError.
893  *
894  * Set the encoding for the input/output of the channel. The internal
895  * encoding is always UTF-8. The default encoding for the
896  * external file is UTF-8.
897  *
898  * The encoding %NULL is safe to use with binary data.
899  * Encodings other than %NULL must use a buffered channel.
900  * Encodings other than %NULL and UTF-8 cannot
901  * use g_io_channel_seek_position() with seek type %G_SEEK_CUR,
902  * and cannot mix reading and writing if the channel is
903  * a file without first doing a seek of type %G_SEEK_SET or
904  * %G_SEEK_END.
905  *
906  * The encoding can only be set under three conditions:
907  *
908  * 1. The channel was just created, and has not been written to
909  *    or read from yet.
910  *
911  * 2. The channel is a file, and the file pointer was just
912  *    repositioned by a call to g_io_channel_seek_position().
913  *    (This flushes all the internal buffers.)
914  *
915  * 3. The current encoding is %NULL or UTF-8.
916  *
917  * Return Value: %G_IO_STATUS_NORMAL if the encoding was succesfully set.
918  **/
919 GIOStatus
920 g_io_channel_set_encoding (GIOChannel   *channel,
921                            const gchar  *encoding,
922                            GError      **error)
923 {
924   GIConv read_cd, write_cd;
925   gboolean did_encode;
926
927   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
928   g_return_val_if_fail ((error == NULL) || (*error == NULL), G_IO_STATUS_ERROR);
929
930   /* Make sure the encoded buffers are empty */
931
932   g_return_val_if_fail (!channel->encoded_read_buf ||
933                         channel->encoded_read_buf->len == 0, G_IO_STATUS_ERROR);
934   g_return_val_if_fail (channel->partial_write_buf[0] == '\0', G_IO_STATUS_ERROR);
935
936   if (!channel->use_buffer)
937     {
938       g_warning ("Need to set the channel buffered before setting the encoding.\n");
939       g_warning ("Assuming this is what you meant and acting accordingly.\n");
940
941       channel->use_buffer = TRUE;
942     }
943
944   did_encode = channel->do_encode;
945
946   if (!encoding || strcmp (encoding, "UTF8") == 0 || strcmp (encoding, "UTF-8") == 0)
947     {
948       channel->do_encode = FALSE;
949       read_cd = write_cd = (GIConv) -1;
950     }
951   else
952     {
953       gint err = 0;
954       const gchar *from_enc = NULL, *to_enc = NULL;
955
956       if (channel->is_readable)
957         {
958           read_cd = g_iconv_open ("UTF-8", encoding);
959
960           if (read_cd == (GIConv) -1)
961             {
962               err = errno;
963               from_enc = "UTF-8";
964               to_enc = encoding;
965             }
966         }
967       else
968         read_cd = (GIConv) -1;
969
970       if (channel->is_writeable && err == 0)
971         {
972           write_cd = g_iconv_open (encoding, "UTF-8");
973
974           if (write_cd == (GIConv) -1)
975             {
976               err = errno;
977               from_enc = encoding;
978               to_enc = "UTF-8";
979             }
980         }
981       else
982         write_cd = (GIConv) -1;
983
984       if (err != 0)
985         {
986           g_assert (from_enc);
987           g_assert (to_enc);
988
989           if (err == EINVAL)
990             g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
991                          _("Conversion from character set `%s' to `%s' is not supported"),
992                          from_enc, to_enc);
993           else
994             g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
995                          _("Could not open converter from `%s' to `%s': %s"),
996                          from_enc, to_enc, strerror (errno));
997
998           if (read_cd != (GIConv) -1)
999             g_iconv_close (read_cd);
1000           if (write_cd != (GIConv) -1)
1001             g_iconv_close (write_cd);
1002
1003           return G_IO_STATUS_ERROR;
1004         }
1005
1006       channel->do_encode = TRUE;
1007     }
1008
1009   /* The encoding is ok, so set the fields in channel */
1010
1011   if (channel->read_cd != (GIConv) -1)
1012     g_iconv_close (channel->read_cd);
1013   if (channel->write_cd != (GIConv) -1)
1014     g_iconv_close (channel->write_cd);
1015
1016   channel->read_cd = read_cd;
1017   channel->write_cd = write_cd;
1018
1019   g_free (channel->encoding);
1020   channel->encoding = g_strdup (encoding);
1021
1022   return G_IO_STATUS_NORMAL;
1023 }
1024
1025 /**
1026  * g_io_channel_get_encoding:
1027  * @channel: a #GIOChannel
1028  *
1029  * Get the encoding for the input/output of the channel. The internal
1030  * encoding is always UTF-8. The encoding %G_IO_CHANNEL_ENCODE_RAW
1031  * disables encoding and turns off internal buffering. Both
1032  * %G_IO_CHANNEL_ENCODE_RAW and the default (no encoding, but buffered)
1033  * are safe to use with binary data.
1034  *
1035  * Return value: A string containing the encoding, this string is
1036  *   owned by GLib and must not be freed.
1037  **/
1038 G_CONST_RETURN gchar*
1039 g_io_channel_get_encoding (GIOChannel      *channel)
1040 {
1041   g_return_val_if_fail (channel != NULL, NULL);
1042
1043   return channel->encoding;
1044 }
1045
1046 static GIOStatus
1047 g_io_channel_fill_buffer (GIOChannel *channel,
1048                           GError    **err)
1049 {
1050   gsize read_size, cur_len, oldlen;
1051   GIOStatus status;
1052
1053   if (channel->is_seekable && channel->write_buf && channel->write_buf->len > 0)
1054     {
1055       status = g_io_channel_flush (channel, err);
1056       if (status != G_IO_STATUS_NORMAL)
1057         return status;
1058     }
1059   if (channel->is_seekable && channel->partial_write_buf[0] != '\0')
1060     {
1061       g_warning ("Partial character at end of write buffer not flushed.\n");
1062       channel->partial_write_buf[0] = '\0';
1063     }
1064
1065   if (!channel->read_buf)
1066     channel->read_buf = g_string_sized_new (channel->buf_size);
1067
1068   cur_len = channel->read_buf->len;
1069
1070   g_string_set_size (channel->read_buf, channel->read_buf->len + channel->buf_size);
1071
1072   status = channel->funcs->io_read (channel, channel->read_buf->str + cur_len,
1073                                     channel->buf_size, &read_size, err);
1074
1075   g_assert ((status == G_IO_STATUS_NORMAL) || (read_size == 0));
1076
1077   g_string_truncate (channel->read_buf, read_size + cur_len);
1078
1079   if ((status != G_IO_STATUS_NORMAL)
1080     && ((status != G_IO_STATUS_EOF) || (channel->read_buf->len == 0)))
1081     return status;
1082
1083   g_assert (channel->read_buf->len > 0);
1084
1085   if (channel->encoded_read_buf)
1086     oldlen = channel->encoded_read_buf->len;
1087   else
1088     oldlen = 0;
1089
1090   if (channel->do_encode)
1091     {
1092       size_t errnum, inbytes_left, outbytes_left;
1093       gchar *inbuf, *outbuf;
1094
1095       if (!channel->encoded_read_buf)
1096         channel->encoded_read_buf = g_string_sized_new (channel->buf_size);
1097
1098 reencode:
1099
1100       inbytes_left = channel->read_buf->len;
1101       outbytes_left = MIN (channel->buf_size / 4,
1102                            channel->encoded_read_buf->allocated_len
1103                            - channel->encoded_read_buf->len);
1104
1105       g_string_set_size (channel->encoded_read_buf,
1106                          channel->encoded_read_buf->len + outbytes_left);
1107
1108       inbuf = channel->read_buf->str;
1109       outbuf = channel->encoded_read_buf->str + channel->encoded_read_buf->len
1110                - outbytes_left;
1111
1112       errnum = g_iconv (channel->read_cd, &inbuf, &inbytes_left,
1113                         &outbuf, &outbytes_left);
1114
1115       g_string_erase (channel->read_buf, 0,
1116                       channel->read_buf->len - inbytes_left);
1117       g_string_truncate (channel->encoded_read_buf,
1118                          channel->encoded_read_buf->len - outbytes_left);
1119
1120       if (errnum == (size_t) -1)
1121         {
1122           switch (errno)
1123             {
1124               case EINVAL:
1125                 if ((oldlen == channel->encoded_read_buf->len)
1126                   && (status == G_IO_STATUS_EOF))
1127                   status = G_IO_STATUS_EOF;
1128                 else
1129                   status = G_IO_STATUS_NORMAL;
1130                 break;
1131               case E2BIG:
1132                 goto reencode;
1133               case EILSEQ:
1134                 if (oldlen < channel->encoded_read_buf->len)
1135                   status = G_IO_STATUS_NORMAL;
1136                 else
1137                   {
1138                     g_set_error (err, G_CONVERT_ERROR,
1139                       G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1140                       _("Invalid byte sequence in conversion input"));
1141                     return G_IO_STATUS_ERROR;
1142                   }
1143                 break;
1144               default:
1145                 g_set_error (err, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1146                   _("Error during conversion: %s"), strerror (errno));
1147                 return G_IO_STATUS_ERROR;
1148             }
1149         }
1150       g_assert ((status != G_IO_STATUS_NORMAL)
1151                || (channel->encoded_read_buf->len > 0));
1152     }
1153   else if (channel->encoding) /* UTF-8 */
1154     {
1155       gchar *nextchar, *lastchar;
1156
1157       nextchar = channel->read_buf->str;
1158       lastchar = channel->read_buf->str + channel->read_buf->len;
1159
1160       while (nextchar < lastchar)
1161         {
1162           gunichar val_char;
1163
1164           val_char = g_utf8_get_char_validated (nextchar, lastchar - nextchar);
1165
1166           switch (val_char)
1167             {
1168               case -2:
1169                 /* stop, leave partial character in buffer */
1170                 lastchar = nextchar;
1171                 break;
1172               case -1:
1173                 if (oldlen > channel->encoded_read_buf->len)
1174                   status = G_IO_STATUS_NORMAL;
1175                 else
1176                   {
1177                     g_set_error (err, G_CONVERT_ERROR,
1178                       G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1179                       _("Invalid byte sequence in conversion input"));
1180                     status = G_IO_STATUS_ERROR;
1181                   }
1182                 lastchar = nextchar;
1183                 break;
1184               default:
1185                 nextchar = g_utf8_next_char (nextchar);
1186                 break;
1187             }
1188         }
1189
1190       if (lastchar > channel->read_buf->str)
1191         {
1192           gint copy_len = lastchar - channel->read_buf->str;
1193
1194           if (!channel->encoded_read_buf)
1195             channel->encoded_read_buf = g_string_sized_new (channel->buf_size);
1196
1197           g_string_append_len (channel->encoded_read_buf, channel->read_buf->str,
1198                                copy_len);
1199           g_string_erase (channel->read_buf, 0, copy_len);
1200         }
1201     }
1202
1203   return status;
1204 }
1205
1206 /**
1207  * g_io_channel_read_line:
1208  * @channel: a #GIOChannel
1209  * @str_return: The line read from the #GIOChannel, not including the
1210  *              line terminator. This data should be freed with g_free()
1211  *              when no longer needed. This
1212  *              is a null terminated string. If a @length of zero is
1213  *              returned, this will be %NULL instead.
1214  * @length: location to store length of the read data, or %NULL
1215  * @terminator_pos: location to store position of line terminator, or %NULL
1216  * @error: A location to return an error of type #GConvertError
1217  *         or #GIOChannelError
1218  *
1219  * Read a line, not including the terminating character(s),
1220  * from a #GIOChannel into a newly allocated string.
1221  * @length will contain allocated memory if the return
1222  * is %G_IO_STATUS_NORMAL.
1223  *
1224  * Return value: a newly allocated string. Free this string
1225  *   with g_free() when you are done with it.
1226  **/
1227 GIOStatus
1228 g_io_channel_read_line (GIOChannel *channel,
1229                         gchar     **str_return,
1230                         gsize      *length,
1231                         gsize      *terminator_pos,
1232                         GError    **error)
1233 {
1234   GIOStatus status;
1235   
1236   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1237   g_return_val_if_fail (str_return != NULL, G_IO_STATUS_ERROR);
1238   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1239                         G_IO_STATUS_ERROR);
1240   g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1241
1242   status = g_io_channel_read_line_backend (channel, length, terminator_pos, error);
1243
1244   if (status == G_IO_STATUS_NORMAL)
1245     {
1246       GString *use_buf;
1247
1248       if (channel->do_encode)
1249         use_buf = channel->encoded_read_buf;
1250       else
1251         use_buf = channel->read_buf;
1252
1253       g_assert (use_buf);
1254
1255       *str_return = g_strndup (use_buf->str, *length);
1256       g_string_erase (use_buf, 0, *length);
1257     }
1258   else
1259     *str_return = NULL;
1260   
1261   return status;
1262 }
1263
1264 /**
1265  * g_io_channel_read_line_string:
1266  * @channel: a #GIOChannel
1267  * @buffer: a #GString into which the line will be written.
1268  *          If @buffer already contains data, the new data will
1269  *          be appended to it.
1270  * @terminator_pos: location to store position of line terminator, or %NULL
1271  * @error: a location to store an error of type #GConvertError
1272  *         or #GIOChannelError
1273  *
1274  * Read a line from a #GIOChannel, using a #GString as a buffer.
1275  *
1276  * Return value:
1277  **/
1278 GIOStatus
1279 g_io_channel_read_line_string (GIOChannel *channel,
1280                                GString    *buffer,
1281                                gsize      *terminator_pos,
1282                                GError    **error)
1283 {
1284   gsize length;
1285   GIOStatus status;
1286
1287   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1288   g_return_val_if_fail (buffer != NULL, G_IO_STATUS_ERROR);
1289   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1290                         G_IO_STATUS_ERROR);
1291   g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1292
1293   if (buffer->len > 0)
1294     g_string_truncate (buffer, 0); /* clear out the buffer */
1295
1296   status = g_io_channel_read_line_backend (channel, &length, terminator_pos, error);
1297
1298   if (status == G_IO_STATUS_NORMAL)
1299     {
1300       GString *use_buf;
1301
1302       if (channel->do_encode)
1303         use_buf = channel->encoded_read_buf;
1304       else
1305         use_buf = channel->read_buf;
1306
1307       g_assert (use_buf);
1308
1309       g_string_append_len (buffer, use_buf->str, length);
1310       g_string_erase (use_buf, 0, length);
1311     }
1312
1313   return status;
1314 }
1315
1316
1317 static GIOStatus
1318 g_io_channel_read_line_backend  (GIOChannel *channel,
1319                                  gsize      *length,
1320                                  gsize      *terminator_pos,
1321                                  GError    **error)
1322 {
1323   GIOStatus status;
1324   gsize checked_to, line_term_len, line_length, got_term_len;
1325   GString *use_buf;
1326   gboolean first_time = TRUE;
1327
1328   if (!channel->use_buffer)
1329     {
1330       /* Can't do a raw read in read_line */
1331       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1332                    _("Can't do a raw read in g_io_channel_read_line_string"));
1333       return G_IO_STATUS_ERROR;
1334     }
1335
1336   if (channel->encoding)
1337     {
1338       if (!channel->encoded_read_buf)
1339         channel->encoded_read_buf = g_string_sized_new (channel->buf_size);
1340       use_buf = channel->encoded_read_buf;
1341     }
1342   else
1343     {
1344       if (!channel->read_buf)
1345         channel->read_buf = g_string_sized_new (channel->buf_size);
1346       use_buf = channel->read_buf;
1347     }
1348
1349   status = G_IO_STATUS_NORMAL;
1350
1351   if (channel->line_term)
1352     line_term_len = strlen (channel->line_term);
1353   else
1354     line_term_len = 3;
1355     /* This value used for setting checked_to, it's the longest of the four
1356      * we autodetect for.
1357      */
1358
1359   checked_to = 0;
1360
1361   while (TRUE)
1362     {
1363       gchar *nextchar, *lastchar;
1364
1365       if (!first_time || (use_buf->len == 0))
1366         {
1367 read_again:
1368           status = g_io_channel_fill_buffer (channel, error);
1369           switch (status)
1370             {
1371               case G_IO_STATUS_NORMAL:
1372                 if (use_buf->len == 0)
1373                   /* Can happen when using conversion and only read
1374                    * part of a character
1375                    */
1376                   {
1377                     first_time = FALSE;
1378                     continue;
1379                   }
1380                 break;
1381               case G_IO_STATUS_EOF:
1382                 if (use_buf->len == 0)
1383                   {
1384                     *length = 0;
1385
1386                     if (channel->do_encode && channel->read_buf->len != 0)
1387                       /* using GIConv conversion, unconverted chars */
1388                       {
1389                         g_set_error (error, G_CONVERT_ERROR,
1390                                      G_CONVERT_ERROR_PARTIAL_INPUT,
1391                                      "Leftover unconverted data in read buffer");
1392                         return G_IO_STATUS_ERROR;
1393                       }
1394                     else
1395                       return G_IO_STATUS_EOF;
1396                   }
1397                 break;
1398               default:
1399                 *length = 0;
1400                 return status;
1401             }
1402         }
1403
1404       g_assert (use_buf->len > 0);
1405
1406       first_time = FALSE;
1407
1408       lastchar = use_buf->str + strlen (use_buf->str);
1409
1410       for (nextchar = use_buf->str + checked_to; nextchar < lastchar;
1411            channel->encoding ? nextchar = g_utf8_next_char (nextchar) : nextchar++)
1412         {
1413           if (channel->line_term)
1414             {
1415               if (strncmp (channel->line_term, nextchar, line_term_len) == 0)
1416                 {
1417                   line_length = nextchar - use_buf->str;
1418                   got_term_len = line_term_len;
1419                   goto done;
1420                 }
1421             }
1422           else /* auto detect */
1423             {
1424               switch (*nextchar)
1425                 {
1426                   case '\n': /* unix */
1427                     line_length = nextchar - use_buf->str;
1428                     got_term_len = 1;
1429                     goto done;
1430                   case '\r': /* Warning: do not use with sockets */
1431                     line_length = nextchar - use_buf->str;
1432                     if ((nextchar == lastchar - 1) && (status != G_IO_STATUS_EOF)
1433                        && (lastchar == use_buf->str + use_buf->len))
1434                       goto read_again; /* Try to read more data */
1435                     if ((nextchar < lastchar - 1) && (*(nextchar + 1) == '\n')) /* dos */
1436                       got_term_len = 2;
1437                     else /* mac */
1438                       got_term_len = 1;
1439                     goto done;
1440                   case '\xe2': /* Unicode paragraph separator */
1441                     if (strncmp ("\xe2\x80\xa9", nextchar, 3) == 0)
1442                       {
1443                         line_length = nextchar - use_buf->str;
1444                         got_term_len = 3;
1445                         goto done;
1446                       }
1447                     break;
1448                   default: /* no match */
1449                     break;
1450                 }
1451             }
1452         }
1453
1454       g_assert (nextchar == lastchar); /* Valid UTF-8, didn't overshoot */
1455
1456       /* Also terminate on '\0' */
1457
1458       line_length = lastchar - use_buf->str;
1459       if (line_length < use_buf->len)
1460         {
1461           got_term_len = 0;
1462           break;
1463         }
1464
1465       /* Check for EOF */
1466
1467       if (status == G_IO_STATUS_EOF)
1468         {
1469           if (channel->encoding && channel->read_buf->len > 0)
1470             {
1471               g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1472                            "Channel terminates in a partial character");
1473               return G_IO_STATUS_ERROR;
1474             }
1475           line_length = use_buf->len;
1476           got_term_len = 0;
1477           break;
1478         }
1479
1480       if (use_buf->len > line_term_len - 1)
1481         checked_to = use_buf->len - (line_term_len - 1);
1482       else
1483         checked_to = 0;
1484     }
1485
1486 done:
1487
1488   if (terminator_pos)
1489     *terminator_pos = line_length;
1490
1491   *length = line_length + got_term_len;
1492
1493   return G_IO_STATUS_NORMAL;
1494 }
1495
1496 /**
1497  * g_io_channel_read_to_end:
1498  * @channel: a #GIOChannel
1499  * @str_return: Location to store a pointer to a string holding
1500  *              the remaining data in the #GIOChannel. This data should
1501  *              be freed with g_free() when no longer needed. This
1502  *              data is terminated by an extra null, but there may be other
1503  *              nulls in the intervening data.
1504  * @length: Location to store length of the data
1505  * @error: A location to return an error of type #GConvertError
1506  *         or #GIOChannelError
1507  *
1508  * Read all the remaining data from the file. Parameters as
1509  * for g_io_channel_read_line.
1510  *
1511  * Return value: One of #G_IO_STATUS_EOF or #G_IO_STATUS_PARTIAL_CHARS
1512  *               on success
1513  **/
1514 GIOStatus
1515 g_io_channel_read_to_end (GIOChannel    *channel,
1516                           gchar        **str_return,
1517                           gsize         *length,
1518                           GError       **error)
1519 {
1520   GIOStatus status;
1521   GString **use_buf;
1522     
1523   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1524   g_return_val_if_fail (str_return != NULL, G_IO_STATUS_ERROR);
1525   g_return_val_if_fail (length != NULL, G_IO_STATUS_ERROR);
1526   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1527     G_IO_STATUS_ERROR);
1528   g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1529
1530   *str_return = NULL;
1531   *length = 0;
1532
1533   if (!channel->use_buffer)
1534     {
1535       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1536                    _("Can't do a raw read in g_io_channel_read_to_end"));
1537       return G_IO_STATUS_ERROR;
1538     }
1539
1540   do
1541     status = g_io_channel_fill_buffer (channel, error);
1542   while (status == G_IO_STATUS_NORMAL);
1543
1544   if (status != G_IO_STATUS_EOF)
1545     return status;
1546
1547   if (channel->encoding)
1548     {
1549       if (channel->read_buf->len > 0)
1550         {
1551           g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1552                        "Channel terminates in a partial character");
1553           return G_IO_STATUS_ERROR;
1554         }
1555
1556       if (!channel->encoded_read_buf)
1557         {
1558           if (length)
1559             *length = 0;
1560           if (str_return)
1561             *str_return = g_strdup ("");
1562         }
1563
1564       use_buf = &channel->encoded_read_buf;
1565     }
1566   else
1567     use_buf = &channel->read_buf;
1568
1569   g_assert (*use_buf); /* Created by fill_buffer if it didn't previously exist */
1570
1571   if (length)
1572     *length = (*use_buf)->len;
1573
1574   if (str_return)
1575     *str_return = g_string_free (*use_buf, FALSE);
1576   else
1577     g_string_free (*use_buf, TRUE);
1578   
1579   *use_buf = NULL;
1580
1581   return G_IO_STATUS_NORMAL;
1582 }
1583
1584 /**
1585  * g_io_channel_read_chars:
1586  * @channel: a #GIOChannel
1587  * @buf: a buffer to read data into
1588  * @count: the size of the buffer. Note that the buffer may
1589  *         not be complelely filled even if there is data
1590  *         in the buffer if the remaining data is not a
1591  *         complete character.
1592  * @bytes_read: The number of bytes read.
1593  * @error: A location to return an error of type #GConvertError
1594  *         or #GIOChannelError.
1595  *
1596  * Replacement for g_io_channel_read() with the new API.
1597  *
1598  * Return value:
1599  **/
1600 GIOStatus
1601 g_io_channel_read_chars (GIOChannel     *channel,
1602                          gchar          *buf,
1603                          gsize           count,
1604                          gsize          *bytes_read,
1605                          GError        **error)
1606 {
1607   GIOStatus status;
1608   GString *use_buf;
1609
1610   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1611   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1612                         G_IO_STATUS_ERROR);
1613   g_return_val_if_fail (bytes_read != NULL, G_IO_STATUS_ERROR);
1614   g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1615
1616   if (count == 0)
1617     {
1618       *bytes_read = 0;
1619       return G_IO_STATUS_NORMAL;
1620     }
1621   g_return_val_if_fail (buf != NULL, G_IO_STATUS_ERROR);
1622
1623   if (!channel->use_buffer)
1624     {
1625       g_assert (!channel->read_buf || channel->read_buf->len == 0);
1626
1627       return channel->funcs->io_read (channel, buf, count, bytes_read, error);
1628     }
1629
1630   if (channel->encoding)
1631     {
1632       if (!channel->encoded_read_buf)
1633         channel->encoded_read_buf = g_string_sized_new (channel->buf_size);
1634       use_buf = channel->encoded_read_buf;
1635     }
1636   else
1637     {
1638       if (!channel->read_buf)
1639         channel->read_buf = g_string_sized_new (channel->buf_size);
1640       use_buf = channel->read_buf;
1641     }
1642
1643   status = G_IO_STATUS_NORMAL;
1644
1645   while (use_buf->len < MAX (count, 6) && status == G_IO_STATUS_NORMAL)
1646     /* Be sure to read in at least one full UTF-8 character
1647      * (max length 6)
1648      */
1649     status = g_io_channel_fill_buffer (channel, error);
1650
1651   switch (status)
1652     {
1653     case G_IO_STATUS_NORMAL:
1654       g_assert (use_buf->len > 0);
1655       break;
1656     case G_IO_STATUS_EOF:
1657       if (use_buf->len == 0)
1658         {
1659           *bytes_read = 0;
1660
1661           if (channel->encoding && channel->read_buf->len != 0)
1662             {
1663               g_set_error (error, G_CONVERT_ERROR,
1664                            G_CONVERT_ERROR_PARTIAL_INPUT,
1665                            "Leftover unconverted data in read buffer");
1666               return G_IO_STATUS_ERROR;
1667             }
1668           else
1669             return G_IO_STATUS_EOF;
1670         }
1671       break;
1672     case G_IO_STATUS_AGAIN:
1673       if (use_buf->len > 0)
1674         break; /* return what we have */
1675       else
1676         {
1677           *bytes_read = 0;
1678           return G_IO_STATUS_AGAIN;
1679         }
1680     default:
1681       *bytes_read = 0;
1682       return status;
1683     }
1684
1685   *bytes_read = MIN (count, use_buf->len);
1686
1687   if (channel->encoding && *bytes_read > 0)
1688     /* Don't validate for NULL encoding, binary safe */
1689     {
1690       gchar *nextchar, *prevchar = NULL;
1691
1692       nextchar = use_buf->str;
1693
1694       while (nextchar < use_buf->str + *bytes_read)
1695         {
1696           prevchar = nextchar;
1697           nextchar = g_utf8_next_char (nextchar);
1698         }
1699
1700       if (nextchar > use_buf->str + *bytes_read)
1701         *bytes_read = prevchar - use_buf->str;
1702
1703       g_assert (*bytes_read > 0 || count < 6);
1704     }
1705
1706   memcpy (buf, use_buf->str, *bytes_read);
1707   g_string_erase (use_buf, 0, *bytes_read);
1708
1709   return G_IO_STATUS_NORMAL;
1710 }
1711
1712 /**
1713  * g_io_channel_write_chars:
1714  * @channel: a #GIOChannel
1715  * @buf: a buffer to write data from
1716  * @count: the size of the buffer. If -1, the buffer
1717  *         is taken to be a nul terminated string.
1718  * @bytes_written: The number of bytes written. This can be nonzero
1719  *                 even if the return value is not %G_IO_STATUS_NORMAL.
1720  * @error: A location to return an error of type #GConvertError
1721  *         or #GIOChannelError
1722  *
1723  * Replacement for g_io_channel_write() with the new API.
1724  *
1725  * Return value:
1726  **/
1727 GIOStatus
1728 g_io_channel_write_chars (GIOChannel    *channel,
1729                           const gchar   *buf,
1730                           gssize         count,
1731                           gsize         *bytes_written,
1732                           GError       **error)
1733 {
1734   GIOStatus status;
1735
1736   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1737   g_return_val_if_fail (bytes_written != NULL, G_IO_STATUS_ERROR);
1738   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1739                         G_IO_STATUS_ERROR);
1740   g_return_val_if_fail (channel->is_writeable, G_IO_STATUS_ERROR);
1741
1742   if ((count < 0) && buf)
1743     count = strlen (buf);
1744   
1745   if (count == 0)
1746     return G_IO_STATUS_NORMAL;
1747
1748   g_return_val_if_fail (buf != NULL, G_IO_STATUS_ERROR);
1749   g_return_val_if_fail (count > 0, G_IO_STATUS_ERROR);
1750
1751   /* Raw write case */
1752
1753   if (!channel->use_buffer)
1754     {
1755       g_assert (!channel->write_buf || channel->write_buf->len == 0);
1756       g_assert (channel->partial_write_buf[0] == '\0');
1757       return channel->funcs->io_write (channel, buf, count, bytes_written, error);
1758     }
1759
1760   /* General case */
1761
1762   if (channel->is_seekable && ((channel->read_buf && channel->read_buf->len > 0)
1763     || (channel->encoded_read_buf && channel->encoded_read_buf->len > 0)))
1764     {
1765       if (channel->encoded_read_buf && channel->encoded_read_buf->len > 0)
1766         {
1767           g_warning("Mixed reading and writing not allowed on encoded files");
1768           return G_IO_STATUS_ERROR;
1769         }
1770       status = g_io_channel_seek_position (channel, 0, G_SEEK_CUR, error);
1771       if (status != G_IO_STATUS_NORMAL)
1772         return status;
1773     }
1774
1775   if (!channel->write_buf)
1776     channel->write_buf = g_string_sized_new (channel->buf_size);
1777
1778   if (!channel->do_encode)
1779     {
1780       guint copy_bytes;
1781
1782       if (channel->encoding)
1783         { 
1784           const gchar *badchar;
1785
1786           if (channel->partial_write_buf[0] != '\0')
1787             {
1788               guint partial_chars = strlen (channel->partial_write_buf);
1789               guint chars_in_buf = MIN (6, partial_chars + count);
1790               gint skip;
1791
1792               memcpy (channel->partial_write_buf + partial_chars, buf,
1793                 chars_in_buf - partial_chars);
1794
1795               g_utf8_validate (channel->partial_write_buf, chars_in_buf, &badchar);
1796
1797               if (badchar < channel->partial_write_buf + partial_chars)
1798                 {
1799                   gunichar try_char;
1800                   gsize left_len = chars_in_buf;
1801
1802                   g_assert (badchar == channel->partial_write_buf);
1803
1804                   try_char = g_utf8_get_char_validated (badchar, left_len);
1805
1806                   switch (try_char)
1807                     {
1808                       case -2:
1809                         g_assert (chars_in_buf < 6);
1810                         channel->partial_write_buf[chars_in_buf] = '\0';
1811                         *bytes_written = count;
1812                         return G_IO_STATUS_NORMAL;
1813                       case -1:
1814                         g_set_error (error, G_CONVERT_ERROR,
1815                                      G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1816                                      "Illegal UTF-8 sequence");
1817                         *bytes_written = 0;
1818                         return G_IO_STATUS_ERROR;
1819                       default:
1820                         g_assert_not_reached ();
1821                         return G_IO_STATUS_ERROR; /* keep the compiler happy */
1822                     }
1823                 }
1824
1825               skip = badchar - (channel->partial_write_buf + partial_chars);
1826
1827               buf += skip;
1828               copy_bytes = count - skip;
1829
1830               g_string_append_len (channel->write_buf, channel->partial_write_buf,
1831                                   badchar - channel->partial_write_buf);
1832               channel->partial_write_buf[0] = '\0';
1833             }
1834           else
1835             copy_bytes = count;
1836
1837           if (!g_utf8_validate (buf, copy_bytes, &badchar))
1838             {
1839               gunichar try_char;
1840               gsize left_len = buf + copy_bytes - badchar;
1841
1842               try_char = g_utf8_get_char_validated (badchar, left_len);
1843
1844               switch (try_char)
1845                 {
1846                   case -2:
1847                     g_assert (left_len < 6);
1848                     break;
1849                   case -1:
1850                     g_set_error (error, G_CONVERT_ERROR,
1851                                  G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1852                                  "Illegal UTF-8 sequence");
1853                     *bytes_written = count - copy_bytes;
1854                     return G_IO_STATUS_ERROR;
1855                   default:
1856                     g_assert_not_reached ();
1857                     return G_IO_STATUS_ERROR; /* Don't confunse the compiler */
1858                 }
1859
1860               g_string_append (channel->write_buf, channel->partial_write_buf);
1861               memcpy (channel->partial_write_buf, badchar, left_len);
1862               channel->partial_write_buf[left_len] = '\0';
1863               copy_bytes = count - left_len;
1864             }
1865           else
1866             {
1867               g_string_append (channel->write_buf, channel->partial_write_buf);
1868               channel->partial_write_buf[0] = '\0';
1869               copy_bytes = count;
1870             }
1871         }
1872       else
1873         {
1874           copy_bytes = count;
1875           g_assert (channel->partial_write_buf[0] == '\0');
1876         }
1877
1878       while (copy_bytes > channel->write_buf->allocated_len - channel->write_buf->len)
1879         {
1880           gsize wrote_bytes;
1881
1882           if (channel->write_buf->len > 0)
1883             {
1884               status = channel->funcs->io_write (channel, channel->write_buf->str,
1885                                                  channel->write_buf->len, &wrote_bytes,
1886                                                  error);
1887               g_string_erase (channel->write_buf, 0, wrote_bytes);
1888             }
1889           else
1890             {
1891               status = channel->funcs->io_write (channel, buf, copy_bytes, &wrote_bytes,
1892                                                  error);
1893               copy_bytes -= wrote_bytes;
1894               buf += wrote_bytes;
1895             }
1896
1897           if (status != G_IO_STATUS_NORMAL)
1898             {
1899               *bytes_written = count - copy_bytes;
1900               if (channel->partial_write_buf[0] != '\0')
1901                 {
1902                   *bytes_written -= strlen (channel->partial_write_buf);
1903                   channel->partial_write_buf[0] = '\0';
1904                 }
1905               return status;
1906             }
1907         }
1908
1909       g_string_append_len (channel->write_buf, buf, copy_bytes);
1910       *bytes_written = count;
1911     }
1912   else
1913     {
1914       gsize bytes_to_go = count, buf_space, err;
1915       gchar *outbuf;
1916       gsize oldlen = channel->write_buf->len;
1917
1918       if (channel->partial_write_buf[0] != '\0')
1919         {
1920           gsize partial_chars = strlen (channel->partial_write_buf);
1921           gsize partial_buf_size = MIN (6, partial_chars + count);
1922           guint chars_in_buf = partial_buf_size;
1923           gchar *inbuf;
1924
1925           g_assert (partial_chars < 6);
1926
1927           memcpy (channel->partial_write_buf + partial_chars, buf,
1928             chars_in_buf - partial_chars);
1929           inbuf = channel->partial_write_buf;
1930 redo:
1931           buf_space = MIN (channel->buf_size / 4, channel->write_buf->allocated_len
1932                            - channel->write_buf->len);
1933           g_string_set_size (channel->write_buf, channel->write_buf->len
1934                              + buf_space);
1935           outbuf = channel->write_buf->str + channel->write_buf->len - buf_space;
1936
1937           err = g_iconv (channel->write_cd, &inbuf, &partial_buf_size,
1938                          &outbuf, &buf_space);
1939
1940           g_string_truncate (channel->write_buf, channel->write_buf->len - buf_space);
1941
1942           if (err == (size_t) -1)
1943             {
1944               if (errno == E2BIG)
1945                 goto redo;
1946
1947               if (errno == EINVAL)
1948                 {
1949                   if (chars_in_buf == partial_buf_size)
1950                     {
1951                       /* Didn't convert anything */
1952
1953                       g_assert (chars_in_buf < 6); /* More of the same character */
1954                       g_assert (chars_in_buf == count + partial_chars);
1955
1956                       channel->partial_write_buf[chars_in_buf] = '\0';
1957                       *bytes_written = count;
1958                       return G_IO_STATUS_NORMAL;
1959                     }
1960
1961                   g_assert (chars_in_buf - partial_buf_size > partial_chars);
1962                   /* Converted the character of which a part was sitting in
1963                    * the partial character buffer before the write.
1964                    */
1965                 }
1966               else
1967                 {
1968                   switch (errno)
1969                     {
1970                       case EINVAL:
1971                       case E2BIG:
1972                         g_assert_not_reached ();
1973                       case EILSEQ:
1974                         g_set_error (error, G_CONVERT_ERROR,
1975                           G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1976                           _("Invalid byte sequence in conversion input"));
1977                       default:
1978                         g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1979                           _("Error during conversion: %s"), strerror (errno));
1980                     }
1981
1982                   g_string_truncate (channel->write_buf, oldlen);
1983                   *bytes_written = 0;
1984                   channel->partial_write_buf[partial_chars] = '\0';
1985
1986                   return G_IO_STATUS_ERROR;
1987                 }
1988             }
1989
1990           *bytes_written = (chars_in_buf - partial_buf_size) - partial_chars;
1991           buf += *bytes_written;
1992           bytes_to_go -= *bytes_written;
1993           channel->partial_write_buf[0] = '\0';
1994         }
1995
1996       do
1997         {
1998           buf_space = MIN (channel->write_buf->allocated_len
1999                            - channel->write_buf->len, channel->buf_size / 4);
2000
2001           g_string_set_size (channel->write_buf, channel->write_buf->len + buf_space);
2002           outbuf = channel->write_buf->str + channel->write_buf->len - buf_space;
2003     
2004           err = g_iconv (channel->write_cd, (gchar**) &buf, &bytes_to_go,
2005                          &outbuf, &buf_space);
2006
2007           g_string_truncate (channel->write_buf, channel->write_buf->len - buf_space);
2008           *bytes_written = count - bytes_to_go;
2009
2010           if (err == (size_t) -1)
2011             {
2012               switch (errno)
2013                 {
2014                   case EINVAL:
2015                     {
2016                       gint bytes_left = count - *bytes_written;
2017
2018                       g_assert (bytes_left < 6);
2019
2020                       memcpy (channel->partial_write_buf, buf, bytes_left);
2021                       channel->partial_write_buf[bytes_left] = '\0';
2022                     }
2023                     *bytes_written = count;
2024
2025                     return G_IO_STATUS_NORMAL;
2026                   case E2BIG:
2027                     {
2028                       gsize wrote_bytes;
2029
2030                       status = channel->funcs->io_write (channel,
2031                         channel->write_buf->str, channel->write_buf->len,
2032                         &wrote_bytes, error);
2033                       g_string_erase (channel->write_buf, 0, wrote_bytes);
2034
2035                       if (status != G_IO_STATUS_NORMAL)
2036                         return status;
2037                     }
2038                     continue;
2039                   case EILSEQ:
2040                     g_set_error (error, G_CONVERT_ERROR,
2041                       G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
2042                       _("Invalid byte sequence in conversion input"));
2043                     return G_IO_STATUS_ERROR;
2044                   default:
2045                     g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
2046                       _("Error during conversion: %s"), strerror (errno));
2047                     return G_IO_STATUS_ERROR;
2048                 }
2049
2050             }
2051         }
2052       while (bytes_to_go > 0);
2053     }
2054
2055   if (channel->write_buf->len > channel->buf_size)
2056     {
2057       gsize wrote_bytes;
2058
2059       status = channel->funcs->io_write (channel, channel->write_buf->str,
2060                                          channel->write_buf->len, &wrote_bytes, error);
2061
2062       if (wrote_bytes > 0)
2063         g_string_erase (channel->write_buf, 0, wrote_bytes);
2064
2065       return status;
2066     }
2067   else
2068     return G_IO_STATUS_NORMAL;
2069 }
2070
2071 /**
2072  * g_io_channel_error_quark:
2073  *
2074  * Return value: The quark used as %G_IO_CHANNEL_ERROR
2075  **/
2076 GQuark
2077 g_io_channel_error_quark (void)
2078 {
2079   static GQuark q = 0;
2080   if (q == 0)
2081     q = g_quark_from_static_string ("g-io-channel-error-quark");
2082
2083   return q;
2084 }