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