agent.c 135 KB
Newer Older
1
2
3
/*
 * This file is part of the Nice GLib ICE library.
 *
4
 * (C) 2006-2010, 2013 Collabora Ltd.
5
6
 *  Contact: Youness Alaoui
 * (C) 2006-2010 Nokia Corporation. All rights reserved.
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 *  Contact: Kai Vehmanen
 *
 * 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:
 *   Dafydd Harries, Collabora Ltd.
26
 *   Youness Alaoui, Collabora Ltd.
27
 *   Kai Vehmanen, Nokia
28
 *   Philip Withnall, Collabora Ltd.
29
30
31
32
33
34
35
36
37
38
39
 *
 * 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.
 */
Dafydd Harries's avatar
Dafydd Harries committed
40

41
42
43

#ifdef HAVE_CONFIG_H
# include <config.h>
44
45
#else
#define NICEAPI_EXPORT
46
47
#endif

48
#include <glib.h>
49
#include <gobject/gvaluecollector.h>
50

Dafydd Harries's avatar
Dafydd Harries committed
51
#include <string.h>
52
#include <errno.h>
Dafydd Harries's avatar
Dafydd Harries committed
53

54
#ifndef G_OS_WIN32
55
56
57
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
58
#endif
Dafydd Harries's avatar
Dafydd Harries committed
59

60
61
#include "debug.h"

62
#include "socket.h"
63
#include "stun/usages/turn.h"
64
#include "candidate.h"
65
#include "component.h"
66
67
#include "conncheck.h"
#include "discovery.h"
68
#include "agent.h"
69
#include "agent-priv.h"
70
#include "agent-signals-marshal.h"
71
#include "iostream.h"
Dafydd Harries's avatar
Dafydd Harries committed
72

73
#include "stream.h"
74
#include "interfaces.h"
Dafydd Harries's avatar
Dafydd Harries committed
75

76
77
#include "pseudotcp.h"

78
79
80
81
/* Maximum size of a UDP packet’s payload, as the packet’s length field is 16b
 * wide. */
#define MAX_BUFFER_SIZE ((1 << 16) - 1)  /* 65535 */

82
#define DEFAULT_STUN_PORT  3478
83
#define DEFAULT_UPNP_TIMEOUT 200
84

85
86
#define MAX_TCP_MTU 1400 /* Use 1400 because of VPNs and we assume IEE 802.3 */

87
static void
88
89
nice_debug_input_message_composition (const NiceInputMessage *messages,
    guint n_messages);
90

Dafydd Harries's avatar
Dafydd Harries committed
91
92
93
94
G_DEFINE_TYPE (NiceAgent, nice_agent, G_TYPE_OBJECT);

enum
{
95
  PROP_COMPATIBILITY = 1,
96
  PROP_MAIN_CONTEXT,
97
  PROP_STUN_SERVER,
98
  PROP_STUN_SERVER_PORT,
99
  PROP_CONTROLLING_MODE,
100
  PROP_FULL_MODE,
101
  PROP_STUN_PACING_TIMER,
102
103
104
105
106
  PROP_MAX_CONNECTIVITY_CHECKS,
  PROP_PROXY_TYPE,
  PROP_PROXY_IP,
  PROP_PROXY_PORT,
  PROP_PROXY_USERNAME,
Youness Alaoui's avatar
Youness Alaoui committed
107
108
  PROP_PROXY_PASSWORD,
  PROP_UPNP,
109
110
  PROP_UPNP_TIMEOUT,
  PROP_RELIABLE
Dafydd Harries's avatar
Dafydd Harries committed
111
112
113
};


114
115
116
enum
{
  SIGNAL_COMPONENT_STATE_CHANGED,
117
  SIGNAL_CANDIDATE_GATHERING_DONE,
118
119
  SIGNAL_NEW_SELECTED_PAIR,
  SIGNAL_NEW_CANDIDATE,
120
  SIGNAL_NEW_REMOTE_CANDIDATE,
121
  SIGNAL_INITIAL_BINDING_REQUEST_RECEIVED,
122
  SIGNAL_RELIABLE_TRANSPORT_WRITABLE,
123
  SIGNAL_STREAMS_REMOVED,
124
125
126
127
128
  N_SIGNALS,
};

static guint signals[N_SIGNALS];

129
130
131
132
133
#if GLIB_CHECK_VERSION(2,31,8)
static GRecMutex agent_mutex;    /* Mutex used for thread-safe lib */
#else
static GStaticRecMutex agent_mutex = G_STATIC_REC_MUTEX_INIT;
#endif
134

Youness Alaoui's avatar
Youness Alaoui committed
135
136
static void priv_free_upnp (NiceAgent *agent);

137
#if GLIB_CHECK_VERSION(2,31,8)
138
139
void agent_lock (void)
{
140
  g_rec_mutex_lock (&agent_mutex);
141
142
143
144
}

void agent_unlock (void)
{
145
146
147
148
149
150
151
  g_rec_mutex_unlock (&agent_mutex);
}

#else
void agent_lock(void)
{
  g_static_rec_mutex_lock (&agent_mutex);
152
153
}

154
155
156
157
void agent_unlock(void)
{
  g_static_rec_mutex_unlock (&agent_mutex);
}
158

159
#endif
160

161
162
163
164
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
196
197
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
typedef struct {
  guint signal_id;
  GSignalQuery query;
  GValue *params;
} QueuedSignal;


static void
free_queued_signal (QueuedSignal *sig)
{
  guint i;

  for (i = 0; i < sig->query.n_params; i++) {
    if (G_VALUE_HOLDS_POINTER (&sig->params[i]))
      g_free (g_value_get_pointer (&sig->params[i]));
    g_value_unset (&sig->params[i]);
  }

  g_slice_free1 (sizeof(GValue) * (sig->query.n_params + 1), sig->params);
  g_slice_free (QueuedSignal, sig);
}

void
agent_unlock_and_emit (NiceAgent *agent)
{
  GQueue queue = G_QUEUE_INIT;
  QueuedSignal *sig;

  queue = agent->pending_signals;
  g_queue_init (&agent->pending_signals);

  agent_unlock ();

  while ((sig = g_queue_pop_head (&queue))) {
    g_signal_emitv (sig->params, sig->signal_id, 0, NULL);

    free_queued_signal (sig);
  }
}

