agent.c 129 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
49
#include <glib.h>

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

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

59
60
#include "debug.h"

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

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

75
76
#include "pseudotcp.h"

77
78
79
80
/* 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 */

81
#define DEFAULT_STUN_PORT  3478
82
#define DEFAULT_UPNP_TIMEOUT 200
83

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

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

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

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


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

static guint signals[N_SIGNALS];

128
129
130
131
132
#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
133

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

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

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

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

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

158
#endif
159

160
161
162
StunUsageIceCompatibility
agent_to_ice_compatibility (NiceAgent *agent)
{
163
  return agent->compatibility == NICE_COMPATIBILITY_GOOGLE ?
164
165
      STUN_USAGE_ICE_COMPATIBILITY_GOOGLE :
      agent->compatibility == NICE_COMPATIBILITY_MSN ?
166
      STUN_USAGE_ICE_COMPATIBILITY_MSN :
Jakub Adam's avatar
Jakub Adam committed
167
168
      agent->compatibility == NICE_COMPATIBILITY_WLM2009 ?
      STUN_USAGE_ICE_COMPATIBILITY_WLM2009 :
Jakub Adam's avatar
Jakub Adam committed
169
170
      agent->compatibility == NICE_COMPATIBILITY_OC2007 ?
      STUN_USAGE_ICE_COMPATIBILITY_MSN :
Jakub Adam's avatar
Jakub Adam committed
171
172
      agent->compatibility == NICE_COMPATIBILITY_OC2007R2 ?
      STUN_USAGE_ICE_COMPATIBILITY_WLM2009 :
173
      STUN_USAGE_ICE_COMPATIBILITY_RFC5245;
174
175
176
177
178
179
}


StunUsageTurnCompatibility
agent_to_turn_compatibility (NiceAgent *agent)
{
180
  return agent->compatibility == NICE_COMPATIBILITY_GOOGLE ?
181
182
      STUN_USAGE_TURN_COMPATIBILITY_GOOGLE :
      agent->compatibility == NICE_COMPATIBILITY_MSN ?
183
184
      STUN_USAGE_TURN_COMPATIBILITY_MSN :
      agent->compatibility == NICE_COMPATIBILITY_WLM2009 ?
Jakub Adam's avatar
Jakub Adam committed
185
186
      STUN_USAGE_TURN_COMPATIBILITY_MSN :
      agent->compatibility == NICE_COMPATIBILITY_OC2007 ?
187
188
189
      STUN_USAGE_TURN_COMPATIBILITY_OC2007 :
      agent->compatibility == NICE_COMPATIBILITY_OC2007R2 ?
      STUN_USAGE_TURN_COMPATIBILITY_OC2007 :
Marcus Lundblad's avatar
Marcus Lundblad committed
190
      STUN_USAGE_TURN_COMPATIBILITY_RFC5766;
191
192
}

193
194
195
NiceTurnSocketCompatibility
agent_to_turn_socket_compatibility (NiceAgent *agent)
{
196
  return agent->compatibility == NICE_COMPATIBILITY_GOOGLE ?
197
198
199
      NICE_TURN_SOCKET_COMPATIBILITY_GOOGLE :
      agent->compatibility == NICE_COMPATIBILITY_MSN ?
      NICE_TURN_SOCKET_COMPATIBILITY_MSN :
200
201
      agent->compatibility == NICE_COMPATIBILITY_WLM2009 ?
      NICE_TURN_SOCKET_COMPATIBILITY_MSN :
Jakub Adam's avatar
Jakub Adam committed
202
      agent->compatibility == NICE_COMPATIBILITY_OC2007 ?
203
204
205
      NICE_TURN_SOCKET_COMPATIBILITY_OC2007 :
      agent->compatibility == NICE_COMPATIBILITY_OC2007R2 ?
      NICE_TURN_SOCKET_COMPATIBILITY_OC2007 :
Marcus Lundblad's avatar
Marcus Lundblad committed
206
      NICE_TURN_SOCKET_COMPATIBILITY_RFC5766;
207
208
}

209
Stream *agent_find_stream (NiceAgent *agent, guint stream_id)
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
{
  GSList *i;

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

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

  return NULL;
}


