giochannel.c 78.4 KB
Newer Older
1 2 3 4 5 6 7
/* GLIB - Library of useful routines for C programming
 * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
 *
 * giochannel.c: IO Channel abstraction
 * Copyright 1998 Owen Taylor
 *
 * This library is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11 12 13 14
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
19 20
 */

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

28 29 30 31
/* 
 * MT safe
 */

32 33
#include "config.h"

34 35
#include <string.h>
#include <errno.h>
36

37 38
#include "giochannel.h"

39
#include "gstrfuncs.h"
40
#include "gstrfuncsprivate.h"
Matthias Clasen's avatar
Matthias Clasen committed
41
#include "gtestutils.h"
42 43
#include "glibintl.h"

44

45
/**
Johan Dahlin's avatar
Johan Dahlin committed
46
 * SECTION:iochannels
47
 * @title: IO Channels
48 49 50
 * @short_description: portable support for using files, pipes and sockets
 * @see_also: g_io_add_watch(), g_io_add_watch_full(), g_source_remove(),
 *     #GMainLoop
51 52 53
 *
 * The #GIOChannel data type aims to provide a portable method for
 * using file descriptors, pipes, and sockets, and integrating them
Matthias Clasen's avatar
Matthias Clasen committed
54 55 56
 * into the [main event loop][glib-The-Main-Event-Loop]. Currently,
 * full support is available on UNIX platforms, support for Windows
 * is only partially complete.
57 58 59 60 61 62 63 64 65 66 67
 *
 * To create a new #GIOChannel on UNIX systems use
 * g_io_channel_unix_new(). This works for plain file descriptors,
 * pipes and sockets. Alternatively, a channel can be created for a
 * file in a system independent manner using g_io_channel_new_file().
 *
 * Once a #GIOChannel has been created, it can be used in a generic
 * manner with the functions g_io_channel_read_chars(),
 * g_io_channel_write_chars(), g_io_channel_seek_position(), and
 * g_io_channel_shutdown().
 *
Matthias Clasen's avatar
Matthias Clasen committed
68 69
 * To add a #GIOChannel to the [main event loop][glib-The-Main-Event-Loop],
 * use g_io_add_watch() or g_io_add_watch_full(). Here you specify which
70 71 72
 * events you are interested in on the #GIOChannel, and provide a
 * function to be called whenever these events occur.
 *
73 74
 * #GIOChannel instances are created with an initial reference count of 1.
 * g_io_channel_ref() and g_io_channel_unref() can be used to
75 76 77
 * increment or decrement the reference count respectively. When the
 * reference count falls to 0, the #GIOChannel is freed. (Though it
 * isn't closed automatically, unless it was created using
Matthias Clasen's avatar
Matthias Clasen committed
78
 * g_io_channel_new_file().) Using g_io_add_watch() or
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
 * g_io_add_watch_full() increments a channel's reference count.
 *
 * The new functions g_io_channel_read_chars(),
 * g_io_channel_read_line(), g_io_channel_read_line_string(),
 * g_io_channel_read_to_end(), g_io_channel_write_chars(),
 * g_io_channel_seek_position(), and g_io_channel_flush() should not be
 * mixed with the deprecated functions g_io_channel_read(),
 * g_io_channel_write(), and g_io_channel_seek() on the same channel.
 **/

/**
 * GIOChannel:
 *
 * A data structure representing an IO Channel. The fields should be
 * considered private and should only be accessed with the following
 * functions.
 **/

/**
 * GIOFuncs:
 * @io_read: reads raw bytes from the channel.  This is called from
 *           various functions such as g_io_channel_read_chars() to
 *           read raw bytes from the channel.  Encoding and buffering
 *           issues are dealt with at a higher level.
 * @io_write: writes raw bytes to the channel.  This is called from
 *            various functions such as g_io_channel_write_chars() to
 *            write raw bytes to the channel.  Encoding and buffering
 *            issues are dealt with at a higher level.
Phillip Wood's avatar
Phillip Wood committed
107
 * @io_seek: (optional) seeks the channel.  This is called from
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
 *           g_io_channel_seek() on channels that support it.
 * @io_close: closes the channel.  This is called from
 *            g_io_channel_close() after flushing the buffers.
 * @io_create_watch: creates a watch on the channel.  This call
 *                   corresponds directly to g_io_create_watch().
 * @io_free: called from g_io_channel_unref() when the channel needs to
 *           be freed.  This function must free the memory associated
 *           with the channel, including freeing the #GIOChannel
 *           structure itself.  The channel buffers have been flushed
 *           and possibly @io_close has been called by the time this
 *           function is called.
 * @io_set_flags: sets the #GIOFlags on the channel.  This is called
 *                from g_io_channel_set_flags() with all flags except
 *                for %G_IO_FLAG_APPEND and %G_IO_FLAG_NONBLOCK masked
 *                out.
 * @io_get_flags: gets the #GIOFlags for the channel.  This function
 *                need only return the %G_IO_FLAG_APPEND and
 *                %G_IO_FLAG_NONBLOCK flags; g_io_channel_get_flags()
 *                automatically adds the others as appropriate.
 *
 * A table of functions used to handle different types of #GIOChannel
 * in a generic way.
 **/

