giochannel.c 66.4 KB
Newer Older
1
2
3
4
5
6
7
/* GLIB - Library of useful routines for C programming
 * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
 *
 * giochannel.c: IO Channel abstraction
 * Copyright 1998 Owen Taylor
 *
 * This library is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
10
11
12
13
14
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * 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
19
20
21
22
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

23
/*
24
 * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
25
26
27
28
29
 * file for a list of people on the GLib Team.  See the ChangeLog
 * files for a list of changes.  These files are distributed with
 * GLib at ftp://ftp.gtk.org/pub/gtk/. 
 */

30
31
32
33
/* 
 * MT safe
 */

34
35
36
#include "config.h"
#include "giochannel.h"

37
38
#include <string.h>
#include <errno.h>
39
40

#ifdef HAVE_UNISTD_H
41
#include <unistd.h>
42
#endif
43

44
45
46
47
48
49
50
51
#undef G_DISABLE_DEPRECATED

#include "glib.h"

#include "glibintl.h"

#define G_IO_NICE_BUF_SIZE	1024

52
53
54
55
56
57
58
59
60
61
62
/* This needs to be as wide as the largest character in any possible encoding */
#define MAX_CHAR_SIZE		10

/* Some simplifying macros, which reduce the need to worry whether the
 * buffers have been allocated. These also make USE_BUF () an lvalue,
 * which is used in g_io_channel_read_to_end ().
 */
#define USE_BUF(channel)	((channel)->encoding ? (channel)->encoded_read_buf \
				 : (channel)->read_buf)
#define BUF_LEN(string)		((string) ? (string)->len : 0)

63
static GIOError		g_io_error_get_from_g_error	(GIOStatus    status,
64
65
66
67
							 GError      *err);
static void		g_io_channel_purge		(GIOChannel  *channel);
static GIOStatus	g_io_channel_fill_buffer	(GIOChannel  *channel,
							 GError     **err);
68
69
70
71
static GIOStatus	g_io_channel_read_line_backend	(GIOChannel  *channel,
							 gsize       *length,
							 gsize       *terminator_pos,
							 GError     **error);
72

73
74
void
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->line_term_len = 0;
80
  channel->buf_size = G_IO_NICE_BUF_SIZE;
81
82
83
84
85
86
  channel->read_cd = (GIConv) -1;
  channel->write_cd = (GIConv) -1;
  channel->read_buf = NULL; /* Lazy allocate buffers */
  channel->encoded_read_buf = NULL;
  channel->write_buf = NULL;
  channel->partial_write_buf[0] = '\0';
87
88
89
  channel->use_buffer = TRUE;
  channel->do_encode = FALSE;
  channel->close_on_unref = FALSE;
90
91
92
93
94
95
96
}

void 
g_io_channel_ref (GIOChannel *channel)
{
  g_return_if_fail (channel != NULL);

97
  channel->ref_count++;
98
99
100
101
102
103
104
}

void 
g_io_channel_unref (GIOChannel *channel)
{
  g_return_if_fail (channel != NULL);

105
106
  channel->ref_count--;
  if (channel->ref_count == 0)
107
108
    {
      if (channel->close_on_unref)
109
        g_io_channel_shutdown (channel, TRUE, NULL);
110
111
112
      else
        g_io_channel_purge (channel);
      g_free (channel->encoding);
113
114
115
116
      if (channel->read_cd != (GIConv) -1)
        g_iconv_close (channel->read_cd);
      if (channel->write_cd != (GIConv) -1)
        g_iconv_close (channel->write_cd);
117
118
      if (channel->line_term)
        g_free (channel->line_term);
119
120
121
122
123
124
      if (channel->read_buf)
        g_string_free (channel->read_buf, TRUE);
      if (channel->write_buf)
        g_string_free (channel->write_buf, TRUE);
      if (channel->encoded_read_buf)
        g_string_free (channel->encoded_read_buf, TRUE);
125
126
      channel->funcs->io_free (channel);
    }
127
128
}

129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
static GIOError
g_io_error_get_from_g_error (GIOStatus status,
			     GError *err)
{
  switch (status)
    {
      case G_IO_STATUS_NORMAL:
      case G_IO_STATUS_EOF:
        return G_IO_ERROR_NONE;
      case G_IO_STATUS_AGAIN:
        return G_IO_ERROR_AGAIN;
      case G_IO_STATUS_ERROR:
        if (err->domain != G_IO_CHANNEL_ERROR)
          return G_IO_ERROR_UNKNOWN;
        switch (err->code)
          {
            case G_IO_CHANNEL_ERROR_INVAL:
              return G_IO_ERROR_INVAL;
            default:
              return G_IO_ERROR_UNKNOWN;
          }
      default:
        g_assert_not_reached ();
        return G_IO_ERROR_UNKNOWN; /* Keep the compiler happy */
    }
}

/**
 * g_io_channel_read:
 * @channel: a #GIOChannel. 
 * @buf: a buffer to read the data into (which should be at least count bytes long).
 * @count: the number of bytes to read from the #GIOChannel.
 * @bytes_read: returns the number of bytes actually read. 
 * 
 * Reads data from a #GIOChannel. This function is depricated. New code should
 * use g_io_channel_read_chars() instead.
 * 
 * Return value: %G_IO_ERROR_NONE if the operation was successful. 
 **/
168
169
170
GIOError 
g_io_channel_read (GIOChannel *channel, 
		   gchar      *buf, 
171
172
		   gsize       count,
		   gsize      *bytes_read)
173
{
174
175
176
177
  GError *err = NULL;
  GIOError error;
  GIOStatus status;

178
  g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
179
180
181
  g_return_val_if_fail (bytes_read != NULL, G_IO_ERROR_UNKNOWN);

  status = channel->funcs->io_read (channel, buf, count, bytes_read, &err);
182

183
184
185
186
187
188
  error = g_io_error_get_from_g_error (status, err);

  if (err)
    g_error_free (err);

  return error;
189
190
}

191
192
193
194
195
196
197
198
199
200
201
202
/**
 * g_io_channel_write:
 * @channel:  a #GIOChannel.
 * @buf: the buffer containing the data to write. 
 * @count: the number of bytes to write.
 * @bytes_written:  the number of bytes actually written.
 * 
 * Writes data to a #GIOChannel. This function is depricated. New code should
 * use g_io_channel_write_chars() instead.
 * 
 * Return value:  %G_IO_ERROR_NONE if the operation was successful.
 **/
