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