/**
 * GIOStatus:
 * @G_IO_STATUS_ERROR: An error occurred.
 * @G_IO_STATUS_NORMAL: Success.
 * @G_IO_STATUS_EOF: End of file.
 * @G_IO_STATUS_AGAIN: Resource temporarily unavailable.
 *
139
 * Statuses returned by most of the #GIOFuncs functions.
140 141 142 143 144 145 146 147 148 149 150 151 152
 **/

/**
 * GIOError:
 * @G_IO_ERROR_NONE: no error
 * @G_IO_ERROR_AGAIN: an EAGAIN error occurred
 * @G_IO_ERROR_INVAL: an EINVAL error occurred
 * @G_IO_ERROR_UNKNOWN: another error occurred
 *
 * #GIOError is only used by the deprecated functions
 * g_io_channel_read(), g_io_channel_write(), and g_io_channel_seek().
 **/

153 154
#define G_IO_NICE_BUF_SIZE	1024

155 156 157 158 159 160 161 162 163 164 165
/* This needs to be as wide as the largest character in any possible encoding */
#define MAX_CHAR_SIZE		10

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

166
static GIOError		g_io_error_get_from_g_error	(GIOStatus    status,
167 168 169 170
							 GError      *err);
static void		g_io_channel_purge		(GIOChannel  *channel);
static GIOStatus	g_io_channel_fill_buffer	(GIOChannel  *channel,
							 GError     **err);
171 172 173 174
static GIOStatus	g_io_channel_read_line_backend	(GIOChannel  *channel,
							 gsize       *length,
							 gsize       *terminator_pos,
							 GError     **error);
175

Matthias Clasen's avatar
Matthias Clasen committed
176 177 178 179 180 181 182 183 184 185
/**
 * g_io_channel_init:
 * @channel: a #GIOChannel
 *
 * Initializes a #GIOChannel struct. 
 *
 * This is called by each of the above functions when creating a 
 * #GIOChannel, and so is not often needed by the application 
 * programmer (unless you are creating a new type of #GIOChannel).
 */
186 187
void
g_io_channel_init (GIOChannel *channel)
188
{
189
  channel->ref_count = 1;
190
  channel->encoding = g_strdup ("UTF-8");
191
  channel->line_term = NULL;
192
  channel->line_term_len = 0;
193
  channel->buf_size = G_IO_NICE_BUF_SIZE;
194 195 196 197 198 199
  channel->read_cd = (GIConv) -1;
  channel->write_cd = (GIConv) -1;
  channel->read_buf = NULL; /* Lazy allocate buffers */
  channel->encoded_read_buf = NULL;
  channel->write_buf = NULL;
  channel->partial_write_buf[0] = '\0';
200 201 202
  channel->use_buffer = TRUE;
  channel->do_encode = FALSE;
  channel->close_on_unref = FALSE;
203 204
}

Matthias Clasen's avatar
Matthias Clasen committed
205 206 207 208 209 210 211 212
/**
 * g_io_channel_ref:
 * @channel: a #GIOChannel
 *
 * Increments the reference count of a #GIOChannel.
 *
 * Returns: the @channel that was passed in (since 2.6)
 */
213
GIOChannel *
214 215
g_io_channel_ref (GIOChannel *channel)
{
216
  g_return_val_if_fail (channel != NULL, NULL);
217

218
  g_atomic_int_inc (&channel->ref_count);
219 220

  return channel;
221 222
}

Matthias Clasen's avatar
Matthias Clasen committed
223 224 225 226 227 228
/**
 * g_io_channel_unref:
 * @channel: a #GIOChannel
 *
 * Decrements the reference count of a #GIOChannel.
 */
