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