203
GIOError 
204
205
206
207
g_io_channel_write (GIOChannel  *channel, 
		    const gchar *buf, 
		    gsize        count,
		    gsize       *bytes_written)
208
{
209
210
211
212
  GError *err = NULL;
  GIOError error;
  GIOStatus status;

213
  g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
214
215
216
217
218
  g_return_val_if_fail (bytes_written != NULL, G_IO_ERROR_UNKNOWN);

  status = channel->funcs->io_write (channel, buf, count, bytes_written, &err);

  error = g_io_error_get_from_g_error (status, err);
219

220
221
222
223
  if (err)
    g_error_free (err);

  return error;
224
225
}

226
227
228
229
230
231
232
233
234
235
236
237
238
239
/**
 * g_io_channel_seek:
 * @channel: a #GIOChannel. 
 * @offset: an offset, in bytes, which is added to the position specified by @type
 * @type: the position in the file, which can be %G_SEEK_CUR (the current
 *        position), %G_SEEK_SET (the start of the file), or %G_SEEK_END (the end of the
 *        file).
 * 
 * Sets the current position in the #GIOChannel, similar to the standard library
 * function fseek(). This function is depricated. New code should
 * use g_io_channel_seek_position() instead.
 * 
 * Return value: %G_IO_ERROR_NONE if the operation was successful.
 **/
240
241
GIOError 
g_io_channel_seek  (GIOChannel   *channel,
242
243
		    glong         offset, 
		    GSeekType     type)
244
{
245
246
247
248
  GError *err = NULL;
  GIOError error;
  GIOStatus status;

249
  g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
250
  g_return_val_if_fail (channel->is_seekable, G_IO_ERROR_UNKNOWN);
251

252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
  switch (type)
    {
      case G_SEEK_CUR:
      case G_SEEK_SET:
      case G_SEEK_END:
        break;
      default:
        g_warning ("g_io_channel_seek: unknown seek type");
        return G_IO_ERROR_UNKNOWN;
    }

  status = channel->funcs->io_seek (channel, offset, type, &err);

  error = g_io_error_get_from_g_error (status, err);

  if (err)
    g_error_free (err);

  return error;
271
}
272
273
274
275
276
277
278
279

/* The function g_io_channel_new_file() is prototyped in both
 * giounix.c and giowin32.c, so we stick its documentation here.
 */

/**
 * g_io_channel_new_file:
 * @filename: A string containing the name of a file.
280
281
282
 * @mode: One of "r", "w", "a", "r+", "w+", "a+". These have
 *        the same meaning as in fopen().
 * @error: A location to return an error of type %G_IO_FILE_ERROR.
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
 *
 * Open a file @filename as a #GIOChannel using mode @mode. This
 * channel will be closed when the last reference to it is dropped,
 * so there is no need to call g_io_channel_close() (though doing
 * so will not cause problems, as long as no attempt is made to
 * access the channel after it is closed).
 *
 * Return value: A #GIOChannel on success, %NULL on failure.
 **/

/**
 * g_io_channel_close:
 * @channel: A #GIOChannel
 * 
 * Close an IO channel. Any pending data to be written will be
 * flushed, ignoring errors. The channel will not be freed until the
 * last reference is dropped using g_io_channel_unref(). This
 * function is deprecated: you should use g_io_channel_shutdown()
 * instead.
 **/
303
304
305
void
g_io_channel_close (GIOChannel *channel)
{
306
307
  GError *err = NULL;
  
308
309
  g_return_if_fail (channel != NULL);

310
311
312
313
314
315
316
317
318
319
320
  g_io_channel_purge (channel);

  channel->funcs->io_close (channel, &err);

  if (err)
    { /* No way to return the error */
      g_warning ("Error closing channel: %s", err->message);
      g_error_free (err);
    }
  
  channel->close_on_unref = FALSE; /* Because we already did */
321
322
323
  channel->is_readable = FALSE;
  channel->is_writeable = FALSE;
  channel->is_seekable = FALSE;
324
325
326
327
328
329
330
331
332
}

/**
 * g_io_channel_shutdown:
 * @channel: a #GIOChannel
 * @flush: if %TRUE, flush pending
 * @err: location to store a #GIOChannelError
 * 
 * Close an IO channel. Any pending data to be written will be
333
 * flushed if @flush is %TRUE. The channel will not be freed until the
334
 * last reference is dropped using g_io_channel_unref().
335
 *
336
 * Return value: the status of the operation.
337
338
339
340
 **/
GIOStatus
g_io_channel_shutdown (GIOChannel *channel,
		       gboolean    flush,
341
		       GError    **err)
342
{
343
344
  GIOStatus status, result;
  GError *tmperr = NULL;
345
346
  
  g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
347
  g_return_val_if_fail (err == NULL || *err == NULL, G_IO_STATUS_ERROR);
348

349
  if (flush && channel->write_buf && channel->write_buf->len > 0)
350
351
352
353
354
355
    {
      GIOFlags flags;
      
      /* Set the channel to blocking, to avoid a busy loop
       */
      flags = g_io_channel_get_flags (channel);
356
357
358
359
360
361
362
363
364
365
      /* Ignore any errors here, they're irrelevant */
      g_io_channel_set_flags (channel, flags & ~G_IO_FLAG_NONBLOCK, NULL);

      result = g_io_channel_flush (channel, &tmperr);

      if (channel->partial_write_buf[0] != '\0')
        {
          g_warning ("Partial character at end of write buffer not flushed.\n");
          channel->partial_write_buf[0] = '\0';
        }
366
    }
367
368
  else
    result = G_IO_STATUS_NORMAL;
369

370
  status = channel->funcs->io_close (channel, err);
371
372

  channel->close_on_unref = FALSE; /* Because we already did */
373
374
375
  channel->is_readable = FALSE;
  channel->is_writeable = FALSE;
  channel->is_seekable = FALSE;
376

377
378
379
380
381
382
383
384
385
386
387
388
  if (status != G_IO_STATUS_NORMAL)
    {
      g_clear_error (&tmperr);
      return status;
    }
  else if (result != G_IO_STATUS_NORMAL)
    {
      g_propagate_error (err, tmperr);
      return result;
    }
  else
    return G_IO_STATUS_NORMAL;
389
390
391
392
393
394
395
}

