Updated FSF's address
[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, see <http://www.gnu.org/licenses/>.
19  */
20
21 /*
22  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
23  * file for a list of people on the GLib Team.  See the ChangeLog
24  * files for a list of changes.  These files are distributed with
25  * GLib at ftp://ftp.gtk.org/pub/gtk/. 
26  */
27
28 /* 
29  * MT safe
30  */
31
32 #include "config.h"
33
34 #include <string.h>
35 #include <errno.h>
36
37 #include "giochannel.h"
38
39 #include "gstrfuncs.h"
40 #include "gtestutils.h"
41 #include "glibintl.h"
42
43
44 /**
45  * SECTION:iochannels
46  * @title: IO Channels
47  * @short_description: portable support for using files, pipes and
48  *                     sockets
49  * @see_also: <para> <variablelist> <varlistentry>
50  *            <term>g_io_add_watch(), g_io_add_watch_full(),
51  *            g_source_remove()</term> <listitem><para> Convenience
52  *            functions for creating #GIOChannel instances and adding
53  *            them to the <link linkend="glib-The-Main-Event-Loop">main
54  *            event loop</link>. </para></listitem> </varlistentry>
55  *            </variablelist> </para>
56  *
57  * The #GIOChannel data type aims to provide a portable method for
58  * using file descriptors, pipes, and sockets, and integrating them
59  * into the <link linkend="glib-The-Main-Event-Loop">main event
60  * loop</link>. Currently full support is available on UNIX platforms,
61  * support for Windows is only partially complete.
62  *
63  * To create a new #GIOChannel on UNIX systems use
64  * g_io_channel_unix_new(). This works for plain file descriptors,
65  * pipes and sockets. Alternatively, a channel can be created for a
66  * file in a system independent manner using g_io_channel_new_file().
67  *
68  * Once a #GIOChannel has been created, it can be used in a generic
69  * manner with the functions g_io_channel_read_chars(),
70  * g_io_channel_write_chars(), g_io_channel_seek_position(), and
71  * g_io_channel_shutdown().
72  *
73  * To add a #GIOChannel to the <link
74  * linkend="glib-The-Main-Event-Loop">main event loop</link> use
75  * g_io_add_watch() or g_io_add_watch_full(). Here you specify which
76  * events you are interested in on the #GIOChannel, and provide a
77  * function to be called whenever these events occur.
78  *
79  * #GIOChannel instances are created with an initial reference count of
80  * 1. g_io_channel_ref() and g_io_channel_unref() can be used to
81  * increment or decrement the reference count respectively. When the
82  * reference count falls to 0, the #GIOChannel is freed. (Though it
83  * isn't closed automatically, unless it was created using
84  * g_io_channel_new_file().) Using g_io_add_watch() or
85  * g_io_add_watch_full() increments a channel's reference count.
86  *
87  * The new functions g_io_channel_read_chars(),
88  * g_io_channel_read_line(), g_io_channel_read_line_string(),
89  * g_io_channel_read_to_end(), g_io_channel_write_chars(),
90  * g_io_channel_seek_position(), and g_io_channel_flush() should not be
91  * mixed with the deprecated functions g_io_channel_read(),
92  * g_io_channel_write(), and g_io_channel_seek() on the same channel.
93  **/
94
95 /**
96  * GIOChannel:
97  *
98  * A data structure representing an IO Channel. The fields should be
99  * considered private and should only be accessed with the following
100  * functions.
101  **/
102
103 /**
104  * GIOFuncs:
105  * @io_read: reads raw bytes from the channel.  This is called from
106  *           various functions such as g_io_channel_read_chars() to
107  *           read raw bytes from the channel.  Encoding and buffering
108  *           issues are dealt with at a higher level.
109  * @io_write: writes raw bytes to the channel.  This is called from
110  *            various functions such as g_io_channel_write_chars() to
111  *            write raw bytes to the channel.  Encoding and buffering
112  *            issues are dealt with at a higher level.
113  * @io_seek: &lpar;optional&rpar; seeks the channel.  This is called from
114  *           g_io_channel_seek() on channels that support it.
115  * @io_close: closes the channel.  This is called from
116  *            g_io_channel_close() after flushing the buffers.
117  * @io_create_watch: creates a watch on the channel.  This call
118  *                   corresponds directly to g_io_create_watch().
119  * @io_free: called from g_io_channel_unref() when the channel needs to
120  *           be freed.  This function must free the memory associated
121  *           with the channel, including freeing the #GIOChannel
122  *           structure itself.  The channel buffers have been flushed
123  *           and possibly @io_close has been called by the time this
124  *           function is called.
125  * @io_set_flags: sets the #GIOFlags on the channel.  This is called
126  *                from g_io_channel_set_flags() with all flags except
127  *                for %G_IO_FLAG_APPEND and %G_IO_FLAG_NONBLOCK masked
128  *                out.
129  * @io_get_flags: gets the #GIOFlags for the channel.  This function
130  *                need only return the %G_IO_FLAG_APPEND and
131  *                %G_IO_FLAG_NONBLOCK flags; g_io_channel_get_flags()
132  *                automatically adds the others as appropriate.
133  *
134  * A table of functions used to handle different types of #GIOChannel
135  * in a generic way.
136  **/
137
138 /**
139  * GIOStatus:
140  * @G_IO_STATUS_ERROR: An error occurred.
141  * @G_IO_STATUS_NORMAL: Success.
142  * @G_IO_STATUS_EOF: End of file.
143  * @G_IO_STATUS_AGAIN: Resource temporarily unavailable.
144  *
145  * Stati returned by most of the #GIOFuncs functions.
146  **/
147
148 /**
149  * GIOError:
150  * @G_IO_ERROR_NONE: no error
151  * @G_IO_ERROR_AGAIN: an EAGAIN error occurred
152  * @G_IO_ERROR_INVAL: an EINVAL error occurred
153  * @G_IO_ERROR_UNKNOWN: another error occurred
154  *
155  * #GIOError is only used by the deprecated functions
156  * g_io_channel_read(), g_io_channel_write(), and g_io_channel_seek().
157  **/
158
159 #define G_IO_NICE_BUF_SIZE      1024
160
161 /* This needs to be as wide as the largest character in any possible encoding */
162 #define MAX_CHAR_SIZE           10
163
164 /* Some simplifying macros, which reduce the need to worry whether the
165  * buffers have been allocated. These also make USE_BUF () an lvalue,
166  * which is used in g_io_channel_read_to_end ().
167  */
168 #define USE_BUF(channel)        ((channel)->encoding ? (channel)->encoded_read_buf \
169                                  : (channel)->read_buf)
170 #define BUF_LEN(string)         ((string) ? (string)->len : 0)
171
172 static GIOError         g_io_error_get_from_g_error     (GIOStatus    status,
173                                                          GError      *err);
174 static void             g_io_channel_purge              (GIOChannel  *channel);
175 static GIOStatus        g_io_channel_fill_buffer        (GIOChannel  *channel,
176                                                          GError     **err);
177 static GIOStatus        g_io_channel_read_line_backend  (GIOChannel  *channel,
178                                                          gsize       *length,
179                                                          gsize       *terminator_pos,
180                                                          GError     **error);
181
182 /**
183  * g_io_channel_init:
184  * @channel: a #GIOChannel
185  *
186  * Initializes a #GIOChannel struct. 
187  *
188  * This is called by each of the above functions when creating a 
189  * #GIOChannel, and so is not often needed by the application 
190  * programmer (unless you are creating a new type of #GIOChannel).
191  */
192 void
193 g_io_channel_init (GIOChannel *channel)
194 {
195   channel->ref_count = 1;
196   channel->encoding = g_strdup ("UTF-8");
197   channel->line_term = NULL;
198   channel->line_term_len = 0;
199   channel->buf_size = G_IO_NICE_BUF_SIZE;
200   channel->read_cd = (GIConv) -1;
201   channel->write_cd = (GIConv) -1;
202   channel->read_buf = NULL; /* Lazy allocate buffers */
203   channel->encoded_read_buf = NULL;
204   channel->write_buf = NULL;
205   channel->partial_write_buf[0] = '\0';
206   channel->use_buffer = TRUE;
207   channel->do_encode = FALSE;
208   channel->close_on_unref = FALSE;
209 }
210
211 /**
212  * g_io_channel_ref:
213  * @channel: a #GIOChannel
214  *
215  * Increments the reference count of a #GIOChannel.
216  *
217  * Returns: the @channel that was passed in (since 2.6)
218  */
219 GIOChannel *
220 g_io_channel_ref (GIOChannel *channel)
221 {
222   g_return_val_if_fail (channel != NULL, NULL);
223
224   g_atomic_int_inc (&channel->ref_count);
225
226   return channel;
227 }
228
229 /**
230  * g_io_channel_unref:
231  * @channel: a #GIOChannel
232  *
233  * Decrements the reference count of a #GIOChannel.
234  */
235 void 
236 g_io_channel_unref (GIOChannel *channel)
237 {
238   gboolean is_zero;
239
240   g_return_if_fail (channel != NULL);
241
242   is_zero = g_atomic_int_dec_and_test (&channel->ref_count);
243
244   if (G_UNLIKELY (is_zero))
245     {
246       if (channel->close_on_unref)
247         g_io_channel_shutdown (channel, TRUE, NULL);
248       else
249         g_io_channel_purge (channel);
250       g_free (channel->encoding);
251       if (channel->read_cd != (GIConv) -1)
252         g_iconv_close (channel->read_cd);
253       if (channel->write_cd != (GIConv) -1)
254         g_iconv_close (channel->write_cd);
255       g_free (channel->line_term);
256       if (channel->read_buf)
257         g_string_free (channel->read_buf, TRUE);
258       if (channel->write_buf)
259         g_string_free (channel->write_buf, TRUE);
260       if (channel->encoded_read_buf)
261         g_string_free (channel->encoded_read_buf, TRUE);
262       channel->funcs->io_free (channel);
263     }
264 }
265
266 static GIOError
267 g_io_error_get_from_g_error (GIOStatus  status,
268                              GError    *err)
269 {
270   switch (status)
271     {
272       case G_IO_STATUS_NORMAL:
273       case G_IO_STATUS_EOF:
274         return G_IO_ERROR_NONE;
275       case G_IO_STATUS_AGAIN:
276         return G_IO_ERROR_AGAIN;
277       case G_IO_STATUS_ERROR:
278         g_return_val_if_fail (err != NULL, G_IO_ERROR_UNKNOWN);
279         
280         if (err->domain != G_IO_CHANNEL_ERROR)
281           return G_IO_ERROR_UNKNOWN;
282         switch (err->code)
283           {
284             case G_IO_CHANNEL_ERROR_INVAL:
285               return G_IO_ERROR_INVAL;
286             default:
287               return G_IO_ERROR_UNKNOWN;
288           }
289       default:
290         g_assert_not_reached ();
291     }
292 }
293
294 /**
295  * g_io_channel_read:
296  * @channel: a #GIOChannel
297  * @buf: a buffer to read the data into (which should be at least 
298  *       count bytes long)
299  * @count: the number of bytes to read from the #GIOChannel
300  * @bytes_read: returns the number of bytes actually read
301  * 
302  * Reads data from a #GIOChannel. 
303  * 
304  * Return value: %G_IO_ERROR_NONE if the operation was successful. 
305  *
306  * Deprecated:2.2: Use g_io_channel_read_chars() instead.
307  **/
308 GIOError 
309 g_io_channel_read (GIOChannel *channel, 
310                    gchar      *buf, 
311                    gsize       count,
312                    gsize      *bytes_read)
313 {
314   GError *err = NULL;
315   GIOError error;
316   GIOStatus status;
317
318   g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
319   g_return_val_if_fail (bytes_read != NULL, G_IO_ERROR_UNKNOWN);
320
321   if (count == 0)
322     {
323       if (bytes_read)
324         *bytes_read = 0;
325       return G_IO_ERROR_NONE;
326     }
327
328   g_return_val_if_fail (buf != NULL, G_IO_ERROR_UNKNOWN);
329
330   status = channel->funcs->io_read (channel, buf, count, bytes_read, &err);
331
332   error = g_io_error_get_from_g_error (status, err);
333
334   if (err)
335     g_error_free (err);
336
337   return error;
338 }
339
340 /**
341  * g_io_channel_write:
342  * @channel:  a #GIOChannel
343  * @buf: the buffer containing the data to write
344  * @count: the number of bytes to write
345  * @bytes_written: the number of bytes actually written
346  * 
347  * Writes data to a #GIOChannel. 
348  * 
349  * Return value:  %G_IO_ERROR_NONE if the operation was successful.
350  *
351  * Deprecated:2.2: Use g_io_channel_write_chars() instead.
352  **/
353 GIOError 
354 g_io_channel_write (GIOChannel  *channel, 
355                     const gchar *buf, 
356                     gsize        count,
357                     gsize       *bytes_written)
358 {
359   GError *err = NULL;
360   GIOError error;
361   GIOStatus status;
362
363   g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
364   g_return_val_if_fail (bytes_written != NULL, G_IO_ERROR_UNKNOWN);
365
366   status = channel->funcs->io_write (channel, buf, count, bytes_written, &err);
367
368   error = g_io_error_get_from_g_error (status, err);
369
370   if (err)
371     g_error_free (err);
372
373   return error;
374 }
375
376 /**
377  * g_io_channel_seek:
378  * @channel: a #GIOChannel
379  * @offset: an offset, in bytes, which is added to the position specified 
380  *          by @type
381  * @type: the position in the file, which can be %G_SEEK_CUR (the current
382  *        position), %G_SEEK_SET (the start of the file), or %G_SEEK_END 
383  *        (the end of the file)
384  * 
385  * Sets the current position in the #GIOChannel, similar to the standard 
386  * library function fseek(). 
387  * 
388  * Return value: %G_IO_ERROR_NONE if the operation was successful.
389  *
390  * Deprecated:2.2: Use g_io_channel_seek_position() instead.
391  **/
392 GIOError 
393 g_io_channel_seek (GIOChannel *channel,
394                    gint64      offset, 
395                    GSeekType   type)
396 {
397   GError *err = NULL;
398   GIOError error;
399   GIOStatus status;
400
401   g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
402   g_return_val_if_fail (channel->is_seekable, G_IO_ERROR_UNKNOWN);
403
404   switch (type)
405     {
406       case G_SEEK_CUR:
407       case G_SEEK_SET:
408       case G_SEEK_END:
409         break;
410       default:
411         g_warning ("g_io_channel_seek: unknown seek type");
412         return G_IO_ERROR_UNKNOWN;
413     }
414
415   status = channel->funcs->io_seek (channel, offset, type, &err);
416
417   error = g_io_error_get_from_g_error (status, err);
418
419   if (err)
420     g_error_free (err);
421
422   return error;
423 }
424
425 /* The function g_io_channel_new_file() is prototyped in both
426  * giounix.c and giowin32.c, so we stick its documentation here.
427  */
428
429 /**
430  * g_io_channel_new_file:
431  * @filename: A string containing the name of a file
432  * @mode: One of "r", "w", "a", "r+", "w+", "a+". These have
433  *        the same meaning as in fopen()
434  * @error: A location to return an error of type %G_FILE_ERROR
435  *
436  * Open a file @filename as a #GIOChannel using mode @mode. This
437  * channel will be closed when the last reference to it is dropped,
438  * so there is no need to call g_io_channel_close() (though doing
439  * so will not cause problems, as long as no attempt is made to
440  * access the channel after it is closed).
441  *
442  * Return value: A #GIOChannel on success, %NULL on failure.
443  **/
444
445 /**
446  * g_io_channel_close:
447  * @channel: A #GIOChannel
448  * 
449  * Close an IO channel. Any pending data to be written will be
450  * flushed, ignoring errors. The channel will not be freed until the
451  * last reference is dropped using g_io_channel_unref(). 
452  *
453  * Deprecated:2.2: Use g_io_channel_shutdown() instead.
454  **/
455 void
456 g_io_channel_close (GIOChannel *channel)
457 {
458   GError *err = NULL;
459   
460   g_return_if_fail (channel != NULL);
461
462   g_io_channel_purge (channel);
463
464   channel->funcs->io_close (channel, &err);
465
466   if (err)
467     { /* No way to return the error */
468       g_warning ("Error closing channel: %s", err->message);
469       g_error_free (err);
470     }
471   
472   channel->close_on_unref = FALSE; /* Because we already did */
473   channel->is_readable = FALSE;
474   channel->is_writeable = FALSE;
475   channel->is_seekable = FALSE;
476 }
477
478 /**
479  * g_io_channel_shutdown:
480  * @channel: a #GIOChannel
481  * @flush: if %TRUE, flush pending
482  * @err: location to store a #GIOChannelError
483  * 
484  * Close an IO channel. Any pending data to be written will be
485  * flushed if @flush is %TRUE. The channel will not be freed until the
486  * last reference is dropped using g_io_channel_unref().
487  *
488  * Return value: the status of the operation.
489  **/
490 GIOStatus
491 g_io_channel_shutdown (GIOChannel  *channel,
492                        gboolean     flush,
493                        GError     **err)
494 {
495   GIOStatus status, result;
496   GError *tmperr = NULL;
497   
498   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
499   g_return_val_if_fail (err == NULL || *err == NULL, G_IO_STATUS_ERROR);
500
501   if (channel->write_buf && channel->write_buf->len > 0)
502     {
503       if (flush)
504         {
505           GIOFlags flags;
506       
507           /* Set the channel to blocking, to avoid a busy loop
508            */
509           flags = g_io_channel_get_flags (channel);
510           /* Ignore any errors here, they're irrelevant */
511           g_io_channel_set_flags (channel, flags & ~G_IO_FLAG_NONBLOCK, NULL);
512
513           result = g_io_channel_flush (channel, &tmperr);
514         }
515       else
516         result = G_IO_STATUS_NORMAL;
517
518       g_string_truncate(channel->write_buf, 0);
519     }
520   else
521     result = G_IO_STATUS_NORMAL;
522
523   if (channel->partial_write_buf[0] != '\0')
524     {
525       if (flush)
526         g_warning ("Partial character at end of write buffer not flushed.\n");
527       channel->partial_write_buf[0] = '\0';
528     }
529
530   status = channel->funcs->io_close (channel, err);
531
532   channel->close_on_unref = FALSE; /* Because we already did */
533   channel->is_readable = FALSE;
534   channel->is_writeable = FALSE;
535   channel->is_seekable = FALSE;
536
537   if (status != G_IO_STATUS_NORMAL)
538     {
539       g_clear_error (&tmperr);
540       return status;
541     }
542   else if (result != G_IO_STATUS_NORMAL)
543     {
544       g_propagate_error (err, tmperr);
545       return result;
546     }
547   else
548     return G_IO_STATUS_NORMAL;
549 }
550
551 /* This function is used for the final flush on close or unref */
552 static void
553 g_io_channel_purge (GIOChannel *channel)
554 {
555   GError *err = NULL;
556   GIOStatus status G_GNUC_UNUSED;
557
558   g_return_if_fail (channel != NULL);
559
560   if (channel->write_buf && channel->write_buf->len > 0)
561     {
562       GIOFlags flags;
563
564       /* Set the channel to blocking, to avoid a busy loop
565        */
566       flags = g_io_channel_get_flags (channel);
567       g_io_channel_set_flags (channel, flags & ~G_IO_FLAG_NONBLOCK, NULL);
568
569       status = g_io_channel_flush (channel, &err);
570
571       if (err)
572         { /* No way to return the error */
573           g_warning ("Error flushing string: %s", err->message);
574           g_error_free (err);
575         }
576     }
577
578   /* Flush these in case anyone tries to close without unrefing */
579
580   if (channel->read_buf)
581     g_string_truncate (channel->read_buf, 0);
582   if (channel->write_buf)
583     g_string_truncate (channel->write_buf, 0);
584   if (channel->encoding)
585     {
586       if (channel->encoded_read_buf)
587         g_string_truncate (channel->encoded_read_buf, 0);
588
589       if (channel->partial_write_buf[0] != '\0')
590         {
591           g_warning ("Partial character at end of write buffer not flushed.\n");
592           channel->partial_write_buf[0] = '\0';
593         }
594     }
595 }
596
597 /**
598  * g_io_create_watch:
599  * @channel: a #GIOChannel to watch
600  * @condition: conditions to watch for
601  *
602  * Creates a #GSource that's dispatched when @condition is met for the 
603  * given @channel. For example, if condition is #G_IO_IN, the source will 
604  * be dispatched when there's data available for reading.
605  *
606  * g_io_add_watch() is a simpler interface to this same functionality, for 
607  * the case where you want to add the source to the default main loop context 
608  * at the default priority.
609  *
610  * On Windows, polling a #GSource created to watch a channel for a socket
611  * puts the socket in non-blocking mode. This is a side-effect of the
612  * implementation and unavoidable.
613  *
614  * Returns: a new #GSource
615  */
616 GSource *
617 g_io_create_watch (GIOChannel   *channel,
618                    GIOCondition  condition)
619 {
620   g_return_val_if_fail (channel != NULL, NULL);
621
622   return channel->funcs->io_create_watch (channel, condition);
623 }
624
625 /**
626  * g_io_add_watch_full:
627  * @channel: a #GIOChannel
628  * @priority: the priority of the #GIOChannel source
629  * @condition: the condition to watch for
630  * @func: the function to call when the condition is satisfied
631  * @user_data: user data to pass to @func
632  * @notify: the function to call when the source is removed
633  *
634  * Adds the #GIOChannel into the default main loop context
635  * with the given priority.
636  *
637  * This internally creates a main loop source using g_io_create_watch()
638  * and attaches it to the main loop context with g_source_attach().
639  * You can do these steps manually if you need greater control.
640  *
641  * Returns: the event source id
642  * Rename to: g_io_add_watch
643  */
644 guint 
645 g_io_add_watch_full (GIOChannel    *channel,
646                      gint           priority,
647                      GIOCondition   condition,
648                      GIOFunc        func,
649                      gpointer       user_data,
650                      GDestroyNotify notify)
651 {
652   GSource *source;
653   guint id;
654   
655   g_return_val_if_fail (channel != NULL, 0);
656
657   source = g_io_create_watch (channel, condition);
658
659   if (priority != G_PRIORITY_DEFAULT)
660     g_source_set_priority (source, priority);
661   g_source_set_callback (source, (GSourceFunc)func, user_data, notify);
662
663   id = g_source_attach (source, NULL);
664   g_source_unref (source);
665
666   return id;
667 }
668
669 /**
670  * g_io_add_watch:
671  * @channel: a #GIOChannel
672  * @condition: the condition to watch for
673  * @func: the function to call when the condition is satisfied
674  * @user_data: user data to pass to @func
675  *
676  * Adds the #GIOChannel into the default main loop context
677  * with the default priority.
678  *
679  * Returns: the event source id
680  */
681 /**
682  * GIOFunc:
683  * @source: the #GIOChannel event source
684  * @condition: the condition which has been satisfied
685  * @data: user data set in g_io_add_watch() or g_io_add_watch_full()
686  *
687  * Specifies the type of function passed to g_io_add_watch() or
688  * g_io_add_watch_full(), which is called when the requested condition
689  * on a #GIOChannel is satisfied.
690  *
691  * Returns: the function should return %FALSE if the event source
692  *          should be removed
693  **/
694 /**
695  * GIOCondition:
696  * @G_IO_IN: There is data to read.
697  * @G_IO_OUT: Data can be written (without blocking).
698  * @G_IO_PRI: There is urgent data to read.
699  * @G_IO_ERR: Error condition.
700  * @G_IO_HUP: Hung up (the connection has been broken, usually for
701  *            pipes and sockets).
702  * @G_IO_NVAL: Invalid request. The file descriptor is not open.
703  *
704  * A bitwise combination representing a condition to watch for on an
705  * event source.
706  **/
707 guint 
708 g_io_add_watch (GIOChannel   *channel,
709                 GIOCondition  condition,
710                 GIOFunc       func,
711                 gpointer      user_data)
712 {
713   return g_io_add_watch_full (channel, G_PRIORITY_DEFAULT, condition, func, user_data, NULL);
714 }
715
716 /**
717  * g_io_channel_get_buffer_condition:
718  * @channel: A #GIOChannel
719  *
720  * This function returns a #GIOCondition depending on whether there
721  * is data to be read/space to write data in the internal buffers in 
722  * the #GIOChannel. Only the flags %G_IO_IN and %G_IO_OUT may be set.
723  *
724  * Return value: A #GIOCondition
725  **/
726 GIOCondition
727 g_io_channel_get_buffer_condition (GIOChannel *channel)
728 {
729   GIOCondition condition = 0;
730
731   if (channel->encoding)
732     {
733       if (channel->encoded_read_buf && (channel->encoded_read_buf->len > 0))
734         condition |= G_IO_IN; /* Only return if we have full characters */
735     }
736   else
737     {
738       if (channel->read_buf && (channel->read_buf->len > 0))
739         condition |= G_IO_IN;
740     }
741
742   if (channel->write_buf && (channel->write_buf->len < channel->buf_size))
743     condition |= G_IO_OUT;
744
745   return condition;
746 }
747
748 /**
749  * g_io_channel_error_from_errno:
750  * @en: an <literal>errno</literal> error number, e.g. <literal>EINVAL</literal>
751  *
752  * Converts an <literal>errno</literal> error number to a #GIOChannelError.
753  *
754  * Return value: a #GIOChannelError error number, e.g. 
755  *      %G_IO_CHANNEL_ERROR_INVAL.
756  **/
757 GIOChannelError
758 g_io_channel_error_from_errno (gint en)
759 {
760 #ifdef EAGAIN
761   g_return_val_if_fail (en != EAGAIN, G_IO_CHANNEL_ERROR_FAILED);
762 #endif
763
764   switch (en)
765     {
766 #ifdef EBADF
767     case EBADF:
768       g_warning("Invalid file descriptor.\n");
769       return G_IO_CHANNEL_ERROR_FAILED;
770 #endif
771
772 #ifdef EFAULT
773     case EFAULT:
774       g_warning("Buffer outside valid address space.\n");
775       return G_IO_CHANNEL_ERROR_FAILED;
776 #endif
777
778 #ifdef EFBIG
779     case EFBIG:
780       return G_IO_CHANNEL_ERROR_FBIG;
781 #endif
782
783 #ifdef EINTR
784     /* In general, we should catch EINTR before we get here,
785      * but close() is allowed to return EINTR by POSIX, so
786      * we need to catch it here; EINTR from close() is
787      * unrecoverable, because it's undefined whether
788      * the fd was actually closed or not, so we just return
789      * a generic error code.
790      */
791     case EINTR:
792       return G_IO_CHANNEL_ERROR_FAILED;
793 #endif
794
795 #ifdef EINVAL
796     case EINVAL:
797       return G_IO_CHANNEL_ERROR_INVAL;
798 #endif
799
800 #ifdef EIO
801     case EIO:
802       return G_IO_CHANNEL_ERROR_IO;
803 #endif
804
805 #ifdef EISDIR
806     case EISDIR:
807       return G_IO_CHANNEL_ERROR_ISDIR;
808 #endif
809
810 #ifdef ENOSPC
811     case ENOSPC:
812       return G_IO_CHANNEL_ERROR_NOSPC;
813 #endif
814
815 #ifdef ENXIO
816     case ENXIO:
817       return G_IO_CHANNEL_ERROR_NXIO;
818 #endif
819
820 #ifdef EOVERFLOW
821 #if EOVERFLOW != EFBIG
822     case EOVERFLOW:
823       return G_IO_CHANNEL_ERROR_OVERFLOW;
824 #endif
825 #endif
826
827 #ifdef EPIPE
828     case EPIPE:
829       return G_IO_CHANNEL_ERROR_PIPE;
830 #endif
831
832     default:
833       return G_IO_CHANNEL_ERROR_FAILED;
834     }
835 }
836
837 /**
838  * g_io_channel_set_buffer_size:
839  * @channel: a #GIOChannel
840  * @size: the size of the buffer, or 0 to let GLib pick a good size
841  *
842  * Sets the buffer size.
843  **/  
844 void
845 g_io_channel_set_buffer_size (GIOChannel *channel,
846                               gsize       size)
847 {
848   g_return_if_fail (channel != NULL);
849
850   if (size == 0)
851     size = G_IO_NICE_BUF_SIZE;
852
853   if (size < MAX_CHAR_SIZE)
854     size = MAX_CHAR_SIZE;
855
856   channel->buf_size = size;
857 }
858
859 /**
860  * g_io_channel_get_buffer_size:
861  * @channel: a #GIOChannel
862  *
863  * Gets the buffer size.
864  *
865  * Return value: the size of the buffer.
866  **/  
867 gsize
868 g_io_channel_get_buffer_size (GIOChannel *channel)
869 {
870   g_return_val_if_fail (channel != NULL, 0);
871
872   return channel->buf_size;
873 }
874
875 /**
876  * g_io_channel_set_line_term:
877  * @channel: a #GIOChannel
878  * @line_term: (allow-none): The line termination string. Use %NULL for
879  *             autodetect.  Autodetection breaks on "\n", "\r\n", "\r", "\0",
880  *             and the Unicode paragraph separator. Autodetection should not be
881  *             used for anything other than file-based channels.
882  * @length: The length of the termination string. If -1 is passed, the
883  *          string is assumed to be nul-terminated. This option allows
884  *          termination strings with embedded nuls.
885  *
886  * This sets the string that #GIOChannel uses to determine
887  * where in the file a line break occurs.
888  **/
889 void
890 g_io_channel_set_line_term (GIOChannel  *channel,
891                             const gchar *line_term,
892                             gint         length)
893 {
894   g_return_if_fail (channel != NULL);
895   g_return_if_fail (line_term == NULL || length != 0); /* Disallow "" */
896
897   if (line_term == NULL)
898     length = 0;
899   else if (length < 0)
900     length = strlen (line_term);
901
902   g_free (channel->line_term);
903   channel->line_term = line_term ? g_memdup (line_term, length) : NULL;
904   channel->line_term_len = length;
905 }
906
907 /**
908  * g_io_channel_get_line_term:
909  * @channel: a #GIOChannel
910  * @length: a location to return the length of the line terminator
911  *
912  * This returns the string that #GIOChannel uses to determine
913  * where in the file a line break occurs. A value of %NULL
914  * indicates autodetection.
915  *
916  * Return value: The line termination string. This value
917  *   is owned by GLib and must not be freed.
918  **/
919 const gchar *
920 g_io_channel_get_line_term (GIOChannel *channel,
921                             gint       *length)
922 {
923   g_return_val_if_fail (channel != NULL, NULL);
924
925   if (length)
926     *length = channel->line_term_len;
927
928   return channel->line_term;
929 }
930
931 /**
932  * g_io_channel_set_flags:
933  * @channel: a #GIOChannel
934  * @flags: the flags to set on the IO channel
935  * @error: A location to return an error of type #GIOChannelError
936  *
937  * Sets the (writeable) flags in @channel to (@flags & %G_IO_FLAG_SET_MASK).
938  *
939  * Return value: the status of the operation. 
940  **/
941 /**
942  * GIOFlags:
943  * @G_IO_FLAG_APPEND: turns on append mode, corresponds to <literal>O_APPEND</literal>
944  *                    (see the documentation of the UNIX open()
945  *                    syscall).
946  * @G_IO_FLAG_NONBLOCK: turns on nonblocking mode, corresponds to
947  *                      <literal>O_NONBLOCK</literal>/<literal>O_NDELAY</literal>
948  *                      (see the documentation of the UNIX open() syscall).
949  * @G_IO_FLAG_IS_READABLE: indicates that the io channel is readable.
950  *                         This flag cannot be changed.
951  * @G_IO_FLAG_IS_WRITABLE: indicates that the io channel is writable.
952  *                          This flag cannot be changed.
953  * @G_IO_FLAG_IS_SEEKABLE: indicates that the io channel is seekable,
954  *                         i.e. that g_io_channel_seek_position() can
955  *                         be used on it.  This flag cannot be changed.
956  * @G_IO_FLAG_MASK: the mask that specifies all the valid flags.
957  * @G_IO_FLAG_GET_MASK: the mask of the flags that are returned from
958  *                      g_io_channel_get_flags().
959  * @G_IO_FLAG_SET_MASK: the mask of the flags that the user can modify
960  *                      with g_io_channel_set_flags().
961  *
962  * Specifies properties of a #GIOChannel. Some of the flags can only be
963  * read with g_io_channel_get_flags(), but not changed with
964  * g_io_channel_set_flags().
965  **/
966 /**
967  * G_IO_FLAG_IS_WRITEABLE:
968  *
969  * This is a misspelled version of G_IO_FLAG_IS_WRITABLE that existed
970  * before the spelling was fixed in GLib 2.30.  It is kept here for
971  * compatibility reasons.
972  *
973  * Deprecated:2.30:Use G_IO_FLAG_IS_WRITABLE instead.
974  **/
975 GIOStatus
976 g_io_channel_set_flags (GIOChannel  *channel,
977                         GIOFlags     flags,
978                         GError     **error)
979 {
980   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
981   g_return_val_if_fail ((error == NULL) || (*error == NULL),
982                         G_IO_STATUS_ERROR);
983
984   return (*channel->funcs->io_set_flags) (channel,
985                                           flags & G_IO_FLAG_SET_MASK,
986                                           error);
987 }
988
989 /**
990  * g_io_channel_get_flags:
991  * @channel: a #GIOChannel
992  *
993  * Gets the current flags for a #GIOChannel, including read-only
994  * flags such as %G_IO_FLAG_IS_READABLE.
995  *
996  * The values of the flags %G_IO_FLAG_IS_READABLE and %G_IO_FLAG_IS_WRITABLE
997  * are cached for internal use by the channel when it is created.
998  * If they should change at some later point (e.g. partial shutdown
999  * of a socket with the UNIX shutdown() function), the user
1000  * should immediately call g_io_channel_get_flags() to update
1001  * the internal values of these flags.
1002  *
1003  * Return value: the flags which are set on the channel
1004  **/
1005 GIOFlags
1006 g_io_channel_get_flags (GIOChannel *channel)
1007 {
1008   GIOFlags flags;
1009
1010   g_return_val_if_fail (channel != NULL, 0);
1011
1012   flags = (* channel->funcs->io_get_flags) (channel);
1013
1014   /* Cross implementation code */
1015
1016   if (channel->is_seekable)
1017     flags |= G_IO_FLAG_IS_SEEKABLE;
1018   if (channel->is_readable)
1019     flags |= G_IO_FLAG_IS_READABLE;
1020   if (channel->is_writeable)
1021     flags |= G_IO_FLAG_IS_WRITABLE;
1022
1023   return flags;
1024 }
1025
1026 /**
1027  * g_io_channel_set_close_on_unref:
1028  * @channel: a #GIOChannel
1029  * @do_close: Whether to close the channel on the final unref of
1030  *            the GIOChannel data structure. The default value of
1031  *            this is %TRUE for channels created by g_io_channel_new_file (),
1032  *            and %FALSE for all other channels.
1033  *
1034  * Setting this flag to %TRUE for a channel you have already closed
1035  * can cause problems.
1036  **/
1037 void
1038 g_io_channel_set_close_on_unref (GIOChannel *channel,
1039                                  gboolean    do_close)
1040 {
1041   g_return_if_fail (channel != NULL);
1042
1043   channel->close_on_unref = do_close;
1044 }
1045
1046 /**
1047  * g_io_channel_get_close_on_unref:
1048  * @channel: a #GIOChannel.
1049  *
1050  * Returns whether the file/socket/whatever associated with @channel
1051  * will be closed when @channel receives its final unref and is
1052  * destroyed. The default value of this is %TRUE for channels created
1053  * by g_io_channel_new_file (), and %FALSE for all other channels.
1054  *
1055  * Return value: Whether the channel will be closed on the final unref of
1056  *               the GIOChannel data structure.
1057  **/
1058 gboolean
1059 g_io_channel_get_close_on_unref (GIOChannel *channel)
1060 {
1061   g_return_val_if_fail (channel != NULL, FALSE);
1062
1063   return channel->close_on_unref;
1064 }
1065
1066 /**
1067  * g_io_channel_seek_position:
1068  * @channel: a #GIOChannel
1069  * @offset: The offset in bytes from the position specified by @type
1070  * @type: a #GSeekType. The type %G_SEEK_CUR is only allowed in those
1071  *                      cases where a call to g_io_channel_set_encoding ()
1072  *                      is allowed. See the documentation for
1073  *                      g_io_channel_set_encoding () for details.
1074  * @error: A location to return an error of type #GIOChannelError
1075  *
1076  * Replacement for g_io_channel_seek() with the new API.
1077  *
1078  * Return value: the status of the operation.
1079  **/
1080 /**
1081  * GSeekType:
1082  * @G_SEEK_CUR: the current position in the file.
1083  * @G_SEEK_SET: the start of the file.
1084  * @G_SEEK_END: the end of the file.
1085  *
1086  * An enumeration specifying the base position for a
1087  * g_io_channel_seek_position() operation.
1088  **/
1089 GIOStatus
1090 g_io_channel_seek_position (GIOChannel  *channel,
1091                             gint64       offset,
1092                             GSeekType    type,
1093                             GError     **error)
1094 {
1095   GIOStatus status;
1096
1097   /* For files, only one of the read and write buffers can contain data.
1098    * For sockets, both can contain data.
1099    */
1100
1101   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1102   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1103                         G_IO_STATUS_ERROR);
1104   g_return_val_if_fail (channel->is_seekable, G_IO_STATUS_ERROR);
1105
1106   switch (type)
1107     {
1108       case G_SEEK_CUR: /* The user is seeking relative to the head of the buffer */
1109         if (channel->use_buffer)
1110           {
1111             if (channel->do_encode && channel->encoded_read_buf
1112                 && channel->encoded_read_buf->len > 0)
1113               {
1114                 g_warning ("Seek type G_SEEK_CUR not allowed for this"
1115                   " channel's encoding.\n");
1116                 return G_IO_STATUS_ERROR;
1117               }
1118           if (channel->read_buf)
1119             offset -= channel->read_buf->len;
1120           if (channel->encoded_read_buf)
1121             {
1122               g_assert (channel->encoded_read_buf->len == 0 || !channel->do_encode);
1123
1124               /* If there's anything here, it's because the encoding is UTF-8,
1125                * so we can just subtract the buffer length, the same as for
1126                * the unencoded data.
1127                */
1128
1129               offset -= channel->encoded_read_buf->len;
1130             }
1131           }
1132         break;
1133       case G_SEEK_SET:
1134       case G_SEEK_END:
1135         break;
1136       default:
1137         g_warning ("g_io_channel_seek_position: unknown seek type");
1138         return G_IO_STATUS_ERROR;
1139     }
1140
1141   if (channel->use_buffer)
1142     {
1143       status = g_io_channel_flush (channel, error);
1144       if (status != G_IO_STATUS_NORMAL)
1145         return status;
1146     }
1147
1148   status = channel->funcs->io_seek (channel, offset, type, error);
1149
1150   if ((status == G_IO_STATUS_NORMAL) && (channel->use_buffer))
1151     {
1152       if (channel->read_buf)
1153         g_string_truncate (channel->read_buf, 0);
1154
1155       /* Conversion state no longer matches position in file */
1156       if (channel->read_cd != (GIConv) -1)
1157         g_iconv (channel->read_cd, NULL, NULL, NULL, NULL);
1158       if (channel->write_cd != (GIConv) -1)
1159         g_iconv (channel->write_cd, NULL, NULL, NULL, NULL);
1160
1161       if (channel->encoded_read_buf)
1162         {
1163           g_assert (channel->encoded_read_buf->len == 0 || !channel->do_encode);
1164           g_string_truncate (channel->encoded_read_buf, 0);
1165         }
1166
1167       if (channel->partial_write_buf[0] != '\0')
1168         {
1169           g_warning ("Partial character at end of write buffer not flushed.\n");
1170           channel->partial_write_buf[0] = '\0';
1171         }
1172     }
1173
1174   return status;
1175 }
1176
1177 /**
1178  * g_io_channel_flush:
1179  * @channel: a #GIOChannel
1180  * @error: location to store an error of type #GIOChannelError
1181  *
1182  * Flushes the write buffer for the GIOChannel.
1183  *
1184  * Return value: the status of the operation: One of
1185  *   #G_IO_STATUS_NORMAL, #G_IO_STATUS_AGAIN, or
1186  *   #G_IO_STATUS_ERROR.
1187  **/
1188 GIOStatus
1189 g_io_channel_flush (GIOChannel  *channel,
1190                     GError     **error)
1191 {
1192   GIOStatus status;
1193   gsize this_time = 1, bytes_written = 0;
1194
1195   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1196   g_return_val_if_fail ((error == NULL) || (*error == NULL), G_IO_STATUS_ERROR);
1197
1198   if (channel->write_buf == NULL || channel->write_buf->len == 0)
1199     return G_IO_STATUS_NORMAL;
1200
1201   do
1202     {
1203       g_assert (this_time > 0);
1204
1205       status = channel->funcs->io_write (channel,
1206                                          channel->write_buf->str + bytes_written,
1207                                          channel->write_buf->len - bytes_written,
1208                                          &this_time, error);
1209       bytes_written += this_time;
1210     }
1211   while ((bytes_written < channel->write_buf->len)
1212          && (status == G_IO_STATUS_NORMAL));
1213
1214   g_string_erase (channel->write_buf, 0, bytes_written);
1215
1216   return status;
1217 }
1218
1219 /**
1220  * g_io_channel_set_buffered:
1221  * @channel: a #GIOChannel
1222  * @buffered: whether to set the channel buffered or unbuffered
1223  *
1224  * The buffering state can only be set if the channel's encoding
1225  * is %NULL. For any other encoding, the channel must be buffered.
1226  *
1227  * A buffered channel can only be set unbuffered if the channel's
1228  * internal buffers have been flushed. Newly created channels or
1229  * channels which have returned %G_IO_STATUS_EOF
1230  * not require such a flush. For write-only channels, a call to
1231  * g_io_channel_flush () is sufficient. For all other channels,
1232  * the buffers may be flushed by a call to g_io_channel_seek_position ().
1233  * This includes the possibility of seeking with seek type %G_SEEK_CUR
1234  * and an offset of zero. Note that this means that socket-based
1235  * channels cannot be set unbuffered once they have had data
1236  * read from them.
1237  *
1238  * On unbuffered channels, it is safe to mix read and write
1239  * calls from the new and old APIs, if this is necessary for
1240  * maintaining old code.
1241  *
1242  * The default state of the channel is buffered.
1243  **/
1244 void
1245 g_io_channel_set_buffered (GIOChannel *channel,
1246                            gboolean    buffered)
1247 {
1248   g_return_if_fail (channel != NULL);
1249
1250   if (channel->encoding != NULL)
1251     {
1252       g_warning ("Need to have NULL encoding to set the buffering state of the "
1253                  "channel.\n");
1254       return;
1255     }
1256
1257   g_return_if_fail (!channel->read_buf || channel->read_buf->len == 0);
1258   g_return_if_fail (!channel->write_buf || channel->write_buf->len == 0);
1259
1260   channel->use_buffer = buffered;
1261 }
1262
1263 /**
1264  * g_io_channel_get_buffered:
1265  * @channel: a #GIOChannel
1266  *
1267  * Returns whether @channel is buffered.
1268  *
1269  * Return Value: %TRUE if the @channel is buffered. 
1270  **/
1271 gboolean
1272 g_io_channel_get_buffered (GIOChannel *channel)
1273 {
1274   g_return_val_if_fail (channel != NULL, FALSE);
1275
1276   return channel->use_buffer;
1277 }
1278
1279 /**
1280  * g_io_channel_set_encoding:
1281  * @channel: a #GIOChannel
1282  * @encoding: (allow-none): the encoding type
1283  * @error: location to store an error of type #GConvertError
1284  *
1285  * Sets the encoding for the input/output of the channel. 
1286  * The internal encoding is always UTF-8. The default encoding 
1287  * for the external file is UTF-8.
1288  *
1289  * The encoding %NULL is safe to use with binary data.
1290  *
1291  * The encoding can only be set if one of the following conditions
1292  * is true:
1293  * <itemizedlist>
1294  * <listitem><para>
1295  *    The channel was just created, and has not been written to or read 
1296  *    from yet.
1297  * </para></listitem>
1298  * <listitem><para>
1299  *    The channel is write-only.
1300  * </para></listitem>
1301  * <listitem><para>
1302  *    The channel is a file, and the file pointer was just
1303  *    repositioned by a call to g_io_channel_seek_position().
1304  *    (This flushes all the internal buffers.)
1305  * </para></listitem>
1306  * <listitem><para>
1307  *    The current encoding is %NULL or UTF-8.
1308  * </para></listitem>
1309  * <listitem><para>
1310  *    One of the (new API) read functions has just returned %G_IO_STATUS_EOF
1311  *    (or, in the case of g_io_channel_read_to_end(), %G_IO_STATUS_NORMAL).
1312  * </para></listitem>
1313  * <listitem><para>
1314  *    One of the functions g_io_channel_read_chars() or 
1315  *    g_io_channel_read_unichar() has returned %G_IO_STATUS_AGAIN or 
1316  *    %G_IO_STATUS_ERROR. This may be useful in the case of 
1317  *    %G_CONVERT_ERROR_ILLEGAL_SEQUENCE.
1318  *    Returning one of these statuses from g_io_channel_read_line(),
1319  *    g_io_channel_read_line_string(), or g_io_channel_read_to_end()
1320  *    does <emphasis>not</emphasis> guarantee that the encoding can 
1321  *    be changed.
1322  * </para></listitem>
1323  * </itemizedlist>
1324  * Channels which do not meet one of the above conditions cannot call
1325  * g_io_channel_seek_position() with an offset of %G_SEEK_CUR, and, if 
1326  * they are "seekable", cannot call g_io_channel_write_chars() after 
1327  * calling one of the API "read" functions.
1328  *
1329  * Return Value: %G_IO_STATUS_NORMAL if the encoding was successfully set.
1330  **/
1331 GIOStatus
1332 g_io_channel_set_encoding (GIOChannel   *channel,
1333                            const gchar  *encoding,
1334                            GError      **error)
1335 {
1336   GIConv read_cd, write_cd;
1337   gboolean did_encode;
1338
1339   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1340   g_return_val_if_fail ((error == NULL) || (*error == NULL), G_IO_STATUS_ERROR);
1341
1342   /* Make sure the encoded buffers are empty */
1343
1344   g_return_val_if_fail (!channel->do_encode || !channel->encoded_read_buf ||
1345                         channel->encoded_read_buf->len == 0, G_IO_STATUS_ERROR);
1346
1347   if (!channel->use_buffer)
1348     {
1349       g_warning ("Need to set the channel buffered before setting the encoding.\n");
1350       g_warning ("Assuming this is what you meant and acting accordingly.\n");
1351
1352       channel->use_buffer = TRUE;
1353     }
1354
1355   if (channel->partial_write_buf[0] != '\0')
1356     {
1357       g_warning ("Partial character at end of write buffer not flushed.\n");
1358       channel->partial_write_buf[0] = '\0';
1359     }
1360
1361   did_encode = channel->do_encode;
1362
1363   if (!encoding || strcmp (encoding, "UTF8") == 0 || strcmp (encoding, "UTF-8") == 0)
1364     {
1365       channel->do_encode = FALSE;
1366       read_cd = write_cd = (GIConv) -1;
1367     }
1368   else
1369     {
1370       gint err = 0;
1371       const gchar *from_enc = NULL, *to_enc = NULL;
1372
1373       if (channel->is_readable)
1374         {
1375           read_cd = g_iconv_open ("UTF-8", encoding);
1376
1377           if (read_cd == (GIConv) -1)
1378             {
1379               err = errno;
1380               from_enc = encoding;
1381               to_enc = "UTF-8";
1382             }
1383         }
1384       else
1385         read_cd = (GIConv) -1;
1386
1387       if (channel->is_writeable && err == 0)
1388         {
1389           write_cd = g_iconv_open (encoding, "UTF-8");
1390
1391           if (write_cd == (GIConv) -1)
1392             {
1393               err = errno;
1394               from_enc = "UTF-8";
1395               to_enc = encoding;
1396             }
1397         }
1398       else
1399         write_cd = (GIConv) -1;
1400
1401       if (err != 0)
1402         {
1403           g_assert (from_enc);
1404           g_assert (to_enc);
1405
1406           if (err == EINVAL)
1407             g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
1408                          _("Conversion from character set '%s' to '%s' is not supported"),
1409                          from_enc, to_enc);
1410           else
1411             g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1412                          _("Could not open converter from '%s' to '%s': %s"),
1413                          from_enc, to_enc, g_strerror (err));
1414
1415           if (read_cd != (GIConv) -1)
1416             g_iconv_close (read_cd);
1417           if (write_cd != (GIConv) -1)
1418             g_iconv_close (write_cd);
1419
1420           return G_IO_STATUS_ERROR;
1421         }
1422
1423       channel->do_encode = TRUE;
1424     }
1425
1426   /* The encoding is ok, so set the fields in channel */
1427
1428   if (channel->read_cd != (GIConv) -1)
1429     g_iconv_close (channel->read_cd);
1430   if (channel->write_cd != (GIConv) -1)
1431     g_iconv_close (channel->write_cd);
1432
1433   if (channel->encoded_read_buf && channel->encoded_read_buf->len > 0)
1434     {
1435       g_assert (!did_encode); /* Encoding UTF-8, NULL doesn't use encoded_read_buf */
1436
1437       /* This is just validated UTF-8, so we can copy it back into read_buf
1438        * so it can be encoded in whatever the new encoding is.
1439        */
1440
1441       g_string_prepend_len (channel->read_buf, channel->encoded_read_buf->str,
1442                             channel->encoded_read_buf->len);
1443       g_string_truncate (channel->encoded_read_buf, 0);
1444     }
1445
1446   channel->read_cd = read_cd;
1447   channel->write_cd = write_cd;
1448
1449   g_free (channel->encoding);
1450   channel->encoding = g_strdup (encoding);
1451
1452   return G_IO_STATUS_NORMAL;
1453 }
1454
1455 /**
1456  * g_io_channel_get_encoding:
1457  * @channel: a #GIOChannel
1458  *
1459  * Gets the encoding for the input/output of the channel. 
1460  * The internal encoding is always UTF-8. The encoding %NULL 
1461  * makes the channel safe for binary data.
1462  *
1463  * Return value: A string containing the encoding, this string is
1464  *   owned by GLib and must not be freed.
1465  **/
1466 const gchar *
1467 g_io_channel_get_encoding (GIOChannel *channel)
1468 {
1469   g_return_val_if_fail (channel != NULL, NULL);
1470
1471   return channel->encoding;
1472 }
1473
1474 static GIOStatus
1475 g_io_channel_fill_buffer (GIOChannel  *channel,
1476                           GError     **err)
1477 {
1478   gsize read_size, cur_len, oldlen;
1479   GIOStatus status;
1480
1481   if (channel->is_seekable && channel->write_buf && channel->write_buf->len > 0)
1482     {
1483       status = g_io_channel_flush (channel, err);
1484       if (status != G_IO_STATUS_NORMAL)
1485         return status;
1486     }
1487   if (channel->is_seekable && channel->partial_write_buf[0] != '\0')
1488     {
1489       g_warning ("Partial character at end of write buffer not flushed.\n");
1490       channel->partial_write_buf[0] = '\0';
1491     }
1492
1493   if (!channel->read_buf)
1494     channel->read_buf = g_string_sized_new (channel->buf_size);
1495
1496   cur_len = channel->read_buf->len;
1497
1498   g_string_set_size (channel->read_buf, channel->read_buf->len + channel->buf_size);
1499
1500   status = channel->funcs->io_read (channel, channel->read_buf->str + cur_len,
1501                                     channel->buf_size, &read_size, err);
1502
1503   g_assert ((status == G_IO_STATUS_NORMAL) || (read_size == 0));
1504
1505   g_string_truncate (channel->read_buf, read_size + cur_len);
1506
1507   if ((status != G_IO_STATUS_NORMAL) &&
1508       ((status != G_IO_STATUS_EOF) || (channel->read_buf->len == 0)))
1509     return status;
1510
1511   g_assert (channel->read_buf->len > 0);
1512
1513   if (channel->encoded_read_buf)
1514     oldlen = channel->encoded_read_buf->len;
1515   else
1516     {
1517       oldlen = 0;
1518       if (channel->encoding)
1519         channel->encoded_read_buf = g_string_sized_new (channel->buf_size);
1520     }
1521
1522   if (channel->do_encode)
1523     {
1524       gsize errnum, inbytes_left, outbytes_left;
1525       gchar *inbuf, *outbuf;
1526       int errval;
1527
1528       g_assert (channel->encoded_read_buf);
1529
1530 reencode:
1531
1532       inbytes_left = channel->read_buf->len;
1533       outbytes_left = MAX (channel->read_buf->len,
1534                            channel->encoded_read_buf->allocated_len
1535                            - channel->encoded_read_buf->len - 1); /* 1 for NULL */
1536       outbytes_left = MAX (outbytes_left, 6);
1537
1538       inbuf = channel->read_buf->str;
1539       g_string_set_size (channel->encoded_read_buf,
1540                          channel->encoded_read_buf->len + outbytes_left);
1541       outbuf = channel->encoded_read_buf->str + channel->encoded_read_buf->len
1542                - outbytes_left;
1543
1544       errnum = g_iconv (channel->read_cd, &inbuf, &inbytes_left,
1545                         &outbuf, &outbytes_left);
1546       errval = errno;
1547
1548       g_assert (inbuf + inbytes_left == channel->read_buf->str
1549                 + channel->read_buf->len);
1550       g_assert (outbuf + outbytes_left == channel->encoded_read_buf->str
1551                 + channel->encoded_read_buf->len);
1552
1553       g_string_erase (channel->read_buf, 0,
1554                       channel->read_buf->len - inbytes_left);
1555       g_string_truncate (channel->encoded_read_buf,
1556                          channel->encoded_read_buf->len - outbytes_left);
1557
1558       if (errnum == (gsize) -1)
1559         {
1560           switch (errval)
1561             {
1562               case EINVAL:
1563                 if ((oldlen == channel->encoded_read_buf->len)
1564                   && (status == G_IO_STATUS_EOF))
1565                   status = G_IO_STATUS_EOF;
1566                 else
1567                   status = G_IO_STATUS_NORMAL;
1568                 break;
1569               case E2BIG:
1570                 /* Buffer size at least 6, wrote at least on character */
1571                 g_assert (inbuf != channel->read_buf->str);
1572                 goto reencode;
1573               case EILSEQ:
1574                 if (oldlen < channel->encoded_read_buf->len)
1575                   status = G_IO_STATUS_NORMAL;
1576                 else
1577                   {
1578                     g_set_error_literal (err, G_CONVERT_ERROR,
1579                       G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1580                       _("Invalid byte sequence in conversion input"));
1581                     return G_IO_STATUS_ERROR;
1582                   }
1583                 break;
1584               default:
1585                 g_assert (errval != EBADF); /* The converter should be open */
1586                 g_set_error (err, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1587                   _("Error during conversion: %s"), g_strerror (errval));
1588                 return G_IO_STATUS_ERROR;
1589             }
1590         }
1591       g_assert ((status != G_IO_STATUS_NORMAL)
1592                || (channel->encoded_read_buf->len > 0));
1593     }
1594   else if (channel->encoding) /* UTF-8 */
1595     {
1596       gchar *nextchar, *lastchar;
1597
1598       g_assert (channel->encoded_read_buf);
1599
1600       nextchar = channel->read_buf->str;
1601       lastchar = channel->read_buf->str + channel->read_buf->len;
1602
1603       while (nextchar < lastchar)
1604         {
1605           gunichar val_char;
1606
1607           val_char = g_utf8_get_char_validated (nextchar, lastchar - nextchar);
1608
1609           switch (val_char)
1610             {
1611               case -2:
1612                 /* stop, leave partial character in buffer */
1613                 lastchar = nextchar;
1614                 break;
1615               case -1:
1616                 if (oldlen < channel->encoded_read_buf->len)
1617                   status = G_IO_STATUS_NORMAL;
1618                 else
1619                   {
1620                     g_set_error_literal (err, G_CONVERT_ERROR,
1621                       G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1622                       _("Invalid byte sequence in conversion input"));
1623                     status = G_IO_STATUS_ERROR;
1624                   }
1625                 lastchar = nextchar;
1626                 break;
1627               default:
1628                 nextchar = g_utf8_next_char (nextchar);
1629                 break;
1630             }
1631         }
1632
1633       if (lastchar > channel->read_buf->str)
1634         {
1635           gint copy_len = lastchar - channel->read_buf->str;
1636
1637           g_string_append_len (channel->encoded_read_buf, channel->read_buf->str,
1638                                copy_len);
1639           g_string_erase (channel->read_buf, 0, copy_len);
1640         }
1641     }
1642
1643   return status;
1644 }
1645
1646 /**
1647  * g_io_channel_read_line:
1648  * @channel: a #GIOChannel
1649  * @str_return: (out): The line read from the #GIOChannel, including the
1650  *              line terminator. This data should be freed with g_free()
1651  *              when no longer needed. This is a nul-terminated string. 
1652  *              If a @length of zero is returned, this will be %NULL instead.
1653  * @length: (allow-none) (out): location to store length of the read data, or %NULL
1654  * @terminator_pos: (allow-none) (out): location to store position of line terminator, or %NULL
1655  * @error: A location to return an error of type #GConvertError
1656  *         or #GIOChannelError
1657  *
1658  * Reads a line, including the terminating character(s),
1659  * from a #GIOChannel into a newly-allocated string.
1660  * @str_return will contain allocated memory if the return
1661  * is %G_IO_STATUS_NORMAL.
1662  *
1663  * Return value: the status of the operation.
1664  **/
1665 GIOStatus
1666 g_io_channel_read_line (GIOChannel  *channel,
1667                         gchar      **str_return,
1668                         gsize       *length,
1669                         gsize       *terminator_pos,
1670                         GError     **error)
1671 {
1672   GIOStatus status;
1673   gsize got_length;
1674   
1675   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1676   g_return_val_if_fail (str_return != NULL, G_IO_STATUS_ERROR);
1677   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1678                         G_IO_STATUS_ERROR);
1679   g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1680
1681   status = g_io_channel_read_line_backend (channel, &got_length, terminator_pos, error);
1682
1683   if (length)
1684     *length = got_length;
1685
1686   if (status == G_IO_STATUS_NORMAL)
1687     {
1688       g_assert (USE_BUF (channel));
1689       *str_return = g_strndup (USE_BUF (channel)->str, got_length);
1690       g_string_erase (USE_BUF (channel), 0, got_length);
1691     }
1692   else
1693     *str_return = NULL;
1694   
1695   return status;
1696 }
1697
1698 /**
1699  * g_io_channel_read_line_string:
1700  * @channel: a #GIOChannel
1701  * @buffer: a #GString into which the line will be written.
1702  *          If @buffer already contains data, the old data will
1703  *          be overwritten.
1704  * @terminator_pos: (allow-none): location to store position of line terminator, or %NULL
1705  * @error: a location to store an error of type #GConvertError
1706  *         or #GIOChannelError
1707  *
1708  * Reads a line from a #GIOChannel, using a #GString as a buffer.
1709  *
1710  * Return value: the status of the operation.
1711  **/
1712 GIOStatus
1713 g_io_channel_read_line_string (GIOChannel  *channel,
1714                                GString     *buffer,
1715                                gsize       *terminator_pos,
1716                                GError     **error)
1717 {
1718   gsize length;
1719   GIOStatus status;
1720
1721   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1722   g_return_val_if_fail (buffer != NULL, G_IO_STATUS_ERROR);
1723   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1724                         G_IO_STATUS_ERROR);
1725   g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1726
1727   if (buffer->len > 0)
1728     g_string_truncate (buffer, 0); /* clear out the buffer */
1729
1730   status = g_io_channel_read_line_backend (channel, &length, terminator_pos, error);
1731
1732   if (status == G_IO_STATUS_NORMAL)
1733     {
1734       g_assert (USE_BUF (channel));
1735       g_string_append_len (buffer, USE_BUF (channel)->str, length);
1736       g_string_erase (USE_BUF (channel), 0, length);
1737     }
1738
1739   return status;
1740 }
1741
1742
1743 static GIOStatus
1744 g_io_channel_read_line_backend (GIOChannel  *channel,
1745                                 gsize       *length,
1746                                 gsize       *terminator_pos,
1747                                 GError     **error)
1748 {
1749   GIOStatus status;
1750   gsize checked_to, line_term_len, line_length, got_term_len;
1751   gboolean first_time = TRUE;
1752
1753   if (!channel->use_buffer)
1754     {
1755       /* Can't do a raw read in read_line */
1756       g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1757                            _("Can't do a raw read in g_io_channel_read_line_string"));
1758       return G_IO_STATUS_ERROR;
1759     }
1760
1761   status = G_IO_STATUS_NORMAL;
1762
1763   if (channel->line_term)
1764     line_term_len = channel->line_term_len;
1765   else
1766     line_term_len = 3;
1767     /* This value used for setting checked_to, it's the longest of the four
1768      * we autodetect for.
1769      */
1770
1771   checked_to = 0;
1772
1773   while (TRUE)
1774     {
1775       gchar *nextchar, *lastchar;
1776       GString *use_buf;
1777
1778       if (!first_time || (BUF_LEN (USE_BUF (channel)) == 0))
1779         {
1780 read_again:
1781           status = g_io_channel_fill_buffer (channel, error);
1782           switch (status)
1783             {
1784               case G_IO_STATUS_NORMAL:
1785                 if (BUF_LEN (USE_BUF (channel)) == 0)
1786                   /* Can happen when using conversion and only read
1787                    * part of a character
1788                    */
1789                   {
1790                     first_time = FALSE;
1791                     continue;
1792                   }
1793                 break;
1794               case G_IO_STATUS_EOF:
1795                 if (BUF_LEN (USE_BUF (channel)) == 0)
1796                   {
1797                     if (length)
1798                       *length = 0;
1799
1800                     if (channel->encoding && channel->read_buf->len != 0)
1801                       {
1802                         g_set_error_literal (error, G_CONVERT_ERROR,
1803                                              G_CONVERT_ERROR_PARTIAL_INPUT,
1804                                              _("Leftover unconverted data in "
1805                                                "read buffer"));
1806                         return G_IO_STATUS_ERROR;
1807                       }
1808                     else
1809                       return G_IO_STATUS_EOF;
1810                   }
1811                 break;
1812               default:
1813                 if (length)
1814                   *length = 0;
1815                 return status;
1816             }
1817         }
1818
1819       g_assert (BUF_LEN (USE_BUF (channel)) != 0);
1820
1821       use_buf = USE_BUF (channel); /* The buffer has been created by this point */
1822
1823       first_time = FALSE;
1824
1825       lastchar = use_buf->str + use_buf->len;
1826
1827       for (nextchar = use_buf->str + checked_to; nextchar < lastchar;
1828            channel->encoding ? nextchar = g_utf8_next_char (nextchar) : nextchar++)
1829         {
1830           if (channel->line_term)
1831             {
1832               if (memcmp (channel->line_term, nextchar, line_term_len) == 0)
1833                 {
1834                   line_length = nextchar - use_buf->str;
1835                   got_term_len = line_term_len;
1836                   goto done;
1837                 }
1838             }
1839           else /* auto detect */
1840             {
1841               switch (*nextchar)
1842                 {
1843                   case '\n': /* unix */
1844                     line_length = nextchar - use_buf->str;
1845                     got_term_len = 1;
1846                     goto done;
1847                   case '\r': /* Warning: do not use with sockets */
1848                     line_length = nextchar - use_buf->str;
1849                     if ((nextchar == lastchar - 1) && (status != G_IO_STATUS_EOF)
1850                        && (lastchar == use_buf->str + use_buf->len))
1851                       goto read_again; /* Try to read more data */
1852                     if ((nextchar < lastchar - 1) && (*(nextchar + 1) == '\n')) /* dos */
1853                       got_term_len = 2;
1854                     else /* mac */
1855                       got_term_len = 1;
1856                     goto done;
1857                   case '\xe2': /* Unicode paragraph separator */
1858                     if (strncmp ("\xe2\x80\xa9", nextchar, 3) == 0)
1859                       {
1860                         line_length = nextchar - use_buf->str;
1861                         got_term_len = 3;
1862                         goto done;
1863                       }
1864                     break;
1865                   case '\0': /* Embeded null in input */
1866                     line_length = nextchar - use_buf->str;
1867                     got_term_len = 1;
1868                     goto done;
1869                   default: /* no match */
1870                     break;
1871                 }
1872             }
1873         }
1874
1875       /* If encoding != NULL, valid UTF-8, didn't overshoot */
1876       g_assert (nextchar == lastchar);
1877
1878       /* Check for EOF */
1879
1880       if (status == G_IO_STATUS_EOF)
1881         {
1882           if (channel->encoding && channel->read_buf->len > 0)
1883             {
1884               g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1885                                    _("Channel terminates in a partial character"));
1886               return G_IO_STATUS_ERROR;
1887             }
1888           line_length = use_buf->len;
1889           got_term_len = 0;
1890           break;
1891         }
1892
1893       if (use_buf->len > line_term_len - 1)
1894         checked_to = use_buf->len - (line_term_len - 1);
1895       else
1896         checked_to = 0;
1897     }
1898
1899 done:
1900
1901   if (terminator_pos)
1902     *terminator_pos = line_length;
1903
1904   if (length)
1905     *length = line_length + got_term_len;
1906
1907   return G_IO_STATUS_NORMAL;
1908 }
1909
1910 /**
1911  * g_io_channel_read_to_end:
1912  * @channel: a #GIOChannel
1913  * @str_return:  (out) (array length=length) (element-type guint8): Location to
1914  *              store a pointer to a string holding the remaining data in the
1915  *              #GIOChannel. This data should be freed with g_free() when no
1916  *              longer needed. This data is terminated by an extra nul
1917  *              character, but there may be other nuls in the intervening data.
1918  * @length: (out): location to store length of the data
1919  * @error: location to return an error of type #GConvertError
1920  *         or #GIOChannelError
1921  *
1922  * Reads all the remaining data from the file.
1923  *
1924  * Return value: %G_IO_STATUS_NORMAL on success. 
1925  *     This function never returns %G_IO_STATUS_EOF.
1926  **/
1927 GIOStatus
1928 g_io_channel_read_to_end (GIOChannel  *channel,
1929                           gchar      **str_return,
1930                           gsize       *length,
1931                           GError     **error)
1932 {
1933   GIOStatus status;
1934     
1935   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1936   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1937     G_IO_STATUS_ERROR);
1938   g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1939
1940   if (str_return)
1941     *str_return = NULL;
1942   if (length)
1943     *length = 0;
1944
1945   if (!channel->use_buffer)
1946     {
1947       g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1948                            _("Can't do a raw read in g_io_channel_read_to_end"));
1949       return G_IO_STATUS_ERROR;
1950     }
1951
1952   do
1953     status = g_io_channel_fill_buffer (channel, error);
1954   while (status == G_IO_STATUS_NORMAL);
1955
1956   if (status != G_IO_STATUS_EOF)
1957     return status;
1958
1959   if (channel->encoding && channel->read_buf->len > 0)
1960     {
1961       g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1962                            _("Channel terminates in a partial character"));
1963       return G_IO_STATUS_ERROR;
1964     }
1965
1966   if (USE_BUF (channel) == NULL)
1967     {
1968       /* length is already set to zero */
1969       if (str_return)
1970         *str_return = g_strdup ("");
1971     }
1972   else
1973     {
1974       if (length)
1975         *length = USE_BUF (channel)->len;
1976
1977       if (str_return)
1978         *str_return = g_string_free (USE_BUF (channel), FALSE);
1979       else
1980         g_string_free (USE_BUF (channel), TRUE);
1981
1982       if (channel->encoding)
1983         channel->encoded_read_buf = NULL;
1984       else
1985         channel->read_buf = NULL;
1986     }
1987
1988   return G_IO_STATUS_NORMAL;
1989 }
1990
1991 /**
1992  * g_io_channel_read_chars:
1993  * @channel: a #GIOChannel
1994  * @buf: (out caller-allocates) (array length=count) (element-type guint8):
1995  *     a buffer to read data into
1996  * @count: (in): the size of the buffer. Note that the buffer may not be
1997  *     complelely filled even if there is data in the buffer if the
1998  *     remaining data is not a complete character.
1999  * @bytes_read: (allow-none) (out): The number of bytes read. This may be
2000  *     zero even on success if count < 6 and the channel's encoding
2001  *     is non-%NULL. This indicates that the next UTF-8 character is
2002  *     too wide for the buffer.
2003  * @error: a location to return an error of type #GConvertError
2004  *     or #GIOChannelError.
2005  *
2006  * Replacement for g_io_channel_read() with the new API.
2007  *
2008  * Return value: the status of the operation.
2009  */
2010 GIOStatus
2011 g_io_channel_read_chars (GIOChannel  *channel,
2012                          gchar       *buf,
2013                          gsize        count,
2014                          gsize       *bytes_read,
2015                          GError     **error)
2016 {
2017   GIOStatus status;
2018   gsize got_bytes;
2019
2020   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
2021   g_return_val_if_fail ((error == NULL) || (*error == NULL), G_IO_STATUS_ERROR);
2022   g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
2023
2024   if (count == 0)
2025     {
2026       if (bytes_read)
2027         *bytes_read = 0;
2028       return G_IO_STATUS_NORMAL;
2029     }
2030   g_return_val_if_fail (buf != NULL, G_IO_STATUS_ERROR);
2031
2032   if (!channel->use_buffer)
2033     {
2034       gsize tmp_bytes;
2035
2036       g_assert (!channel->read_buf || channel->read_buf->len == 0);
2037
2038       status = channel->funcs->io_read (channel, buf, count, &tmp_bytes, error);
2039
2040       if (bytes_read)
2041         *bytes_read = tmp_bytes;
2042
2043       return status;
2044     }
2045
2046   status = G_IO_STATUS_NORMAL;
2047
2048   while (BUF_LEN (USE_BUF (channel)) < count && status == G_IO_STATUS_NORMAL)
2049     status = g_io_channel_fill_buffer (channel, error);
2050
2051   /* Only return an error if we have no data */
2052
2053   if (BUF_LEN (USE_BUF (channel)) == 0)
2054     {
2055       g_assert (status != G_IO_STATUS_NORMAL);
2056
2057       if (status == G_IO_STATUS_EOF && channel->encoding
2058           && BUF_LEN (channel->read_buf) > 0)
2059         {
2060           g_set_error_literal (error, G_CONVERT_ERROR,
2061                                G_CONVERT_ERROR_PARTIAL_INPUT,
2062                                _("Leftover unconverted data in read buffer"));
2063           status = G_IO_STATUS_ERROR;
2064         }
2065
2066       if (bytes_read)
2067         *bytes_read = 0;
2068
2069       return status;
2070     }
2071
2072   if (status == G_IO_STATUS_ERROR)
2073     g_clear_error (error);
2074
2075   got_bytes = MIN (count, BUF_LEN (USE_BUF (channel)));
2076
2077   g_assert (got_bytes > 0);
2078
2079   if (channel->encoding)
2080     /* Don't validate for NULL encoding, binary safe */
2081     {
2082       gchar *nextchar, *prevchar;
2083
2084       g_assert (USE_BUF (channel) == channel->encoded_read_buf);
2085
2086       nextchar = channel->encoded_read_buf->str;
2087
2088       do
2089         {
2090           prevchar = nextchar;
2091           nextchar = g_utf8_next_char (nextchar);
2092           g_assert (nextchar != prevchar); /* Possible for *prevchar of -1 or -2 */
2093         }
2094       while (nextchar < channel->encoded_read_buf->str + got_bytes);
2095
2096       if (nextchar > channel->encoded_read_buf->str + got_bytes)
2097         got_bytes = prevchar - channel->encoded_read_buf->str;
2098
2099       g_assert (got_bytes > 0 || count < 6);
2100     }
2101
2102   memcpy (buf, USE_BUF (channel)->str, got_bytes);
2103   g_string_erase (USE_BUF (channel), 0, got_bytes);
2104
2105   if (bytes_read)
2106     *bytes_read = got_bytes;
2107
2108   return G_IO_STATUS_NORMAL;
2109 }
2110
2111 /**
2112  * g_io_channel_read_unichar:
2113  * @channel: a #GIOChannel
2114  * @thechar: (out): a location to return a character
2115  * @error: a location to return an error of type #GConvertError
2116  *         or #GIOChannelError
2117  *
2118  * Reads a Unicode character from @channel.
2119  * This function cannot be called on a channel with %NULL encoding.
2120  *
2121  * Return value: a #GIOStatus
2122  **/
2123 GIOStatus
2124 g_io_channel_read_unichar (GIOChannel  *channel,
2125                            gunichar    *thechar,
2126                            GError     **error)
2127 {
2128   GIOStatus status = G_IO_STATUS_NORMAL;
2129
2130   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
2131   g_return_val_if_fail (channel->encoding != NULL, G_IO_STATUS_ERROR);
2132   g_return_val_if_fail ((error == NULL) || (*error == NULL),
2133                         G_IO_STATUS_ERROR);
2134   g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
2135
2136   while (BUF_LEN (channel->encoded_read_buf) == 0 && status == G_IO_STATUS_NORMAL)
2137     status = g_io_channel_fill_buffer (channel, error);
2138
2139   /* Only return an error if we have no data */
2140
2141   if (BUF_LEN (USE_BUF (channel)) == 0)
2142     {
2143       g_assert (status != G_IO_STATUS_NORMAL);
2144
2145       if (status == G_IO_STATUS_EOF && BUF_LEN (channel->read_buf) > 0)
2146         {
2147           g_set_error_literal (error, G_CONVERT_ERROR,
2148                                G_CONVERT_ERROR_PARTIAL_INPUT,
2149                                _("Leftover unconverted data in read buffer"));
2150           status = G_IO_STATUS_ERROR;
2151         }
2152
2153       if (thechar)
2154         *thechar = (gunichar) -1;
2155
2156       return status;
2157     }
2158
2159   if (status == G_IO_STATUS_ERROR)
2160     g_clear_error (error);
2161
2162   if (thechar)
2163     *thechar = g_utf8_get_char (channel->encoded_read_buf->str);
2164
2165   g_string_erase (channel->encoded_read_buf, 0,
2166                   g_utf8_next_char (channel->encoded_read_buf->str)
2167                   - channel->encoded_read_buf->str);
2168
2169   return G_IO_STATUS_NORMAL;
2170 }
2171
2172 /**
2173  * g_io_channel_write_chars:
2174  * @channel: a #GIOChannel
2175  * @buf: (array) (element-type guint8): a buffer to write data from
2176  * @count: the size of the buffer. If -1, the buffer
2177  *         is taken to be a nul-terminated string.
2178  * @bytes_written: (out): The number of bytes written. This can be nonzero
2179  *                 even if the return value is not %G_IO_STATUS_NORMAL.
2180  *                 If the return value is %G_IO_STATUS_NORMAL and the
2181  *                 channel is blocking, this will always be equal
2182  *                 to @count if @count >= 0.
2183  * @error: a location to return an error of type #GConvertError
2184  *         or #GIOChannelError
2185  *
2186  * Replacement for g_io_channel_write() with the new API.
2187  *
2188  * On seekable channels with encodings other than %NULL or UTF-8, generic
2189  * mixing of reading and writing is not allowed. A call to g_io_channel_write_chars ()
2190  * may only be made on a channel from which data has been read in the
2191  * cases described in the documentation for g_io_channel_set_encoding ().
2192  *
2193  * Return value: the status of the operation.
2194  **/
2195 GIOStatus
2196 g_io_channel_write_chars (GIOChannel   *channel,
2197                           const gchar  *buf,
2198                           gssize        count,
2199                           gsize        *bytes_written,
2200                           GError      **error)
2201 {
2202   GIOStatus status;
2203   gssize wrote_bytes = 0;
2204
2205   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
2206   g_return_val_if_fail ((error == NULL) || (*error == NULL),
2207                         G_IO_STATUS_ERROR);
2208   g_return_val_if_fail (channel->is_writeable, G_IO_STATUS_ERROR);
2209
2210   if ((count < 0) && buf)
2211     count = strlen (buf);
2212   
2213   if (count == 0)
2214     {
2215       if (bytes_written)
2216         *bytes_written = 0;
2217       return G_IO_STATUS_NORMAL;
2218     }
2219
2220   g_return_val_if_fail (buf != NULL, G_IO_STATUS_ERROR);
2221   g_return_val_if_fail (count > 0, G_IO_STATUS_ERROR);
2222
2223   /* Raw write case */
2224
2225   if (!channel->use_buffer)
2226     {
2227       gsize tmp_bytes;
2228       
2229       g_assert (!channel->write_buf || channel->write_buf->len == 0);
2230       g_assert (channel->partial_write_buf[0] == '\0');
2231       
2232       status = channel->funcs->io_write (channel, buf, count, &tmp_bytes, error);
2233
2234       if (bytes_written)
2235         *bytes_written = tmp_bytes;
2236
2237       return status;
2238     }
2239
2240   /* General case */
2241
2242   if (channel->is_seekable && (( BUF_LEN (channel->read_buf) > 0)
2243     || (BUF_LEN (channel->encoded_read_buf) > 0)))
2244     {
2245       if (channel->do_encode && BUF_LEN (channel->encoded_read_buf) > 0)
2246         {
2247           g_warning("Mixed reading and writing not allowed on encoded files");
2248           return G_IO_STATUS_ERROR;
2249         }
2250       status = g_io_channel_seek_position (channel, 0, G_SEEK_CUR, error);
2251       if (status != G_IO_STATUS_NORMAL)
2252         {
2253           if (bytes_written)
2254             *bytes_written = 0;
2255           return status;
2256         }
2257     }
2258
2259   if (!channel->write_buf)
2260     channel->write_buf = g_string_sized_new (channel->buf_size);
2261
2262   while (wrote_bytes < count)
2263     {
2264       gsize space_in_buf;
2265
2266       /* If the buffer is full, try a write immediately. In
2267        * the nonblocking case, this prevents the user from
2268        * writing just a little bit to the buffer every time
2269        * and never receiving an EAGAIN.
2270        */
2271
2272       if (channel->write_buf->len >= channel->buf_size - MAX_CHAR_SIZE)
2273         {
2274           gsize did_write = 0, this_time;
2275
2276           do
2277             {
2278               status = channel->funcs->io_write (channel, channel->write_buf->str
2279                                                  + did_write, channel->write_buf->len
2280                                                  - did_write, &this_time, error);
2281               did_write += this_time;
2282             }
2283           while (status == G_IO_STATUS_NORMAL &&
2284                  did_write < MIN (channel->write_buf->len, MAX_CHAR_SIZE));
2285
2286           g_string_erase (channel->write_buf, 0, did_write);
2287
2288           if (status != G_IO_STATUS_NORMAL)
2289             {
2290               if (status == G_IO_STATUS_AGAIN && wrote_bytes > 0)
2291                 status = G_IO_STATUS_NORMAL;
2292               if (bytes_written)
2293                 *bytes_written = wrote_bytes;
2294               return status;
2295             }
2296         }
2297
2298       space_in_buf = MAX (channel->buf_size, channel->write_buf->allocated_len - 1)
2299                      - channel->write_buf->len; /* 1 for NULL */
2300
2301       /* This is only true because g_io_channel_set_buffer_size ()
2302        * ensures that channel->buf_size >= MAX_CHAR_SIZE.
2303        */
2304       g_assert (space_in_buf >= MAX_CHAR_SIZE);
2305
2306       if (!channel->encoding)
2307         {
2308           gssize write_this = MIN (space_in_buf, count - wrote_bytes);
2309
2310           g_string_append_len (channel->write_buf, buf, write_this);
2311           buf += write_this;
2312           wrote_bytes += write_this;
2313         }
2314       else
2315         {
2316           const gchar *from_buf;
2317           gsize from_buf_len, from_buf_old_len, left_len;
2318           gsize err;
2319           gint errnum;
2320
2321           if (channel->partial_write_buf[0] != '\0')
2322             {
2323               g_assert (wrote_bytes == 0);
2324
2325               from_buf = channel->partial_write_buf;
2326               from_buf_old_len = strlen (channel->partial_write_buf);
2327               g_assert (from_buf_old_len > 0);
2328               from_buf_len = MIN (6, from_buf_old_len + count);
2329
2330               memcpy (channel->partial_write_buf + from_buf_old_len, buf,
2331                       from_buf_len - from_buf_old_len);
2332             }
2333           else
2334             {
2335               from_buf = buf;
2336               from_buf_len = count - wrote_bytes;
2337               from_buf_old_len = 0;
2338             }
2339
2340 reconvert:
2341
2342           if (!channel->do_encode) /* UTF-8 encoding */
2343             {
2344               const gchar *badchar;
2345               gsize try_len = MIN (from_buf_len, space_in_buf);
2346
2347               /* UTF-8, just validate, emulate g_iconv */
2348
2349               if (!g_utf8_validate (from_buf, try_len, &badchar))
2350                 {
2351                   gunichar try_char;
2352                   gsize incomplete_len = from_buf + try_len - badchar;
2353
2354                   left_len = from_buf + from_buf_len - badchar;
2355
2356                   try_char = g_utf8_get_char_validated (badchar, incomplete_len);
2357
2358                   switch (try_char)
2359                     {
2360                       case -2:
2361                         g_assert (incomplete_len < 6);
2362                         if (try_len == from_buf_len)
2363                           {
2364                             errnum = EINVAL;
2365                             err = (gsize) -1;
2366                           }
2367                         else
2368                           {
2369                             errnum = 0;
2370                             err = (gsize) 0;
2371                           }
2372                         break;
2373                       case -1:
2374                         g_warning ("Invalid UTF-8 passed to g_io_channel_write_chars().");
2375                         /* FIXME bail here? */
2376                         errnum = EILSEQ;
2377                         err = (gsize) -1;
2378                         break;
2379                       default:
2380                         g_assert_not_reached ();
2381                         err = (gsize) -1;
2382                         errnum = 0; /* Don't confunse the compiler */
2383                     }
2384                 }
2385               else
2386                 {
2387                   err = (gsize) 0;
2388                   errnum = 0;
2389                   left_len = from_buf_len - try_len;
2390                 }
2391
2392               g_string_append_len (channel->write_buf, from_buf,
2393                                    from_buf_len - left_len);
2394               from_buf += from_buf_len - left_len;
2395             }
2396           else
2397             {
2398                gchar *outbuf;
2399
2400                left_len = from_buf_len;
2401                g_string_set_size (channel->write_buf, channel->write_buf->len
2402                                   + space_in_buf);
2403                outbuf = channel->write_buf->str + channel->write_buf->len
2404                         - space_in_buf;
2405                err = g_iconv (channel->write_cd, (gchar **) &from_buf, &left_len,
2406                               &outbuf, &space_in_buf);
2407                errnum = errno;
2408                g_string_truncate (channel->write_buf, channel->write_buf->len
2409                                   - space_in_buf);
2410             }
2411
2412           if (err == (gsize) -1)
2413             {
2414               switch (errnum)
2415                 {
2416                   case EINVAL:
2417                     g_assert (left_len < 6);
2418
2419                     if (from_buf_old_len == 0)
2420                       {
2421                         /* Not from partial_write_buf */
2422
2423                         memcpy (channel->partial_write_buf, from_buf, left_len);
2424                         channel->partial_write_buf[left_len] = '\0';
2425                         if (bytes_written)
2426                           *bytes_written = count;
2427                         return G_IO_STATUS_NORMAL;
2428                       }
2429
2430                     /* Working in partial_write_buf */
2431
2432                     if (left_len == from_buf_len)
2433                       {
2434                         /* Didn't convert anything, must still have
2435                          * less than a full character
2436                          */
2437
2438                         g_assert (count == from_buf_len - from_buf_old_len);
2439
2440                         channel->partial_write_buf[from_buf_len] = '\0';
2441
2442                         if (bytes_written)
2443                           *bytes_written = count;
2444
2445                         return G_IO_STATUS_NORMAL;
2446                       }
2447
2448                     g_assert (from_buf_len - left_len >= from_buf_old_len);
2449
2450                     /* We converted all the old data. This is fine */
2451
2452                     break;
2453                   case E2BIG:
2454                     if (from_buf_len == left_len)
2455                       {
2456                         /* Nothing was written, add enough space for
2457                          * at least one character.
2458                          */
2459                         space_in_buf += MAX_CHAR_SIZE;
2460                         goto reconvert;
2461                       }
2462                     break;
2463                   case EILSEQ:
2464                     g_set_error_literal (error, G_CONVERT_ERROR,
2465                       G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
2466                       _("Invalid byte sequence in conversion input"));
2467                     if (from_buf_old_len > 0 && from_buf_len == left_len)
2468                       g_warning ("Illegal sequence due to partial character "
2469                                  "at the end of a previous write.\n");
2470                     else
2471                       wrote_bytes += from_buf_len - left_len - from_buf_old_len;
2472                     if (bytes_written)
2473                       *bytes_written = wrote_bytes;
2474                     channel->partial_write_buf[0] = '\0';
2475                     return G_IO_STATUS_ERROR;
2476                   default:
2477                     g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
2478                       _("Error during conversion: %s"), g_strerror (errnum));
2479                     if (from_buf_len >= left_len + from_buf_old_len)
2480                       wrote_bytes += from_buf_len - left_len - from_buf_old_len;
2481                     if (bytes_written)
2482                       *bytes_written = wrote_bytes;
2483                     channel->partial_write_buf[0] = '\0';
2484                     return G_IO_STATUS_ERROR;
2485                 }
2486             }
2487
2488           g_assert (from_buf_len - left_len >= from_buf_old_len);
2489
2490           wrote_bytes += from_buf_len - left_len - from_buf_old_len;
2491
2492           if (from_buf_old_len > 0)
2493             {
2494               /* We were working in partial_write_buf */
2495
2496               buf += from_buf_len - left_len - from_buf_old_len;
2497               channel->partial_write_buf[0] = '\0';
2498             }
2499           else
2500             buf = from_buf;
2501         }
2502     }
2503
2504   if (bytes_written)
2505     *bytes_written = count;
2506
2507   return G_IO_STATUS_NORMAL;
2508 }
2509
2510 /**
2511  * g_io_channel_write_unichar:
2512  * @channel: a #GIOChannel
2513  * @thechar: a character
2514  * @error: location to return an error of type #GConvertError
2515  *         or #GIOChannelError
2516  *
2517  * Writes a Unicode character to @channel.
2518  * This function cannot be called on a channel with %NULL encoding.
2519  *
2520  * Return value: a #GIOStatus
2521  **/
2522 GIOStatus
2523 g_io_channel_write_unichar (GIOChannel  *channel,
2524                             gunichar     thechar,
2525                             GError     **error)
2526 {
2527   GIOStatus status;
2528   gchar static_buf[6];
2529   gsize char_len, wrote_len;
2530
2531   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
2532   g_return_val_if_fail (channel->encoding != NULL, G_IO_STATUS_ERROR);
2533   g_return_val_if_fail ((error == NULL) || (*error == NULL),
2534                         G_IO_STATUS_ERROR);
2535   g_return_val_if_fail (channel->is_writeable, G_IO_STATUS_ERROR);
2536
2537   char_len = g_unichar_to_utf8 (thechar, static_buf);
2538
2539   if (channel->partial_write_buf[0] != '\0')
2540     {
2541       g_warning ("Partial charater written before writing unichar.\n");
2542       channel->partial_write_buf[0] = '\0';
2543     }
2544
2545   status = g_io_channel_write_chars (channel, static_buf,
2546                                      char_len, &wrote_len, error);
2547
2548   /* We validate UTF-8, so we can't get a partial write */
2549
2550   g_assert (wrote_len == char_len || status != G_IO_STATUS_NORMAL);
2551
2552   return status;
2553 }
2554
2555 /**
2556  * g_io_channel_error_quark:
2557  *
2558  * Return value: the quark used as %G_IO_CHANNEL_ERROR
2559  **/
2560 /**
2561  * G_IO_CHANNEL_ERROR:
2562  *
2563  * Error domain for #GIOChannel operations. Errors in this domain will
2564  * be from the #GIOChannelError enumeration. See #GError for
2565  * information on error domains.
2566  **/
2567 /**
2568  * GIOChannelError:
2569  * @G_IO_CHANNEL_ERROR_FBIG: File too large.
2570  * @G_IO_CHANNEL_ERROR_INVAL: Invalid argument.
2571  * @G_IO_CHANNEL_ERROR_IO: IO error.
2572  * @G_IO_CHANNEL_ERROR_ISDIR: File is a directory.
2573  * @G_IO_CHANNEL_ERROR_NOSPC: No space left on device.
2574  * @G_IO_CHANNEL_ERROR_NXIO: No such device or address.
2575  * @G_IO_CHANNEL_ERROR_OVERFLOW: Value too large for defined datatype.
2576  * @G_IO_CHANNEL_ERROR_PIPE: Broken pipe.
2577  * @G_IO_CHANNEL_ERROR_FAILED: Some other error.
2578  *
2579  * Error codes returned by #GIOChannel operations.
2580  **/
2581
2582 G_DEFINE_QUARK (g-io-channel-error-quark, g_io_channel_error)