225
226
gboolean
agent_find_component (
227
228
229
230
231
232
233
  NiceAgent *agent,
  guint stream_id,
  guint component_id,
  Stream **stream,
  Component **component)
{
  Stream *s;
234
  Component *c;
235

236
  s = agent_find_stream (agent, stream_id);
237

238
  if (s == NULL)
239
240
    return FALSE;

241
242
243
244
245
  c = stream_find_component_by_id (s, component_id);

  if (c == NULL)
    return FALSE;

246
247
248
249
  if (stream)
    *stream = s;

  if (component)
250
    *component = c;
251
252
253
254
255

  return TRUE;
}


Dafydd Harries's avatar
Dafydd Harries committed
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
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;

283
  /* install properties */
284
285
286
287
288
289
  /**
   * 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.
   */
290
291
292
293
294
295
296
  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));

297
298
299
300
301
302
303
  /**
   * NiceAgent:compatibility:
   *
   * The Nice agent can work in various compatibility modes depending on
   * what the application/peer needs.
   * <para> See also: #NiceCompatibility</para>
   */
304
305
306
307
308
  g_object_class_install_property (gobject_class, PROP_COMPATIBILITY,
      g_param_spec_uint (
         "compatibility",
         "ICE specification compatibility",
         "The compatibility mode for the agent",
309
310
         NICE_COMPATIBILITY_RFC5245, NICE_COMPATIBILITY_LAST,
         NICE_COMPATIBILITY_RFC5245,
311
312
         G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));

Dafydd Harries's avatar
Dafydd Harries committed
313
  g_object_class_install_property (gobject_class, PROP_STUN_SERVER,
314
      g_param_spec_string (
Dafydd Harries's avatar
Dafydd Harries committed
315
        "stun-server",
316
317
        "STUN server IP address",
        "The IP address (not the hostname) of the STUN server to use",
318
        NULL,
Dafydd Harries's avatar
Dafydd Harries committed
319
320
        G_PARAM_READWRITE));

321
322
323
324
  g_object_class_install_property (gobject_class, PROP_STUN_SERVER_PORT,
      g_param_spec_uint (
        "stun-server-port",
        "STUN server port",
325
        "Port of the STUN server used to gather server-reflexive candidates",
Youness Alaoui's avatar
Youness Alaoui committed
326
        1, 65536,
327
	1, /* not a construct property, ignored */
328
329
        G_PARAM_READWRITE));

330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
  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));

346
347
348
349
  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
350
351
        "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
352
        1, 0xffffffff,
353
354
355
	NICE_AGENT_TIMER_TA_DEFAULT,
        G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));

356
  /* note: according to spec recommendation in sect 5.7.3 (ID-19) */
357
358
359
360
361
  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
362
        0, 0xffffffff,
363
364
365
	0, /* default set in init */
        G_PARAM_READWRITE));

366
367
368
369
370
371
372
  /**
   * NiceAgent:proxy-ip:
   *
   * The proxy server IP used to bypass a proxy firewall
   *
   * Since: 0.0.4
   */
373
374
375
376
  g_object_class_install_property (gobject_class, PROP_PROXY_IP,
      g_param_spec_string (
        "proxy-ip",
        "Proxy server IP",
377
        "The proxy server IP used to bypass a proxy firewall",
378
379
380
        NULL,
        G_PARAM_READWRITE));

381
382
383
384
385
386
387
  /**
   * NiceAgent:proxy-port:
   *
   * The proxy server port used to bypass a proxy firewall
   *
   * Since: 0.0.4
   */
388
389
390
391
  g_object_class_install_property (gobject_class, PROP_PROXY_PORT,
      g_param_spec_uint (
        "proxy-port",
        "Proxy server port",
392
        "The Proxy server port used to bypass a proxy firewall",
393
394
395
396
        1, 65536,
	1,
        G_PARAM_READWRITE));

397
398
399
400
401
402
403
  /**
   * NiceAgent:proxy-type:
   *
   * The type of proxy set in the proxy-ip property
   *
   * Since: 0.0.4
   */
404
405
406
407
408
409
410
411
412
  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));

413
414
415
416
417
418
419
  /**
   * NiceAgent:proxy-username:
   *
   * The username used to authenticate with the proxy
   *
   * Since: 0.0.4
   */
420
421
422
423
424
425
426
427
  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));

428
429
430
431
432
433
434
  /**
   * NiceAgent:proxy-password:
   *
   * The password used to authenticate with the proxy
   *
   * Since: 0.0.4
   */
435
436
437
438
439
440
441
442
  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));

