outputstream.c 19.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
/*
 * This file is part of the Nice GLib ICE library.
 *
 * (C) 2010, 2013 Collabora Ltd.
 *  Contact: Youness Alaoui
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is the Nice GLib ICE library.
 *
 * The Initial Developers of the Original Code are Collabora Ltd and Nokia
 * Corporation. All Rights Reserved.
 *
 * Contributors:
 *   Youness Alaoui, Collabora Ltd.
 *   Philip Withnall, Collabora Ltd.
 *
 * Alternatively, the contents of this file may be used under the terms of the
 * the GNU Lesser General Public License Version 2.1 (the "LGPL"), in which
 * case the provisions of LGPL are applicable instead of those above. If you
 * wish to allow use of your version of this file only under the terms of the
 * LGPL and not to allow others to use your version of this file under the
 * MPL, indicate your decision by deleting the provisions above and replace
 * them with the notice and other provisions required by the LGPL. If you do
 * not delete the provisions above, a recipient may use your version of this
 * file under either the MPL or the LGPL.
 */

37
/***
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
 * SECTION:nice_output_stream
 * @short_description: #GOutputStream implementation for libnice
 * @see_also: #NiceAgent
 * @include: outputstream.h
 * @stability: Stable
 *
 * #NiceOutputStream is a #GOutputStream wrapper for a single reliable stream
 * and component of a #NiceAgent. Given an existing reliable #NiceAgent, plus
 * the IDs of an existing stream and component in the agent, it will provide a
 * streaming output interface for writing to the given component.
 *
 * A single #NiceOutputStream can only be used with a single agent, stream and
 * component triple, and will be closed as soon as that stream is removed from
 * the agent (e.g. if nice_agent_remove_stream() is called from another thread).
 * If g_output_stream_close() is called on a #NiceOutputStream, the output
 * stream will be marked as closed, but the underlying #NiceAgent stream will
 * not be removed. Use nice_agent_remove_stream() to do that.
 *
 * The output stream can only be used once the
 * #NiceAgent::reliable-transport-writable signal has been received for the
 * stream/component pair. Any calls to g_output_stream_write() before then will
 * return %G_IO_ERROR_BROKEN_PIPE.
 *
 * Since: 0.1.5
 */

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

68 69
#include <errno.h>

70
#include "outputstream.h"
71
#include "agent-priv.h"
72

73 74
static void nice_output_stream_init_pollable (
    GPollableOutputStreamInterface *iface);
75 76 77
static void streams_removed_cb (NiceAgent *agent, guint *stream_ids,
    gpointer user_data);

78 79 80 81
G_DEFINE_TYPE_WITH_CODE (NiceOutputStream,
                         nice_output_stream, G_TYPE_OUTPUT_STREAM,
                         G_IMPLEMENT_INTERFACE (G_TYPE_POLLABLE_OUTPUT_STREAM,
                                                nice_output_stream_init_pollable));
82 83 84 85 86 87 88 89 90 91 92 93 94

enum
{
  PROP_AGENT = 1,
  PROP_STREAM_ID,
  PROP_COMPONENT_ID,
};

struct _NiceOutputStreamPrivate
{
  GWeakRef/*<NiceAgent>*/ agent_ref;
  guint stream_id;
  guint component_id;
95 96

  GCancellable *closed_cancellable;
97 98 99 100 101 102 103 104 105 106 107
};

static void nice_output_stream_dispose (GObject *object);
static void nice_output_stream_get_property (GObject *object, guint prop_id,
    GValue *value, GParamSpec *pspec);
static void nice_output_stream_set_property (GObject *object, guint prop_id,
    const GValue *value, GParamSpec *pspec);

static gssize nice_output_stream_write (GOutputStream *stream,
    const void *buffer, gsize count, GCancellable *cancellable, GError **error);

108 109 110 111 112 113
static gboolean nice_output_stream_is_writable (GPollableOutputStream *stream);
static gssize nice_output_stream_write_nonblocking (
    GPollableOutputStream *stream, const void *buffer, gsize count,
    GError **error);
static GSource *nice_output_stream_create_source (GPollableOutputStream *stream,
    GCancellable *cancellable);
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129

/* Output Stream */
static void
nice_output_stream_class_init (NiceOutputStreamClass *klass)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
  GOutputStreamClass *stream_class = G_OUTPUT_STREAM_CLASS (klass);

  g_type_class_add_private (klass, sizeof (NiceOutputStreamPrivate));

  stream_class->write_fn = nice_output_stream_write;

  gobject_class->set_property = nice_output_stream_set_property;
  gobject_class->get_property = nice_output_stream_get_property;
  gobject_class->dispose = nice_output_stream_dispose;