/* This function is used for the final flush on close or unref */
static void
g_io_channel_purge (GIOChannel *channel)
{
  GError *err = NULL;
396
  GIOStatus status;
397
398
399

  g_return_if_fail (channel != NULL);

400
  if (channel->write_buf && channel->write_buf->len > 0)
401
402
403
404
405
406
407
408
    {
      GIOFlags flags;
      
      /* Set the channel to blocking, to avoid a busy loop
       */
      flags = g_io_channel_get_flags (channel);
      g_io_channel_set_flags (channel, flags & ~G_IO_FLAG_NONBLOCK, NULL);

409
      status = g_io_channel_flush (channel, &err);
410
411
412
413
414
415
416
417
418
419

      if (err)
	{ /* No way to return the error */
	  g_warning ("Error flushing string: %s", err->message);
	  g_error_free (err);
	}
    }

  /* Flush these in case anyone tries to close without unrefing */

420
421
422
423
  if (channel->read_buf)
    g_string_truncate (channel->read_buf, 0);
  if (channel->write_buf)
    g_string_truncate (channel->write_buf, 0);
424
  if (channel->encoding)
425
426
427
428
429
430
431
432
433
434
    {
      if (channel->encoded_read_buf)
        g_string_truncate (channel->encoded_read_buf, 0);

      if (channel->partial_write_buf[0] != '\0')
        {
          g_warning ("Partial character at end of write buffer not flushed.\n");
          channel->partial_write_buf[0] = '\0';
        }
    }
435
436
}

437
438
439
440
441
442
443
444
445
GSource *
g_io_create_watch (GIOChannel  *channel,
		   GIOCondition condition)
{
  g_return_val_if_fail (channel != NULL, NULL);

  return channel->funcs->io_create_watch (channel, condition);
}

446
guint 
447
g_io_add_watch_full (GIOChannel    *channel,
448
449
450
451
452
453
		     gint           priority,
		     GIOCondition   condition,
		     GIOFunc        func,
		     gpointer       user_data,
		     GDestroyNotify notify)
{
454
  GSource *source;
455
  guint id;
456
  
457
458
  g_return_val_if_fail (channel != NULL, 0);

459
460
461
462
463
464
  source = g_io_create_watch (channel, condition);

  if (priority != G_PRIORITY_DEFAULT)
    g_source_set_priority (source, priority);
  g_source_set_callback (source, (GSourceFunc)func, user_data, notify);

465
466
467
468
  id = g_source_attach (source, NULL);
  g_source_unref (source);

  return id;
469
470
471
}

guint 
472
g_io_add_watch (GIOChannel    *channel,
473
474
475
476
		GIOCondition   condition,
		GIOFunc        func,
		gpointer       user_data)
{
477
  return g_io_add_watch_full (channel, G_PRIORITY_DEFAULT, condition, func, user_data, NULL);
478
}
479
480
481
482
483

/**
 * g_io_channel_get_buffer_condition:
 * @channel: A #GIOChannel
 *
484
485
 * This function returns a #GIOCondition depending on whether there
 * is data to be read/space to write data in the
486
 * internal buffers in the #GIOChannel. Only the flags %G_IO_IN and
487
 * %G_IO_OUT may be set.
488
489
490
491
492
493
 *
 * Return value: A #GIOCondition
 **/
GIOCondition
g_io_channel_get_buffer_condition (GIOChannel *channel)
{
494
495
  GIOCondition condition = 0;

496
497
498
499
500
501
502
503
504
505
  if (channel->encoding)
    {
      if (channel->encoded_read_buf && (channel->encoded_read_buf->len > 0))
        condition |= G_IO_IN; /* Only return if we have full characters */
    }
  else
    {
      if (channel->read_buf && (channel->read_buf->len > 0))
        condition |= G_IO_IN;
    }
506
507

  if (channel->write_buf && (channel->write_buf->len < channel->buf_size))
508
    condition |= G_IO_OUT;
509
510

  return condition;
511
512
513
}

/**
514
 * g_io_channel_error_from_errno:
515
 * @en: an <literal>errno</literal> error number, e.g. %EINVAL.
516
 *
517
518
519
 * Converts an <literal>errno</literal> error number to a #GIOChannelError.
 *
 * Return value: a #GIOChannelError error number, e.g. %G_IO_CHANNEL_ERROR_INVAL.
520
521
 **/
GIOChannelError
522
g_io_channel_error_from_errno (gint en)
523
524
525
526
527
528
529
530
531
532
533
534
{
#ifdef EAGAIN
  g_return_val_if_fail (en != EAGAIN, G_IO_CHANNEL_ERROR_FAILED);
#endif
#ifdef EINTR
  g_return_val_if_fail (en != EINTR, G_IO_CHANNEL_ERROR_FAILED);
#endif

  switch (en)
    {
#ifdef EBADF
    case EBADF:
535
536
      g_warning("Invalid file descriptor.\n");
      return G_IO_CHANNEL_ERROR_FAILED;
537
538
539
540
#endif

#ifdef EFAULT
    case EFAULT:
541
542
543
544
545
546
547
      g_warning("File descriptor outside valid address space.\n");
      return G_IO_CHANNEL_ERROR_FAILED;
#endif

#ifdef EFBIG
    case EFBIG:
      return G_IO_CHANNEL_ERROR_FBIG;
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
#endif

#ifdef EINVAL
    case EINVAL:
      return G_IO_CHANNEL_ERROR_INVAL;
#endif

#ifdef EIO
    case EIO:
      return G_IO_CHANNEL_ERROR_IO;
#endif

#ifdef EISDIR
    case EISDIR:
      return G_IO_CHANNEL_ERROR_ISDIR;
#endif

#ifdef ENOSPC
    case ENOSPC:
      return G_IO_CHANNEL_ERROR_NOSPC;
#endif

570
571
572
#ifdef ENXIO
    case ENXIO:
      return G_IO_CHANNEL_ERROR_NXIO;
573
#endif
574
575
576
577
578
579

#ifdef EOVERFLOW
    case EOVERFLOW:
      return G_IO_CHANNEL_ERROR_OVERFLOW;
#endif

580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
#ifdef EPIPE
    case EPIPE:
      return G_IO_CHANNEL_ERROR_PIPE;
#endif

    default:
      return G_IO_CHANNEL_ERROR_FAILED;
    }
}