443
444
445
446
447
448
449
450
  /**
   * 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
451
452
453
   g_object_class_install_property (gobject_class, PROP_UPNP,
      g_param_spec_boolean (
        "upnp",
454
#ifdef HAVE_GUPNP
Youness Alaoui's avatar
Youness Alaoui committed
455
456
457
        "Use UPnP",
        "Whether the agent should use UPnP to open a port in the router and "
        "get the external IP",
458
459
460
461
#else
        "Use UPnP (disabled in build)",
        "Does nothing because libnice was not built with UPnP support",
#endif
Youness Alaoui's avatar
Youness Alaoui committed
462
463
464
	TRUE, /* enable UPnP by default */
        G_PARAM_READWRITE| G_PARAM_CONSTRUCT));

465
466
467
468
  /**
   * NiceAgent:upnp-timeout:
   *
   * The maximum amount of time to wait for UPnP discovery to finish before
469
   * signaling the #NiceAgent::candidate-gathering-done signal
470
471
472
   *
   * Since: 0.0.7
   */
Youness Alaoui's avatar
Youness Alaoui committed
473
474
475
  g_object_class_install_property (gobject_class, PROP_UPNP_TIMEOUT,
      g_param_spec_uint (
        "upnp-timeout",
476
#ifdef HAVE_GUPNP
Youness Alaoui's avatar
Youness Alaoui committed
477
478
479
        "Timeout for UPnP discovery",
        "The maximum amount of time to wait for UPnP discovery to finish before "
        "signaling the candidate-gathering-done signal",
480
481
482
483
#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
484
        100, 60000,
485
	DEFAULT_UPNP_TIMEOUT,
Youness Alaoui's avatar
Youness Alaoui committed
486
487
        G_PARAM_READWRITE | G_PARAM_CONSTRUCT));

Youness Alaoui's avatar
Youness Alaoui committed
488
489
490
491
492
493
494
495
  /**
   * NiceAgent:reliable:
   *
   * Whether the agent should use PseudoTcp to ensure a reliable transport
   * of messages
   *
   * Since: 0.0.11
   */
496
497
498
499
   g_object_class_install_property (gobject_class, PROP_RELIABLE,
      g_param_spec_boolean (
        "reliable",
        "reliable mode",
Youness Alaoui's avatar
Youness Alaoui committed
500
        "Whether the agent should use PseudoTcp to ensure a reliable transport"
501
502
503
504
        "of messages",
	FALSE,
        G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));

505
506
  /* install signals */

507
508
  /**
   * NiceAgent::component-state-changed
Youness Alaoui's avatar
Youness Alaoui committed
509
   * @agent: The #NiceAgent object
510
511
512
513
514
515
   * @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
   */
516
517
518
519
  signals[SIGNAL_COMPONENT_STATE_CHANGED] =
      g_signal_new (
          "component-state-changed",
          G_OBJECT_CLASS_TYPE (klass),
520
          G_SIGNAL_RUN_LAST,
521
522
523
524
525
526
527
528
          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);
529

530
531
  /**
   * NiceAgent::candidate-gathering-done:
Youness Alaoui's avatar
Youness Alaoui committed
532
   * @agent: The #NiceAgent object
533
534
535
536
537
   * @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()
   */
538
539
540
541
  signals[SIGNAL_CANDIDATE_GATHERING_DONE] =
      g_signal_new (
          "candidate-gathering-done",
          G_OBJECT_CLASS_TYPE (klass),
542
          G_SIGNAL_RUN_LAST,
543
544
545
          0,
          NULL,
          NULL,
546
          agent_marshal_VOID__UINT,
547
          G_TYPE_NONE,
548
549
          1,
          G_TYPE_UINT, G_TYPE_INVALID);
550

551
552
  /**
   * NiceAgent::new-selected-pair
Youness Alaoui's avatar
Youness Alaoui committed
553
   * @agent: The #NiceAgent object
554
555
556
557
558
559
560
561
   * @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
   */
562
563
564
565
  signals[SIGNAL_NEW_SELECTED_PAIR] =
      g_signal_new (
          "new-selected-pair",
          G_OBJECT_CLASS_TYPE (klass),
566
          G_SIGNAL_RUN_LAST,
567
568
569
570
571
572
573
574
575
          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);