static void
agent_queue_signal (NiceAgent *agent, guint signal_id, ...)
{
  QueuedSignal *sig;
  guint i;
  gchar *error = NULL;
  va_list var_args;

  sig = g_slice_new (QueuedSignal);
  g_signal_query (signal_id, &sig->query);

  sig->signal_id = signal_id;
  sig->params = g_slice_alloc0 (sizeof(GValue) * (sig->query.n_params + 1));

  g_value_init (&sig->params[0], G_TYPE_OBJECT);
  g_value_set_object (&sig->params[0], agent);

  va_start (var_args, signal_id);
  for (i = 0; i < sig->query.n_params; i++) {
    G_VALUE_COLLECT_INIT (&sig->params[i + 1], sig->query.param_types[i],
        var_args, 0, &error);
    if (error)
      break;
  }
  va_end (var_args);

  if (error) {
    free_queued_signal (sig);
    g_critical ("Error collecting values for signal: %s", error);
    g_free (error);
    return;
  }

  g_queue_push_tail (&agent->pending_signals, sig);
}


238
239
240
StunUsageIceCompatibility
agent_to_ice_compatibility (NiceAgent *agent)
{
241
  return agent->compatibility == NICE_COMPATIBILITY_GOOGLE ?
242
243
      STUN_USAGE_ICE_COMPATIBILITY_GOOGLE :
      agent->compatibility == NICE_COMPATIBILITY_MSN ?
244
      STUN_USAGE_ICE_COMPATIBILITY_MSN :
Jakub Adam's avatar
Jakub Adam committed
245
246
      agent->compatibility == NICE_COMPATIBILITY_WLM2009 ?
      STUN_USAGE_ICE_COMPATIBILITY_WLM2009 :
Jakub Adam's avatar
Jakub Adam committed
247
248
      agent->compatibility == NICE_COMPATIBILITY_OC2007 ?
      STUN_USAGE_ICE_COMPATIBILITY_MSN :
Jakub Adam's avatar
Jakub Adam committed
249
250
      agent->compatibility == NICE_COMPATIBILITY_OC2007R2 ?
      STUN_USAGE_ICE_COMPATIBILITY_WLM2009 :
251
      STUN_USAGE_ICE_COMPATIBILITY_RFC5245;
252
253
254
255
256
257
}


StunUsageTurnCompatibility
agent_to_turn_compatibility (NiceAgent *agent)
{
258
  return agent->compatibility == NICE_COMPATIBILITY_GOOGLE ?
259
260
      STUN_USAGE_TURN_COMPATIBILITY_GOOGLE :
      agent->compatibility == NICE_COMPATIBILITY_MSN ?
261
262
      STUN_USAGE_TURN_COMPATIBILITY_MSN :
      agent->compatibility == NICE_COMPATIBILITY_WLM2009 ?
Jakub Adam's avatar
Jakub Adam committed
263
264
      STUN_USAGE_TURN_COMPATIBILITY_MSN :
      agent->compatibility == NICE_COMPATIBILITY_OC2007 ?
265
266
267
      STUN_USAGE_TURN_COMPATIBILITY_OC2007 :
      agent->compatibility == NICE_COMPATIBILITY_OC2007R2 ?
      STUN_USAGE_TURN_COMPATIBILITY_OC2007 :
Marcus Lundblad's avatar
Marcus Lundblad committed
268
      STUN_USAGE_TURN_COMPATIBILITY_RFC5766;
269
270
}

271
272
273
NiceTurnSocketCompatibility
agent_to_turn_socket_compatibility (NiceAgent *agent)
{
274
  return agent->compatibility == NICE_COMPATIBILITY_GOOGLE ?
275
276
277
      NICE_TURN_SOCKET_COMPATIBILITY_GOOGLE :
      agent->compatibility == NICE_COMPATIBILITY_MSN ?
      NICE_TURN_SOCKET_COMPATIBILITY_MSN :
278
279
      agent->compatibility == NICE_COMPATIBILITY_WLM2009 ?
      NICE_TURN_SOCKET_COMPATIBILITY_MSN :
Jakub Adam's avatar
Jakub Adam committed
280
      agent->compatibility == NICE_COMPATIBILITY_OC2007 ?
281
282
283
      NICE_TURN_SOCKET_COMPATIBILITY_OC2007 :
      agent->compatibility == NICE_COMPATIBILITY_OC2007R2 ?
      NICE_TURN_SOCKET_COMPATIBILITY_OC2007 :
Marcus Lundblad's avatar
Marcus Lundblad committed
284
      NICE_TURN_SOCKET_COMPATIBILITY_RFC5766;
285
286
}

287
Stream *agent_find_stream (NiceAgent *agent, guint stream_id)
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
{
  GSList *i;

  for (i = agent->streams; i; i = i->next)
    {
      Stream *s = i->data;

      if (s->id == stream_id)
        return s;
    }

  return NULL;
}


303
304
gboolean
agent_find_component (
305
306
307
308
309
310
311
  NiceAgent *agent,
  guint stream_id,
  guint component_id,
  Stream **stream,
  Component **component)
{
  Stream *s;
312
  Component *c;
313

314
  s = agent_find_stream (agent, stream_id);
315

316
  if (s == NULL)
317
318
    return FALSE;

319
320
321
322
323
  c = stream_find_component_by_id (s, component_id);

  if (c == NULL)
    return FALSE;

324
325
326
327
  if (stream)
    *stream = s;

  if (component)
328
    *component = c;
329
330
331
332
333

  return TRUE;
}


Dafydd Harries's avatar
Dafydd Harries committed
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
static void
nice_agent_dispose (GObject *object);

static void
nice_agent_get_property (
  GObject *object,
  guint property_id,
  GValue *value,
  GParamSpec *pspec);

static void
nice_agent_set_property (
  GObject *object,
  guint property_id,
  const GValue *value,
  GParamSpec *pspec);


static void
nice_agent_class_init (NiceAgentClass *klass)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);

  gobject_class->get_property = nice_agent_get_property;
  gobject_class->set_property = nice_agent_set_property;
  gobject_class->dispose = nice_agent_dispose;

361
  /* install properties */
362
363
364
365
366
367
  /**
   * NiceAgent:main-context:
   *
   * A GLib main context is needed for all timeouts used by libnice.
   * This is a property being set by the nice_agent_new() call.
   */
368
369
370
371
372
373
374
  g_object_class_install_property (gobject_class, PROP_MAIN_CONTEXT,
      g_param_spec_pointer (
         "main-context",
         "The GMainContext to use for timeouts",
         "The GMainContext to use for timeouts",
         G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));