130
  /***
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
   * NiceOutputStream:agent:
   *
   * The #NiceAgent to wrap with an output stream. This must be an existing
   * reliable agent.
   *
   * A reference is not held on the #NiceAgent. If the agent is destroyed before
   * the #NiceOutputStream, %G_IO_ERROR_CLOSED will be returned for all
   * subsequent operations on the stream.
   *
   * Since: 0.1.5
   */
  g_object_class_install_property (gobject_class, PROP_AGENT,
      g_param_spec_object ("agent",
          "NiceAgent",
          "The underlying NiceAgent",
          NICE_TYPE_AGENT,
          G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

149
  /***
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
   * NiceOutputStream:stream-id:
   *
   * ID of the stream to use in the #NiceOutputStream:agent.
   *
   * Since: 0.1.5
   */
  g_object_class_install_property (gobject_class, PROP_STREAM_ID,
      g_param_spec_uint (
          "stream-id",
          "Agent’s stream ID",
          "The ID of the agent’s stream to wrap.",
          0, G_MAXUINT,
          0,
          G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

165
  /***
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
   * NiceOutputStream:component-id:
   *
   * ID of the component to use in the #NiceOutputStream:agent.
   *
   * Since: 0.1.5
   */
  g_object_class_install_property (gobject_class, PROP_COMPONENT_ID,
      g_param_spec_uint (
          "component-id",
          "Agent’s component ID",
          "The ID of the agent’s component to wrap.",
          0, G_MAXUINT,
          0,
          G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
}

static void
nice_output_stream_dispose (GObject *object)
{
  NiceOutputStream *self = NICE_OUTPUT_STREAM (object);
  NiceAgent *agent;

  agent = g_weak_ref_get (&self->priv->agent_ref);
  if (agent != NULL) {
    g_signal_handlers_disconnect_by_func (agent, streams_removed_cb, self);
    g_object_unref (agent);
  }

  g_weak_ref_clear (&self->priv->agent_ref);

196 197
  g_clear_object (&self->priv->closed_cancellable);

198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
  G_OBJECT_CLASS (nice_output_stream_parent_class)->dispose (object);
}

static void
nice_output_stream_get_property (GObject *object, guint prop_id,
    GValue *value, GParamSpec *pspec)
{
  NiceOutputStream *self = NICE_OUTPUT_STREAM (object);

  switch (prop_id) {
    case PROP_AGENT:
      g_value_take_object (value, g_weak_ref_get (&self->priv->agent_ref));
      break;
    case PROP_STREAM_ID:
      g_value_set_uint (value, self->priv->stream_id);
      break;
    case PROP_COMPONENT_ID:
      g_value_set_uint (value, self->priv->component_id);
      break;
     default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
    }
}

static void
nice_output_stream_set_property (GObject *object, guint prop_id,
    const GValue *value, GParamSpec *pspec)
{
  NiceOutputStream *self = NICE_OUTPUT_STREAM (object);

  switch (prop_id) {
    case PROP_AGENT: {
      /* Construct only. */
      NiceAgent *agent = g_value_dup_object (value);
      g_weak_ref_set (&self->priv->agent_ref, agent);

      /* agent may be NULL if the stream is being constructed by
       * nice_io_stream_get_output_stream() after the NiceIOStream’s agent has
       * already been finalised. */
      if (agent != NULL) {
        g_signal_connect (agent, "streams-removed",
            (GCallback) streams_removed_cb, self);
        g_object_unref (agent);
      }

      break;
    }
    case PROP_STREAM_ID:
      /* Construct only. */
      self->priv->stream_id = g_value_get_uint (value);
      break;
    case PROP_COMPONENT_ID:
      /* Construct only. */
      self->priv->component_id = g_value_get_uint (value);
      break;
     default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
    }
}

static void
nice_output_stream_init (NiceOutputStream *stream)
{
  stream->priv = G_TYPE_INSTANCE_GET_PRIVATE (stream, NICE_TYPE_OUTPUT_STREAM,
      NiceOutputStreamPrivate);

  g_weak_ref_init (&stream->priv->agent_ref, NULL);
265
  stream->priv->closed_cancellable = g_cancellable_new ();
266 267
}

268 269 270 271 272 273 274 275
static void
nice_output_stream_init_pollable (GPollableOutputStreamInterface *iface)
{
  iface->is_writable = nice_output_stream_is_writable;
  iface->write_nonblocking = nice_output_stream_write_nonblocking;
  iface->create_source = nice_output_stream_create_source;
}

276
/***
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
 * nice_output_stream_new:
 * @agent: A #NiceAgent
 * @stream_id: The ID of the agent’s stream to wrap
 * @component_id: The ID of the agent’s component to wrap
 *
 * Create a new #NiceOutputStream wrapping the given stream/component from
 * @agent, which must be a reliable #NiceAgent.
 *
 * The constructed #NiceOutputStream will not hold a reference to @agent. If
 * @agent is destroyed before the output stream, %G_IO_ERROR_CLOSED will be
 * returned for all subsequent operations on the stream.
 *
 * Returns: The new #NiceOutputStream object
 *
 * Since: 0.1.5
 */
NiceOutputStream *
nice_output_stream_new (NiceAgent *agent, guint stream_id, guint component_id)
{
  g_return_val_if_fail (NICE_IS_AGENT (agent), NULL);
  g_return_val_if_fail (stream_id >= 1, NULL);
  g_return_val_if_fail (component_id >= 1, NULL);

  return g_object_new (NICE_TYPE_OUTPUT_STREAM,
      "agent", agent,
      "stream-id", stream_id,
      "component-id", component_id,
      NULL);
}

typedef struct {
308 309
  volatile gint ref_count;

310 311
  GCond cond;
  GMutex mutex;
312 313

  gboolean writable;
314
  gboolean cancelled;
315 316
} WriteData;

317 318 319 320 321 322 323
static WriteData *
write_data_ref (WriteData *write_data)
{
  g_atomic_int_inc (&write_data->ref_count);
  return write_data;
}

324 325 326 327 328 329 330 331 332 333
static void
write_data_unref (WriteData *write_data)
{
  if (g_atomic_int_dec_and_test (&write_data->ref_count)) {
    g_cond_clear (&write_data->cond);
    g_mutex_clear (&write_data->mutex);
    g_slice_free (WriteData, write_data);
  }
}

334 335 336 337 338 339 340
static void
write_cancelled_cb (GCancellable *cancellable, gpointer user_data)
{
  WriteData *write_data = user_data;

  g_mutex_lock (&write_data->mutex);
  g_cond_broadcast (&write_data->cond);
341
  write_data->cancelled = TRUE;
342 343 344 345 346 347 348 349 350 351
  g_mutex_unlock (&write_data->mutex);
}

static void
reliable_transport_writeable_cb (NiceAgent *agent, guint stream_id,
    guint component_id, gpointer user_data)
{
  WriteData *write_data = user_data;

  g_mutex_lock (&write_data->mutex);
352
  write_data->writable = TRUE;
353 354 355 356 357 358 359 360 361
  g_cond_broadcast (&write_data->cond);
  g_mutex_unlock (&write_data->mutex);
}

static gssize
nice_output_stream_write (GOutputStream *stream, const void *buffer, gsize count,
    GCancellable *cancellable, GError **error)
{
  NiceOutputStream *self = NICE_OUTPUT_STREAM (stream);
Olivier Crête's avatar
Olivier Crête committed
362 363
  const gchar* buf = buffer;
  gssize len = 0;
364
  gint n_sent;
365
  NiceAgent *agent = NULL;  /* owned */
366
  gulong cancel_id = 0, closed_cancel_id, writeable_id;
367
  WriteData *write_data;
368 369 370

  /* Closed streams are not writeable. */
  if (g_output_stream_is_closed (stream)) {
371
    g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
372
        "Stream is closed.");
373
    return -1;
374 375 376 377 378
  }

  /* Has the agent disappeared? */
  agent = g_weak_ref_get (&self->priv->agent_ref);
  if (agent == NULL) {
379
    g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
380
        "Stream is closed due to the NiceAgent being finalised.");
381
    return -1;
382 383
  }

384 385
  if (count == 0) {
    g_object_unref (agent);
386
    return 0;
387
  }
388

389
  /* FIXME: nice_agent_send() is non-blocking, which is a bit unexpected
390 391 392
   * since nice_agent_recv() is blocking. Currently this uses a fairly dodgy
   * GCond solution; would be much better for nice_agent_send() to block
   * properly in the main loop. */
393
  write_data = g_slice_new0 (WriteData);
394
  write_data->ref_count = 1;
395 396
  g_mutex_init (&write_data->mutex);
  g_cond_init (&write_data->cond);
397 398 399

  if (cancellable != NULL) {
    cancel_id = g_cancellable_connect (cancellable,
400
        (GCallback) write_cancelled_cb, write_data_ref (write_data),
401
        (GDestroyNotify) write_data_unref);
402 403
  }

404
  closed_cancel_id = g_cancellable_connect (self->priv->closed_cancellable,
405
      (GCallback) write_cancelled_cb, write_data_ref (write_data),
406 407
      (GDestroyNotify) write_data_unref);

408 409 410
  g_mutex_lock (&write_data->mutex);

  writeable_id = g_signal_connect_data (G_OBJECT (agent),
411
      "reliable-transport-writable",
412
      (GCallback) reliable_transport_writeable_cb, write_data_ref (write_data),
413
      (GClosureNotify) write_data_unref, 0);
414 415 416


  do {
417 418 419 420
    /* Have to unlock while calling into the agent because
     * it will take the agent lock which will cause a deadlock if one of
     * the callbacks is called.
     */
421 422
    if (g_cancellable_is_cancelled (cancellable) ||
        g_cancellable_is_cancelled (self->priv->closed_cancellable))
423 424
      break;

425
    write_data->writable = FALSE;
426 427
    g_mutex_unlock (&write_data->mutex);

428
    n_sent = nice_agent_send (agent, self->priv->stream_id,
Olivier Crête's avatar
Olivier Crête committed
429
        self->priv->component_id, count - len, buf + len);
430

431
    g_mutex_lock (&write_data->mutex);
432

433 434
    if (n_sent <= 0) {
      if (!write_data->writable && !write_data->cancelled)
435
        g_cond_wait (&write_data->cond, &write_data->mutex);
436
    } else if (n_sent > 0) {
437
      /* Success. */
438
      len += n_sent;
439 440 441 442
    }
  } while ((gsize) len < count);

  g_signal_handler_disconnect (G_OBJECT (agent), writeable_id);
443
  g_mutex_unlock (&write_data->mutex);
444

445
  if (cancel_id)
446
    g_cancellable_disconnect (cancellable, cancel_id);
447
  g_cancellable_disconnect (self->priv->closed_cancellable, closed_cancel_id);
448 449 450

  if (len == 0) {
    len = -1;
451 452 453 454 455
    if (!g_cancellable_set_error_if_cancelled (cancellable, error)) {
      if (g_cancellable_is_cancelled (self->priv->closed_cancellable))
        g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
            "Stream has been removed from agent");
    }
456
  }
457

458
  write_data_unref (write_data);
459

460 461 462
  g_object_unref (agent);
  g_assert (len != 0);

463 464 465
  return len;
}

466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
static gboolean
nice_output_stream_is_writable (GPollableOutputStream *stream)
{
  NiceOutputStreamPrivate *priv = NICE_OUTPUT_STREAM (stream)->priv;
  Component *component = NULL;
  Stream *_stream = NULL;
  gboolean retval = FALSE;
  GSList *i;
  NiceAgent *agent;  /* owned */

  /* Closed streams are not writeable. */
  if (g_output_stream_is_closed (G_OUTPUT_STREAM (stream)))
    return FALSE;

  /* Has the agent disappeared? */
  agent = g_weak_ref_get (&priv->agent_ref);
  if (agent == NULL)
    return FALSE;

  agent_lock ();

  if (!agent_find_component (agent, priv->stream_id, priv->component_id,
          &_stream, &component)) {
    g_warning ("Could not find component %u in stream %u", priv->component_id,
        priv->stream_id);
    goto done;
  }

  /* If it’s a reliable agent, see if there’s any space in the pseudo-TCP output
   * buffer. */
496 497
  if (component->tcp != NULL) {
    retval = pseudo_tcp_socket_can_send (component->tcp);
498 499 500
    goto done;
  }

501 502 503 504 505 506 507 508
  /* If it's a non-reliable agent, it never blocks, so one can
   * always write
   */
  if (!agent->reliable) {
    retval = TRUE;
    goto done;
  }

509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
  /* Check whether any of the component’s FDs are pollable. */
  for (i = component->socket_sources; i != NULL; i = i->next) {
    SocketSource *socket_source = i->data;
    NiceSocket *socket = socket_source->socket;

    if (g_socket_condition_check (socket->fileno, G_IO_OUT) != 0) {
      retval = TRUE;
      break;
    }
  }

done:
  agent_unlock ();

  g_object_unref (agent);

  return retval;
}

static gssize
nice_output_stream_write_nonblocking (GPollableOutputStream *stream,
    const void *buffer, gsize count, GError **error)
{
  NiceOutputStreamPrivate *priv = NICE_OUTPUT_STREAM (stream)->priv;
  NiceAgent *agent;  /* owned */
534
  gint n_sent;
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560

  /* Closed streams are not writeable. */
  if (g_output_stream_is_closed (G_OUTPUT_STREAM (stream))) {
    g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
        "Stream is closed.");
    return -1;
  }

  /* Has the agent disappeared? */
  agent = g_weak_ref_get (&priv->agent_ref);
  if (agent == NULL) {
    g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
        "Stream is closed due to the NiceAgent being finalised.");
    return -1;
  }

  if (count == 0)
    return 0;

  /* This is equivalent to the default GPollableOutputStream implementation. */
  if (!g_pollable_output_stream_is_writable (stream)) {
    g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK,
        g_strerror (EAGAIN));
    return -1;
  }

