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