375
376
377
378
379
380
381
  /**
   * NiceAgent:compatibility:
   *
   * The Nice agent can work in various compatibility modes depending on
   * what the application/peer needs.
   * <para> See also: #NiceCompatibility</para>
   */
382
383
384
385
386
  g_object_class_install_property (gobject_class, PROP_COMPATIBILITY,
      g_param_spec_uint (
         "compatibility",
         "ICE specification compatibility",
         "The compatibility mode for the agent",
387
388
         NICE_COMPATIBILITY_RFC5245, NICE_COMPATIBILITY_LAST,
         NICE_COMPATIBILITY_RFC5245,
389
390
         G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));

Dafydd Harries's avatar
Dafydd Harries committed
391
  g_object_class_install_property (gobject_class, PROP_STUN_SERVER,
392
      g_param_spec_string (
Dafydd Harries's avatar
Dafydd Harries committed
393
        "stun-server",
394
395
        "STUN server IP address",
        "The IP address (not the hostname) of the STUN server to use",
396
        NULL,
Dafydd Harries's avatar
Dafydd Harries committed
397
398
        G_PARAM_READWRITE));

399
400
401
402
  g_object_class_install_property (gobject_class, PROP_STUN_SERVER_PORT,
      g_param_spec_uint (
        "stun-server-port",
        "STUN server port",
403
        "Port of the STUN server used to gather server-reflexive candidates",
Youness Alaoui's avatar
Youness Alaoui committed
404
        1, 65536,
405
	1, /* not a construct property, ignored */
406
407
        G_PARAM_READWRITE));

408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
  g_object_class_install_property (gobject_class, PROP_CONTROLLING_MODE,
      g_param_spec_boolean (
        "controlling-mode",
        "ICE controlling mode",
        "Whether the agent is in controlling mode",
	FALSE, /* not a construct property, ignored */
        G_PARAM_READWRITE));

   g_object_class_install_property (gobject_class, PROP_FULL_MODE,
      g_param_spec_boolean (
        "full-mode",
        "ICE full mode",
        "Whether agent runs in ICE full mode",
	TRUE, /* use full mode by default */
        G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));

424
425
426
427
  g_object_class_install_property (gobject_class, PROP_STUN_PACING_TIMER,
      g_param_spec_uint (
        "stun-pacing-timer",
        "STUN pacing timer",
Youness Alaoui's avatar
Youness Alaoui committed
428
429
        "Timer 'Ta' (msecs) used in the IETF ICE specification for pacing "
        "candidate gathering and sending of connectivity checks",
Youness Alaoui's avatar
Youness Alaoui committed
430
        1, 0xffffffff,
431
432
433
	NICE_AGENT_TIMER_TA_DEFAULT,
        G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));

434
  /* note: according to spec recommendation in sect 5.7.3 (ID-19) */
435
436
437
438
439
  g_object_class_install_property (gobject_class, PROP_MAX_CONNECTIVITY_CHECKS,
      g_param_spec_uint (
        "max-connectivity-checks",
        "Maximum number of connectivity checks",
        "Upper limit for the total number of connectivity checks performed",
Youness Alaoui's avatar
Youness Alaoui committed
440
        0, 0xffffffff,
441
442
443
	0, /* default set in init */
        G_PARAM_READWRITE));

444
445
446
447
448
449
450
  /**
   * NiceAgent:proxy-ip:
   *
   * The proxy server IP used to bypass a proxy firewall
   *
   * Since: 0.0.4
   */
451
452
453
454
  g_object_class_install_property (gobject_class, PROP_PROXY_IP,
      g_param_spec_string (
        "proxy-ip",
        "Proxy server IP",
455
        "The proxy server IP used to bypass a proxy firewall",
456
457
458
        NULL,
        G_PARAM_READWRITE));

459
460
461
462
463
464
465
  /**
   * NiceAgent:proxy-port:
   *
   * The proxy server port used to bypass a proxy firewall
   *
   * Since: 0.0.4
   */
466
467
468
469
  g_object_class_install_property (gobject_class, PROP_PROXY_PORT,
      g_param_spec_uint (
        "proxy-port",
        "Proxy server port",
470
        "The Proxy server port used to bypass a proxy firewall",
471
472
473
474
        1, 65536,
	1,
        G_PARAM_READWRITE));

475
476
477
478
479
480
481
  /**
   * NiceAgent:proxy-type:
   *
   * The type of proxy set in the proxy-ip property
   *
   * Since: 0.0.4
   */
482
483
484
485
486
487
488
489
490
  g_object_class_install_property (gobject_class, PROP_PROXY_TYPE,
      g_param_spec_uint (
         "proxy-type",
         "Type of proxy to use",
         "The type of proxy set in the proxy-ip property",
         NICE_PROXY_TYPE_NONE, NICE_PROXY_TYPE_LAST,
         NICE_PROXY_TYPE_NONE,
         G_PARAM_READWRITE));

491
492
493
494
495
496
497
  /**
   * NiceAgent:proxy-username:
   *
   * The username used to authenticate with the proxy
   *
   * Since: 0.0.4
   */
498
499
500
501
502
503
504
505
  g_object_class_install_property (gobject_class, PROP_PROXY_USERNAME,
      g_param_spec_string (
        "proxy-username",
        "Proxy server username",
        "The username used to authenticate with the proxy",
        NULL,
        G_PARAM_READWRITE));

506
507
508
509
510
511
512
  /**
   * NiceAgent:proxy-password:
   *
   * The password used to authenticate with the proxy
   *
   * Since: 0.0.4
   */
513
514
515
516
517
518
519
520
  g_object_class_install_property (gobject_class, PROP_PROXY_PASSWORD,
      g_param_spec_string (
        "proxy-password",
        "Proxy server password",
        "The password used to authenticate with the proxy",
        NULL,
        G_PARAM_READWRITE));

521
522
523
524
525
526
527
528
  /**
   * NiceAgent:upnp:
   *
   * Whether the agent should use UPnP to open a port in the router and
   * get the external IP
   *
   * Since: 0.0.7
   */
Youness Alaoui's avatar
Youness Alaoui committed
529
530
531
   g_object_class_install_property (gobject_class, PROP_UPNP,
      g_param_spec_boolean (
        "upnp",
532
#ifdef HAVE_GUPNP
Youness Alaoui's avatar
Youness Alaoui committed
533
534
535
        "Use UPnP",
        "Whether the agent should use UPnP to open a port in the router and "
        "get the external IP",
536
537
538
539
#else
        "Use UPnP (disabled in build)",
        "Does nothing because libnice was not built with UPnP support",
#endif
Youness Alaoui's avatar
Youness Alaoui committed
540
541
542
	TRUE, /* enable UPnP by default */
        G_PARAM_READWRITE| G_PARAM_CONSTRUCT));