229 230 231
void 
g_io_channel_unref (GIOChannel *channel)
{
232 233
  gboolean is_zero;

234 235
  g_return_if_fail (channel != NULL);

236 237 238
  is_zero = g_atomic_int_dec_and_test (&channel->ref_count);

  if (G_UNLIKELY (is_zero))
239 240
    {
      if (channel->close_on_unref)
241
        g_io_channel_shutdown (channel, TRUE, NULL);
242 243 244
      else
        g_io_channel_purge (channel);
      g_free (channel->encoding);
245 246 247 248
      if (channel->read_cd != (GIConv) -1)
        g_iconv_close (channel->read_cd);
      if (channel->write_cd != (GIConv) -1)
        g_iconv_close (channel->write_cd);
Matthias Clasen's avatar
Matthias Clasen committed
249
      g_free (channel->line_term);
250 251 252 253 254 255
      if (channel->read_buf)
        g_string_free (channel->read_buf, TRUE);
      if (channel->write_buf)
        g_string_free (channel->write_buf, TRUE);
      if (channel->encoded_read_buf)
        g_string_free (channel->encoded_read_buf, TRUE);
256 257
      channel->funcs->io_free (channel);
    }
258 259
}

260
static GIOError
261 262
g_io_error_get_from_g_error (GIOStatus  status,
			     GError    *err)
263 264 265 266 267 268 269 270 271
{
  switch (status)
    {
      case G_IO_STATUS_NORMAL:
      case G_IO_STATUS_EOF:
        return G_IO_ERROR_NONE;
      case G_IO_STATUS_AGAIN:
        return G_IO_ERROR_AGAIN;
      case G_IO_STATUS_ERROR:
272 273
	g_return_val_if_fail (err != NULL, G_IO_ERROR_UNKNOWN);
	
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
        if (err->domain != G_IO_CHANNEL_ERROR)
          return G_IO_ERROR_UNKNOWN;
        switch (err->code)
          {
            case G_IO_CHANNEL_ERROR_INVAL:
              return G_IO_ERROR_INVAL;
            default:
              return G_IO_ERROR_UNKNOWN;
          }
      default:
        g_assert_not_reached ();
    }
}

/**
 * g_io_channel_read:
290 291 292 293 294
 * @channel: a #GIOChannel
 * @buf: a buffer to read the data into (which should be at least 
 *       count bytes long)
 * @count: the number of bytes to read from the #GIOChannel
 * @bytes_read: returns the number of bytes actually read
295
 * 
296
 * Reads data from a #GIOChannel. 
297
 * 
298
 * Returns: %G_IO_ERROR_NONE if the operation was successful. 
299
 *
300
 * Deprecated:2.2: Use g_io_channel_read_chars() instead.
301
 **/
302 303 304
GIOError 
g_io_channel_read (GIOChannel *channel, 
		   gchar      *buf, 
305 306
		   gsize       count,
		   gsize      *bytes_read)
307
{
308 309 310 311
  GError *err = NULL;
  GIOError error;
  GIOStatus status;

312
  g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
313 314
  g_return_val_if_fail (bytes_read != NULL, G_IO_ERROR_UNKNOWN);

315 316 317 318
  if (count == 0)
    {
      if (bytes_read)
        *bytes_read = 0;
319
      return G_IO_ERROR_NONE;
320 321 322 323
    }

  g_return_val_if_fail (buf != NULL, G_IO_ERROR_UNKNOWN);

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

326 327 328 329 330 331
  error = g_io_error_get_from_g_error (status, err);

  if (err)
    g_error_free (err);

  return error;
332 333
}

334 335
/**
 * g_io_channel_write:
336 337 338 339
 * @channel:  a #GIOChannel
 * @buf: the buffer containing the data to write
 * @count: the number of bytes to write
 * @bytes_written: the number of bytes actually written
340
 * 
341
 * Writes data to a #GIOChannel. 
342
 * 
343
 * Returns:  %G_IO_ERROR_NONE if the operation was successful.
344
 *
345
 * Deprecated:2.2: Use g_io_channel_write_chars() instead.
346
 **/
347
GIOError 
348 349 350 351
g_io_channel_write (GIOChannel  *channel, 
		    const gchar *buf, 
		    gsize        count,
		    gsize       *bytes_written)
352
{
353 354 355 356
  GError *err = NULL;
  GIOError error;
  GIOStatus status;

357
  g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
358 359 360 361 362
  g_return_val_if_fail (bytes_written != NULL, G_IO_ERROR_UNKNOWN);

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

  error = g_io_error_get_from_g_error (status, err);
363

364 365 366 367
  if (err)
    g_error_free (err);

  return error;
368 369
}

370 371
/**
 * g_io_channel_seek:
372 373 374
 * @channel: a #GIOChannel
 * @offset: an offset, in bytes, which is added to the position specified 
 *          by @type
375
 * @type: the position in the file, which can be %G_SEEK_CUR (the current
376 377
 *        position), %G_SEEK_SET (the start of the file), or %G_SEEK_END 
 *        (the end of the file)
378
 * 
379 380
 * Sets the current position in the #GIOChannel, similar to the standard 
 * library function fseek(). 
381
 * 
382
 * Returns: %G_IO_ERROR_NONE if the operation was successful.
383
 *
384
 * Deprecated:2.2: Use g_io_channel_seek_position() instead.
385
 **/
