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