576
577
  /**
   * NiceAgent::new-candidate
Youness Alaoui's avatar
Youness Alaoui committed
578
   * @agent: The #NiceAgent object
579
580
581
582
583
   * @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
584
   * <para> See also: #NiceAgent::candidate-gathering-done </para>
585
   */
586
587
588
589
  signals[SIGNAL_NEW_CANDIDATE] =
      g_signal_new (
          "new-candidate",
          G_OBJECT_CLASS_TYPE (klass),
590
          G_SIGNAL_RUN_LAST,
591
592
593
594
595
596
597
598
599
          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);

600
601
  /**
   * NiceAgent::new-remote-candidate
Youness Alaoui's avatar
Youness Alaoui committed
602
   * @agent: The #NiceAgent object
603
604
605
606
607
608
609
   * @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.
   */
610
611
612
613
  signals[SIGNAL_NEW_REMOTE_CANDIDATE] =
      g_signal_new (
          "new-remote-candidate",
          G_OBJECT_CLASS_TYPE (klass),
614
          G_SIGNAL_RUN_LAST,
615
616
617
618
619
620
621
622
623
          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);

624
625
  /**
   * NiceAgent::initial-binding-request-received
Youness Alaoui's avatar
Youness Alaoui committed
626
   * @agent: The #NiceAgent object
627
628
629
630
631
   * @stream_id: The ID of the stream
   *
   * This signal is fired when we received our first binding request from
   * the peer.
   */
632
633
634
635
  signals[SIGNAL_INITIAL_BINDING_REQUEST_RECEIVED] =
      g_signal_new (
          "initial-binding-request-received",
          G_OBJECT_CLASS_TYPE (klass),
636
          G_SIGNAL_RUN_LAST,
637
638
639
640
641
642
643
644
645
          0,
          NULL,
          NULL,
          agent_marshal_VOID__UINT,
          G_TYPE_NONE,
          1,
          G_TYPE_UINT,
          G_TYPE_INVALID);

646
647
  /**
   * NiceAgent::reliable-transport-writable
Youness Alaoui's avatar
Youness Alaoui committed
648
   * @agent: The #NiceAgent object
649
650
651
652
653
654
655
656
   * @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.
657
658
   *
   * Since: 0.0.11
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
   */
  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);

674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
  /**
   * 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);
698

699
700
  /* Init debug options depending on env variables */
  nice_debug_init ();
Dafydd Harries's avatar
Dafydd Harries committed
701
702
}

703
704
705
706
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
707
708
709
710
711
712

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

714
  /* set defaults; not construct params, so set here */
715
  agent->stun_server_port = DEFAULT_STUN_PORT;
716
  agent->controlling_mode = TRUE;
717
  agent->max_conn_checks = NICE_AGENT_MAX_CONNECTIVITY_CHECKS_DEFAULT;
718
719

  agent->discovery_list = NULL;
720
  agent->discovery_unsched_items = 0;
721
722
723
  agent->discovery_timer_source = NULL;
  agent->conncheck_timer_source = NULL;
  agent->keepalive_timer_source = NULL;
724
  agent->refresh_list = NULL;
725
  agent->media_after_tick = FALSE;
726
  agent->software_attribute = NULL;
727

728
  agent->compatibility = NICE_COMPATIBILITY_RFC5245;
729
  agent->reliable = FALSE;
730

731
  stun_agent_init (&agent->stun_agent, STUN_ALL_KNOWN_ATTRIBUTES,
732
      STUN_COMPATIBILITY_RFC5389,
733
734
735
      STUN_AGENT_USAGE_SHORT_TERM_CREDENTIALS |
      STUN_AGENT_USAGE_USE_FINGERPRINT);

Dafydd Harries's avatar
Dafydd Harries committed
736
  agent->rng = nice_rng_new ();
737
  priv_generate_tie_breaker (agent);
Dafydd Harries's avatar
Dafydd Harries committed
738
739
740
}


741
NICEAPI_EXPORT NiceAgent *
742
nice_agent_new (GMainContext *ctx, NiceCompatibility compat)
Dafydd Harries's avatar
Dafydd Harries committed
743
{
744
745
  NiceAgent *agent = g_object_new (NICE_TYPE_AGENT,
      "compatibility", compat,
746
      "main-context", ctx,
747
748
749
750
751
752
753
754
755
756
757
758
759
760
      "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
761
      NULL);
762
763

  return agent;
Dafydd Harries's avatar
Dafydd Harries committed
764
765
766
767
768
769
770
771
772
773
774
}


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
775

