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