386
GIOError 
387 388 389
g_io_channel_seek (GIOChannel *channel,
		   gint64      offset, 
		   GSeekType   type)
390
{
391 392 393 394
  GError *err = NULL;
  GIOError error;
  GIOStatus status;

395
  g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
396
  g_return_val_if_fail (channel->is_seekable, G_IO_ERROR_UNKNOWN);
397

398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
  switch (type)
    {
      case G_SEEK_CUR:
      case G_SEEK_SET:
      case G_SEEK_END:
        break;
      default:
        g_warning ("g_io_channel_seek: unknown seek type");
        return G_IO_ERROR_UNKNOWN;
    }

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

  error = g_io_error_get_from_g_error (status, err);

  if (err)
    g_error_free (err);

  return error;
417
}
418 419 420 421 422 423 424

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

/**
 * g_io_channel_new_file:
425
 * @filename: (type filename): A string containing the name of a file
426
 * @mode: One of "r", "w", "a", "r+", "w+", "a+". These have
427 428
 *        the same meaning as in fopen()
 * @error: A location to return an error of type %G_FILE_ERROR
429 430 431 432 433 434 435
 *
 * Open a file @filename as a #GIOChannel using mode @mode. This
 * channel will be closed when the last reference to it is dropped,
 * so there is no need to call g_io_channel_close() (though doing
 * so will not cause problems, as long as no attempt is made to
 * access the channel after it is closed).
 *
436
 * Returns: A #GIOChannel on success, %NULL on failure.
437 438 439 440 441 442 443 444
 **/

/**
 * g_io_channel_close:
 * @channel: A #GIOChannel
 * 
 * Close an IO channel. Any pending data to be written will be
 * flushed, ignoring errors. The channel will not be freed until the
445 446
 * last reference is dropped using g_io_channel_unref(). 
 *
447
 * Deprecated:2.2: Use g_io_channel_shutdown() instead.
448
 **/
449 450 451
void
g_io_channel_close (GIOChannel *channel)
{
452 453
  GError *err = NULL;
  
454 455
  g_return_if_fail (channel != NULL);

456 457 458 459 460 461 462 463 464 465 466
  g_io_channel_purge (channel);

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

  if (err)
    { /* No way to return the error */
      g_warning ("Error closing channel: %s", err->message);
      g_error_free (err);
    }
  
  channel->close_on_unref = FALSE; /* Because we already did */
467 468 469
  channel->is_readable = FALSE;
  channel->is_writeable = FALSE;
  channel->is_seekable = FALSE;
470 471 472 473 474 475 476 477 478
}

/**
 * g_io_channel_shutdown:
 * @channel: a #GIOChannel
 * @flush: if %TRUE, flush pending
 * @err: location to store a #GIOChannelError
 * 
 * Close an IO channel. Any pending data to be written will be
479
 * flushed if @flush is %TRUE. The channel will not be freed until the
480
 * last reference is dropped using g_io_channel_unref().
481
 *
482
 * Returns: the status of the operation.
483 484
 **/
GIOStatus
485 486 487
g_io_channel_shutdown (GIOChannel  *channel,
		       gboolean     flush,
		       GError     **err)
488
{
489 490
  GIOStatus status, result;
  GError *tmperr = NULL;
491 492
  
  g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
493
  g_return_val_if_fail (err == NULL || *err == NULL, G_IO_STATUS_ERROR);
494

495
  if (channel->write_buf && channel->write_buf->len > 0)
496
    {
497 498 499
      if (flush)
        {
          GIOFlags flags;
500
      
501 502 503 504 505
          /* Set the channel to blocking, to avoid a busy loop
           */
          flags = g_io_channel_get_flags (channel);
          /* Ignore any errors here, they're irrelevant */
          g_io_channel_set_flags (channel, flags & ~G_IO_FLAG_NONBLOCK, NULL);
506

507
          result = g_io_channel_flush (channel, &tmperr);
508
        }
509 510 511 512
      else
        result = G_IO_STATUS_NORMAL;

      g_string_truncate(channel->write_buf, 0);
513
    }
514 515
  else
    result = G_IO_STATUS_NORMAL;
516

517 518 519
  if (channel->partial_write_buf[0] != '\0')
    {
      if (flush)
520
        g_warning ("Partial character at end of write buffer not flushed.");
521 522 523
      channel->partial_write_buf[0] = '\0';
    }

524
  status = channel->funcs->io_close (channel, err);
525 526

  channel->close_on_unref = FALSE; /* Because we already did */
527 528 529
  channel->is_readable = FALSE;
  channel->is_writeable = FALSE;
  channel->is_seekable = FALSE;
530

531 532 533 534 535 536 537 538 539 540 541 542
  if (status != G_IO_STATUS_NORMAL)
    {
      g_clear_error (&tmperr);
      return status;
    }
  else if (result != G_IO_STATUS_NORMAL)
    {
      g_propagate_error (err, tmperr);
      return result;
    }
  else
    return G_IO_STATUS_NORMAL;
543 544 545 546 547 548 549
}