776
  agent_lock();
Youness Alaoui's avatar
Youness Alaoui committed
777

Dafydd Harries's avatar
Dafydd Harries committed
778
779
  switch (property_id)
    {
780
781
782
783
    case PROP_MAIN_CONTEXT:
      g_value_set_pointer (value, agent->main_context);
      break;

784
785
786
787
    case PROP_COMPATIBILITY:
      g_value_set_uint (value, agent->compatibility);
      break;

Dafydd Harries's avatar
Dafydd Harries committed
788
    case PROP_STUN_SERVER:
789
      g_value_set_string (value, agent->stun_server_ip);
790
      break;
791
792
793

    case PROP_STUN_SERVER_PORT:
      g_value_set_uint (value, agent->stun_server_port);
794
      break;
795

796
797
798
799
800
801
802
    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
803

804
805
806
807
    case PROP_STUN_PACING_TIMER:
      g_value_set_uint (value, agent->timer_ta);
      break;

808
809
810
811
812
    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;

813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
    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
833
    case PROP_UPNP:
834
#ifdef HAVE_GUPNP
Youness Alaoui's avatar
Youness Alaoui committed
835
      g_value_set_boolean (value, agent->upnp_enabled);
836
837
838
#else
      g_value_set_boolean (value, FALSE);
#endif
Youness Alaoui's avatar
Youness Alaoui committed
839
840
841
      break;

    case PROP_UPNP_TIMEOUT:
842
#ifdef HAVE_GUPNP
Youness Alaoui's avatar
Youness Alaoui committed
843
      g_value_set_uint (value, agent->upnp_timeout);
844
845
#else
      g_value_set_uint (value, DEFAULT_UPNP_TIMEOUT);
Youness Alaoui's avatar
Youness Alaoui committed
846
#endif
847
      break;
Youness Alaoui's avatar
Youness Alaoui committed
848

849
850
851
852
    case PROP_RELIABLE:
      g_value_set_boolean (value, agent->reliable);
      break;

Dafydd Harries's avatar
Dafydd Harries committed
853
854
855
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
    }
Youness Alaoui's avatar
Youness Alaoui committed
856

857
  agent_unlock();
Dafydd Harries's avatar
Dafydd Harries committed
858
859
860
861
862
863
864
865
866
867
868
869
}


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

870
  agent_lock();
Youness Alaoui's avatar
Youness Alaoui committed
871

Dafydd Harries's avatar
Dafydd Harries committed
872
873
  switch (property_id)
    {
874
875
    case PROP_MAIN_CONTEXT:
      agent->main_context = g_value_get_pointer (value);
876
877
      if (agent->main_context != NULL)
        g_main_context_ref (agent->main_context);
878
879
      break;

880
881
    case PROP_COMPATIBILITY:
      agent->compatibility = g_value_get_uint (value);
882
      if (agent->compatibility == NICE_COMPATIBILITY_GOOGLE) {
883
884
885
886
        stun_agent_init (&agent->stun_agent, STUN_ALL_KNOWN_ATTRIBUTES,
            STUN_COMPATIBILITY_RFC3489,
            STUN_AGENT_USAGE_SHORT_TERM_CREDENTIALS |
            STUN_AGENT_USAGE_IGNORE_CREDENTIALS);
887
      } else if (agent->compatibility == NICE_COMPATIBILITY_MSN) {
Youness Alaoui's avatar
Youness Alaoui committed
888
889
        stun_agent_init (&agent->stun_agent, STUN_ALL_KNOWN_ATTRIBUTES,
            STUN_COMPATIBILITY_RFC3489,
890
891
            STUN_AGENT_USAGE_SHORT_TERM_CREDENTIALS |
            STUN_AGENT_USAGE_FORCE_VALIDATER);
892
893
894
895
      } 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
896
            STUN_AGENT_USAGE_USE_FINGERPRINT);
897
898
899
900
901
902
      } 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
903
904
905
906
      } 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 |
907
908
            STUN_AGENT_USAGE_USE_FINGERPRINT |
            STUN_AGENT_USAGE_NO_ALIGNED_ATTRIBUTES);
909
910
911
912
913
      } 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);
914
      }
915
      stun_agent_set_software (&agent->stun_agent, agent->software_attribute);
916

917
918
      break;

