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