/**
 * g_io_channel_set_buffer_size:
 * @channel: a #GIOChannel
 * @size: the size of the buffer. 0 == pick a good size
 *
 * Set the buffer size.
 **/  
void
g_io_channel_set_buffer_size (GIOChannel	*channel,
                              gsize		 size)
{
  g_return_if_fail (channel != NULL);

  if (size == 0)
    size = G_IO_NICE_BUF_SIZE;

606
607
  if (size < MAX_CHAR_SIZE)
    size = MAX_CHAR_SIZE;
608

609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
  channel->buf_size = size;
}

/**
 * g_io_channel_get_buffer_size:
 * @channel: a #GIOChannel
 *
 * Get the buffer size.
 *
 * Return value: the size of the buffer.
 **/  
gsize
g_io_channel_get_buffer_size (GIOChannel	*channel)
{
  g_return_val_if_fail (channel != NULL, 0);

  return channel->buf_size;
}

/**
 * g_io_channel_set_line_term:
 * @channel: a #GIOChannel
 * @line_term: The line termination string. Use %NULL for auto detect.
632
 *             Auto detection breaks on "\n", "\r\n", "\r", "\0", and
633
634
 *             the unicode paragraph separator. Auto detection should
 *             not be used for anything other than file-based channels.
635
636
637
 * @length: The length of the termination string. If -1 is passed, the
 *          string is assumed to be null terminated. This option allows
 *          termination strings with embeded nulls.
638
639
640
641
642
643
 *
 * This sets the string that #GIOChannel uses to determine
 * where in the file a line break occurs.
 **/
void
g_io_channel_set_line_term (GIOChannel	*channel,
644
645
                            const gchar	*line_term,
			    gint         length)
646
647
{
  g_return_if_fail (channel != NULL);
648
  g_return_if_fail (line_term == NULL || length != 0); /* Disallow "" */
649

650
651
652
653
654
655
656
657
658
  if (line_term == NULL)
    length = 0;
  else if (length < 0)
    length = strlen (line_term);

  if (channel->line_term)
    g_free (channel->line_term);
  channel->line_term = line_term ? g_memdup (line_term, length) : NULL;
  channel->line_term_len = length;
659
660
661
662
663
}

/**
 * g_io_channel_get_line_term:
 * @channel: a #GIOChannel
664
 * @length: a location to return the length of the line terminator
665
666
667
668
669
670
671
672
673
 *
 * This returns the string that #GIOChannel uses to determine
 * where in the file a line break occurs. A value of %NULL
 * indicates auto detection.
 *
 * Return value: The line termination string. This value
 *   is owned by GLib and must not be freed.
 **/
G_CONST_RETURN gchar*
674
675
g_io_channel_get_line_term (GIOChannel	*channel,
			    gint        *length)
676
677
678
{
  g_return_val_if_fail (channel != NULL, 0);

679
680
681
  if (length)
    *length = channel->line_term_len;

682
683
684
685
686
  return channel->line_term;
}

/**
 * g_io_channel_set_flags:
687
688
689
690
691
 * @channel: a #GIOChannel.
 * @flags: the flags to set on the channel.
 * @error: A location to return an error of type #GIOChannelError.
 *
 * Sets flags on the channel.
692
 *
693
 * Return value: the status of the operation. 
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
 **/
GIOStatus
g_io_channel_set_flags (GIOChannel *channel,
                        GIOFlags    flags,
                        GError    **error)
{
  g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
  g_return_val_if_fail ((error == NULL) || (*error == NULL),
			G_IO_STATUS_ERROR);

  return (* channel->funcs->io_set_flags)(channel,
					  flags & G_IO_FLAG_SET_MASK,
					  error);
}

/**
 * g_io_channel_get_flags:
 * @channel: a #GIOChannel
 *
 * Gets the current flags for a #GIOChannel, including read-only
 * flags such as %G_IO_FLAG_IS_READABLE.
715
 *
716
717
718
719
720
721
722
 * The values of the flags %G_IO_FLAG_IS_READABLE and %G_IO_FLAG_IS_WRITEABLE
 * are cached for internal use by the channel when it is created.
 * If they should change at some later point (e.g. partial shutdown
 * of a socket with the unix shutdown () function), the user
 * should immediately call g_io_channel_get_flags () to update
 * the internal values of these flags.
 *
723
 * Return value: the flags which are set on the channel
724
725
726
727
 **/
GIOFlags
g_io_channel_get_flags (GIOChannel *channel)
{
728
729
  GIOFlags flags;

730
731
  g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);

732
733
734
735
736
737
738
739
740
741
742
743
  flags = (* channel->funcs->io_get_flags) (channel);

  /* Cross implementation code */

  if (channel->is_seekable)
    flags |= G_IO_FLAG_IS_SEEKABLE;
  if (channel->is_readable)
    flags |= G_IO_FLAG_IS_READABLE;
  if (channel->is_writeable)
    flags |= G_IO_FLAG_IS_WRITEABLE;

  return flags;
744
745
}

746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
/**
 * g_io_channel_set_close_on_unref:
 * @channel: a #GIOChannel
 * @do_close: Whether to close the channel on the final unref of
 *            the GIOChannel data structure. The default value of
 *            this is %TRUE for channels created by g_io_channel_new_file (),
 *            and %FALSE for all other channels.
 *
 * Setting this flag to %TRUE for a channel you have already closed
 * can cause problems.
 **/
void
g_io_channel_set_close_on_unref	(GIOChannel *channel,
				 gboolean    do_close)
{
  g_return_if_fail (channel != NULL);

  channel->close_on_unref = do_close;
}