543
544
545
546
  /**
   * NiceAgent:upnp-timeout:
   *
   * The maximum amount of time to wait for UPnP discovery to finish before
547
   * signaling the #NiceAgent::candidate-gathering-done signal
548
549
550
   *
   * Since: 0.0.7
   */
Youness Alaoui's avatar
Youness Alaoui committed
551
552
553
  g_object_class_install_property (gobject_class, PROP_UPNP_TIMEOUT,
      g_param_spec_uint (
        "upnp-timeout",
554
#ifdef HAVE_GUPNP
Youness Alaoui's avatar
Youness Alaoui committed
555
556
557
        "Timeout for UPnP discovery",
        "The maximum amount of time to wait for UPnP discovery to finish before "
        "signaling the candidate-gathering-done signal",
558
559
560
561
#else
        "Timeout for UPnP discovery (disabled in build)",
        "Does nothing because libnice was not built with UPnP support",
#endif
Youness Alaoui's avatar
Youness Alaoui committed
562
        100, 60000,
563
	DEFAULT_UPNP_TIMEOUT,
Youness Alaoui's avatar
Youness Alaoui committed
564
565
        G_PARAM_READWRITE | G_PARAM_CONSTRUCT));

Youness Alaoui's avatar
Youness Alaoui committed
566
567
568
569
570
571
572
573
  /**
   * NiceAgent:reliable:
   *
   * Whether the agent should use PseudoTcp to ensure a reliable transport
   * of messages
   *
   * Since: 0.0.11
   */
574
575
576
577
   g_object_class_install_property (gobject_class, PROP_RELIABLE,
      g_param_spec_boolean (
        "reliable",
        "reliable mode",
Youness Alaoui's avatar
Youness Alaoui committed
578
        "Whether the agent should use PseudoTcp to ensure a reliable transport"
579
580
581
582
        "of messages",
	FALSE,
        G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));

583
584
  /* install signals */

585
586
  /**
   * NiceAgent::component-state-changed
Youness Alaoui's avatar
Youness Alaoui committed
587
   * @agent: The #NiceAgent object
588
589
590
591
592
593
   * @stream_id: The ID of the stream
   * @component_id: The ID of the component
   * @state: The #NiceComponentState of the component
   *
   * This signal is fired whenever a component's state changes
   */
594
595
596
597
  signals[SIGNAL_COMPONENT_STATE_CHANGED] =
      g_signal_new (
          "component-state-changed",
          G_OBJECT_CLASS_TYPE (klass),
598
          G_SIGNAL_RUN_LAST,
599
600
601
602
603
604
605
606
          0,
          NULL,
          NULL,
          agent_marshal_VOID__UINT_UINT_UINT,
          G_TYPE_NONE,
          3,
          G_TYPE_UINT, G_TYPE_UINT, G_TYPE_UINT,
          G_TYPE_INVALID);
607

608
609
  /**
   * NiceAgent::candidate-gathering-done:
Youness Alaoui's avatar
Youness Alaoui committed
610
   * @agent: The #NiceAgent object
611
612
613
614
615
   * @stream_id: The ID of the stream
   *
   * This signal is fired whenever a stream has finished gathering its
   * candidates after a call to nice_agent_gather_candidates()
   */
616
617
618
619
  signals[SIGNAL_CANDIDATE_GATHERING_DONE] =
      g_signal_new (
          "candidate-gathering-done",
          G_OBJECT_CLASS_TYPE (klass),
620
          G_SIGNAL_RUN_LAST,
621
622
623
          0,
          NULL,
          NULL,
624
          agent_marshal_VOID__UINT,
625
          G_TYPE_NONE,
626
627
          1,
          G_TYPE_UINT, G_TYPE_INVALID);
628

629
630
  /**
   * NiceAgent::new-selected-pair
Youness Alaoui's avatar
Youness Alaoui committed
631
   * @agent: The #NiceAgent object
632
633
634
635
636
637
638
639
   * @stream_id: The ID of the stream
   * @component_id: The ID of the component
   * @lfoundation: The local foundation of the selected candidate pair
   * @rfoundation: The remote foundation of the selected candidate pair
   *
   * This signal is fired once a candidate pair is selected for data transfer for
   * a stream's component
   */
640
641
642
643
  signals[SIGNAL_NEW_SELECTED_PAIR] =
      g_signal_new (
          "new-selected-pair",
          G_OBJECT_CLASS_TYPE (klass),
644
          G_SIGNAL_RUN_LAST,
645
646
647
648
649
650
651
652
653
          0,
          NULL,
          NULL,
          agent_marshal_VOID__UINT_UINT_STRING_STRING,
          G_TYPE_NONE,
          4,
          G_TYPE_UINT, G_TYPE_UINT, G_TYPE_STRING, G_TYPE_STRING,
          G_TYPE_INVALID);

654
655
  /**
   * NiceAgent::new-candidate
Youness Alaoui's avatar
Youness Alaoui committed
656
   * @agent: The #NiceAgent object
657
658
659
660
661
   * @stream_id: The ID of the stream
   * @component_id: The ID of the component
   * @foundation: The foundation of the new candidate
   *
   * This signal is fired when the agent discovers a new candidate
662
   * <para> See also: #NiceAgent::candidate-gathering-done </para>
663
   */
664
665
666
667
  signals[SIGNAL_NEW_CANDIDATE] =
      g_signal_new (
          "new-candidate",
          G_OBJECT_CLASS_TYPE (klass),
668
          G_SIGNAL_RUN_LAST,
669
670
671
672
673
674
675
676
677
          0,
          NULL,
          NULL,
          agent_marshal_VOID__UINT_UINT_STRING,
          G_TYPE_NONE,
          3,
          G_TYPE_UINT, G_TYPE_UINT, G_TYPE_STRING,
          G_TYPE_INVALID);

678
679
  /**
   * NiceAgent::new-remote-candidate
Youness Alaoui's avatar
Youness Alaoui committed
680
   * @agent: The #NiceAgent object
681
682
683
684
685
686
687
   * @stream_id: The ID of the stream
   * @component_id: The ID of the component
   * @foundation: The foundation of the new candidate
   *
   * This signal is fired when the agent discovers a new remote candidate.
   * This can happen with peer reflexive candidates.
   */
