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