/* This function is used for the final flush on close or unref */
static void
g_io_channel_purge (GIOChannel *channel)
{
  GError *err = NULL;
Matthias Clasen's avatar
Matthias Clasen committed
550
  GIOStatus status G_GNUC_UNUSED;
551 552 553

  g_return_if_fail (channel != NULL);

554
  if (channel->write_buf && channel->write_buf->len > 0)
555 556
    {
      GIOFlags flags;
Matthias Clasen's avatar
Matthias Clasen committed
557

558 559 560 561 562
      /* Set the channel to blocking, to avoid a busy loop
       */
      flags = g_io_channel_get_flags (channel);
      g_io_channel_set_flags (channel, flags & ~G_IO_FLAG_NONBLOCK, NULL);

563
      status = g_io_channel_flush (channel, &err);
564 565

      if (err)
Matthias Clasen's avatar
Matthias Clasen committed
566 567 568 569
        { /* No way to return the error */
          g_warning ("Error flushing string: %s", err->message);
          g_error_free (err);
        }
570 571 572 573
    }

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

574 575 576 577
  if (channel->read_buf)
    g_string_truncate (channel->read_buf, 0);
  if (channel->write_buf)
    g_string_truncate (channel->write_buf, 0);
578
  if (channel->encoding)
579 580 581 582 583 584
    {
      if (channel->encoded_read_buf)
        g_string_truncate (channel->encoded_read_buf, 0);

      if (channel->partial_write_buf[0] != '\0')
        {
585
          g_warning ("Partial character at end of write buffer not flushed.");
586 587 588
          channel->partial_write_buf[0] = '\0';
        }
    }
589 590
}

Matthias Clasen's avatar
Matthias Clasen committed
591 592 593 594 595 596 597 598 599
/**
 * g_io_create_watch:
 * @channel: a #GIOChannel to watch
 * @condition: conditions to watch for
 *
 * Creates a #GSource that's dispatched when @condition is met for the 
 * given @channel. For example, if condition is #G_IO_IN, the source will 
 * be dispatched when there's data available for reading.
 *
600 601 602
 * The callback function invoked by the #GSource should be added with
 * g_source_set_callback(), but it has type #GIOFunc (not #GSourceFunc).
 *
Matthias Clasen's avatar
Matthias Clasen committed
603 604 605 606 607 608 609 610 611 612
 * g_io_add_watch() is a simpler interface to this same functionality, for 
 * the case where you want to add the source to the default main loop context 
 * at the default priority.
 *
 * On Windows, polling a #GSource created to watch a channel for a socket
 * puts the socket in non-blocking mode. This is a side-effect of the
 * implementation and unavoidable.
 *
 * Returns: a new #GSource
 */
613
GSource *
614 615
g_io_create_watch (GIOChannel   *channel,
		   GIOCondition  condition)