/**
 * g_io_channel_get_close_on_unref:
768
 * @channel: a #GIOChannel.
769
 *
770
771
772
773
774
775
776
 * Returns whether the channel will be closed on the final unref of the 
 * #GIOChannel data structure. The default value of this is %TRUE for 
 * channels created by g_io_channel_new_file(), and %FALSE for all other 
 * channels.
 * 
 * Return value: %TRUE if the channel will be closed on the final unref of
 *               the #GIOChannel data structure. 
777
778
779
780
781
782
783
784
785
 **/
gboolean
g_io_channel_get_close_on_unref	(GIOChannel *channel)
{
  g_return_val_if_fail (channel != NULL, FALSE);

  return channel->close_on_unref;
}

786
787
788
789
/**
 * g_io_channel_seek_position:
 * @channel: a #GIOChannel
 * @offset: The offset in bytes from the position specified by @type
790
791
792
793
 * @type: a #GSeekType. The type %G_SEEK_CUR is only allowed in those
 *                      cases where a call to g_io_channel_set_encoding ()
 *                      is allowed. See the documentation for
 *                      g_io_channel_set_encoding () for details.
794
795
796
797
 * @error: A location to return an error of type #GIOChannelError
 *
 * Replacement for g_io_channel_seek() with the new API.
 *
798
 * Return value: the status of the operation.
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
 **/
GIOStatus
g_io_channel_seek_position	(GIOChannel* channel,
				 glong       offset,
				 GSeekType   type,
				 GError    **error)
{
  GIOStatus status;

  /* For files, only one of the read and write buffers can contain data.
   * For sockets, both can contain data.
   */

  g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
  g_return_val_if_fail ((error == NULL) || (*error == NULL),
			G_IO_STATUS_ERROR);
815
  g_return_val_if_fail (channel->is_seekable, G_IO_STATUS_ERROR);
816
817
818
819

  switch (type)
    {
      case G_SEEK_CUR: /* The user is seeking relative to the head of the buffer */
820
        if (channel->use_buffer)
821
          {
822
823
            if (channel->do_encode && channel->encoded_read_buf
                && channel->encoded_read_buf->len > 0)
824
825
826
827
828
829
830
              {
                g_warning ("Seek type G_SEEK_CUR not allowed for this"
                  " channel's encoding.\n");
                return G_IO_STATUS_ERROR;
              }
          if (channel->read_buf)
            offset -= channel->read_buf->len;
831
832
          if (channel->encoded_read_buf)
            {
833
              g_assert (channel->encoded_read_buf->len == 0 || !channel->do_encode);
834
835
836
837
838
839
840
841

              /* If there's anything here, it's because the encoding is UTF-8,
               * so we can just subtract the buffer length, the same as for
               * the unencoded data.
               */

              offset -= channel->encoded_read_buf->len;
            }
842
          }
843
        break;
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
      case G_SEEK_SET:
      case G_SEEK_END:
        break;
      default:
        g_warning ("g_io_channel_seek_position: unknown seek type");
        return G_IO_STATUS_ERROR;
    }

  if (channel->use_buffer)
    {
      status = g_io_channel_flush (channel, error);
      if (status != G_IO_STATUS_NORMAL)
        return status;
    }

  status = channel->funcs->io_seek (channel, offset, type, error);

  if ((status == G_IO_STATUS_NORMAL) && (channel->use_buffer))
    {
863
864
      if (channel->read_buf)
        g_string_truncate (channel->read_buf, 0);
865
866
867
868
869
870
871
872

      /* Conversion state no longer matches position in file */
      if (channel->read_cd != (GIConv) -1)
        g_iconv (channel->read_cd, NULL, NULL, NULL, NULL);
      if (channel->write_cd != (GIConv) -1)
        g_iconv (channel->write_cd, NULL, NULL, NULL, NULL);

      if (channel->encoded_read_buf)
873
        {
874
875
          g_assert (channel->encoded_read_buf->len == 0 || !channel->do_encode);
          g_string_truncate (channel->encoded_read_buf, 0);
876
        }
877

878
879
880
881
      if (channel->partial_write_buf[0] != '\0')
        {
          g_warning ("Partial character at end of write buffer not flushed.\n");
          channel->partial_write_buf[0] = '\0';
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
        }
    }

  return status;
}

/**
 * g_io_channel_flush:
 * @channel: a #GIOChannel
 * @error: location to store an error of type #GIOChannelError
 *
 * Flush the write buffer for the GIOChannel.
 *
 * Return value: the status of the operation: One of
 *   G_IO_CHANNEL_NORMAL, G_IO_CHANNEL_AGAIN, or
 *   G_IO_CHANNEL_ERROR.
 **/
GIOStatus
g_io_channel_flush (GIOChannel	*channel,
		    GError     **error)
{
  GIOStatus status;
904
  gsize this_time = 1, bytes_written = 0;
905
906
907
908

  g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
  g_return_val_if_fail ((error == NULL) || (*error == NULL), G_IO_STATUS_ERROR);

909
  if (channel->write_buf == NULL || channel->write_buf->len == 0)
910
    return G_IO_STATUS_NORMAL;
911
912
913

  do
    {
914
915
      g_assert (this_time > 0);

916
      status = channel->funcs->io_write (channel,
917
918
919
					 channel->write_buf->str + bytes_written,
					 channel->write_buf->len - bytes_written,
					 &this_time, error);
920
921
922
      bytes_written += this_time;
    }
  while ((bytes_written < channel->write_buf->len)
923
         && (status == G_IO_STATUS_NORMAL));
924
925
926

  g_string_erase (channel->write_buf, 0, bytes_written);

927
928
  return status;
}
929

930
931
932
933
934
935
936
937
/**
 * g_io_channel_set_buffered:
 * @channel: a #GIOChannel
 * @buffered: whether to set the channel buffered or unbuffered
 *
 * The buffering state can only be set if the channel's encoding
 * is %NULL. For any other encoding, the channel must be buffered.
 *
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
 * A buffered channel can only be set unbuffered if the channel's
 * internal buffers have been flushed. Newly created channels or
 * channels which have returned G_IO_STATUS_EOF
 * not require such a flush. For write-only channels, a call to
 * g_io_channel_flush () is sufficient. For all other channels,
 * the buffers may be flushed by a call to g_io_channel_seek_position ().
 * This includes the possibility of seeking with seek type %G_SEEK_CUR
 * and an offset of zero. Note that this means that socket-based
 * channels cannot be set unbuffered once they have had data
 * read from them.
 *
 * On unbuffered channels, it is safe to mix read and write
 * calls from the new and old APIs, if this is necessary for
 * maintaining old code.
 *
953
954
955
956
957
958
959
 * The default state of the channel is buffered.
 **/