Dafydd Harries's avatar
Dafydd Harries committed
919
    case PROP_STUN_SERVER:
920
      g_free (agent->stun_server_ip);
921
922
923
924
925
926
927
      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;

928
929
930
931
932
933
934
935
    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;

936
937
938
939
    case PROP_STUN_PACING_TIMER:
      agent->timer_ta = g_value_get_uint (value);
      break;

940
941
942
943
    case PROP_MAX_CONNECTIVITY_CHECKS:
      agent->max_conn_checks = g_value_get_uint (value);
      break;

944
    case PROP_PROXY_IP:
945
      g_free (agent->proxy_ip);
946
947
948
949
950
951
952
953
954
955
956
957
      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:
958
      g_free (agent->proxy_username);
959
960
961
962
      agent->proxy_username = g_value_dup_string (value);
      break;

    case PROP_PROXY_PASSWORD:
963
      g_free (agent->proxy_password);
964
965
966
      agent->proxy_password = g_value_dup_string (value);
      break;

Youness Alaoui's avatar
Youness Alaoui committed
967
    case PROP_UPNP_TIMEOUT:
968
#ifdef HAVE_GUPNP
Youness Alaoui's avatar
Youness Alaoui committed
969
      agent->upnp_timeout = g_value_get_uint (value);
970
#endif
Youness Alaoui's avatar
Youness Alaoui committed
971
972
973
      break;

    case PROP_UPNP:
974
#ifdef HAVE_GUPNP
Youness Alaoui's avatar
Youness Alaoui committed
975
976
      agent->upnp_enabled = g_value_get_boolean (value);
#endif
977
      break;
978
979
980
981
982

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

Dafydd Harries's avatar
Dafydd Harries committed
983
984
985
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
    }
Youness Alaoui's avatar
Youness Alaoui committed
986

987
  agent_unlock();
Youness Alaoui's avatar
Youness Alaoui committed
988

Dafydd Harries's avatar
Dafydd Harries committed
989
990
}

991
992
993
static void priv_pseudo_tcp_error (NiceAgent *agent, Stream *stream,
    Component *component)
{
994
995
996
997
998
  if (component->tcp_writable_cancellable) {
    g_cancellable_reset (component->tcp_writable_cancellable);
    g_clear_object (&component->tcp_writable_cancellable);
  }

999
1000
1001
  if (component->tcp) {
    agent_signal_component_state_change (agent, stream->id,
        component->id, NICE_COMPONENT_STATE_FAILED);
1002
    component_detach_all_sockets (component);
1003
    pseudo_tcp_socket_close (component->tcp, TRUE);
1004
    g_clear_object (&component->tcp);
1005
1006
1007
1008
1009
1010
  }

  if (component->tcp_clock) {
    g_source_destroy (component->tcp_clock);
    g_source_unref (component->tcp_clock);
    component->tcp_clock = NULL;
1011
1012
1013
1014
1015
  }
}

static void
adjust_tcp_clock (NiceAgent *agent, Stream *stream, Component *component);
1016
1017
1018
1019
1020


static void
pseudo_tcp_socket_opened (PseudoTcpSocket *sock, gpointer user_data)
{
1021
1022
1023
  Component *component = user_data;
  NiceAgent *agent = component->agent;
  Stream *stream = component->stream;
1024

1025
  nice_debug ("Agent %p: s%d:%d pseudo Tcp socket Opened", agent,
1026
      stream->id, component->id);
1027
  g_cancellable_cancel (component->tcp_writable_cancellable);
1028
1029
1030
1031
  g_signal_emit (agent, signals[SIGNAL_RELIABLE_TRANSPORT_WRITABLE], 0,
      stream->id, component->id);
}

1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
/* 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
 * a negative number on error. */
static gint
pseudo_tcp_socket_send_messages (PseudoTcpSocket *self,
    const NiceOutputMessage *messages, guint n_messages, GError **error)
{
  guint i;

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

    /* If 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
     * and indicating that a message was partially sent. */
1054
1055
    if (output_message_get_size (message) >
        pseudo_tcp_socket_get_available_send_space (self)) {
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
      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 */
      if (ret < 0 && pseudo_tcp_socket_get_error (self) == EWOULDBLOCK) {
        ret = 0;
        return i;
      } else if (ret < 0 && 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.");
        return ret;
      } else if (ret < 0) {
        g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
            "Error writing data to pseudo-TCP socket.");
        return ret;
      }
    }
  }

  return i;
}