616 617 618 619 620 621
{
  g_return_val_if_fail (channel != NULL, NULL);

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

Matthias Clasen's avatar
Matthias Clasen committed
622
/**
623
 * g_io_add_watch_full: (rename-to g_io_add_watch)
Matthias Clasen's avatar
Matthias Clasen committed
624 625 626 627 628 629 630 631 632 633 634 635
 * @channel: a #GIOChannel
 * @priority: the priority of the #GIOChannel source
 * @condition: the condition to watch for
 * @func: the function to call when the condition is satisfied
 * @user_data: user data to pass to @func
 * @notify: the function to call when the source is removed
 *
 * Adds the #GIOChannel into the default main loop context
 * with the given priority.
 *
 * This internally creates a main loop source using g_io_create_watch()
 * and attaches it to the main loop context with g_source_attach().
Behdad Esfahbod's avatar
Behdad Esfahbod committed
636
 * You can do these steps manually if you need greater control.
Matthias Clasen's avatar
Matthias Clasen committed
637 638 639
 *
 * Returns: the event source id
 */
640
guint 
641
g_io_add_watch_full (GIOChannel    *channel,
642 643 644 645 646 647
		     gint           priority,
		     GIOCondition   condition,
		     GIOFunc        func,
		     gpointer       user_data,
		     GDestroyNotify notify)
{
648
  GSource *source;
649
  guint id;
650
  
651 652
  g_return_val_if_fail (channel != NULL, 0);

653 654 655 656 657 658
  source = g_io_create_watch (channel, condition);

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

659 660 661 662
  id = g_source_attach (source, NULL);
  g_source_unref (source);

  return id;
663 664
}

Matthias Clasen's avatar
Matthias Clasen committed
665 666 667 668 669 670 671 672 673 674 675 676
/**
 * g_io_add_watch:
 * @channel: a #GIOChannel
 * @condition: the condition to watch for
 * @func: the function to call when the condition is satisfied
 * @user_data: user data to pass to @func
 *
 * Adds the #GIOChannel into the default main loop context
 * with the default priority.
 *
 * Returns: the event source id
 */
677 678 679 680 681 682 683 684 685
/**
 * GIOFunc:
 * @source: the #GIOChannel event source
 * @condition: the condition which has been satisfied
 * @data: user data set in g_io_add_watch() or g_io_add_watch_full()
 *
 * Specifies the type of function passed to g_io_add_watch() or
 * g_io_add_watch_full(), which is called when the requested condition
 * on a #GIOChannel is satisfied.
686 687 688
 *
 * Returns: the function should return %FALSE if the event source
 *          should be removed
689 690 691 692 693 694 695 696 697 698 699 700 701 702
 **/
/**
 * GIOCondition:
 * @G_IO_IN: There is data to read.
 * @G_IO_OUT: Data can be written (without blocking).
 * @G_IO_PRI: There is urgent data to read.
 * @G_IO_ERR: Error condition.
 * @G_IO_HUP: Hung up (the connection has been broken, usually for
 *            pipes and sockets).
 * @G_IO_NVAL: Invalid request. The file descriptor is not open.
 *
 * A bitwise combination representing a condition to watch for on an
 * event source.
 **/
703
guint 
704 705 706 707
g_io_add_watch (GIOChannel   *channel,
		GIOCondition  condition,
		GIOFunc       func,
		gpointer      user_data)
708
{
709
  return g_io_add_watch_full (channel, G_PRIORITY_DEFAULT, condition, func, user_data, NULL);
710
}
711 712 713 714 715

/**
 * g_io_channel_get_buffer_condition:
 * @channel: A #GIOChannel
 *
716
 * This function returns a #GIOCondition depending on whether there
717 718
 * is data to be read/space to write data in the internal buffers in 
 * the #GIOChannel. Only the flags %G_IO_IN and %G_IO_OUT may be set.
719
 *
720
 * Returns: A #GIOCondition
721 722 723 724
 **/
GIOCondition
g_io_channel_get_buffer_condition (GIOChannel *channel)
{
725 726
  GIOCondition condition = 0;

727 728 729 730 731 732 733 734 735 736
  if (channel->encoding)
    {
      if (channel->encoded_read_buf && (channel->encoded_read_buf->len > 0))
        condition |= G_IO_IN; /* Only return if we have full characters */
    }
  else
    {
      if (channel->read_buf && (channel->read_buf->len > 0))
        condition |= G_IO_IN;
    }
737 738

  if (channel->write_buf && (channel->write_buf->len < channel->buf_size))
739
    condition |= G_IO_OUT;
740 741

  return condition;
742 743 744
}

/**
745
 * g_io_channel_error_from_errno:
Matthias Clasen's avatar
Matthias Clasen committed
746
 * @en: an `errno` error number, e.g. `EINVAL`
747
 *
Matthias Clasen's avatar
Matthias Clasen committed
748
 * Converts an `errno` error number to a #GIOChannelError.
749
 *
750
 * Returns: a #GIOChannelError error number, e.g. 
751
 *      %G_IO_CHANNEL_ERROR_INVAL.
752 753
 **/
GIOChannelError
754
g_io_channel_error_from_errno (gint en)
755 756 757 758 759 760 761 762 763
{
#ifdef EAGAIN
  g_return_val_if_fail (en != EAGAIN, G_IO_CHANNEL_ERROR_FAILED);
#endif

  switch (en)
    {
#ifdef EBADF
    case EBADF:
764
      g_warning ("Invalid file descriptor.");
765
      return G_IO_CHANNEL_ERROR_FAILED;
766 767 768 769
#endif

#ifdef EFAULT
    case EFAULT:
770
      g_warning ("Buffer outside valid address space.");
771 772 773 774 775 776
      return G_IO_CHANNEL_ERROR_FAILED;
#endif

#ifdef EFBIG
    case EFBIG:
      return G_IO_CHANNEL_ERROR_FBIG;
777 778
#endif

779 780 781 782 783 784 785 786 787 788 789 790
#ifdef EINTR
    /* In general, we should catch EINTR before we get here,
     * but close() is allowed to return EINTR by POSIX, so
     * we need to catch it here; EINTR from close() is
     * unrecoverable, because it's undefined whether
     * the fd was actually closed or not, so we just return
     * a generic error code.
     */
    case EINTR:
      return G_IO_CHANNEL_ERROR_FAILED;
#endif

791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
#ifdef EINVAL
    case EINVAL:
      return G_IO_CHANNEL_ERROR_INVAL;
#endif

#ifdef EIO
    case EIO:
      return G_IO_CHANNEL_ERROR_IO;
#endif

#ifdef EISDIR
    case EISDIR:
      return G_IO_CHANNEL_ERROR_ISDIR;
#endif

#ifdef ENOSPC
    case ENOSPC:
      return G_IO_CHANNEL_ERROR_NOSPC;
#endif

811 812 813
#ifdef ENXIO
    case ENXIO:
      return G_IO_CHANNEL_ERROR_NXIO;
814
#endif
815 816

#ifdef EOVERFLOW
817
#if EOVERFLOW != EFBIG
818 819 820
    case EOVERFLOW:
      return G_IO_CHANNEL_ERROR_OVERFLOW;
#endif
821
#endif
822

823 824 825 826 827 828 829 830 831 832 833 834 835
#ifdef EPIPE
    case EPIPE:
      return G_IO_CHANNEL_ERROR_PIPE;
#endif

    default:
      return G_IO_CHANNEL_ERROR_FAILED;
    }
}

/**
 * g_io_channel_set_buffer_size:
 * @channel: a #GIOChannel
836
 * @size: the size of the buffer, or 0 to let GLib pick a good size
837
 *
Matthias Clasen's avatar
Matthias Clasen committed
838
 * Sets the buffer size.
839 840
 **/  
void
841 842
g_io_channel_set_buffer_size (GIOChannel *channel,
                              gsize       size)
843 844 845 846 847 848
{
  g_return_if_fail (channel != NULL);

  if (size == 0)
    size = G_IO_NICE_BUF_SIZE;

849 850
  if (size < MAX_CHAR_SIZE)
    size = MAX_CHAR_SIZE;
851

852 853 854 855 856 857 858
  channel->buf_size = size;
}

/**
 * g_io_channel_get_buffer_size:
 * @channel: a #GIOChannel
 *
Matthias Clasen's avatar
Matthias Clasen committed
859
 * Gets the buffer size.
860
 *
861
 * Returns: the size of the buffer.
862 863
 **/  
gsize
864
g_io_channel_get_buffer_size (GIOChannel *channel)
865 866 867 868 869 870 871 872 873
{
  g_return_val_if_fail (channel != NULL, 0);

  return channel->buf_size;
}

/**
 * g_io_channel_set_line_term:
 * @channel: a #GIOChannel
874
 * @line_term: (nullable): The line termination string. Use %NULL for
875 876 877
 *             autodetect.  Autodetection breaks on "\n", "\r\n", "\r", "\0",
 *             and the Unicode paragraph separator. Autodetection should not be
 *             used for anything other than file-based channels.
878
 * @length: The length of the termination string. If -1 is passed, the
Matthias Clasen's avatar
Matthias Clasen committed
879
 *          string is assumed to be nul-terminated. This option allows
880
 *          termination strings with embedded nuls.
881 882 883 884 885 886
 *
 * This sets the string that #GIOChannel uses to determine
 * where in the file a line break occurs.
 **/
void
g_io_channel_set_line_term (GIOChannel	*channel,
887 888
                            const gchar	*line_term,
			    gint         length)
889 890
{
  g_return_if_fail (channel != NULL);
891
  g_return_if_fail (line_term == NULL || length != 0); /* Disallow "" */
892

893 894 895 896 897
  if (line_term == NULL)
    length = 0;
  else if (length < 0)
    length = strlen (line_term);

Matthias Clasen's avatar
Matthias Clasen committed
898
  g_free (channel->line_term);
899 900
  channel->line_term = line_term ? g_memdup (line_term, length) : NULL;
  channel->line_term_len = length;
901 902 903 904 905
}

/**
 * g_io_channel_get_line_term:
 * @channel: a #GIOChannel
906
 * @length: a location to return the length of the line terminator
907 908 909
 *
 * This returns the string that #GIOChannel uses to determine
 * where in the file a line break occurs. A value of %NULL
910
 * indicates autodetection.
911
 *
912
 * Returns: The line termination string. This value
913 914
 *   is owned by GLib and must not be freed.
 **/
915
const gchar *
916 917
g_io_channel_get_line_term (GIOChannel *channel,
			    gint       *length)
918
{
919
  g_return_val_if_fail (channel != NULL, NULL);
920

921 922 923
  if (length)
    *length = channel->line_term_len;

924 925 926 927 928
  return channel->line_term;
}

/**
 * g_io_channel_set_flags:
929 930 931
 * @channel: a #GIOChannel
 * @flags: the flags to set on the IO channel
 * @error: A location to return an error of type #GIOChannelError
932
 *
Stef Walter's avatar
Stef Walter committed
933
 * Sets the (writeable) flags in @channel to (@flags & %G_IO_FLAG_SET_MASK).
934
 *
935
 * Returns: the status of the operation. 
936
 **/
937 938
/**
 * GIOFlags:
939 940
 * @G_IO_FLAG_APPEND: turns on append mode, corresponds to %O_APPEND
 *     (see the documentation of the UNIX open() syscall)
941
 * @G_IO_FLAG_NONBLOCK: turns on nonblocking mode, corresponds to
942 943
 *     %O_NONBLOCK/%O_NDELAY (see the documentation of the UNIX open()
 *     syscall)
944
 * @G_IO_FLAG_IS_READABLE: indicates that the io channel is readable.
945
 *     This flag cannot be changed.
946
 * @G_IO_FLAG_IS_WRITABLE: indicates that the io channel is writable.
947
 *     This flag cannot be changed.
948
 * @G_IO_FLAG_IS_WRITEABLE: a misspelled version of @G_IO_FLAG_IS_WRITABLE
949 950
 *     that existed before the spelling was fixed in GLib 2.30. It is kept
 *     here for compatibility reasons. Deprecated since 2.30
951
 * @G_IO_FLAG_IS_SEEKABLE: indicates that the io channel is seekable,
952 953
 *     i.e. that g_io_channel_seek_position() can be used on it.
 *     This flag cannot be changed.
954 955
 * @G_IO_FLAG_MASK: the mask that specifies all the valid flags.
 * @G_IO_FLAG_GET_MASK: the mask of the flags that are returned from
956
 *     g_io_channel_get_flags()
957
 * @G_IO_FLAG_SET_MASK: the mask of the flags that the user can modify
958
 *     with g_io_channel_set_flags()
959 960 961 962
 *
 * Specifies properties of a #GIOChannel. Some of the flags can only be
 * read with g_io_channel_get_flags(), but not changed with
 * g_io_channel_set_flags().
963
 */
964
GIOStatus
965 966 967
g_io_channel_set_flags (GIOChannel  *channel,
                        GIOFlags     flags,
                        GError     **error)
968 969 970 971 972
{
  g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
  g_return_val_if_fail ((error == NULL) || (*error == NULL),
			G_IO_STATUS_ERROR);

973
  return (*channel->funcs->io_set_flags) (channel,
974 975 976 977 978 979 980 981 982 983
					  flags & G_IO_FLAG_SET_MASK,
					  error);
}

/**
 * g_io_channel_get_flags:
 * @channel: a #GIOChannel
 *
 * Gets the current flags for a #GIOChannel, including read-only
 * flags such as %G_IO_FLAG_IS_READABLE.
984
 *
985
 * The values of the flags %G_IO_FLAG_IS_READABLE and %G_IO_FLAG_IS_WRITABLE
986 987
 * are cached for internal use by the channel when it is created.
 * If they should change at some later point (e.g. partial shutdown
988
 * of a socket with the UNIX shutdown() function), the user
989
 * should immediately call g_io_channel_get_flags() to update
990 991
 * the internal values of these flags.
 *
992
 * Returns: the flags which are set on the channel
993 994 995 996
 **/
GIOFlags
g_io_channel_get_flags (GIOChannel *channel)
{
997 998
  GIOFlags flags;

999
  g_return_val_if_fail (channel != NULL, 0);
1000

1001 1002 1003 1004 1005 1006 1007 1008 1009
  flags = (* channel->funcs->io_get_flags) (channel);

  /* Cross implementation code */

  if (channel->is_seekable)
    flags |= G_IO_FLAG_IS_SEEKABLE;
  if (channel->is_readable)
    flags |= G_IO_FLAG_IS_READABLE;
  if (channel->is_writeable)
1010
    flags |= G_IO_FLAG_IS_WRITABLE;
1011 1012

  return flags;
1013 1014
}

1015 1016 1017 1018
/**
 * g_io_channel_set_close_on_unref:
 * @channel: a #GIOChannel
 * @do_close: Whether to close the channel on the final unref of
1019 1020 1021 1022 1023
 *            the GIOChannel data structure.
 *
 * Whether to close the channel on the final unref of the #GIOChannel
 * data structure. The default value of this is %TRUE for channels
 * created by g_io_channel_new_file (), and %FALSE for all other channels.