void
g_io_channel_set_buffered	(GIOChannel *channel,
				 gboolean    buffered)
{
  g_return_if_fail (channel != NULL);
960

961
962
963
964
965
966
  if (channel->encoding != NULL)
    {
      g_warning ("Need to have NULL encoding to set the buffering state of the "
                 "channel.\n");
      return;
    }
967

968
969
970
971
972
973
974
975
  g_return_if_fail (!channel->read_buf || channel->read_buf->len == 0);
  g_return_if_fail (!channel->write_buf || channel->write_buf->len == 0);

  channel->use_buffer = buffered;
}

/**
 * g_io_channel_get_buffered:
976
977
978
 * @channel: a #GIOChannel.
 *
 * Returns the buffering state of the channel.
979
 *
980
 * Return Value: %TRUE if the @channel is buffered. 
981
982
983
984
985
986
987
 **/
gboolean
g_io_channel_get_buffered	(GIOChannel *channel)
{
  g_return_val_if_fail (channel != NULL, FALSE);

  return channel->use_buffer;
988
989
990
991
992
993
994
995
996
}

/**
 * g_io_channel_set_encoding:
 * @channel: a #GIOChannel
 * @encoding: the encoding type
 * @error: location to store an error of type #GConvertError.
 *
 * Set the encoding for the input/output of the channel. The internal
997
998
 * encoding is always UTF-8. The default encoding for the
 * external file is UTF-8.
999
 *
1000
 * The encoding %NULL is safe to use with binary data.
1001
 *
1002
 * The encoding can only be set under the following conditions:
1003
1004
1005
1006
 *
 * 1. The channel was just created, and has not been written to
 *    or read from yet.
 *
1007
1008
1009
 * 2. The channel is write-only.
 *
 * 3. The channel is a file, and the file pointer was just
1010
1011
1012
 *    repositioned by a call to g_io_channel_seek_position().
 *    (This flushes all the internal buffers.)
 *
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
 * 4. The current encoding is %NULL or UTF-8.
 *
 * 5. One of the (new API) read functions has just returned G_IO_STATUS_EOF
 *    (or, in the case of g_io_channel_read_to_end (), G_IO_STATUS_NORMAL).
 *
 * 6. One of the functions g_io_channel_read_chars () or g_io_channel_read_unichar ()
 *    has returned G_IO_STATUS_AGAIN or G_IO_STATUS_ERROR. This may be
 *    useful in the case of G_CONVERT_ERROR_ILLEGAL_SEQUENCE.
 *    Returning one of these statuses from g_io_channel_read_line (),
 *    g_io_channel_read_line_string (), or g_io_channel_read_to_end ()
 *    does _not_ guarantee that the encoding can be changed.
 *
 * Channels which do not meet the above conditions cannot call
 * g_io_channel_seek_position () with an offset of %G_SEEK_CUR,
 * and if they are "seekable" cannot
 * call g_io_channel_write_chars () after calling one
 * of the API "read" functions.
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
 *
 * Return Value: %G_IO_STATUS_NORMAL if the encoding was succesfully set.
 **/
GIOStatus
g_io_channel_set_encoding (GIOChannel	*channel,
                           const gchar	*encoding,
			   GError      **error)
{
  GIConv read_cd, write_cd;
  gboolean did_encode;

  g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
  g_return_val_if_fail ((error == NULL) || (*error == NULL), G_IO_STATUS_ERROR);

1044
  /* Make sure the encoded buffers are empty */
1045

1046
  g_return_val_if_fail (!channel->do_encode || !channel->encoded_read_buf ||
1047
1048
			channel->encoded_read_buf->len == 0, G_IO_STATUS_ERROR);

1049
  if (!channel->use_buffer)
1050
    {
1051
1052
1053
      g_warning ("Need to set the channel buffered before setting the encoding.\n");
      g_warning ("Assuming this is what you meant and acting accordingly.\n");

1054
1055
      channel->use_buffer = TRUE;
    }
1056

1057
1058
1059
1060
1061
1062
  if (channel->partial_write_buf[0] != '\0')
    {
      g_warning ("Partial character at end of write buffer not flushed.\n");
      channel->partial_write_buf[0] = '\0';
    }

1063
1064
1065
  did_encode = channel->do_encode;

  if (!encoding || strcmp (encoding, "UTF8") == 0 || strcmp (encoding, "UTF-8") == 0)
1066
1067
    {
      channel->do_encode = FALSE;
1068
      read_cd = write_cd = (GIConv) -1;
1069
1070
1071
    }
  else
    {
1072
1073
      gint err = 0;
      const gchar *from_enc = NULL, *to_enc = NULL;
1074

1075
      if (channel->is_readable)
1076
        {
1077
1078
1079
1080
1081
1082
1083
1084
          read_cd = g_iconv_open ("UTF-8", encoding);

          if (read_cd == (GIConv) -1)
            {
              err = errno;
              from_enc = "UTF-8";
              to_enc = encoding;
            }
1085
1086
        }
      else
1087
1088
1089
        read_cd = (GIConv) -1;

      if (channel->is_writeable && err == 0)
1090
1091
        {
          write_cd = g_iconv_open (encoding, "UTF-8");
1092

1093
1094
1095
1096
1097
1098
1099
          if (write_cd == (GIConv) -1)
            {
              err = errno;
              from_enc = encoding;
              to_enc = "UTF-8";
            }
        }
1100
1101
      else
        write_cd = (GIConv) -1;
1102

1103
      if (err != 0)
1104
        {
1105
1106
1107
          g_assert (from_enc);
          g_assert (to_enc);

1108
1109
1110
1111
1112
1113
1114
          if (err == EINVAL)
            g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
                         _("Conversion from character set `%s' to `%s' is not supported"),
                         from_enc, to_enc);
          else
            g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
                         _("Could not open converter from `%s' to `%s': %s"),
1115
                         from_enc, to_enc, strerror (err));
1116
1117
1118
1119
1120
1121

          if (read_cd != (GIConv) -1)
            g_iconv_close (read_cd);
          if (write_cd != (GIConv) -1)
            g_iconv_close (write_cd);

1122
1123
1124
1125
1126
1127
1128
1129
          return G_IO_STATUS_ERROR;
        }

      channel->do_encode = TRUE;
    }

  /* The encoding is ok, so set the fields in channel */

