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