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