1130
1131
1132
1133
  if (channel->read_cd != (GIConv) -1)
    g_iconv_close (channel->read_cd);
  if (channel->write_cd != (GIConv) -1)
    g_iconv_close (channel->write_cd);
1134

1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
  if (channel->encoded_read_buf && channel->encoded_read_buf->len > 0)
    {
      g_assert (!did_encode); /* Encoding UTF-8, NULL doesn't use encoded_read_buf */

      /* This is just validated UTF-8, so we can copy it back into read_buf
       * so it can be encoded in whatever the new encoding is.
       */

      g_string_prepend_len (channel->read_buf, channel->encoded_read_buf->str,
                            channel->encoded_read_buf->len);
      g_string_truncate (channel->encoded_read_buf, 0);
    }

1148
1149
  channel->read_cd = read_cd;
  channel->write_cd = write_cd;
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161

  g_free (channel->encoding);
  channel->encoding = g_strdup (encoding);

  return G_IO_STATUS_NORMAL;
}

/**
 * g_io_channel_get_encoding:
 * @channel: a #GIOChannel
 *
 * Get the encoding for the input/output of the channel. The internal
1162
1163
 * encoding is always UTF-8. The encoding %NULL makes the
 * channel safe for binary data.
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
 *
 * Return value: A string containing the encoding, this string is
 *   owned by GLib and must not be freed.
 **/
G_CONST_RETURN gchar*
g_io_channel_get_encoding (GIOChannel      *channel)
{
  g_return_val_if_fail (channel != NULL, NULL);

  return channel->encoding;
}

static GIOStatus
g_io_channel_fill_buffer (GIOChannel *channel,
                          GError    **err)
{
  gsize read_size, cur_len, oldlen;
  GIOStatus status;

1183
  if (channel->is_seekable && channel->write_buf && channel->write_buf->len > 0)
1184
    {
1185
1186
1187
1188
1189
1190
1191
1192
      status = g_io_channel_flush (channel, err);
      if (status != G_IO_STATUS_NORMAL)
        return status;
    }
  if (channel->is_seekable && channel->partial_write_buf[0] != '\0')
    {
      g_warning ("Partial character at end of write buffer not flushed.\n");
      channel->partial_write_buf[0] = '\0';
1193
1194
    }

1195
1196
  if (!channel->read_buf)
    channel->read_buf = g_string_sized_new (channel->buf_size);
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214

  cur_len = channel->read_buf->len;

  g_string_set_size (channel->read_buf, channel->read_buf->len + channel->buf_size);

  status = channel->funcs->io_read (channel, channel->read_buf->str + cur_len,
                                    channel->buf_size, &read_size, err);

  g_assert ((status == G_IO_STATUS_NORMAL) || (read_size == 0));

  g_string_truncate (channel->read_buf, read_size + cur_len);

  if ((status != G_IO_STATUS_NORMAL)
    && ((status != G_IO_STATUS_EOF) || (channel->read_buf->len == 0)))
    return status;

  g_assert (channel->read_buf->len > 0);

1215
1216
1217
  if (channel->encoded_read_buf)
    oldlen = channel->encoded_read_buf->len;
  else
1218
1219
    {
      oldlen = 0;
1220
1221
      if (channel->encoding)
        channel->encoded_read_buf = g_string_sized_new (channel->buf_size);
1222
    }
1223

1224
1225
1226
1227
  if (channel->do_encode)
    {
      size_t errnum, inbytes_left, outbytes_left;
      gchar *inbuf, *outbuf;
1228
      int errval;
1229

1230
1231
      g_assert (channel->encoded_read_buf);

1232
1233
1234
reencode:

      inbytes_left = channel->read_buf->len;
1235
      outbytes_left = MAX (channel->read_buf->len,
1236
                           channel->encoded_read_buf->allocated_len
1237
1238
                           - channel->encoded_read_buf->len - 1); /* 1 for NULL */
      outbytes_left = MAX (outbytes_left, 6);
1239
1240

      inbuf = channel->read_buf->str;
1241
1242
      g_string_set_size (channel->encoded_read_buf,
                         channel->encoded_read_buf->len + outbytes_left);
1243
1244
      outbuf = channel->encoded_read_buf->str + channel->encoded_read_buf->len
               - outbytes_left;
1245
1246
1247

      errnum = g_iconv (channel->read_cd, &inbuf, &inbytes_left,
			&outbuf, &outbytes_left);
1248
1249
1250
1251
1252
1253
      errval = errno;

      g_assert (inbuf + inbytes_left == channel->read_buf->str
                + channel->read_buf->len);
      g_assert (outbuf + outbytes_left == channel->encoded_read_buf->str
                + channel->encoded_read_buf->len);
1254
1255
1256
1257
1258
1259
1260
1261

      g_string_erase (channel->read_buf, 0,
		      channel->read_buf->len - inbytes_left);
      g_string_truncate (channel->encoded_read_buf,
			 channel->encoded_read_buf->len - outbytes_left);

      if (errnum == (size_t) -1)
        {
1262
          switch (errval)
1263
1264
1265
1266
            {
              case EINVAL:
                if ((oldlen == channel->encoded_read_buf->len)
                  && (status == G_IO_STATUS_EOF))
1267
                  status = G_IO_STATUS_EOF;
1268
1269
1270
1271
                else
                  status = G_IO_STATUS_NORMAL;
                break;
              case E2BIG:
1272
1273
                /* Buffer size at least 6, wrote at least on character */
                g_assert (inbuf != channel->read_buf->str);
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
                goto reencode;
              case EILSEQ:
                if (oldlen < channel->encoded_read_buf->len)
                  status = G_IO_STATUS_NORMAL;
                else
                  {
                    g_set_error (err, G_CONVERT_ERROR,
                      G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
                      _("Invalid byte sequence in conversion input"));
                    return G_IO_STATUS_ERROR;
                  }
                break;
              default:
1287
                g_assert (errval != EBADF); /* The converter should be open */
1288
                g_set_error (err, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1289
                  _("Error during conversion: %s"), strerror (errval));
1290
1291
1292
                return G_IO_STATUS_ERROR;
            }
        }
1293
1294
1295
1296
1297
1298
1299
      g_assert ((status != G_IO_STATUS_NORMAL)
               || (channel->encoded_read_buf->len > 0));
    }
  else if (channel->encoding) /* UTF-8 */
    {
      gchar *nextchar, *lastchar;

1300
1301
      g_assert (channel->encoded_read_buf);

1302
1303
1304
1305
      nextchar = channel->read_buf->str;
      lastchar = channel->read_buf->str + channel->read_buf->len;

      while (nextchar < lastchar)
1306
        {
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
          gunichar val_char;

          val_char = g_utf8_get_char_validated (nextchar, lastchar - nextchar);

          switch (val_char)
            {
              case -2:
                /* stop, leave partial character in buffer */
                lastchar = nextchar;
                break;
              case -1:
1318
                if (oldlen < channel->encoded_read_buf->len)
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
                  status = G_IO_STATUS_NORMAL;
                else
                  {
                    g_set_error (err, G_CONVERT_ERROR,
                      G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
                      _("Invalid byte sequence in conversion input"));
                    status = G_IO_STATUS_ERROR;
                  }
                lastchar = nextchar;
                break;
              default:
                nextchar = g_utf8_next_char (nextchar);
                break;
            }
        }

      if (lastchar > channel->read_buf->str)
        {
          gint copy_len = lastchar - channel->read_buf->str;

          g_string_append_len (channel->encoded_read_buf, channel->read_buf->str,
                               copy_len);
          g_string_erase (channel->read_buf, 0, copy_len);
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
        }
    }

  return status;
}