1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
/* 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);
}

1156
/* This is called with the agent lock held. */
1157
1158
1159
static void
pseudo_tcp_socket_readable (PseudoTcpSocket *sock, gpointer user_data)
{
1160
1161
1162
  Component *component = user_data;
  NiceAgent *agent = component->agent;
  Stream *stream = component->stream;
1163
  gboolean has_io_callback;
1164
1165
1166
1167

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

1168
1169
  component->tcp_readable = TRUE;

1170
1171
  g_object_add_weak_pointer (G_OBJECT (sock), (gpointer *)&sock);
  g_object_add_weak_pointer (G_OBJECT (agent), (gpointer *)&agent);
1172
  has_io_callback = component_has_io_callback (component);
1173

1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
  /* 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? */
1185
      len = pseudo_tcp_socket_recv (sock, (gchar *) buf, sizeof(buf));
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
      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;
      }
1214

1215
      component_emit_io_callback (component, buf, len);
1216

1217
1218
1219
1220
      if (sock == NULL) {
        nice_debug ("PseudoTCP socket got destroyed in readable callback!");
        break;
      }
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236

      has_io_callback = component_has_io_callback (component);
    } while (has_io_callback);
  } else if (component->recv_messages != NULL) {
    gint n_valid_messages;

    /* Fill up every buffer in every message until the connection closes or an
     * error occurs. Copy the data directly into the client’s receive message
     * array without making any callbacks. Update component->recv_messages_iter
     * as we go. */
    n_valid_messages = pseudo_tcp_socket_recv_messages (sock,
        component->recv_messages, component->n_recv_messages,
        &component->recv_messages_iter, component->recv_buf_error);

    nice_debug ("%s: Client buffers case: Received %d valid messages:",
        G_STRFUNC, n_valid_messages);
1237
    nice_debug_input_message_composition (component->recv_messages,
1238
1239
1240
        component->n_recv_messages);

    if (n_valid_messages < 0) {
1241
      nice_debug ("%s: calling priv_pseudo_tcp_error()", G_STRFUNC);
1242
      priv_pseudo_tcp_error (agent, stream, component);
1243
    } else if (n_valid_messages == 0) {
1244
      component->tcp_readable = FALSE;
1245
    }
1246
1247
1248
  } else {
    nice_debug ("%s: no data read", G_STRFUNC);
  }
1249

1250
  if (agent) {
1251
    adjust_tcp_clock (agent, stream, component);
1252
1253
    g_object_remove_weak_pointer (G_OBJECT (agent), (gpointer *)&agent);
  } else {
1254
    nice_debug ("Not calling adjust_tcp_clock.. agent got destroyed!");
1255
1256
1257
  }
  if (sock)
    g_object_remove_weak_pointer (G_OBJECT (sock), (gpointer *)&sock);
1258
1259
1260
1261
1262
}

static void
pseudo_tcp_socket_writable (PseudoTcpSocket *sock, gpointer user_data)
{
1263
1264
1265
  Component *component = user_data;
  NiceAgent *agent = component->agent;
  Stream *stream = component->stream;
1266

1267
1268
  nice_debug ("Agent %p: s%d:%d pseudo Tcp socket writable", agent,
      stream->id, component->id);
1269
  g_cancellable_cancel (component->tcp_writable_cancellable);
1270
1271
1272
1273
1274
1275
1276
1277
  g_signal_emit (agent, signals[SIGNAL_RELIABLE_TRANSPORT_WRITABLE], 0,
      stream->id, component->id);
}

static void
pseudo_tcp_socket_closed (PseudoTcpSocket *sock, guint32 err,
    gpointer user_data)
{
1278
1279
1280
  Component *component = user_data;
  NiceAgent *agent = component->agent;
  Stream *stream = component->stream;
1281

1282
1283
  nice_debug ("Agent %p: s%d:%d pseudo Tcp socket closed. "
      "Calling priv_pseudo_tcp_error().",  agent, stream->id, component->id);
1284
  priv_pseudo_tcp_error (agent, stream, component);
1285
1286
1287
1288
}


static PseudoTcpWriteResult
Philip Withnall's avatar
Philip Withnall committed
1289
pseudo_tcp_socket_write_packet (PseudoTcpSocket *socket,
1290
1291
    const gchar *buffer, guint32 len, gpointer user_data)