688
689
690
691
  signals[SIGNAL_NEW_REMOTE_CANDIDATE] =
      g_signal_new (
          "new-remote-candidate",
          G_OBJECT_CLASS_TYPE (klass),
692
          G_SIGNAL_RUN_LAST,
693
694
695
696
697
698
699
700
701
          0,
          NULL,
          NULL,
          agent_marshal_VOID__UINT_UINT_STRING,
          G_TYPE_NONE,
          3,
          G_TYPE_UINT, G_TYPE_UINT, G_TYPE_STRING,
          G_TYPE_INVALID);

702
703
  /**
   * NiceAgent::initial-binding-request-received
Youness Alaoui's avatar
Youness Alaoui committed
704
   * @agent: The #NiceAgent object
705
706
707
708
709
   * @stream_id: The ID of the stream
   *
   * This signal is fired when we received our first binding request from
   * the peer.
   */
710
711
712
713
  signals[SIGNAL_INITIAL_BINDING_REQUEST_RECEIVED] =
      g_signal_new (
          "initial-binding-request-received",
          G_OBJECT_CLASS_TYPE (klass),
714
          G_SIGNAL_RUN_LAST,
715
716
717
718
719
720
721
722
723
          0,
          NULL,
          NULL,
          agent_marshal_VOID__UINT,
          G_TYPE_NONE,
          1,
          G_TYPE_UINT,
          G_TYPE_INVALID);

724
725
  /**
   * NiceAgent::reliable-transport-writable
Youness Alaoui's avatar
Youness Alaoui committed
726
   * @agent: The #NiceAgent object
727
728
729
730
731
732
733
734
   * @stream_id: The ID of the stream
   * @component_id: The ID of the component
   *
   * This signal is fired on the reliable #NiceAgent when the underlying reliable
   * transport becomes writable.
   * This signal is only emitted when the nice_agent_send() function returns less
   * bytes than requested to send (or -1) and once when the connection
   * is established.
735
736
   *
   * Since: 0.0.11
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
   */
  signals[SIGNAL_RELIABLE_TRANSPORT_WRITABLE] =
      g_signal_new (
          "reliable-transport-writable",
          G_OBJECT_CLASS_TYPE (klass),
          G_SIGNAL_RUN_LAST,
          0,
          NULL,
          NULL,
          agent_marshal_VOID__UINT_UINT,
          G_TYPE_NONE,
          2,
          G_TYPE_UINT, G_TYPE_UINT,
          G_TYPE_INVALID);

752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
  /**
   * NiceAgent::streams-removed
   * @agent: The #NiceAgent object
   * @stream_ids: (array zero-terminated=1) (element-type uint): An array of
   * unsigned integer stream IDs, ending with a 0 ID
   *
   * This signal is fired whenever one or more streams are removed from the
   * @agent.
   *
   * Since: 0.1.5
   */
  signals[SIGNAL_STREAMS_REMOVED] =
      g_signal_new (
          "streams-removed",
          G_OBJECT_CLASS_TYPE (klass),
          G_SIGNAL_RUN_LAST,
          0,
          NULL,
          NULL,
          g_cclosure_marshal_VOID__POINTER,
          G_TYPE_NONE,
          1,
          G_TYPE_POINTER,
          G_TYPE_INVALID);
776

777
778
  /* Init debug options depending on env variables */
  nice_debug_init ();
Dafydd Harries's avatar
Dafydd Harries committed
779
780
}

781
782
783
784
static void priv_generate_tie_breaker (NiceAgent *agent) 
{
  nice_rng_generate_bytes (agent->rng, 8, (gchar*)&agent->tie_breaker);
}
Dafydd Harries's avatar
Dafydd Harries committed
785
786
787
788
789
790

static void
nice_agent_init (NiceAgent *agent)
{
  agent->next_candidate_id = 1;
  agent->next_stream_id = 1;
791

792
  /* set defaults; not construct params, so set here */
793
  agent->stun_server_port = DEFAULT_STUN_PORT;
794
  agent->controlling_mode = TRUE;
795
  agent->max_conn_checks = NICE_AGENT_MAX_CONNECTIVITY_CHECKS_DEFAULT;
796
797

  agent->discovery_list = NULL;
798
  agent->discovery_unsched_items = 0;
799
800
801
  agent->discovery_timer_source = NULL;
  agent->conncheck_timer_source = NULL;
  agent->keepalive_timer_source = NULL;
802
  agent->refresh_list = NULL;
803
  agent->media_after_tick = FALSE;
804
  agent->software_attribute = NULL;
805

806
  agent->compatibility = NICE_COMPATIBILITY_RFC5245;
807
  agent->reliable = FALSE;
808

809
  stun_agent_init (&agent->stun_agent, STUN_ALL_KNOWN_ATTRIBUTES,
810
      STUN_COMPATIBILITY_RFC5389,
811
812
813
      STUN_AGENT_USAGE_SHORT_TERM_CREDENTIALS |
      STUN_AGENT_USAGE_USE_FINGERPRINT);

Dafydd Harries's avatar
Dafydd Harries committed
814
  agent->rng = nice_rng_new ();
815
  priv_generate_tie_breaker (agent);
816
817

  g_queue_init (&agent->pending_signals);
Dafydd Harries's avatar
Dafydd Harries committed
818
819
820
}


821
NICEAPI_EXPORT NiceAgent *
822
nice_agent_new (GMainContext *ctx, NiceCompatibility compat)
Dafydd Harries's avatar
Dafydd Harries committed
823
{
824
825
  NiceAgent *agent = g_object_new (NICE_TYPE_AGENT,
      "compatibility", compat,
826
      "main-context", ctx,
827
828
829
830
831
832
833
834
835
836
837
838
839
840
      "reliable", FALSE,
      NULL);

  return agent;
}


NICEAPI_EXPORT NiceAgent *
nice_agent_new_reliable (GMainContext *ctx, NiceCompatibility compat)
{
  NiceAgent *agent = g_object_new (NICE_TYPE_AGENT,
      "compatibility", compat,
      "main-context", ctx,
      "reliable", TRUE,
Dafydd Harries's avatar
Dafydd Harries committed
841
      NULL);
842
843

  return agent;
Dafydd Harries's avatar
Dafydd Harries committed
844
845
846
847
848
849
850
851
852
853
854
}


