1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * giochannel.c: IO Channel abstraction
5 * Copyright 1998 Owen Taylor
7 * SPDX-License-Identifier: LGPL-2.1-or-later
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
24 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
25 * file for a list of people on the GLib Team. See the ChangeLog
26 * files for a list of changes. These files are distributed with
27 * GLib at ftp://ftp.gtk.org/pub/gtk/.
39 #include "giochannel.h"
41 #include "gstrfuncs.h"
42 #include "gtestutils.h"
49 * @short_description: portable support for using files, pipes and sockets
50 * @see_also: g_io_add_watch(), g_io_add_watch_full(), g_source_remove(),
53 * The #GIOChannel data type aims to provide a portable method for
54 * using file descriptors, pipes, and sockets, and integrating them
55 * into the [main event loop][glib-The-Main-Event-Loop]. Currently,
56 * full support is available on UNIX platforms, support for Windows
57 * is only partially complete.
59 * To create a new #GIOChannel on UNIX systems use
60 * g_io_channel_unix_new(). This works for plain file descriptors,
61 * pipes and sockets. Alternatively, a channel can be created for a
62 * file in a system independent manner using g_io_channel_new_file().
64 * Once a #GIOChannel has been created, it can be used in a generic
65 * manner with the functions g_io_channel_read_chars(),
66 * g_io_channel_write_chars(), g_io_channel_seek_position(), and
67 * g_io_channel_shutdown().
69 * To add a #GIOChannel to the [main event loop][glib-The-Main-Event-Loop],
70 * use g_io_add_watch() or g_io_add_watch_full(). Here you specify which
71 * events you are interested in on the #GIOChannel, and provide a
72 * function to be called whenever these events occur.
74 * #GIOChannel instances are created with an initial reference count of 1.
75 * g_io_channel_ref() and g_io_channel_unref() can be used to
76 * increment or decrement the reference count respectively. When the
77 * reference count falls to 0, the #GIOChannel is freed. (Though it
78 * isn't closed automatically, unless it was created using
79 * g_io_channel_new_file().) Using g_io_add_watch() or
80 * g_io_add_watch_full() increments a channel's reference count.
82 * The new functions g_io_channel_read_chars(),
83 * g_io_channel_read_line(), g_io_channel_read_line_string(),
84 * g_io_channel_read_to_end(), g_io_channel_write_chars(),
85 * g_io_channel_seek_position(), and g_io_channel_flush() should not be
86 * mixed with the deprecated functions g_io_channel_read(),
87 * g_io_channel_write(), and g_io_channel_seek() on the same channel.
93 * A data structure representing an IO Channel. The fields should be
94 * considered private and should only be accessed with the following
100 * @io_read: reads raw bytes from the channel. This is called from
101 * various functions such as g_io_channel_read_chars() to
102 * read raw bytes from the channel. Encoding and buffering
103 * issues are dealt with at a higher level.
104 * @io_write: writes raw bytes to the channel. This is called from
105 * various functions such as g_io_channel_write_chars() to
106 * write raw bytes to the channel. Encoding and buffering
107 * issues are dealt with at a higher level.
108 * @io_seek: (optional) seeks the channel. This is called from
109 * g_io_channel_seek() on channels that support it.
110 * @io_close: closes the channel. This is called from
111 * g_io_channel_close() after flushing the buffers.
112 * @io_create_watch: creates a watch on the channel. This call
113 * corresponds directly to g_io_create_watch().
114 * @io_free: called from g_io_channel_unref() when the channel needs to
115 * be freed. This function must free the memory associated
116 * with the channel, including freeing the #GIOChannel
117 * structure itself. The channel buffers have been flushed
118 * and possibly @io_close has been called by the time this
119 * function is called.
120 * @io_set_flags: sets the #GIOFlags on the channel. This is called
121 * from g_io_channel_set_flags() with all flags except
122 * for %G_IO_FLAG_APPEND and %G_IO_FLAG_NONBLOCK masked
124 * @io_get_flags: gets the #GIOFlags for the channel. This function
125 * need only return the %G_IO_FLAG_APPEND and
126 * %G_IO_FLAG_NONBLOCK flags; g_io_channel_get_flags()
127 * automatically adds the others as appropriate.
129 * A table of functions used to handle different types of #GIOChannel
135 * @G_IO_STATUS_ERROR: An error occurred.
136 * @G_IO_STATUS_NORMAL: Success.
137 * @G_IO_STATUS_EOF: End of file.
138 * @G_IO_STATUS_AGAIN: Resource temporarily unavailable.
140 * Statuses returned by most of the #GIOFuncs functions.
145 * @G_IO_ERROR_NONE: no error
146 * @G_IO_ERROR_AGAIN: an EAGAIN error occurred
147 * @G_IO_ERROR_INVAL: an EINVAL error occurred
148 * @G_IO_ERROR_UNKNOWN: another error occurred
150 * #GIOError is only used by the deprecated functions
151 * g_io_channel_read(), g_io_channel_write(), and g_io_channel_seek().
154 #define G_IO_NICE_BUF_SIZE 1024
156 /* This needs to be as wide as the largest character in any possible encoding */
157 #define MAX_CHAR_SIZE 10
159 /* Some simplifying macros, which reduce the need to worry whether the
160 * buffers have been allocated. These also make USE_BUF () an lvalue,
161 * which is used in g_io_channel_read_to_end ().
163 #define USE_BUF(channel) ((channel)->encoding ? (channel)->encoded_read_buf \
164 : (channel)->read_buf)
165 #define BUF_LEN(string) ((string) ? (string)->len : 0)
167 static GIOError g_io_error_get_from_g_error (GIOStatus status,
169 static void g_io_channel_purge (GIOChannel *channel);
170 static GIOStatus g_io_channel_fill_buffer (GIOChannel *channel,
172 static GIOStatus g_io_channel_read_line_backend (GIOChannel *channel,
174 gsize *terminator_pos,
179 * @channel: a #GIOChannel
181 * Initializes a #GIOChannel struct.
183 * This is called by each of the above functions when creating a
184 * #GIOChannel, and so is not often needed by the application
185 * programmer (unless you are creating a new type of #GIOChannel).
188 g_io_channel_init (GIOChannel *channel)
190 channel->ref_count = 1;
191 channel->encoding = g_strdup ("UTF-8");
192 channel->line_term = NULL;
193 channel->line_term_len = 0;
194 channel->buf_size = G_IO_NICE_BUF_SIZE;
195 channel->read_cd = (GIConv) -1;
196 channel->write_cd = (GIConv) -1;
197 channel->read_buf = NULL; /* Lazy allocate buffers */
198 channel->encoded_read_buf = NULL;
199 channel->write_buf = NULL;
200 channel->partial_write_buf[0] = '\0';
201 channel->use_buffer = TRUE;
202 channel->do_encode = FALSE;
203 channel->close_on_unref = FALSE;
208 * @channel: a #GIOChannel
210 * Increments the reference count of a #GIOChannel.
212 * Returns: the @channel that was passed in (since 2.6)
215 g_io_channel_ref (GIOChannel *channel)
217 g_return_val_if_fail (channel != NULL, NULL);
219 g_atomic_int_inc (&channel->ref_count);
225 * g_io_channel_unref:
226 * @channel: a #GIOChannel
228 * Decrements the reference count of a #GIOChannel.
231 g_io_channel_unref (GIOChannel *channel)
235 g_return_if_fail (channel != NULL);
237 is_zero = g_atomic_int_dec_and_test (&channel->ref_count);
239 if (G_UNLIKELY (is_zero))
241 if (channel->close_on_unref)
242 g_io_channel_shutdown (channel, TRUE, NULL);
244 g_io_channel_purge (channel);
245 g_free (channel->encoding);
246 if (channel->read_cd != (GIConv) -1)
247 g_iconv_close (channel->read_cd);
248 if (channel->write_cd != (GIConv) -1)
249 g_iconv_close (channel->write_cd);
250 g_free (channel->line_term);
251 if (channel->read_buf)
252 g_string_free (channel->read_buf, TRUE);
253 if (channel->write_buf)
254 g_string_free (channel->write_buf, TRUE);
255 if (channel->encoded_read_buf)
256 g_string_free (channel->encoded_read_buf, TRUE);
257 channel->funcs->io_free (channel);
262 g_io_error_get_from_g_error (GIOStatus status,
267 case G_IO_STATUS_NORMAL:
268 case G_IO_STATUS_EOF:
269 return G_IO_ERROR_NONE;
270 case G_IO_STATUS_AGAIN:
271 return G_IO_ERROR_AGAIN;
272 case G_IO_STATUS_ERROR:
273 g_return_val_if_fail (err != NULL, G_IO_ERROR_UNKNOWN);
275 if (err->domain != G_IO_CHANNEL_ERROR)
276 return G_IO_ERROR_UNKNOWN;
279 case G_IO_CHANNEL_ERROR_INVAL:
280 return G_IO_ERROR_INVAL;
282 return G_IO_ERROR_UNKNOWN;
285 g_assert_not_reached ();
291 * @channel: a #GIOChannel
292 * @buf: a buffer to read the data into (which should be at least
294 * @count: the number of bytes to read from the #GIOChannel
295 * @bytes_read: returns the number of bytes actually read
297 * Reads data from a #GIOChannel.
299 * Returns: %G_IO_ERROR_NONE if the operation was successful.
301 * Deprecated:2.2: Use g_io_channel_read_chars() instead.
304 g_io_channel_read (GIOChannel *channel,
313 g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
314 g_return_val_if_fail (bytes_read != NULL, G_IO_ERROR_UNKNOWN);
320 return G_IO_ERROR_NONE;
323 g_return_val_if_fail (buf != NULL, G_IO_ERROR_UNKNOWN);
325 status = channel->funcs->io_read (channel, buf, count, bytes_read, &err);
327 error = g_io_error_get_from_g_error (status, err);
336 * g_io_channel_write:
337 * @channel: a #GIOChannel
338 * @buf: the buffer containing the data to write
339 * @count: the number of bytes to write
340 * @bytes_written: the number of bytes actually written
342 * Writes data to a #GIOChannel.
344 * Returns: %G_IO_ERROR_NONE if the operation was successful.
346 * Deprecated:2.2: Use g_io_channel_write_chars() instead.
349 g_io_channel_write (GIOChannel *channel,
352 gsize *bytes_written)
358 g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
359 g_return_val_if_fail (bytes_written != NULL, G_IO_ERROR_UNKNOWN);
361 status = channel->funcs->io_write (channel, buf, count, bytes_written, &err);
363 error = g_io_error_get_from_g_error (status, err);
373 * @channel: a #GIOChannel
374 * @offset: an offset, in bytes, which is added to the position specified
376 * @type: the position in the file, which can be %G_SEEK_CUR (the current
377 * position), %G_SEEK_SET (the start of the file), or %G_SEEK_END
378 * (the end of the file)
380 * Sets the current position in the #GIOChannel, similar to the standard
381 * library function fseek().
383 * Returns: %G_IO_ERROR_NONE if the operation was successful.
385 * Deprecated:2.2: Use g_io_channel_seek_position() instead.
388 g_io_channel_seek (GIOChannel *channel,
396 g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
397 g_return_val_if_fail (channel->is_seekable, G_IO_ERROR_UNKNOWN);
406 g_warning ("g_io_channel_seek: unknown seek type");
407 return G_IO_ERROR_UNKNOWN;
410 status = channel->funcs->io_seek (channel, offset, type, &err);
412 error = g_io_error_get_from_g_error (status, err);
420 /* The function g_io_channel_new_file() is prototyped in both
421 * giounix.c and giowin32.c, so we stick its documentation here.
425 * g_io_channel_new_file:
426 * @filename: (type filename): A string containing the name of a file
427 * @mode: One of "r", "w", "a", "r+", "w+", "a+". These have
428 * the same meaning as in fopen()
429 * @error: A location to return an error of type %G_FILE_ERROR
431 * Open a file @filename as a #GIOChannel using mode @mode. This
432 * channel will be closed when the last reference to it is dropped,
433 * so there is no need to call g_io_channel_close() (though doing
434 * so will not cause problems, as long as no attempt is made to
435 * access the channel after it is closed).
437 * Returns: A #GIOChannel on success, %NULL on failure.
441 * g_io_channel_close:
442 * @channel: A #GIOChannel
444 * Close an IO channel. Any pending data to be written will be
445 * flushed, ignoring errors. The channel will not be freed until the
446 * last reference is dropped using g_io_channel_unref().
448 * Deprecated:2.2: Use g_io_channel_shutdown() instead.
451 g_io_channel_close (GIOChannel *channel)
455 g_return_if_fail (channel != NULL);
457 g_io_channel_purge (channel);
459 channel->funcs->io_close (channel, &err);
462 { /* No way to return the error */
463 g_warning ("Error closing channel: %s", err->message);
467 channel->close_on_unref = FALSE; /* Because we already did */
468 channel->is_readable = FALSE;
469 channel->is_writeable = FALSE;
470 channel->is_seekable = FALSE;
474 * g_io_channel_shutdown:
475 * @channel: a #GIOChannel
476 * @flush: if %TRUE, flush pending
477 * @err: location to store a #GIOChannelError
479 * Close an IO channel. Any pending data to be written will be
480 * flushed if @flush is %TRUE. The channel will not be freed until the
481 * last reference is dropped using g_io_channel_unref().
483 * Returns: the status of the operation.
486 g_io_channel_shutdown (GIOChannel *channel,
490 GIOStatus status, result;
491 GError *tmperr = NULL;
493 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
494 g_return_val_if_fail (err == NULL || *err == NULL, G_IO_STATUS_ERROR);
496 if (channel->write_buf && channel->write_buf->len > 0)
502 /* Set the channel to blocking, to avoid a busy loop
504 flags = g_io_channel_get_flags (channel);
505 /* Ignore any errors here, they're irrelevant */
506 g_io_channel_set_flags (channel, flags & ~G_IO_FLAG_NONBLOCK, NULL);
508 result = g_io_channel_flush (channel, &tmperr);
511 result = G_IO_STATUS_NORMAL;
513 g_string_truncate(channel->write_buf, 0);
516 result = G_IO_STATUS_NORMAL;
518 if (channel->partial_write_buf[0] != '\0')
521 g_warning ("Partial character at end of write buffer not flushed.");
522 channel->partial_write_buf[0] = '\0';
525 status = channel->funcs->io_close (channel, err);
527 channel->close_on_unref = FALSE; /* Because we already did */
528 channel->is_readable = FALSE;
529 channel->is_writeable = FALSE;
530 channel->is_seekable = FALSE;
532 if (status != G_IO_STATUS_NORMAL)
534 g_clear_error (&tmperr);
537 else if (result != G_IO_STATUS_NORMAL)
539 g_propagate_error (err, tmperr);
543 return G_IO_STATUS_NORMAL;
546 /* This function is used for the final flush on close or unref */
548 g_io_channel_purge (GIOChannel *channel)
551 GIOStatus status G_GNUC_UNUSED;
553 g_return_if_fail (channel != NULL);
555 if (channel->write_buf && channel->write_buf->len > 0)
559 /* Set the channel to blocking, to avoid a busy loop
561 flags = g_io_channel_get_flags (channel);
562 g_io_channel_set_flags (channel, flags & ~G_IO_FLAG_NONBLOCK, NULL);
564 status = g_io_channel_flush (channel, &err);
567 { /* No way to return the error */
568 g_warning ("Error flushing string: %s", err->message);
573 /* Flush these in case anyone tries to close without unrefing */
575 if (channel->read_buf)
576 g_string_truncate (channel->read_buf, 0);
577 if (channel->write_buf)
578 g_string_truncate (channel->write_buf, 0);
579 if (channel->encoding)
581 if (channel->encoded_read_buf)
582 g_string_truncate (channel->encoded_read_buf, 0);
584 if (channel->partial_write_buf[0] != '\0')
586 g_warning ("Partial character at end of write buffer not flushed.");
587 channel->partial_write_buf[0] = '\0';
594 * @channel: a #GIOChannel to watch
595 * @condition: conditions to watch for
597 * Creates a #GSource that's dispatched when @condition is met for the
598 * given @channel. For example, if condition is %G_IO_IN, the source will
599 * be dispatched when there's data available for reading.
601 * The callback function invoked by the #GSource should be added with
602 * g_source_set_callback(), but it has type #GIOFunc (not #GSourceFunc).
604 * g_io_add_watch() is a simpler interface to this same functionality, for
605 * the case where you want to add the source to the default main loop context
606 * at the default priority.
608 * On Windows, polling a #GSource created to watch a channel for a socket
609 * puts the socket in non-blocking mode. This is a side-effect of the
610 * implementation and unavoidable.
612 * Returns: a new #GSource
615 g_io_create_watch (GIOChannel *channel,
616 GIOCondition condition)
618 g_return_val_if_fail (channel != NULL, NULL);
620 return channel->funcs->io_create_watch (channel, condition);
624 * g_io_add_watch_full: (rename-to g_io_add_watch)
625 * @channel: a #GIOChannel
626 * @priority: the priority of the #GIOChannel source
627 * @condition: the condition to watch for
628 * @func: the function to call when the condition is satisfied
629 * @user_data: user data to pass to @func
630 * @notify: the function to call when the source is removed
632 * Adds the #GIOChannel into the default main loop context
633 * with the given priority.
635 * This internally creates a main loop source using g_io_create_watch()
636 * and attaches it to the main loop context with g_source_attach().
637 * You can do these steps manually if you need greater control.
639 * Returns: the event source id
642 g_io_add_watch_full (GIOChannel *channel,
644 GIOCondition condition,
647 GDestroyNotify notify)
652 g_return_val_if_fail (channel != NULL, 0);
654 source = g_io_create_watch (channel, condition);
656 if (priority != G_PRIORITY_DEFAULT)
657 g_source_set_priority (source, priority);
658 g_source_set_callback (source, (GSourceFunc)func, user_data, notify);
660 id = g_source_attach (source, NULL);
661 g_source_unref (source);
668 * @channel: a #GIOChannel
669 * @condition: the condition to watch for
670 * @func: the function to call when the condition is satisfied
671 * @user_data: user data to pass to @func
673 * Adds the #GIOChannel into the default main loop context
674 * with the default priority.
676 * Returns: the event source id
680 * @source: the #GIOChannel event source
681 * @condition: the condition which has been satisfied
682 * @data: user data set in g_io_add_watch() or g_io_add_watch_full()
684 * Specifies the type of function passed to g_io_add_watch() or
685 * g_io_add_watch_full(), which is called when the requested condition
686 * on a #GIOChannel is satisfied.
688 * Returns: the function should return %FALSE if the event source
693 * @G_IO_IN: There is data to read.
694 * @G_IO_OUT: Data can be written (without blocking).
695 * @G_IO_PRI: There is urgent data to read.
696 * @G_IO_ERR: Error condition.
697 * @G_IO_HUP: Hung up (the connection has been broken, usually for
698 * pipes and sockets).
699 * @G_IO_NVAL: Invalid request. The file descriptor is not open.
701 * A bitwise combination representing a condition to watch for on an
705 g_io_add_watch (GIOChannel *channel,
706 GIOCondition condition,
710 return g_io_add_watch_full (channel, G_PRIORITY_DEFAULT, condition, func, user_data, NULL);
714 * g_io_channel_get_buffer_condition:
715 * @channel: A #GIOChannel
717 * This function returns a #GIOCondition depending on whether there
718 * is data to be read/space to write data in the internal buffers in
719 * the #GIOChannel. Only the flags %G_IO_IN and %G_IO_OUT may be set.
721 * Returns: A #GIOCondition
724 g_io_channel_get_buffer_condition (GIOChannel *channel)
726 GIOCondition condition = 0;
728 if (channel->encoding)
730 if (channel->encoded_read_buf && (channel->encoded_read_buf->len > 0))
731 condition |= G_IO_IN; /* Only return if we have full characters */
735 if (channel->read_buf && (channel->read_buf->len > 0))
736 condition |= G_IO_IN;
739 if (channel->write_buf && (channel->write_buf->len < channel->buf_size))
740 condition |= G_IO_OUT;
746 * g_io_channel_error_from_errno:
747 * @en: an `errno` error number, e.g. `EINVAL`
749 * Converts an `errno` error number to a #GIOChannelError.
751 * Returns: a #GIOChannelError error number, e.g.
752 * %G_IO_CHANNEL_ERROR_INVAL.
755 g_io_channel_error_from_errno (gint en)
758 g_return_val_if_fail (en != EAGAIN, G_IO_CHANNEL_ERROR_FAILED);
765 g_warning ("Invalid file descriptor.");
766 return G_IO_CHANNEL_ERROR_FAILED;
771 g_warning ("Buffer outside valid address space.");
772 return G_IO_CHANNEL_ERROR_FAILED;
777 return G_IO_CHANNEL_ERROR_FBIG;
781 /* In general, we should catch EINTR before we get here,
782 * but close() is allowed to return EINTR by POSIX, so
783 * we need to catch it here; EINTR from close() is
784 * unrecoverable, because it's undefined whether
785 * the fd was actually closed or not, so we just return
786 * a generic error code.
789 return G_IO_CHANNEL_ERROR_FAILED;
794 return G_IO_CHANNEL_ERROR_INVAL;
799 return G_IO_CHANNEL_ERROR_IO;
804 return G_IO_CHANNEL_ERROR_ISDIR;
809 return G_IO_CHANNEL_ERROR_NOSPC;
814 return G_IO_CHANNEL_ERROR_NXIO;
818 #if EOVERFLOW != EFBIG
820 return G_IO_CHANNEL_ERROR_OVERFLOW;
826 return G_IO_CHANNEL_ERROR_PIPE;
830 return G_IO_CHANNEL_ERROR_FAILED;
835 * g_io_channel_set_buffer_size:
836 * @channel: a #GIOChannel
837 * @size: the size of the buffer, or 0 to let GLib pick a good size
839 * Sets the buffer size.
842 g_io_channel_set_buffer_size (GIOChannel *channel,
845 g_return_if_fail (channel != NULL);
848 size = G_IO_NICE_BUF_SIZE;
850 if (size < MAX_CHAR_SIZE)
851 size = MAX_CHAR_SIZE;
853 channel->buf_size = size;
857 * g_io_channel_get_buffer_size:
858 * @channel: a #GIOChannel
860 * Gets the buffer size.
862 * Returns: the size of the buffer.
865 g_io_channel_get_buffer_size (GIOChannel *channel)
867 g_return_val_if_fail (channel != NULL, 0);
869 return channel->buf_size;
873 * g_io_channel_set_line_term:
874 * @channel: a #GIOChannel
875 * @line_term: (nullable): The line termination string. Use %NULL for
876 * autodetect. Autodetection breaks on "\n", "\r\n", "\r", "\0",
877 * and the Unicode paragraph separator. Autodetection should not be
878 * used for anything other than file-based channels.
879 * @length: The length of the termination string. If -1 is passed, the
880 * string is assumed to be nul-terminated. This option allows
881 * termination strings with embedded nuls.
883 * This sets the string that #GIOChannel uses to determine
884 * where in the file a line break occurs.
887 g_io_channel_set_line_term (GIOChannel *channel,
888 const gchar *line_term,
891 guint length_unsigned;
893 g_return_if_fail (channel != NULL);
894 g_return_if_fail (line_term == NULL || length != 0); /* Disallow "" */
896 if (line_term == NULL)
898 else if (length >= 0)
899 length_unsigned = (guint) length;
902 /* FIXME: We’re constrained by line_term_len being a guint here */
903 gsize length_size = strlen (line_term);
904 g_return_if_fail (length_size <= G_MAXUINT);
905 length_unsigned = (guint) length_size;
908 g_free (channel->line_term);
909 channel->line_term = line_term ? g_memdup2 (line_term, length_unsigned) : NULL;
910 channel->line_term_len = length_unsigned;
914 * g_io_channel_get_line_term:
915 * @channel: a #GIOChannel
916 * @length: (out) (optional): a location to return the length of the line terminator
918 * This returns the string that #GIOChannel uses to determine
919 * where in the file a line break occurs. A value of %NULL
920 * indicates autodetection.
922 * Returns: The line termination string. This value
923 * is owned by GLib and must not be freed.
926 g_io_channel_get_line_term (GIOChannel *channel,
929 g_return_val_if_fail (channel != NULL, NULL);
932 *length = channel->line_term_len;
934 return channel->line_term;
938 * g_io_channel_set_flags:
939 * @channel: a #GIOChannel
940 * @flags: the flags to set on the IO channel
941 * @error: A location to return an error of type #GIOChannelError
943 * Sets the (writeable) flags in @channel to (@flags & %G_IO_FLAG_SET_MASK).
945 * Returns: the status of the operation.
949 * @G_IO_FLAG_NONE: no special flags set. Since: 2.74
950 * @G_IO_FLAG_APPEND: turns on append mode, corresponds to %O_APPEND
951 * (see the documentation of the UNIX open() syscall)
952 * @G_IO_FLAG_NONBLOCK: turns on nonblocking mode, corresponds to
953 * %O_NONBLOCK/%O_NDELAY (see the documentation of the UNIX open()
955 * @G_IO_FLAG_IS_READABLE: indicates that the io channel is readable.
956 * This flag cannot be changed.
957 * @G_IO_FLAG_IS_WRITABLE: indicates that the io channel is writable.
958 * This flag cannot be changed.
959 * @G_IO_FLAG_IS_WRITEABLE: a misspelled version of @G_IO_FLAG_IS_WRITABLE
960 * that existed before the spelling was fixed in GLib 2.30. It is kept
961 * here for compatibility reasons. Deprecated since 2.30
962 * @G_IO_FLAG_IS_SEEKABLE: indicates that the io channel is seekable,
963 * i.e. that g_io_channel_seek_position() can be used on it.
964 * This flag cannot be changed.
965 * @G_IO_FLAG_MASK: the mask that specifies all the valid flags.
966 * @G_IO_FLAG_GET_MASK: the mask of the flags that are returned from
967 * g_io_channel_get_flags()
968 * @G_IO_FLAG_SET_MASK: the mask of the flags that the user can modify
969 * with g_io_channel_set_flags()
971 * Specifies properties of a #GIOChannel. Some of the flags can only be
972 * read with g_io_channel_get_flags(), but not changed with
973 * g_io_channel_set_flags().
976 g_io_channel_set_flags (GIOChannel *channel,
980 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
981 g_return_val_if_fail ((error == NULL) || (*error == NULL),
984 return (*channel->funcs->io_set_flags) (channel,
985 flags & G_IO_FLAG_SET_MASK,
990 * g_io_channel_get_flags:
991 * @channel: a #GIOChannel
993 * Gets the current flags for a #GIOChannel, including read-only
994 * flags such as %G_IO_FLAG_IS_READABLE.
996 * The values of the flags %G_IO_FLAG_IS_READABLE and %G_IO_FLAG_IS_WRITABLE
997 * are cached for internal use by the channel when it is created.
998 * If they should change at some later point (e.g. partial shutdown
999 * of a socket with the UNIX shutdown() function), the user
1000 * should immediately call g_io_channel_get_flags() to update
1001 * the internal values of these flags.
1003 * Returns: the flags which are set on the channel
1006 g_io_channel_get_flags (GIOChannel *channel)
1010 g_return_val_if_fail (channel != NULL, 0);
1012 flags = (* channel->funcs->io_get_flags) (channel);
1014 /* Cross implementation code */
1016 if (channel->is_seekable)
1017 flags |= G_IO_FLAG_IS_SEEKABLE;
1018 if (channel->is_readable)
1019 flags |= G_IO_FLAG_IS_READABLE;
1020 if (channel->is_writeable)
1021 flags |= G_IO_FLAG_IS_WRITABLE;
1027 * g_io_channel_set_close_on_unref:
1028 * @channel: a #GIOChannel
1029 * @do_close: Whether to close the channel on the final unref of
1030 * the GIOChannel data structure.
1032 * Whether to close the channel on the final unref of the #GIOChannel
1033 * data structure. The default value of this is %TRUE for channels
1034 * created by g_io_channel_new_file (), and %FALSE for all other channels.
1036 * Setting this flag to %TRUE for a channel you have already closed
1037 * can cause problems when the final reference to the #GIOChannel is dropped.
1040 g_io_channel_set_close_on_unref (GIOChannel *channel,
1043 g_return_if_fail (channel != NULL);
1045 channel->close_on_unref = do_close;
1049 * g_io_channel_get_close_on_unref:
1050 * @channel: a #GIOChannel.
1052 * Returns whether the file/socket/whatever associated with @channel
1053 * will be closed when @channel receives its final unref and is
1054 * destroyed. The default value of this is %TRUE for channels created
1055 * by g_io_channel_new_file (), and %FALSE for all other channels.
1057 * Returns: %TRUE if the channel will be closed, %FALSE otherwise.
1060 g_io_channel_get_close_on_unref (GIOChannel *channel)
1062 g_return_val_if_fail (channel != NULL, FALSE);
1064 return channel->close_on_unref;
1068 * g_io_channel_seek_position:
1069 * @channel: a #GIOChannel
1070 * @offset: The offset in bytes from the position specified by @type
1071 * @type: a #GSeekType. The type %G_SEEK_CUR is only allowed in those
1072 * cases where a call to g_io_channel_set_encoding ()
1073 * is allowed. See the documentation for
1074 * g_io_channel_set_encoding () for details.
1075 * @error: A location to return an error of type #GIOChannelError
1077 * Replacement for g_io_channel_seek() with the new API.
1079 * Returns: the status of the operation.
1083 * @G_SEEK_CUR: the current position in the file.
1084 * @G_SEEK_SET: the start of the file.
1085 * @G_SEEK_END: the end of the file.
1087 * An enumeration specifying the base position for a
1088 * g_io_channel_seek_position() operation.
1091 g_io_channel_seek_position (GIOChannel *channel,
1098 /* For files, only one of the read and write buffers can contain data.
1099 * For sockets, both can contain data.
1102 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1103 g_return_val_if_fail ((error == NULL) || (*error == NULL),
1105 g_return_val_if_fail (channel->is_seekable, G_IO_STATUS_ERROR);
1109 case G_SEEK_CUR: /* The user is seeking relative to the head of the buffer */
1110 if (channel->use_buffer)
1112 if (channel->do_encode && channel->encoded_read_buf
1113 && channel->encoded_read_buf->len > 0)
1115 g_warning ("Seek type G_SEEK_CUR not allowed for this"
1116 " channel's encoding.");
1117 return G_IO_STATUS_ERROR;
1119 if (channel->read_buf)
1120 offset -= channel->read_buf->len;
1121 if (channel->encoded_read_buf)
1123 g_assert (channel->encoded_read_buf->len == 0 || !channel->do_encode);
1125 /* If there's anything here, it's because the encoding is UTF-8,
1126 * so we can just subtract the buffer length, the same as for
1127 * the unencoded data.
1130 offset -= channel->encoded_read_buf->len;
1138 g_warning ("g_io_channel_seek_position: unknown seek type");
1139 return G_IO_STATUS_ERROR;
1142 if (channel->use_buffer)
1144 status = g_io_channel_flush (channel, error);
1145 if (status != G_IO_STATUS_NORMAL)
1149 status = channel->funcs->io_seek (channel, offset, type, error);
1151 if ((status == G_IO_STATUS_NORMAL) && (channel->use_buffer))
1153 if (channel->read_buf)
1154 g_string_truncate (channel->read_buf, 0);
1156 /* Conversion state no longer matches position in file */
1157 if (channel->read_cd != (GIConv) -1)
1158 g_iconv (channel->read_cd, NULL, NULL, NULL, NULL);
1159 if (channel->write_cd != (GIConv) -1)
1160 g_iconv (channel->write_cd, NULL, NULL, NULL, NULL);
1162 if (channel->encoded_read_buf)
1164 g_assert (channel->encoded_read_buf->len == 0 || !channel->do_encode);
1165 g_string_truncate (channel->encoded_read_buf, 0);
1168 if (channel->partial_write_buf[0] != '\0')
1170 g_warning ("Partial character at end of write buffer not flushed.");
1171 channel->partial_write_buf[0] = '\0';
1179 * g_io_channel_flush:
1180 * @channel: a #GIOChannel
1181 * @error: location to store an error of type #GIOChannelError
1183 * Flushes the write buffer for the GIOChannel.
1185 * Returns: the status of the operation: One of
1186 * %G_IO_STATUS_NORMAL, %G_IO_STATUS_AGAIN, or
1187 * %G_IO_STATUS_ERROR.
1190 g_io_channel_flush (GIOChannel *channel,
1194 gsize this_time = 1, bytes_written = 0;
1196 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1197 g_return_val_if_fail ((error == NULL) || (*error == NULL), G_IO_STATUS_ERROR);
1199 if (channel->write_buf == NULL || channel->write_buf->len == 0)
1200 return G_IO_STATUS_NORMAL;
1204 g_assert (this_time > 0);
1206 status = channel->funcs->io_write (channel,
1207 channel->write_buf->str + bytes_written,
1208 channel->write_buf->len - bytes_written,
1210 bytes_written += this_time;
1212 while ((bytes_written < channel->write_buf->len)
1213 && (status == G_IO_STATUS_NORMAL));
1215 g_string_erase (channel->write_buf, 0, bytes_written);
1221 * g_io_channel_set_buffered:
1222 * @channel: a #GIOChannel
1223 * @buffered: whether to set the channel buffered or unbuffered
1225 * The buffering state can only be set if the channel's encoding
1226 * is %NULL. For any other encoding, the channel must be buffered.
1228 * A buffered channel can only be set unbuffered if the channel's
1229 * internal buffers have been flushed. Newly created channels or
1230 * channels which have returned %G_IO_STATUS_EOF
1231 * not require such a flush. For write-only channels, a call to
1232 * g_io_channel_flush () is sufficient. For all other channels,
1233 * the buffers may be flushed by a call to g_io_channel_seek_position ().
1234 * This includes the possibility of seeking with seek type %G_SEEK_CUR
1235 * and an offset of zero. Note that this means that socket-based
1236 * channels cannot be set unbuffered once they have had data
1239 * On unbuffered channels, it is safe to mix read and write
1240 * calls from the new and old APIs, if this is necessary for
1241 * maintaining old code.
1243 * The default state of the channel is buffered.
1246 g_io_channel_set_buffered (GIOChannel *channel,
1249 g_return_if_fail (channel != NULL);
1251 if (channel->encoding != NULL)
1253 g_warning ("Need to have NULL encoding to set the buffering state of the "
1258 g_return_if_fail (!channel->read_buf || channel->read_buf->len == 0);
1259 g_return_if_fail (!channel->write_buf || channel->write_buf->len == 0);
1261 channel->use_buffer = buffered;
1265 * g_io_channel_get_buffered:
1266 * @channel: a #GIOChannel
1268 * Returns whether @channel is buffered.
1270 * Return Value: %TRUE if the @channel is buffered.
1273 g_io_channel_get_buffered (GIOChannel *channel)
1275 g_return_val_if_fail (channel != NULL, FALSE);
1277 return channel->use_buffer;
1281 * g_io_channel_set_encoding:
1282 * @channel: a #GIOChannel
1283 * @encoding: (nullable): the encoding type
1284 * @error: location to store an error of type #GConvertError
1286 * Sets the encoding for the input/output of the channel.
1287 * The internal encoding is always UTF-8. The default encoding
1288 * for the external file is UTF-8.
1290 * The encoding %NULL is safe to use with binary data.
1292 * The encoding can only be set if one of the following conditions
1295 * - The channel was just created, and has not been written to or read from yet.
1297 * - The channel is write-only.
1299 * - The channel is a file, and the file pointer was just repositioned
1300 * by a call to g_io_channel_seek_position(). (This flushes all the
1301 * internal buffers.)
1303 * - The current encoding is %NULL or UTF-8.
1305 * - One of the (new API) read functions has just returned %G_IO_STATUS_EOF
1306 * (or, in the case of g_io_channel_read_to_end(), %G_IO_STATUS_NORMAL).
1308 * - One of the functions g_io_channel_read_chars() or
1309 * g_io_channel_read_unichar() has returned %G_IO_STATUS_AGAIN or
1310 * %G_IO_STATUS_ERROR. This may be useful in the case of
1311 * %G_CONVERT_ERROR_ILLEGAL_SEQUENCE.
1312 * Returning one of these statuses from g_io_channel_read_line(),
1313 * g_io_channel_read_line_string(), or g_io_channel_read_to_end()
1314 * does not guarantee that the encoding can be changed.
1316 * Channels which do not meet one of the above conditions cannot call
1317 * g_io_channel_seek_position() with an offset of %G_SEEK_CUR, and, if
1318 * they are "seekable", cannot call g_io_channel_write_chars() after
1319 * calling one of the API "read" functions.
1321 * Return Value: %G_IO_STATUS_NORMAL if the encoding was successfully set
1324 g_io_channel_set_encoding (GIOChannel *channel,
1325 const gchar *encoding,
1328 GIConv read_cd, write_cd;
1329 #ifndef G_DISABLE_ASSERT
1330 gboolean did_encode;
1333 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1334 g_return_val_if_fail ((error == NULL) || (*error == NULL), G_IO_STATUS_ERROR);
1336 /* Make sure the encoded buffers are empty */
1338 g_return_val_if_fail (!channel->do_encode || !channel->encoded_read_buf ||
1339 channel->encoded_read_buf->len == 0, G_IO_STATUS_ERROR);
1341 if (!channel->use_buffer)
1343 g_warning ("Need to set the channel buffered before setting the encoding.");
1344 g_warning ("Assuming this is what you meant and acting accordingly.");
1346 channel->use_buffer = TRUE;
1349 if (channel->partial_write_buf[0] != '\0')
1351 g_warning ("Partial character at end of write buffer not flushed.");
1352 channel->partial_write_buf[0] = '\0';
1355 #ifndef G_DISABLE_ASSERT
1356 did_encode = channel->do_encode;
1359 if (!encoding || strcmp (encoding, "UTF8") == 0 || strcmp (encoding, "UTF-8") == 0)
1361 channel->do_encode = FALSE;
1362 read_cd = write_cd = (GIConv) -1;
1367 const gchar *from_enc = NULL, *to_enc = NULL;
1369 if (channel->is_readable)
1371 read_cd = g_iconv_open ("UTF-8", encoding);
1373 if (read_cd == (GIConv) -1)
1376 from_enc = encoding;
1381 read_cd = (GIConv) -1;
1383 if (channel->is_writeable && err == 0)
1385 write_cd = g_iconv_open (encoding, "UTF-8");
1387 if (write_cd == (GIConv) -1)
1395 write_cd = (GIConv) -1;
1399 g_assert (from_enc);
1403 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
1404 _("Conversion from character set “%s” to “%s” is not supported"),
1407 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1408 _("Could not open converter from “%s” to “%s”: %s"),
1409 from_enc, to_enc, g_strerror (err));
1411 if (read_cd != (GIConv) -1)
1412 g_iconv_close (read_cd);
1413 if (write_cd != (GIConv) -1)
1414 g_iconv_close (write_cd);
1416 return G_IO_STATUS_ERROR;
1419 channel->do_encode = TRUE;
1422 /* The encoding is ok, so set the fields in channel */
1424 if (channel->read_cd != (GIConv) -1)
1425 g_iconv_close (channel->read_cd);
1426 if (channel->write_cd != (GIConv) -1)
1427 g_iconv_close (channel->write_cd);
1429 if (channel->encoded_read_buf && channel->encoded_read_buf->len > 0)
1431 g_assert (!did_encode); /* Encoding UTF-8, NULL doesn't use encoded_read_buf */
1433 /* This is just validated UTF-8, so we can copy it back into read_buf
1434 * so it can be encoded in whatever the new encoding is.
1437 g_string_prepend_len (channel->read_buf, channel->encoded_read_buf->str,
1438 channel->encoded_read_buf->len);
1439 g_string_truncate (channel->encoded_read_buf, 0);
1442 channel->read_cd = read_cd;
1443 channel->write_cd = write_cd;
1445 g_free (channel->encoding);
1446 channel->encoding = g_strdup (encoding);
1448 return G_IO_STATUS_NORMAL;
1452 * g_io_channel_get_encoding:
1453 * @channel: a #GIOChannel
1455 * Gets the encoding for the input/output of the channel.
1456 * The internal encoding is always UTF-8. The encoding %NULL
1457 * makes the channel safe for binary data.
1459 * Returns: A string containing the encoding, this string is
1460 * owned by GLib and must not be freed.
1463 g_io_channel_get_encoding (GIOChannel *channel)
1465 g_return_val_if_fail (channel != NULL, NULL);
1467 return channel->encoding;
1471 g_io_channel_fill_buffer (GIOChannel *channel,
1474 gsize read_size, cur_len, oldlen;
1477 if (channel->is_seekable && channel->write_buf && channel->write_buf->len > 0)
1479 status = g_io_channel_flush (channel, err);
1480 if (status != G_IO_STATUS_NORMAL)
1483 if (channel->is_seekable && channel->partial_write_buf[0] != '\0')
1485 g_warning ("Partial character at end of write buffer not flushed.");
1486 channel->partial_write_buf[0] = '\0';
1489 if (!channel->read_buf)
1490 channel->read_buf = g_string_sized_new (channel->buf_size);
1492 cur_len = channel->read_buf->len;
1494 g_string_set_size (channel->read_buf, channel->read_buf->len + channel->buf_size);
1496 status = channel->funcs->io_read (channel, channel->read_buf->str + cur_len,
1497 channel->buf_size, &read_size, err);
1499 g_assert ((status == G_IO_STATUS_NORMAL) || (read_size == 0));
1501 g_string_truncate (channel->read_buf, read_size + cur_len);
1503 if ((status != G_IO_STATUS_NORMAL) &&
1504 ((status != G_IO_STATUS_EOF) || (channel->read_buf->len == 0)))
1507 g_assert (channel->read_buf->len > 0);
1509 if (channel->encoded_read_buf)
1510 oldlen = channel->encoded_read_buf->len;
1514 if (channel->encoding)
1515 channel->encoded_read_buf = g_string_sized_new (channel->buf_size);
1518 if (channel->do_encode)
1520 gsize errnum, inbytes_left, outbytes_left;
1521 gchar *inbuf, *outbuf;
1524 g_assert (channel->encoded_read_buf);
1528 inbytes_left = channel->read_buf->len;
1529 outbytes_left = MAX (channel->read_buf->len,
1530 channel->encoded_read_buf->allocated_len
1531 - channel->encoded_read_buf->len - 1); /* 1 for NULL */
1532 outbytes_left = MAX (outbytes_left, 6);
1534 inbuf = channel->read_buf->str;
1535 g_string_set_size (channel->encoded_read_buf,
1536 channel->encoded_read_buf->len + outbytes_left);
1537 outbuf = channel->encoded_read_buf->str + channel->encoded_read_buf->len
1540 errnum = g_iconv (channel->read_cd, &inbuf, &inbytes_left,
1541 &outbuf, &outbytes_left);
1544 g_assert (inbuf + inbytes_left == channel->read_buf->str
1545 + channel->read_buf->len);
1546 g_assert (outbuf + outbytes_left == channel->encoded_read_buf->str
1547 + channel->encoded_read_buf->len);
1549 g_string_erase (channel->read_buf, 0,
1550 channel->read_buf->len - inbytes_left);
1551 g_string_truncate (channel->encoded_read_buf,
1552 channel->encoded_read_buf->len - outbytes_left);
1554 if (errnum == (gsize) -1)
1559 if ((oldlen == channel->encoded_read_buf->len)
1560 && (status == G_IO_STATUS_EOF))
1561 status = G_IO_STATUS_EOF;
1563 status = G_IO_STATUS_NORMAL;
1566 /* Buffer size at least 6, wrote at least on character */
1567 g_assert (inbuf != channel->read_buf->str);
1570 if (oldlen < channel->encoded_read_buf->len)
1571 status = G_IO_STATUS_NORMAL;
1574 g_set_error_literal (err, G_CONVERT_ERROR,
1575 G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1576 _("Invalid byte sequence in conversion input"));
1577 return G_IO_STATUS_ERROR;
1581 g_assert (errval != EBADF); /* The converter should be open */
1582 g_set_error (err, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1583 _("Error during conversion: %s"), g_strerror (errval));
1584 return G_IO_STATUS_ERROR;
1587 g_assert ((status != G_IO_STATUS_NORMAL)
1588 || (channel->encoded_read_buf->len > 0));
1590 else if (channel->encoding) /* UTF-8 */
1592 gchar *nextchar, *lastchar;
1594 g_assert (channel->encoded_read_buf);
1596 nextchar = channel->read_buf->str;
1597 lastchar = channel->read_buf->str + channel->read_buf->len;
1599 while (nextchar < lastchar)
1603 val_char = g_utf8_get_char_validated (nextchar, lastchar - nextchar);
1608 /* stop, leave partial character in buffer */
1609 lastchar = nextchar;
1612 if (oldlen < channel->encoded_read_buf->len)
1613 status = G_IO_STATUS_NORMAL;
1616 g_set_error_literal (err, G_CONVERT_ERROR,
1617 G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1618 _("Invalid byte sequence in conversion input"));
1619 status = G_IO_STATUS_ERROR;
1621 lastchar = nextchar;
1624 nextchar = g_utf8_next_char (nextchar);
1629 if (lastchar > channel->read_buf->str)
1631 gint copy_len = lastchar - channel->read_buf->str;
1633 g_string_append_len (channel->encoded_read_buf, channel->read_buf->str,
1635 g_string_erase (channel->read_buf, 0, copy_len);
1643 * g_io_channel_read_line:
1644 * @channel: a #GIOChannel
1645 * @str_return: (out): The line read from the #GIOChannel, including the
1646 * line terminator. This data should be freed with g_free()
1647 * when no longer needed. This is a nul-terminated string.
1648 * If a @length of zero is returned, this will be %NULL instead.
1649 * @length: (out) (optional): location to store length of the read data, or %NULL
1650 * @terminator_pos: (out) (optional): location to store position of line terminator, or %NULL
1651 * @error: A location to return an error of type #GConvertError
1652 * or #GIOChannelError
1654 * Reads a line, including the terminating character(s),
1655 * from a #GIOChannel into a newly-allocated string.
1656 * @str_return will contain allocated memory if the return
1657 * is %G_IO_STATUS_NORMAL.
1659 * Returns: the status of the operation.
1662 g_io_channel_read_line (GIOChannel *channel,
1665 gsize *terminator_pos,
1671 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1672 g_return_val_if_fail (str_return != NULL, G_IO_STATUS_ERROR);
1673 g_return_val_if_fail ((error == NULL) || (*error == NULL),
1675 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1677 status = g_io_channel_read_line_backend (channel, &got_length, terminator_pos, error);
1679 if (length && status != G_IO_STATUS_ERROR)
1680 *length = got_length;
1682 if (status == G_IO_STATUS_NORMAL)
1686 /* Copy the read bytes (including any embedded nuls) and nul-terminate.
1687 * `USE_BUF (channel)->str` is guaranteed to be nul-terminated as it’s a
1688 * #GString, so it’s safe to call g_memdup2() with +1 length to allocate
1689 * a nul-terminator. */
1690 g_assert (USE_BUF (channel));
1691 line = g_memdup2 (USE_BUF (channel)->str, got_length + 1);
1692 line[got_length] = '\0';
1693 *str_return = g_steal_pointer (&line);
1694 g_string_erase (USE_BUF (channel), 0, got_length);
1703 * g_io_channel_read_line_string:
1704 * @channel: a #GIOChannel
1705 * @buffer: a #GString into which the line will be written.
1706 * If @buffer already contains data, the old data will
1708 * @terminator_pos: (nullable): location to store position of line terminator, or %NULL
1709 * @error: a location to store an error of type #GConvertError
1710 * or #GIOChannelError
1712 * Reads a line from a #GIOChannel, using a #GString as a buffer.
1714 * Returns: the status of the operation.
1717 g_io_channel_read_line_string (GIOChannel *channel,
1719 gsize *terminator_pos,
1725 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1726 g_return_val_if_fail (buffer != NULL, G_IO_STATUS_ERROR);
1727 g_return_val_if_fail ((error == NULL) || (*error == NULL),
1729 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1731 if (buffer->len > 0)
1732 g_string_truncate (buffer, 0); /* clear out the buffer */
1734 status = g_io_channel_read_line_backend (channel, &length, terminator_pos, error);
1736 if (status == G_IO_STATUS_NORMAL)
1738 g_assert (USE_BUF (channel));
1739 g_string_append_len (buffer, USE_BUF (channel)->str, length);
1740 g_string_erase (USE_BUF (channel), 0, length);
1748 g_io_channel_read_line_backend (GIOChannel *channel,
1750 gsize *terminator_pos,
1754 gsize checked_to, line_term_len, line_length, got_term_len;
1755 gboolean first_time = TRUE;
1757 if (!channel->use_buffer)
1759 /* Can't do a raw read in read_line */
1760 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1761 _("Can’t do a raw read in g_io_channel_read_line_string"));
1762 return G_IO_STATUS_ERROR;
1765 status = G_IO_STATUS_NORMAL;
1767 if (channel->line_term)
1768 line_term_len = channel->line_term_len;
1771 /* This value used for setting checked_to, it's the longest of the four
1772 * we autodetect for.
1779 gchar *nextchar, *lastchar;
1782 if (!first_time || (BUF_LEN (USE_BUF (channel)) == 0))
1785 status = g_io_channel_fill_buffer (channel, error);
1788 case G_IO_STATUS_NORMAL:
1789 if (BUF_LEN (USE_BUF (channel)) == 0)
1790 /* Can happen when using conversion and only read
1791 * part of a character
1798 case G_IO_STATUS_EOF:
1799 if (BUF_LEN (USE_BUF (channel)) == 0)
1804 if (channel->encoding && channel->read_buf->len != 0)
1806 g_set_error_literal (error, G_CONVERT_ERROR,
1807 G_CONVERT_ERROR_PARTIAL_INPUT,
1808 _("Leftover unconverted data in "
1810 return G_IO_STATUS_ERROR;
1813 return G_IO_STATUS_EOF;
1823 g_assert (BUF_LEN (USE_BUF (channel)) != 0);
1825 use_buf = USE_BUF (channel); /* The buffer has been created by this point */
1829 lastchar = use_buf->str + use_buf->len;
1831 for (nextchar = use_buf->str + checked_to; nextchar < lastchar;
1832 channel->encoding ? nextchar = g_utf8_next_char (nextchar) : nextchar++)
1834 if (channel->line_term)
1836 if (memcmp (channel->line_term, nextchar, line_term_len) == 0)
1838 line_length = nextchar - use_buf->str;
1839 got_term_len = line_term_len;
1843 else /* auto detect */
1847 case '\n': /* unix */
1848 line_length = nextchar - use_buf->str;
1851 case '\r': /* Warning: do not use with sockets */
1852 line_length = nextchar - use_buf->str;
1853 if ((nextchar == lastchar - 1) && (status != G_IO_STATUS_EOF)
1854 && (lastchar == use_buf->str + use_buf->len))
1855 goto read_again; /* Try to read more data */
1856 if ((nextchar < lastchar - 1) && (*(nextchar + 1) == '\n')) /* dos */
1861 case '\xe2': /* Unicode paragraph separator */
1862 if (strncmp ("\xe2\x80\xa9", nextchar, 3) == 0)
1864 line_length = nextchar - use_buf->str;
1869 case '\0': /* Embedded null in input */
1870 line_length = nextchar - use_buf->str;
1873 default: /* no match */
1879 /* If encoding != NULL, valid UTF-8, didn't overshoot */
1880 g_assert (nextchar == lastchar);
1884 if (status == G_IO_STATUS_EOF)
1886 if (channel->encoding && channel->read_buf->len > 0)
1888 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1889 _("Channel terminates in a partial character"));
1890 return G_IO_STATUS_ERROR;
1892 line_length = use_buf->len;
1897 if (use_buf->len > line_term_len - 1)
1898 checked_to = use_buf->len - (line_term_len - 1);
1906 *terminator_pos = line_length;
1909 *length = line_length + got_term_len;
1911 return G_IO_STATUS_NORMAL;
1915 * g_io_channel_read_to_end:
1916 * @channel: a #GIOChannel
1917 * @str_return: (out) (array length=length) (element-type guint8): Location to
1918 * store a pointer to a string holding the remaining data in the
1919 * #GIOChannel. This data should be freed with g_free() when no
1920 * longer needed. This data is terminated by an extra nul
1921 * character, but there may be other nuls in the intervening data.
1922 * @length: (out): location to store length of the data
1923 * @error: location to return an error of type #GConvertError
1924 * or #GIOChannelError
1926 * Reads all the remaining data from the file.
1928 * Returns: %G_IO_STATUS_NORMAL on success.
1929 * This function never returns %G_IO_STATUS_EOF.
1932 g_io_channel_read_to_end (GIOChannel *channel,
1939 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1940 g_return_val_if_fail ((error == NULL) || (*error == NULL),
1942 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1949 if (!channel->use_buffer)
1951 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1952 _("Can’t do a raw read in g_io_channel_read_to_end"));
1953 return G_IO_STATUS_ERROR;
1957 status = g_io_channel_fill_buffer (channel, error);
1958 while (status == G_IO_STATUS_NORMAL);
1960 if (status != G_IO_STATUS_EOF)
1963 if (channel->encoding && channel->read_buf->len > 0)
1965 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1966 _("Channel terminates in a partial character"));
1967 return G_IO_STATUS_ERROR;
1970 if (USE_BUF (channel) == NULL)
1972 /* length is already set to zero */
1974 *str_return = g_strdup ("");
1979 *length = USE_BUF (channel)->len;
1982 *str_return = g_string_free (USE_BUF (channel), FALSE);
1984 g_string_free (USE_BUF (channel), TRUE);
1986 if (channel->encoding)
1987 channel->encoded_read_buf = NULL;
1989 channel->read_buf = NULL;
1992 return G_IO_STATUS_NORMAL;
1996 * g_io_channel_read_chars:
1997 * @channel: a #GIOChannel
1998 * @buf: (out caller-allocates) (array length=count) (element-type guint8):
1999 * a buffer to read data into
2000 * @count: (in): the size of the buffer. Note that the buffer may not be
2001 * completely filled even if there is data in the buffer if the
2002 * remaining data is not a complete character.
2003 * @bytes_read: (out) (optional): The number of bytes read. This may be
2004 * zero even on success if count < 6 and the channel's encoding
2005 * is non-%NULL. This indicates that the next UTF-8 character is
2006 * too wide for the buffer.
2007 * @error: a location to return an error of type #GConvertError
2008 * or #GIOChannelError.
2010 * Replacement for g_io_channel_read() with the new API.
2012 * Returns: the status of the operation.
2015 g_io_channel_read_chars (GIOChannel *channel,
2024 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
2025 g_return_val_if_fail ((error == NULL) || (*error == NULL), G_IO_STATUS_ERROR);
2026 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
2032 return G_IO_STATUS_NORMAL;
2034 g_return_val_if_fail (buf != NULL, G_IO_STATUS_ERROR);
2036 if (!channel->use_buffer)
2040 g_assert (!channel->read_buf || channel->read_buf->len == 0);
2042 status = channel->funcs->io_read (channel, buf, count, &tmp_bytes, error);
2045 *bytes_read = tmp_bytes;
2050 status = G_IO_STATUS_NORMAL;
2052 while (BUF_LEN (USE_BUF (channel)) < count && status == G_IO_STATUS_NORMAL)
2053 status = g_io_channel_fill_buffer (channel, error);
2055 /* Only return an error if we have no data */
2057 if (BUF_LEN (USE_BUF (channel)) == 0)
2059 g_assert (status != G_IO_STATUS_NORMAL);
2061 if (status == G_IO_STATUS_EOF && channel->encoding
2062 && BUF_LEN (channel->read_buf) > 0)
2064 g_set_error_literal (error, G_CONVERT_ERROR,
2065 G_CONVERT_ERROR_PARTIAL_INPUT,
2066 _("Leftover unconverted data in read buffer"));
2067 status = G_IO_STATUS_ERROR;
2076 if (status == G_IO_STATUS_ERROR)
2077 g_clear_error (error);
2079 got_bytes = MIN (count, BUF_LEN (USE_BUF (channel)));
2081 g_assert (got_bytes > 0);
2083 if (channel->encoding)
2084 /* Don't validate for NULL encoding, binary safe */
2086 gchar *nextchar, *prevchar;
2088 g_assert (USE_BUF (channel) == channel->encoded_read_buf);
2090 nextchar = channel->encoded_read_buf->str;
2094 prevchar = nextchar;
2095 nextchar = g_utf8_next_char (nextchar);
2096 g_assert (nextchar != prevchar); /* Possible for *prevchar of -1 or -2 */
2098 while (nextchar < channel->encoded_read_buf->str + got_bytes);
2100 if (nextchar > channel->encoded_read_buf->str + got_bytes)
2101 got_bytes = prevchar - channel->encoded_read_buf->str;
2103 g_assert (got_bytes > 0 || count < 6);
2106 memcpy (buf, USE_BUF (channel)->str, got_bytes);
2107 g_string_erase (USE_BUF (channel), 0, got_bytes);
2110 *bytes_read = got_bytes;
2112 return G_IO_STATUS_NORMAL;
2116 * g_io_channel_read_unichar:
2117 * @channel: a #GIOChannel
2118 * @thechar: (out): a location to return a character
2119 * @error: a location to return an error of type #GConvertError
2120 * or #GIOChannelError
2122 * Reads a Unicode character from @channel.
2123 * This function cannot be called on a channel with %NULL encoding.
2125 * Returns: a #GIOStatus
2128 g_io_channel_read_unichar (GIOChannel *channel,
2132 GIOStatus status = G_IO_STATUS_NORMAL;
2134 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
2135 g_return_val_if_fail (channel->encoding != NULL, G_IO_STATUS_ERROR);
2136 g_return_val_if_fail ((error == NULL) || (*error == NULL),
2138 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
2140 while (BUF_LEN (channel->encoded_read_buf) == 0 && status == G_IO_STATUS_NORMAL)
2141 status = g_io_channel_fill_buffer (channel, error);
2143 /* Only return an error if we have no data */
2145 if (BUF_LEN (USE_BUF (channel)) == 0)
2147 g_assert (status != G_IO_STATUS_NORMAL);
2149 if (status == G_IO_STATUS_EOF && BUF_LEN (channel->read_buf) > 0)
2151 g_set_error_literal (error, G_CONVERT_ERROR,
2152 G_CONVERT_ERROR_PARTIAL_INPUT,
2153 _("Leftover unconverted data in read buffer"));
2154 status = G_IO_STATUS_ERROR;
2158 *thechar = (gunichar) -1;
2163 if (status == G_IO_STATUS_ERROR)
2164 g_clear_error (error);
2167 *thechar = g_utf8_get_char (channel->encoded_read_buf->str);
2169 g_string_erase (channel->encoded_read_buf, 0,
2170 g_utf8_next_char (channel->encoded_read_buf->str)
2171 - channel->encoded_read_buf->str);
2173 return G_IO_STATUS_NORMAL;
2177 * g_io_channel_write_chars:
2178 * @channel: a #GIOChannel
2179 * @buf: (array) (element-type guint8): a buffer to write data from
2180 * @count: the size of the buffer. If -1, the buffer
2181 * is taken to be a nul-terminated string.
2182 * @bytes_written: (out): The number of bytes written. This can be nonzero
2183 * even if the return value is not %G_IO_STATUS_NORMAL.
2184 * If the return value is %G_IO_STATUS_NORMAL and the
2185 * channel is blocking, this will always be equal
2186 * to @count if @count >= 0.
2187 * @error: a location to return an error of type #GConvertError
2188 * or #GIOChannelError
2190 * Replacement for g_io_channel_write() with the new API.
2192 * On seekable channels with encodings other than %NULL or UTF-8, generic
2193 * mixing of reading and writing is not allowed. A call to g_io_channel_write_chars ()
2194 * may only be made on a channel from which data has been read in the
2195 * cases described in the documentation for g_io_channel_set_encoding ().
2197 * Returns: the status of the operation.
2200 g_io_channel_write_chars (GIOChannel *channel,
2203 gsize *bytes_written,
2206 gsize count_unsigned;
2208 gsize wrote_bytes = 0;
2210 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
2211 g_return_val_if_fail (buf != NULL || count == 0, G_IO_STATUS_ERROR);
2212 g_return_val_if_fail ((error == NULL) || (*error == NULL),
2214 g_return_val_if_fail (channel->is_writeable, G_IO_STATUS_ERROR);
2217 count_unsigned = strlen (buf);
2219 count_unsigned = count;
2221 if (count_unsigned == 0)
2225 return G_IO_STATUS_NORMAL;
2228 g_assert (count_unsigned > 0);
2230 /* Raw write case */
2232 if (!channel->use_buffer)
2236 g_assert (!channel->write_buf || channel->write_buf->len == 0);
2237 g_assert (channel->partial_write_buf[0] == '\0');
2239 status = channel->funcs->io_write (channel, buf, count_unsigned,
2243 *bytes_written = tmp_bytes;
2250 if (channel->is_seekable && (( BUF_LEN (channel->read_buf) > 0)
2251 || (BUF_LEN (channel->encoded_read_buf) > 0)))
2253 if (channel->do_encode && BUF_LEN (channel->encoded_read_buf) > 0)
2255 g_warning ("Mixed reading and writing not allowed on encoded files");
2256 return G_IO_STATUS_ERROR;
2258 status = g_io_channel_seek_position (channel, 0, G_SEEK_CUR, error);
2259 if (status != G_IO_STATUS_NORMAL)
2267 if (!channel->write_buf)
2268 channel->write_buf = g_string_sized_new (channel->buf_size);
2270 while (wrote_bytes < count_unsigned)
2274 /* If the buffer is full, try a write immediately. In
2275 * the nonblocking case, this prevents the user from
2276 * writing just a little bit to the buffer every time
2277 * and never receiving an EAGAIN.
2280 if (channel->write_buf->len >= channel->buf_size - MAX_CHAR_SIZE)
2282 gsize did_write = 0, this_time;
2286 status = channel->funcs->io_write (channel, channel->write_buf->str
2287 + did_write, channel->write_buf->len
2288 - did_write, &this_time, error);
2289 did_write += this_time;
2291 while (status == G_IO_STATUS_NORMAL &&
2292 did_write < MIN (channel->write_buf->len, MAX_CHAR_SIZE));
2294 g_string_erase (channel->write_buf, 0, did_write);
2296 if (status != G_IO_STATUS_NORMAL)
2298 if (status == G_IO_STATUS_AGAIN && wrote_bytes > 0)
2299 status = G_IO_STATUS_NORMAL;
2301 *bytes_written = wrote_bytes;
2306 space_in_buf = MAX (channel->buf_size, channel->write_buf->allocated_len - 1)
2307 - channel->write_buf->len; /* 1 for NULL */
2309 /* This is only true because g_io_channel_set_buffer_size ()
2310 * ensures that channel->buf_size >= MAX_CHAR_SIZE.
2312 g_assert (space_in_buf >= MAX_CHAR_SIZE);
2314 if (!channel->encoding)
2316 gsize write_this = MIN (space_in_buf, count_unsigned - wrote_bytes);
2318 /* g_string_append_len() takes a gssize, so don’t overflow it*/
2319 if (write_this > G_MAXSSIZE)
2320 write_this = G_MAXSSIZE;
2322 g_string_append_len (channel->write_buf, buf, write_this);
2324 wrote_bytes += write_this;
2328 const gchar *from_buf;
2329 gsize from_buf_len, from_buf_old_len, left_len;
2333 if (channel->partial_write_buf[0] != '\0')
2335 g_assert (wrote_bytes == 0);
2337 from_buf = channel->partial_write_buf;
2338 from_buf_old_len = strlen (channel->partial_write_buf);
2339 g_assert (from_buf_old_len > 0);
2340 from_buf_len = MIN (6, from_buf_old_len + count_unsigned);
2342 memcpy (channel->partial_write_buf + from_buf_old_len, buf,
2343 from_buf_len - from_buf_old_len);
2348 from_buf_len = count_unsigned - wrote_bytes;
2349 from_buf_old_len = 0;
2354 if (!channel->do_encode) /* UTF-8 encoding */
2356 const gchar *badchar;
2357 gsize try_len = MIN (from_buf_len, space_in_buf);
2359 /* UTF-8, just validate, emulate g_iconv */
2361 if (!g_utf8_validate_len (from_buf, try_len, &badchar))
2364 gsize incomplete_len = from_buf + try_len - badchar;
2366 left_len = from_buf + from_buf_len - badchar;
2368 try_char = g_utf8_get_char_validated (badchar, incomplete_len);
2373 g_assert (incomplete_len < 6);
2374 if (try_len == from_buf_len)
2386 g_warning ("Invalid UTF-8 passed to g_io_channel_write_chars().");
2387 /* FIXME bail here? */
2392 g_assert_not_reached ();
2394 errnum = 0; /* Don't confuse the compiler */
2401 left_len = from_buf_len - try_len;
2404 g_string_append_len (channel->write_buf, from_buf,
2405 from_buf_len - left_len);
2406 from_buf += from_buf_len - left_len;
2412 left_len = from_buf_len;
2413 g_string_set_size (channel->write_buf, channel->write_buf->len
2415 outbuf = channel->write_buf->str + channel->write_buf->len
2417 err = g_iconv (channel->write_cd, (gchar **) &from_buf, &left_len,
2418 &outbuf, &space_in_buf);
2420 g_string_truncate (channel->write_buf, channel->write_buf->len
2424 if (err == (gsize) -1)
2429 g_assert (left_len < 6);
2431 if (from_buf_old_len == 0)
2433 /* Not from partial_write_buf */
2435 memcpy (channel->partial_write_buf, from_buf, left_len);
2436 channel->partial_write_buf[left_len] = '\0';
2438 *bytes_written = count_unsigned;
2439 return G_IO_STATUS_NORMAL;
2442 /* Working in partial_write_buf */
2444 if (left_len == from_buf_len)
2446 /* Didn't convert anything, must still have
2447 * less than a full character
2450 g_assert (count_unsigned == from_buf_len - from_buf_old_len);
2452 channel->partial_write_buf[from_buf_len] = '\0';
2455 *bytes_written = count_unsigned;
2457 return G_IO_STATUS_NORMAL;
2460 g_assert (from_buf_len - left_len >= from_buf_old_len);
2462 /* We converted all the old data. This is fine */
2466 if (from_buf_len == left_len)
2468 /* Nothing was written, add enough space for
2469 * at least one character.
2471 space_in_buf += MAX_CHAR_SIZE;
2476 g_set_error_literal (error, G_CONVERT_ERROR,
2477 G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
2478 _("Invalid byte sequence in conversion input"));
2479 if (from_buf_old_len > 0 && from_buf_len == left_len)
2480 g_warning ("Illegal sequence due to partial character "
2481 "at the end of a previous write.");
2484 g_assert (from_buf_len >= left_len + from_buf_old_len);
2485 wrote_bytes += from_buf_len - left_len - from_buf_old_len;
2488 *bytes_written = wrote_bytes;
2489 channel->partial_write_buf[0] = '\0';
2490 return G_IO_STATUS_ERROR;
2492 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
2493 _("Error during conversion: %s"), g_strerror (errnum));
2494 if (from_buf_len >= left_len + from_buf_old_len)
2495 wrote_bytes += from_buf_len - left_len - from_buf_old_len;
2497 *bytes_written = wrote_bytes;
2498 channel->partial_write_buf[0] = '\0';
2499 return G_IO_STATUS_ERROR;
2503 g_assert (from_buf_len - left_len >= from_buf_old_len);
2505 wrote_bytes += from_buf_len - left_len - from_buf_old_len;
2507 if (from_buf_old_len > 0)
2509 /* We were working in partial_write_buf */
2511 buf += from_buf_len - left_len - from_buf_old_len;
2512 channel->partial_write_buf[0] = '\0';
2520 *bytes_written = count_unsigned;
2522 return G_IO_STATUS_NORMAL;
2526 * g_io_channel_write_unichar:
2527 * @channel: a #GIOChannel
2528 * @thechar: a character
2529 * @error: location to return an error of type #GConvertError
2530 * or #GIOChannelError
2532 * Writes a Unicode character to @channel.
2533 * This function cannot be called on a channel with %NULL encoding.
2535 * Returns: a #GIOStatus
2538 g_io_channel_write_unichar (GIOChannel *channel,
2543 gchar static_buf[6];
2544 gsize char_len, wrote_len;
2546 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
2547 g_return_val_if_fail (channel->encoding != NULL, G_IO_STATUS_ERROR);
2548 g_return_val_if_fail ((error == NULL) || (*error == NULL),
2550 g_return_val_if_fail (channel->is_writeable, G_IO_STATUS_ERROR);
2552 char_len = g_unichar_to_utf8 (thechar, static_buf);
2554 if (channel->partial_write_buf[0] != '\0')
2556 g_warning ("Partial character written before writing unichar.");
2557 channel->partial_write_buf[0] = '\0';
2560 status = g_io_channel_write_chars (channel, static_buf,
2561 char_len, &wrote_len, error);
2563 /* We validate UTF-8, so we can't get a partial write */
2565 g_assert (wrote_len == char_len || status != G_IO_STATUS_NORMAL);
2571 * G_IO_CHANNEL_ERROR:
2573 * Error domain for #GIOChannel operations. Errors in this domain will
2574 * be from the #GIOChannelError enumeration. See #GError for
2575 * information on error domains.
2579 * @G_IO_CHANNEL_ERROR_FBIG: File too large.
2580 * @G_IO_CHANNEL_ERROR_INVAL: Invalid argument.
2581 * @G_IO_CHANNEL_ERROR_IO: IO error.
2582 * @G_IO_CHANNEL_ERROR_ISDIR: File is a directory.
2583 * @G_IO_CHANNEL_ERROR_NOSPC: No space left on device.
2584 * @G_IO_CHANNEL_ERROR_NXIO: No such device or address.
2585 * @G_IO_CHANNEL_ERROR_OVERFLOW: Value too large for defined datatype.
2586 * @G_IO_CHANNEL_ERROR_PIPE: Broken pipe.
2587 * @G_IO_CHANNEL_ERROR_FAILED: Some other error.
2589 * Error codes returned by #GIOChannel operations.
2592 G_DEFINE_QUARK (g-io-channel-error-quark, g_io_channel_error)