Coverage Report

Created: 2025-10-10 07:05

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