static void
nice_agent_get_property (
  GObject *object,
  guint property_id,
  GValue *value,
  GParamSpec *pspec)
{
  NiceAgent *agent = NICE_AGENT (object);
Dafydd Harries's avatar
Dafydd Harries committed
855

856
  agent_lock();
Youness Alaoui's avatar
Youness Alaoui committed
857

Dafydd Harries's avatar
Dafydd Harries committed
858
859
  switch (property_id)
    {
860
861
862
863
    case PROP_MAIN_CONTEXT:
      g_value_set_pointer (value, agent->main_context);
      break;

864
865
866
867
    case PROP_COMPATIBILITY:
      g_value_set_uint (value, agent->compatibility);
      break;

Dafydd Harries's avatar
Dafydd Harries committed
868
    case PROP_STUN_SERVER:
869
      g_value_set_string (value, agent->stun_server_ip);
870
      break;
871
872
873

    case PROP_STUN_SERVER_PORT:
      g_value_set_uint (value, agent->stun_server_port);
874
      break;
875

876
877
878
879
880
881
882
    case PROP_CONTROLLING_MODE:
      g_value_set_boolean (value, agent->controlling_mode);
      break;

    case PROP_FULL_MODE:
      g_value_set_boolean (value, agent->full_mode);
      break;
Dafydd Harries's avatar
Dafydd Harries committed
883

884
885
886
887
    case PROP_STUN_PACING_TIMER:
      g_value_set_uint (value, agent->timer_ta);
      break;

888
889
890
891
892
    case PROP_MAX_CONNECTIVITY_CHECKS:
      g_value_set_uint (value, agent->max_conn_checks);
      /* XXX: should we prune the list of already existing checks? */
      break;

893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
    case PROP_PROXY_IP:
      g_value_set_string (value, agent->proxy_ip);
      break;

    case PROP_PROXY_PORT:
      g_value_set_uint (value, agent->proxy_port);
      break;

    case PROP_PROXY_TYPE:
      g_value_set_uint (value, agent->proxy_type);
      break;

    case PROP_PROXY_USERNAME:
      g_value_set_string (value, agent->proxy_username);
      break;

    case PROP_PROXY_PASSWORD:
      g_value_set_string (value, agent->proxy_password);
      break;

Youness Alaoui's avatar
Youness Alaoui committed
913
    case PROP_UPNP:
914
#ifdef HAVE_GUPNP
Youness Alaoui's avatar
Youness Alaoui committed
915
      g_value_set_boolean (value, agent->upnp_enabled);
916
917
918
#else
      g_value_set_boolean (value, FALSE);
#endif
Youness Alaoui's avatar
Youness Alaoui committed
919
920
921
      break;

    case PROP_UPNP_TIMEOUT:
922
#ifdef HAVE_GUPNP
Youness Alaoui's avatar
Youness Alaoui committed
923
      g_value_set_uint (value, agent->upnp_timeout);
924
925
#else
      g_value_set_uint (value, DEFAULT_UPNP_TIMEOUT);
Youness Alaoui's avatar
Youness Alaoui committed
926
#endif
927
      break;
Youness Alaoui's avatar
Youness Alaoui committed
928

929
930
931
932
    case PROP_RELIABLE:
      g_value_set_boolean (value, agent->reliable);
      break;

Dafydd Harries's avatar
Dafydd Harries committed
933
934
935
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
    }
Youness Alaoui's avatar
Youness Alaoui committed
936

937
  agent_unlock_and_emit(agent);
Dafydd Harries's avatar
Dafydd Harries committed
938
939
940
941
942
943
944
945
946
947
948
949
}


