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