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