static void
nice_agent_set_property (
  GObject *object,
  guint property_id,
  const GValue *value,
  GParamSpec *pspec)
{
  NiceAgent *agent = NICE_AGENT (object);

950
  agent_lock();
Youness Alaoui's avatar
Youness Alaoui committed
951

Dafydd Harries's avatar
Dafydd Harries committed
952
953
  switch (property_id)
    {
954
955
    case PROP_MAIN_CONTEXT:
      agent->main_context = g_value_get_pointer (value);
956
957
      if (agent->main_context != NULL)
        g_main_context_ref (agent->main_context);
958
959
      break;

960
961
    case PROP_COMPATIBILITY:
      agent->compatibility = g_value_get_uint (value);
962
      if (agent->compatibility == NICE_COMPATIBILITY_GOOGLE) {
963
964
965
966
        stun_agent_init (&agent->stun_agent, STUN_ALL_KNOWN_ATTRIBUTES,
            STUN_COMPATIBILITY_RFC3489,
            STUN_AGENT_USAGE_SHORT_TERM_CREDENTIALS |
            STUN_AGENT_USAGE_IGNORE_CREDENTIALS);
967
      } else if (agent->compatibility == NICE_COMPATIBILITY_MSN) {
Youness Alaoui's avatar
Youness Alaoui committed
968
969
        stun_agent_init (&agent->stun_agent, STUN_ALL_KNOWN_ATTRIBUTES,
            STUN_COMPATIBILITY_RFC3489,
970
971
            STUN_AGENT_USAGE_SHORT_TERM_CREDENTIALS |
            STUN_AGENT_USAGE_FORCE_VALIDATER);
972
973
974
975
      } else if (agent->compatibility == NICE_COMPATIBILITY_WLM2009) {
        stun_agent_init (&agent->stun_agent, STUN_ALL_KNOWN_ATTRIBUTES,
            STUN_COMPATIBILITY_WLM2009,
            STUN_AGENT_USAGE_SHORT_TERM_CREDENTIALS |
Jakub Adam's avatar
Jakub Adam committed
976
            STUN_AGENT_USAGE_USE_FINGERPRINT);
977
978
979
980
981
982
      } else if (agent->compatibility == NICE_COMPATIBILITY_OC2007) {
        stun_agent_init (&agent->stun_agent, STUN_ALL_KNOWN_ATTRIBUTES,
            STUN_COMPATIBILITY_RFC3489,
            STUN_AGENT_USAGE_SHORT_TERM_CREDENTIALS |
            STUN_AGENT_USAGE_FORCE_VALIDATER |
            STUN_AGENT_USAGE_NO_ALIGNED_ATTRIBUTES);
Jakub Adam's avatar
Jakub Adam committed
983
984
985
986
      } else if (agent->compatibility == NICE_COMPATIBILITY_OC2007R2) {
        stun_agent_init (&agent->stun_agent, STUN_ALL_KNOWN_ATTRIBUTES,
            STUN_COMPATIBILITY_WLM2009,
            STUN_AGENT_USAGE_SHORT_TERM_CREDENTIALS |
987
988
            STUN_AGENT_USAGE_USE_FINGERPRINT |
            STUN_AGENT_USAGE_NO_ALIGNED_ATTRIBUTES);
989
990
991
992
993
      } else {
        stun_agent_init (&agent->stun_agent, STUN_ALL_KNOWN_ATTRIBUTES,
            STUN_COMPATIBILITY_RFC5389,
            STUN_AGENT_USAGE_SHORT_TERM_CREDENTIALS |
            STUN_AGENT_USAGE_USE_FINGERPRINT);
994
      }
995
      stun_agent_set_software (&agent->stun_agent, agent->software_attribute);
996

997
998
      break;

Dafydd Harries's avatar
Dafydd Harries committed
999
    case PROP_STUN_SERVER:
1000
      g_free (agent->stun_server_ip);
1001
1002
1003
1004
1005
1006
1007
      agent->stun_server_ip = g_value_dup_string (value);
      break;

    case PROP_STUN_SERVER_PORT:
      agent->stun_server_port = g_value_get_uint (value);
      break;

1008
1009
1010
1011
1012
1013
1014
1015
    case PROP_CONTROLLING_MODE:
      agent->controlling_mode = g_value_get_boolean (value);
      break;

    case PROP_FULL_MODE:
      agent->full_mode = g_value_get_boolean (value);
      break;

1016
1017
1018
1019
    case PROP_STUN_PACING_TIMER:
      agent->timer_ta = g_value_get_uint (value);
      break;

1020
1021
1022
1023
    case PROP_MAX_CONNECTIVITY_CHECKS:
      agent->max_conn_checks = g_value_get_uint (value);
      break;

1024
    case PROP_PROXY_IP:
1025
      g_free (agent->proxy_ip);
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
      agent->proxy_ip = g_value_dup_string (value);
      break;

    case PROP_PROXY_PORT:
      agent->proxy_port = g_value_get_uint (value);
      break;

    case PROP_PROXY_TYPE:
      agent->proxy_type = g_value_get_uint (value);
      break;

    case PROP_PROXY_USERNAME:
1038
      g_free (agent->proxy_username);
1039
1040
1041
1042
      agent->proxy_username = g_value_dup_string (value);
      break;

    case PROP_PROXY_PASSWORD:
1043
      g_free (agent->proxy_password);
1044
1045
1046
      agent->proxy_password = g_value_dup_string (value);
      break;

Youness Alaoui's avatar
Youness Alaoui committed
1047
    case PROP_UPNP_TIMEOUT:
1048
#ifdef HAVE_GUPNP
Youness Alaoui's avatar
Youness Alaoui committed
1049
      agent->upnp_timeout = g_value_get_uint (value);
1050
#endif
Youness Alaoui's avatar
Youness Alaoui committed
1051
1052
1053
      break;

    case PROP_UPNP:
1054
#ifdef HAVE_GUPNP
Youness Alaoui's avatar
Youness Alaoui committed
1055
1056
      agent->upnp_enabled = g_value_get_boolean (value);
#endif
1057
      break;
1058
1059
1060
1061
1062

    case PROP_RELIABLE:
      agent->reliable = g_value_get_boolean (value);
      break;

Dafydd Harries's avatar
Dafydd Harries committed
1063
1064
1065
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
    }
Youness Alaoui's avatar
Youness Alaoui committed
1066

1067
  agent_unlock_and_emit (agent);
Youness Alaoui's avatar
Youness Alaoui committed
1068

Dafydd Harries's avatar
Dafydd Harries committed
1069
1070
}

1071
1072
1073
static void priv_pseudo_tcp_error (NiceAgent *agent, Stream *stream,
    Component *component)
{
1074
  if (component->tcp_writable_cancellable) {
1075
    g_cancellable_cancel (component->tcp_writable_cancellable);
1076
1077
1078
    g_clear_object (&component->tcp_writable_cancellable);
  }

1079
1080
1081
  if (component->tcp) {
    agent_signal_component_state_change (agent, stream->id,
        component->id, NICE_COMPONENT_STATE_FAILED);
1082
    component_detach_all_sockets (component);
1083
    pseudo_tcp_socket_close (component->tcp, TRUE);
1084
    g_clear_object (&component->tcp);
1085
1086
1087
1088
1089
1090
  }

  if (component->tcp_clock) {
    g_source_destroy (component->tcp_clock);
    g_source_unref (component->tcp_clock);
    component->tcp_clock = NULL;
1091
1092
1093
1094
1095
  }
}

static void
adjust_tcp_clock (NiceAgent *agent, Stream *stream, Component *component);
1096
1097
1098
1099
1100


static void
pseudo_tcp_socket_opened (PseudoTcpSocket *sock, gpointer user_data)
{
1101
1102
1103
  Component *component = user_data;
  NiceAgent *agent = component->agent;
  Stream *stream = component->stream;
1104

1105
  nice_debug ("Agent %p: s%d:%d pseudo Tcp socket Opened", agent,
1106
      stream->id, component->id);
1107
  g_cancellable_cancel (component->tcp_writable_cancellable);
1108
1109

  agent_queue_signal (agent, signals[SIGNAL_RELIABLE_TRANSPORT_WRITABLE],
1110
1111
1112
      stream->id, component->id);
}

1113
1114
1115
1116
1117
1118
/* Will attempt to queue all @n_messages into the pseudo-TCP transmission
 * buffer. This is always used in reliable mode, so essentially treats @messages
 * as a massive flat array of buffers.
 *
 * Returns the number of messages successfully sent on success (which may be
 * zero if sending the first buffer of the message would have blocked), or
1119
1120
1121
 * a negative number on error. If "allow_partial" is TRUE, then it returns
 * the number of bytes sent
 */
1122
1123
static gint
pseudo_tcp_socket_send_messages (PseudoTcpSocket *self,
1124
1125
    const NiceOutputMessage *messages, guint n_messages, gboolean allow_partial,
    GError **error)
