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