561 562 563 564 565 566 567 568
  n_sent = nice_agent_send (agent, priv->stream_id, priv->component_id,
      count, buffer);

  if (n_sent == -1)
    g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK,
        g_strerror (EAGAIN));


569 570 571

  g_object_unref (agent);

572
  return n_sent;
573 574 575 576 577 578 579 580 581 582 583 584
}

static GSource *
nice_output_stream_create_source (GPollableOutputStream *stream,
    GCancellable *cancellable)
{
  NiceOutputStreamPrivate *priv = NICE_OUTPUT_STREAM (stream)->priv;
  GSource *component_source = NULL;
  Component *component = NULL;
  Stream *_stream = NULL;
  NiceAgent *agent;  /* owned */

585 586 587 588 589 590 591 592 593 594
  component_source = g_pollable_source_new (G_OBJECT (stream));

  if (cancellable) {
    GSource *cancellable_source = g_cancellable_source_new (cancellable);

    g_source_set_dummy_callback (cancellable_source);
    g_source_add_child_source (component_source, cancellable_source);
    g_source_unref (cancellable_source);
  }

595 596
  /* Closed streams cannot have sources. */
  if (g_output_stream_is_closed (G_OUTPUT_STREAM (stream)))
597
    return component_source;
598 599 600 601

  /* Has the agent disappeared? */
  agent = g_weak_ref_get (&priv->agent_ref);
  if (agent == NULL)
602
    return component_source;
603 604 605 606 607 608 609 610 611 612 613

  agent_lock ();

  /* Grab the socket for this component. */
  if (!agent_find_component (agent, priv->stream_id, priv->component_id,
          &_stream, &component)) {
    g_warning ("Could not find component %u in stream %u", priv->component_id,
        priv->stream_id);
    goto done;
  }

614 615 616 617 618 619 620
   if (component->tcp_writable_cancellable) {
    GSource *cancellable_source =
        g_cancellable_source_new (component->tcp_writable_cancellable);

    g_source_set_dummy_callback (cancellable_source);
    g_source_add_child_source (component_source, cancellable_source);
    g_source_unref (cancellable_source);
621 622 623 624 625 626 627 628 629
  } else if (!agent->reliable) {
    /* UDP streams are almost always writeable. */
    GSource *child_source;

    child_source = component_source_new (agent, priv->stream_id,
      priv->component_id, G_OBJECT (stream), G_IO_OUT, cancellable);
    g_source_set_dummy_callback (child_source);
    g_source_add_child_source (component_source, child_source);
    g_source_unref (child_source);
630
  }
631 632 633 634 635 636 637 638 639

done:
  agent_unlock ();

  g_object_unref (agent);

  return component_source;
}

640 641 642 643 644 645 646 647 648
static void
streams_removed_cb (NiceAgent *agent, guint *stream_ids, gpointer user_data)
{
  NiceOutputStream *self = NICE_OUTPUT_STREAM (user_data);
  guint i;

  for (i = 0; stream_ids[i] != 0; i++) {
    if (stream_ids[i] == self->priv->stream_id) {
      /* The socket has been closed. */
649 650
      g_cancellable_cancel (self->priv->closed_cancellable);

651 652 653 654 655
      g_output_stream_close (G_OUTPUT_STREAM (self), NULL, NULL);
      break;
    }
  }
}