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