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