/**
 * g_io_channel_read_line:
 * @channel: a #GIOChannel
 * @str_return: The line read from the #GIOChannel, not including the
 *              line terminator. This data should be freed with g_free()
 *              when no longer needed. This
 *              is a null terminated string. If a @length of zero is
 *              returned, this will be %NULL instead.
 * @length: location to store length of the read data, or %NULL
 * @terminator_pos: location to store position of line terminator, or %NULL
 * @error: A location to return an error of type #GConvertError
 *         or #GIOChannelError
 *
1361
 * Read a line, including the terminating character(s),
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
 * from a #GIOChannel into a newly allocated string.
 * @length will contain allocated memory if the return
 * is %G_IO_STATUS_NORMAL.
 *
 * Return value: a newly allocated string. Free this string
 *   with g_free() when you are done with it.
 **/
GIOStatus
g_io_channel_read_line (GIOChannel *channel,
                        gchar     **str_return,
                        gsize      *length,
			gsize      *terminator_pos,
		        GError    **error)
{
  GIOStatus status;
1377
  gsize got_length;
1378
1379
1380
1381
1382
  
  g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
  g_return_val_if_fail (str_return != NULL, G_IO_STATUS_ERROR);
  g_return_val_if_fail ((error == NULL) || (*error == NULL),
			G_IO_STATUS_ERROR);
1383
  g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1384

1385
1386
1387
1388
  status = g_io_channel_read_line_backend (channel, &got_length, terminator_pos, error);

  if (length)
    *length = got_length;
1389

1390
1391
  if (status == G_IO_STATUS_NORMAL)
    {
1392
1393
1394
      g_assert (USE_BUF (channel));
      *str_return = g_strndup (USE_BUF (channel)->str, got_length);
      g_string_erase (USE_BUF (channel), 0, got_length);
1395
    }
1396
  else
1397
    *str_return = NULL;
1398
1399
1400
1401
1402
1403
1404
1405
  
  return status;
}

/**
 * g_io_channel_read_line_string:
 * @channel: a #GIOChannel
 * @buffer: a #GString into which the line will be written.
1406
1407
 *          If @buffer already contains data, the old data will
 *          be overwritten.
1408
1409
1410
1411
1412
1413
 * @terminator_pos: location to store position of line terminator, or %NULL
 * @error: a location to store an error of type #GConvertError
 *         or #GIOChannelError
 *
 * Read a line from a #GIOChannel, using a #GString as a buffer.
 *
1414
 * Return value: the status of the operation.
1415
1416
1417
1418
1419
1420
1421
 **/
GIOStatus
g_io_channel_read_line_string (GIOChannel *channel,
                               GString	  *buffer,
			       gsize      *terminator_pos,
                               GError	 **error)
{
1422
  gsize length;
1423
1424
1425
1426
1427
1428
  GIOStatus status;

  g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
  g_return_val_if_fail (buffer != NULL, G_IO_STATUS_ERROR);
  g_return_val_if_fail ((error == NULL) || (*error == NULL),
			G_IO_STATUS_ERROR);
1429
1430
1431
1432
1433
1434
1435
1436
1437
  g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);

  if (buffer->len > 0)
    g_string_truncate (buffer, 0); /* clear out the buffer */

  status = g_io_channel_read_line_backend (channel, &length, terminator_pos, error);

  if (status == G_IO_STATUS_NORMAL)
    {
1438
1439
1440
      g_assert (USE_BUF (channel));
      g_string_append_len (buffer, USE_BUF (channel)->str, length);
      g_string_erase (USE_BUF (channel), 0, length);
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
    }

  return status;
}


static GIOStatus
g_io_channel_read_line_backend	(GIOChannel *channel,
				 gsize      *length,
				 gsize      *terminator_pos,
				 GError    **error)
{
  GIOStatus status;
  gsize checked_to, line_term_len, line_length, got_term_len;
  gboolean first_time = TRUE;

1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
  if (!channel->use_buffer)
    {
      /* Can't do a raw read in read_line */
      g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
                   _("Can't do a raw read in g_io_channel_read_line_string"));
      return G_IO_STATUS_ERROR;
    }

  status = G_IO_STATUS_NORMAL;

  if (channel->line_term)
1468
    line_term_len = channel->line_term_len;
1469
  else
1470
1471
1472
1473
    line_term_len = 3;
    /* This value used for setting checked_to, it's the longest of the four
     * we autodetect for.
     */