1126
1127
{
  guint i;
1128
  gint bytes_sent = 0;
1129
1130
1131
1132
1133

  for (i = 0; i < n_messages; i++) {
    const NiceOutputMessage *message = &messages[i];
    guint j;

1134
1135
1136
1137
1138
    /* If allow_partial is FALSE and there’s not enough space for the
     * entire message, bail now before queuing anything. This doesn’t
     * gel with the fact this function is only used in reliable mode,
     * and there is no concept of a ‘message’, but is necessary
     * because the calling API has no way of returning to the client
1139
     * and indicating that a message was partially sent. */
1140
1141
    if (!allow_partial &&
        output_message_get_size (message) >
1142
        pseudo_tcp_socket_get_available_send_space (self)) {
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
      return i;
    }

    for (j = 0;
         (message->n_buffers >= 0 && j < (guint) message->n_buffers) ||
         (message->n_buffers < 0 && message->buffers[j].buffer != NULL);
         j++) {
      const GOutputVector *buffer = &message->buffers[j];
      gssize ret;

      /* Send on the pseudo-TCP socket. */
      ret = pseudo_tcp_socket_send (self, buffer->buffer, buffer->size);

      /* In case of -1, the error is either EWOULDBLOCK or ENOTCONN, which both
       * need the user to wait for the reliable-transport-writable signal */
1158
1159
1160
1161
1162
1163
1164
1165
1166
      if (ret < 0) {
        if (pseudo_tcp_socket_get_error (self) == EWOULDBLOCK)
          goto out;

        if (pseudo_tcp_socket_get_error (self) == ENOTCONN)
          g_set_error (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK,
              "TCP connection is not yet established.");
        else
          g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1167
            "Error writing data to pseudo-TCP socket.");
1168
1169
1170
        return -1;
      } else {
        bytes_sent += ret;
1171
1172
1173
1174
      }
    }
  }

1175
1176
1177
 out:

  return allow_partial ? bytes_sent : (gint) i;
1178
1179
}

1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
/* Will fill up @messages from the first free byte onwards (as determined using
 * @iter). This is always used in reliable mode, so it essentially treats
 * @messages as a massive flat array of buffers.
 *
 * Updates @iter in place. @iter and @messages are left in invalid states if
 * an error is returned.
 *
 * Returns the number of valid messages in @messages on success (which may be
 * zero if reading into the first buffer of the message would have blocked), or
 * a negative number on error. */
static gint
pseudo_tcp_socket_recv_messages (PseudoTcpSocket *self,
    NiceInputMessage *messages, guint n_messages, NiceInputMessageIter *iter,
    GError **error)
{
  for (; iter->message < n_messages; iter->message++) {
    NiceInputMessage *message = &messages[iter->message];

    if (iter->buffer == 0 && iter->offset == 0) {
      message->length = 0;
    }

    for (;
         (message->n_buffers >= 0 && iter->buffer < (guint) message->n_buffers) ||
         (message->n_buffers < 0 && message->buffers[iter->buffer].buffer != NULL);
         iter->buffer++) {
      GInputVector *buffer = &message->buffers[iter->buffer];

      do {
        gssize len;

        len = pseudo_tcp_socket_recv (self,
            (gchar *) buffer->buffer + iter->offset,
            buffer->size - iter->offset);

        nice_debug ("%s: Received %" G_GSSIZE_FORMAT " bytes into "
            "buffer %p (offset %" G_GSIZE_FORMAT ", length %" G_GSIZE_FORMAT
            ").", G_STRFUNC, len, buffer->buffer, iter->offset, buffer->size);

        if (len < 0 && pseudo_tcp_socket_get_error (self) == EWOULDBLOCK) {
          len = 0;
          goto done;
        } else if (len < 0 && pseudo_tcp_socket_get_error (self) == ENOTCONN) {
          g_set_error (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK,
              "Error reading data from pseudo-TCP socket: not connected.");
          return len;
        } else if (len < 0) {
          g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
              "Error reading data from pseudo-TCP socket.");
          return len;
        } else {
          /* Got some data! */
          message->length += len;
          iter->offset += len;
        }
      } while (iter->offset < buffer->size);

      iter->offset = 0;
    }

    iter->buffer = 0;
  }

done:
  return nice_input_message_iter_get_n_valid_messages (iter);
}

1247
/* This is called with the agent lock held. */
1248
1249
1250
static void
pseudo_tcp_socket_readable (PseudoTcpSocket *sock, gpointer user_data)
{
1251
1252
1253
  Component *component = user_data;
  NiceAgent *agent = component->agent;
  Stream *stream = component->stream;
1254
  gboolean has_io_callback;
1255
1256
1257
1258
  guint stream_id = stream->id;
  guint component_id = component->id;

  g_object_ref (agent);
1259
1260
1261
1262

  nice_debug ("Agent %p: s%d:%d pseudo Tcp socket readable", agent,
      stream->id, component->id);

1263
1264
  component->tcp_readable = TRUE;

1265
  has_io_callback = component_has_io_callback (component);
1266

1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
  /* Only dequeue pseudo-TCP data if we can reliably inform the client. The
   * agent lock is held here, so has_io_callback can only change during
   * component_emit_io_callback(), after which it’s re-queried. This ensures
   * no data loss of packets already received and dequeued. */
  if (has_io_callback) {
    do {
      guint8 buf[MAX_BUFFER_SIZE];
      gssize len;

      /* FIXME: Why copy into a temporary buffer here? Why can’t the I/O
       * callbacks be emitted directly from the pseudo-TCP receive buffer? */
1278
      len = pseudo_tcp_socket_recv (sock, (gchar *) buf, sizeof(buf));
1279

1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
      nice_debug ("%s: I/O callback case: Received %" G_GSSIZE_FORMAT " bytes",
          G_STRFUNC, len);

      if (len == 0) {
        component->tcp_readable = FALSE;
        break;
      } else if (len <= 0) {
        /* Handle errors. */
        if (pseudo_tcp_socket_get_error (sock) != EWOULDBLOCK) {
          nice_debug ("%s: calling priv_pseudo_tcp_error()", G_STRFUNC);
          priv_pseudo_tcp_error (agent, stream, component);

          if (component->recv_buf_error != NULL) {
            GIOErrorEnum error_code;

            if (pseudo_tcp_socket_get_error (sock) == ENOTCONN)
              error_code = G_IO_ERROR_BROKEN_PIPE;
            else
              error_code = G_IO_ERROR_FAILED;

            g_set_error (component->recv_buf_error, G_IO_ERROR, error_code,
                "Error reading data from pseudo-TCP socket.");
          }
        }

        break;
      }
1307

1308
      component_emit_io_callback (component, buf, len);
1309

1310
1311
1312
1313
1314
1315
      if (!agent_find_component (agent, stream_id, component_id,
              &stream, &component)) {
        nice_debug ("Stream or Component disappeared during the callback");
        goto out;
      }
      if (!component->tcp) {
1316
        nice_debug ("PseudoTCP socket got destroyed in readable callback!");
1317
        goto out;