discovery.c 40.3 KB
Newer Older
1
2
3
/*
 * This file is part of the Nice GLib ICE library.
 *
4
5
6
 * (C) 2008-2009 Collabora Ltd.
 *  Contact: Youness Alaoui
 * (C) 2007-2009 Nokia Corporation. All rights reserved.
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 *  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:
25
 *   Youness Alaoui, Collabora Ltd.
26
27
28
29
30
31
32
33
34
35
36
37
38
 *   Kai Vehmanen, Nokia
 *
 * 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.
 */

39
/*
40
41
42
 * @file discovery.c
 * @brief ICE candidate discovery functions
 */
43

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

48
49
#include <glib.h>

50
51
52
#include <stdlib.h>
#include <string.h>
#include <errno.h>
53

54
55
#include "debug.h"

56
57
58
59
#include "agent.h"
#include "agent-priv.h"
#include "component.h"
#include "discovery.h"
60
61
#include "stun/usages/bind.h"
#include "stun/usages/turn.h"
62
#include "socket.h"
63

64
static inline int priv_timer_expired (GTimeVal *timer, GTimeVal *now)
65
66
67
68
69
70
{
  return (now->tv_sec == timer->tv_sec) ?
    now->tv_usec >= timer->tv_usec :
    now->tv_sec >= timer->tv_sec;
}

71
/*
72
 * Frees the CandidateDiscovery structure pointed to
73
 * by 'user data'. Compatible with g_slist_free_full().
74
 */
75
static void discovery_free_item (CandidateDiscovery *cand)
76
{
77
78
79
  if (cand->turn)
    turn_server_unref (cand->turn);

80
81
82
  g_slice_free (CandidateDiscovery, cand);
}

83
/*
84
85
86
87
 * Frees all discovery related resources for the agent.
 */
void discovery_free (NiceAgent *agent)
{
88
89
  g_slist_free_full (agent->discovery_list,
      (GDestroyNotify) discovery_free_item);
90
91
  agent->discovery_list = NULL;
  agent->discovery_unsched_items = 0;
92

93
94
95
96
97
  if (agent->discovery_timer_source != NULL) {
    g_source_destroy (agent->discovery_timer_source);
    g_source_unref (agent->discovery_timer_source);
    agent->discovery_timer_source = NULL;
  }
98
99
}

100
/*
101
 * Prunes the list of discovery processes for items related
Youness Alaoui's avatar
Youness Alaoui committed
102
 * to stream 'stream_id'.
103
104
105
 *
 * @return TRUE on success, FALSE on a fatal error
 */
106
void discovery_prune_stream (NiceAgent *agent, guint stream_id)
107
108
109
110
{
  GSList *i;

  for (i = agent->discovery_list; i ; ) {
111
112
    CandidateDiscovery *cand = i->data;
    GSList *next = i->next;
113

114
    if (cand->stream_id == stream_id) {
115
      agent->discovery_list = g_slist_remove (agent->discovery_list, cand);
116
      discovery_free_item (cand);
117
    }
118
    i = next;
119
120
  }

121
122
123
124
125
126
  if (agent->discovery_list == NULL) {
    /* noone using the timer anymore, clean it up */
    discovery_free (agent);
  }
}

127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
/*
 * Prunes the list of discovery processes for items related
 * to socket @sock.
 *
 * @return TRUE on success, FALSE on a fatal error
 */
void discovery_prune_socket (NiceAgent *agent, NiceSocket *sock)
{
  GSList *i;

  for (i = agent->discovery_list; i ; ) {
    CandidateDiscovery *discovery = i->data;
    GSList *next = i->next;

    if (discovery->nicesock == sock) {
      agent->discovery_list = g_slist_remove (agent->discovery_list, discovery);
      discovery_free_item (discovery);
    }
    i = next;
  }

  if (agent->discovery_list == NULL) {
    /* noone using the timer anymore, clean it up */
    discovery_free (agent);
  }
}

154
155
156
157
158
159
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
/*
 * Frees a CandidateRefresh and calls destroy callback if it has been set.
 */
void refresh_free (NiceAgent *agent, CandidateRefresh *cand)
{
  nice_debug ("Freeing candidate refresh %p", cand);

  agent->refresh_list = g_slist_remove (agent->refresh_list, cand);

  if (cand->timer_source != NULL) {
    g_source_destroy (cand->timer_source);
    g_clear_pointer (&cand->timer_source, g_source_unref);
  }

  if (cand->tick_source) {
    g_source_destroy (cand->tick_source);
    g_clear_pointer (&cand->tick_source, g_source_unref);
  }

  if (cand->destroy_cb) {
    cand->destroy_cb (cand->destroy_cb_data);
  }

  g_slice_free (CandidateRefresh, cand);
}

static gboolean on_refresh_remove_timeout (NiceAgent *agent,
    CandidateRefresh *cand)
{
  switch (stun_timer_refresh (&cand->timer)) {
    case STUN_USAGE_TIMER_RETURN_TIMEOUT:
      {
        StunTransactionId id;

        nice_debug ("TURN deallocate for refresh %p timed out", cand);

        stun_message_id (&cand->stun_message, id);
        stun_agent_forget_transaction (&cand->stun_agent, id);

        refresh_free (agent, cand);
        break;
      }
    case STUN_USAGE_TIMER_RETURN_RETRANSMIT:
      nice_debug ("Retransmitting TURN deallocate for refresh %p", cand);

      agent_socket_send (cand->nicesock, &cand->server,
          stun_message_length (&cand->stun_message), (gchar *)cand->stun_buffer);

      G_GNUC_FALLTHROUGH;
    case STUN_USAGE_TIMER_RETURN_SUCCESS:
      agent_timeout_add_with_context (agent, &cand->tick_source,
          "TURN deallocate retransmission", stun_timer_remainder (&cand->timer),
          (NiceTimeoutLockedCallback) on_refresh_remove_timeout, cand);
      break;
    default:
      break;
  }

  return G_SOURCE_REMOVE;
}
214

215
/*
216
217
218
 * Closes the port associated with the candidate refresh on the TURN server by
 * sending a refresh request that has zero lifetime. After a response is
 * received or the request times out, 'cand' gets freed and 'cb' is called.
219
 */
220
221
static gboolean refresh_remove_async (NiceAgent *agent, CandidateRefresh *cand,
    GDestroyNotify cb, gpointer cb_data)
222
{
223
  uint8_t *username;
224
  gsize username_len;
225
  uint8_t *password;
226
  gsize password_len;
227
  size_t buffer_len = 0;
228
  StunUsageTurnCompatibility turn_compat = agent_to_turn_compatibility (agent);
229

230
231
232
233
234
235
236
  if (cand->disposing) {
    return FALSE;
  }

  nice_debug ("Sending request to remove TURN allocation for refresh %p", cand);

  cand->disposing = TRUE;
237

238
239
240
241
242
243
  if (cand->timer_source != NULL) {
    g_source_destroy (cand->timer_source);
    g_source_unref (cand->timer_source);
    cand->timer_source = NULL;
  }

244
245
246
247
  username = (uint8_t *)cand->candidate->turn->username;
  username_len = (size_t) strlen (cand->candidate->turn->username);
  password = (uint8_t *)cand->candidate->turn->password;
  password_len = (size_t) strlen (cand->candidate->turn->password);
248

249
250
  if (turn_compat == STUN_USAGE_TURN_COMPATIBILITY_MSN ||
      turn_compat == STUN_USAGE_TURN_COMPATIBILITY_OC2007) {
251
252
253
254
    username = cand->candidate->turn->decoded_username;
    password = cand->candidate->turn->decoded_password;
    username_len = cand->candidate->turn->decoded_username_len;
    password_len = cand->candidate->turn->decoded_password_len;
255
256
  }

257
  buffer_len = stun_usage_turn_create_refresh (&cand->stun_agent,
258
259
260
261
      &cand->stun_message,  cand->stun_buffer, sizeof(cand->stun_buffer),
      cand->stun_resp_msg.buffer == NULL ? NULL : &cand->stun_resp_msg, 0,
      username, username_len,
      password, password_len,
262
      agent_to_turn_compatibility (agent));
263
264

  if (buffer_len > 0) {
265
266
    agent_socket_send (cand->nicesock, &cand->server, buffer_len,
        (gchar *)cand->stun_buffer);
267

268
269
    stun_timer_start (&cand->timer, agent->stun_initial_timeout,
        agent->stun_max_retransmissions);
270

271
272
273
    agent_timeout_add_with_context (agent, &cand->tick_source,
        "TURN deallocate retransmission", stun_timer_remainder (&cand->timer),
        (NiceTimeoutLockedCallback) on_refresh_remove_timeout, cand);
274
275
  }

276
277
278
279
  cand->destroy_cb = cb;
  cand->destroy_cb_data = cb_data;

  return TRUE;
280
281
}

282
283
284
285
286
287
288
289
290
291
292
293
294
295
typedef struct {
  NiceAgent *agent;
  gpointer user_data;
  guint items_to_free;
  NiceTimeoutLockedCallback cb;
} RefreshPruneAsyncData;

static void on_refresh_removed (RefreshPruneAsyncData *data)
{
  if (data->items_to_free == 0 || --(data->items_to_free) == 0) {
    GSource *timeout_source = NULL;
    agent_timeout_add_with_context (data->agent, &timeout_source,
        "Async refresh prune", 0, data->cb, data->user_data);

Fabrice Bellet's avatar
Fabrice Bellet committed
296
    g_source_unref (timeout_source);
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
    g_free (data);
  }
}

static void refresh_prune_async (NiceAgent *agent, GSList *refreshes,
  NiceTimeoutLockedCallback function, gpointer user_data)
{
  RefreshPruneAsyncData *data = g_new0 (RefreshPruneAsyncData, 1);
  GSList *it;

  data->agent = agent;
  data->user_data = user_data;
  data->cb = function;

  for (it = refreshes; it; it = it->next) {
    if (refresh_remove_async (agent, it->data,
        (GDestroyNotify) on_refresh_removed, data)) {
      ++data->items_to_free;
    }
  }

  if (data->items_to_free == 0) {
    /* Stream doesn't have any refreshes to remove. Invoke our callback once to
     * schedule client's callback function. */
    on_refresh_removed (data);
  }
}

void refresh_prune_agent_async (NiceAgent *agent,
326
    NiceTimeoutLockedCallback function, gpointer user_data)
327
{
328
  refresh_prune_async (agent, agent->refresh_list, function, user_data);
329
330
}

331
/*
332
333
334
 * Removes the candidate refreshes related to 'stream' and asynchronously
 * closes the associated port allocations on TURN server. Invokes 'function'
 * when the process finishes.
335
 */
336
337
void refresh_prune_stream_async (NiceAgent *agent, NiceStream *stream,
    NiceTimeoutLockedCallback function)
338
{
339
  GSList *refreshes = NULL;
340
341
  GSList *i;

342
  for (i = agent->refresh_list; i ; i = i->next) {
343
344
    CandidateRefresh *cand = i->data;

345
346
347
    /* Don't free the candidate refresh to the currently selected local candidate
     * unless the whole pair is being destroyed.
     */
348
349
    if (cand->stream_id == stream->id) {
      refreshes = g_slist_append (refreshes, cand);
350
351
352
    }
  }

353
354
  refresh_prune_async (agent, refreshes, function, stream);
  g_slist_free (refreshes);
355
356
}

357
358
359
360
361
362
/*
 * Removes the candidate refreshes related to 'candidate'. The function does not
 * close any associated port allocations on TURN server. Its purpose is in
 * situations when an error is detected in socket communication that prevents
 * sending more requests to the server.
 */
363
364
365
366
367
368
369
370
371
void refresh_prune_candidate (NiceAgent *agent, NiceCandidate *candidate)
{
  GSList *i;

  for (i = agent->refresh_list; i;) {
    GSList *next = i->next;
    CandidateRefresh *refresh = i->data;

    if (refresh->candidate == candidate) {
372
      refresh_free(agent, refresh);
373
374
375
376
377
378
    }

    i = next;
  }
}

379
380
381
382
383
384
385
/*
 * Removes the candidate refreshes related to 'candidate' and asynchronously
 * closes the associated port allocations on TURN server. Invokes 'function'
 * when the process finishes.
 */
void refresh_prune_candidate_async (NiceAgent *agent, NiceCandidate *candidate,
    NiceTimeoutLockedCallback function)
386
{
387
388
  GSList *refreshes = NULL;
  GSList *i;
389

390
391
392
393
394
395
396
397
398
399
400
  for (i = agent->refresh_list; i; i = i->next) {
    CandidateRefresh *refresh = i->data;

    if (refresh->candidate == candidate) {
      refreshes = g_slist_append (refreshes, refresh);
    }
  }

  refresh_prune_async (agent, refreshes, function, candidate);
  g_slist_free (refreshes);
}
401

402
/*
403
 * Adds a new local candidate. Implements the candidate pruning
404
 * defined in ICE spec section 4.1.3 "Eliminating Redundant
405
 * Candidates" (ID-19).
406
 */
407
static gboolean priv_add_local_candidate_pruned (NiceAgent *agent, guint stream_id, NiceComponent *component, NiceCandidate *candidate)
408
{
409
  GSList *i;
410

411
412
  g_assert (candidate != NULL);

413
414
  for (i = component->local_candidates; i ; i = i->next) {
    NiceCandidate *c = i->data;
415

416
    if (nice_address_equal (&c->base_addr, &candidate->base_addr) &&
417
418
        nice_address_equal (&c->addr, &candidate->addr) &&
        c->transport == candidate->transport) {
419
      nice_debug ("Candidate %p (component-id %u) redundant, ignoring.", candidate, component->id);
420
421
422
423
      return FALSE;
    }
  }

424
425
  component->local_candidates = g_slist_append (component->local_candidates,
      candidate);
426
  conn_check_add_for_local_candidate(agent, stream_id, component, candidate);
427
428
429
430

  return TRUE;
}

431
static guint priv_highest_remote_foundation (NiceComponent *component)
432
433
434
435
436
437
438
439
{
  GSList *i;
  guint highest = 1;
  gchar foundation[NICE_CANDIDATE_MAX_FOUNDATION];

  for (highest = 1;; highest++) {
    gboolean taken = FALSE;

440
    g_snprintf (foundation, NICE_CANDIDATE_MAX_FOUNDATION, "remote%u",
441
        highest);
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
    for (i = component->remote_candidates; i; i = i->next) {
      NiceCandidate *cand = i->data;
      if (strncmp (foundation, cand->foundation,
              NICE_CANDIDATE_MAX_FOUNDATION) == 0) {
        taken = TRUE;
        break;
      }
    }
    if (!taken)
      return highest;
  }

  g_return_val_if_reached (highest);
}

457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
/* From RFC 5245 section 4.1.3:
 *
 *   for reflexive and relayed candidates, the STUN or TURN servers
 *   used to obtain them have the same IP address.
 */
static gboolean
priv_compare_turn_servers (TurnServer *turn1, TurnServer *turn2)
{
  if (turn1 == turn2)
    return TRUE;
  if (turn1 == NULL || turn2 == NULL)
    return FALSE;

  return nice_address_equal_no_port (&turn1->server, &turn2->server);
}

473
/*
474
475
 * Assings a foundation to the candidate.
 *
476
 * Implements the mechanism described in ICE sect
477
 * 4.1.1.3 "Computing Foundations" (ID-19).
478
 */
479
static void priv_assign_foundation (NiceAgent *agent, NiceCandidate *candidate)
480
{
481
482
483
  GSList *i, *j, *k;

  for (i = agent->streams; i; i = i->next) {
484
    NiceStream *stream = i->data;
485
    for (j = stream->components; j; j = j->next) {
486
      NiceComponent *component = j->data;
487
488
      for (k = component->local_candidates; k; k = k->next) {
	NiceCandidate *n = k->data;
489
490
491
492

	/* note: candidate must not on the local candidate list */
	g_assert (candidate != n);

493
	if (candidate->type == n->type &&
494
            candidate->transport == n->transport &&
495
	    nice_address_equal_no_port (&candidate->base_addr, &n->base_addr) &&
496
497
            (candidate->type != NICE_CANDIDATE_TYPE_RELAYED ||
                priv_compare_turn_servers (candidate->turn, n->turn)) &&
498
            !(agent->compatibility == NICE_COMPATIBILITY_GOOGLE &&
499
                n->type == NICE_CANDIDATE_TYPE_RELAYED)) {
500
	  /* note: currently only one STUN server per stream at a
501
502
	   *       time is supported, so there is no need to check
	   *       for candidates that would otherwise share the
503
	   *       foundation, but have different STUN servers */
504
505
	  g_strlcpy (candidate->foundation, n->foundation,
              NICE_CANDIDATE_MAX_FOUNDATION);
506
507
508
509
510
511
512
513
          if (n->username) {
            g_free (candidate->username);
            candidate->username = g_strdup (n->username);
          }
          if (n->password) {
            g_free (candidate->password);
            candidate->password = g_strdup (n->password);
          }
514
515
516
	  return;
	}
      }
517
518
    }
  }
Youness Alaoui's avatar
Youness Alaoui committed
519

520
521
  g_snprintf (candidate->foundation, NICE_CANDIDATE_MAX_FOUNDATION,
      "%u", agent->next_candidate_id++);
522
523
}

524
525
526
527
static void priv_assign_remote_foundation (NiceAgent *agent, NiceCandidate *candidate)
{
  GSList *i, *j, *k;
  guint next_remote_id;
528
  NiceComponent *component = NULL;
529
530

  for (i = agent->streams; i; i = i->next) {
531
    NiceStream *stream = i->data;
532
    for (j = stream->components; j; j = j->next) {
533
      NiceComponent *c = j->data;
534
535
536
537
538
539
540
541
542
543
544

      if (c->id == candidate->component_id)
        component = c;

      for (k = c->remote_candidates; k; k = k->next) {
	NiceCandidate *n = k->data;

	/* note: candidate must not on the remote candidate list */
	g_assert (candidate != n);

	if (candidate->type == n->type &&
545
            candidate->transport == n->transport &&
546
            candidate->stream_id == n->stream_id &&
547
	    nice_address_equal_no_port (&candidate->addr, &n->addr)) {
548
549
550
	  /* note: No need to check for STUN/TURN servers, as these candidate
           * will always be peer reflexive, never relayed or serve reflexive.
           */
551
552
	  g_strlcpy (candidate->foundation, n->foundation,
              NICE_CANDIDATE_MAX_FOUNDATION);
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
          if (n->username) {
            g_free (candidate->username);
            candidate->username = g_strdup (n->username);
          }
          if (n->password) {
            g_free (candidate->password);
            candidate->password = g_strdup (n->password);
          }
	  return;
	}
      }
    }
  }

  if (component) {
    next_remote_id = priv_highest_remote_foundation (component);
    g_snprintf (candidate->foundation, NICE_CANDIDATE_MAX_FOUNDATION,
570
        "remote%u", next_remote_id);
571
572
573
574
  }
}


575
static
576
577
void priv_generate_candidate_credentials (NiceAgent *agent,
    NiceCandidate *candidate)
578
579
{

Jakub Adam's avatar
Jakub Adam committed
580
581
  if (agent->compatibility == NICE_COMPATIBILITY_MSN ||
      agent->compatibility == NICE_COMPATIBILITY_OC2007) {
582
583
584
    guchar username[32];
    guchar password[16];

Olivier Crête's avatar
Olivier Crête committed
585
586
    g_free (candidate->username);
    g_free (candidate->password);
587
588
589
590
591
592
593

    nice_rng_generate_bytes (agent->rng, 32, (gchar *)username);
    nice_rng_generate_bytes (agent->rng, 16, (gchar *)password);

    candidate->username = g_base64_encode (username, 32);
    candidate->password = g_base64_encode (password, 16);

594
595
596
  } else if (agent->compatibility == NICE_COMPATIBILITY_GOOGLE) {
    gchar username[16];

Olivier Crête's avatar
Olivier Crête committed
597
598
    g_free (candidate->username);
    g_free (candidate->password);
599
600
601
602
    candidate->password = NULL;

    nice_rng_generate_bytes_print (agent->rng, 16, (gchar *)username);

603
    candidate->username = g_strndup (username, 16);
604
605
606
607
608
  }


}

609
/*
610
611
612
613
614
 * Creates a local host candidate for 'component_id' of stream
 * 'stream_id'.
 *
 * @return pointer to the created candidate, or NULL on error
 */
615
HostCandidateResult discovery_add_local_host_candidate (
616
617
618
  NiceAgent *agent,
  guint stream_id,
  guint component_id,
619
  NiceAddress *address,
620
621
  NiceCandidateTransport transport,
  NiceCandidate **outcandidate)
622
623
{
  NiceCandidate *candidate;
624
  NiceComponent *component;
625
  NiceStream *stream;
626
  NiceSocket *nicesock = NULL;
627
  HostCandidateResult res = HOST_CANDIDATE_FAILED;
628
629

  if (!agent_find_component (agent, stream_id, component_id, &stream, &component))
630
    return res;
631
632

  candidate = nice_candidate_new (NICE_CANDIDATE_TYPE_HOST);
633
  candidate->transport = transport;
634
635
636
637
638
639
  candidate->stream_id = stream_id;
  candidate->component_id = component_id;
  candidate->addr = *address;
  candidate->base_addr = *address;
  if (agent->compatibility == NICE_COMPATIBILITY_GOOGLE) {
    candidate->priority = nice_candidate_jingle_priority (candidate);
Jakub Adam's avatar
Jakub Adam committed
640
641
  } else if (agent->compatibility == NICE_COMPATIBILITY_MSN ||
             agent->compatibility == NICE_COMPATIBILITY_OC2007)  {
642
    candidate->priority = nice_candidate_msn_priority (candidate);
643
644
645
  } else if (agent->compatibility == NICE_COMPATIBILITY_OC2007R2) {
    candidate->priority =  nice_candidate_ms_ice_priority (candidate,
        agent->reliable, FALSE);
646
  } else {
647
648
    candidate->priority = nice_candidate_ice_priority (candidate,
        agent->reliable, FALSE);
649
  }
650

651
  candidate->priority = ensure_unique_priority (stream, component,
652
      candidate->priority);
653
654
655
656
657
  priv_generate_candidate_credentials (agent, candidate);
  priv_assign_foundation (agent, candidate);

  /* note: candidate username and password are left NULL as stream
     level ufrag/password are used */
658
659
  if (transport == NICE_CANDIDATE_TRANSPORT_UDP) {
    nicesock = nice_udp_bsd_socket_new (address);
Youness Alaoui's avatar
Youness Alaoui committed
660
  } else if (transport == NICE_CANDIDATE_TRANSPORT_TCP_ACTIVE) {
661
    nicesock = nice_tcp_active_socket_new (agent->main_context, address);
Youness Alaoui's avatar
Youness Alaoui committed
662
  } else if (transport == NICE_CANDIDATE_TRANSPORT_TCP_PASSIVE) {
663
    nicesock = nice_tcp_passive_socket_new (agent->main_context, address);
664
  } else {
Youness Alaoui's avatar
Youness Alaoui committed
665
    /* TODO: Add TCP-SO */
666
  }
667
668
  if (!nicesock) {
    res = HOST_CANDIDATE_CANT_CREATE_SOCKET;
669
    goto errors;
670
  }
671

672
673
674
  candidate->sockptr = nicesock;
  candidate->addr = nicesock->addr;
  candidate->base_addr = nicesock->addr;
675

676
677
678
  if (!priv_add_local_candidate_pruned (agent, stream_id, component,
          candidate)) {
    res = HOST_CANDIDATE_REDUNDANT;
679
    goto errors;
680
  }
681

682
  _priv_set_socket_tos (agent, nicesock, stream->tos);
683
  nice_component_attach_socket (component, nicesock);
Youness Alaoui's avatar
Youness Alaoui committed
684

685
686
687
  *outcandidate = candidate;

  return HOST_CANDIDATE_SUCCESS;
688
689
690

errors:
  nice_candidate_free (candidate);
691
692
  if (nicesock)
    nice_socket_free (nicesock);
693
  return res;
694
695
}

696
/*
697
698
699
700
701
 * Creates a server reflexive candidate for 'component_id' of stream
 * 'stream_id'.
 *
 * @return pointer to the created candidate, or NULL on error
 */
Youness Alaoui's avatar
Youness Alaoui committed
702
NiceCandidate*
703
704
705
706
707
discovery_add_server_reflexive_candidate (
  NiceAgent *agent,
  guint stream_id,
  guint component_id,
  NiceAddress *address,
708
  NiceCandidateTransport transport,
709
710
  NiceSocket *base_socket,
  gboolean nat_assisted)
711
712
{
  NiceCandidate *candidate;
713
  NiceComponent *component;
714
  NiceStream *stream;
715
  gboolean result = FALSE;
716
717
718
719
720

  if (!agent_find_component (agent, stream_id, component_id, &stream, &component))
    return NULL;

  candidate = nice_candidate_new (NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE);
721
722
723
724
  candidate->transport = transport;
  candidate->stream_id = stream_id;
  candidate->component_id = component_id;
  candidate->addr = *address;
725

726
727
728
729
  /* step: link to the base candidate+socket */
  candidate->sockptr = base_socket;
  candidate->base_addr = base_socket->addr;

730
731
  if (agent->compatibility == NICE_COMPATIBILITY_GOOGLE) {
    candidate->priority = nice_candidate_jingle_priority (candidate);
Jakub Adam's avatar
Jakub Adam committed
732
733
  } else if (agent->compatibility == NICE_COMPATIBILITY_MSN ||
             agent->compatibility == NICE_COMPATIBILITY_OC2007)  {
734
    candidate->priority = nice_candidate_msn_priority (candidate);
735
736
737
  } else if (agent->compatibility == NICE_COMPATIBILITY_OC2007R2) {
    candidate->priority =  nice_candidate_ms_ice_priority (candidate,
        agent->reliable, nat_assisted);
738
  } else {
739
740
    candidate->priority =  nice_candidate_ice_priority (candidate,
        agent->reliable, nat_assisted);
741
  }
742

743
  candidate->priority = ensure_unique_priority (stream, component,
744
      candidate->priority);
745
746
  priv_generate_candidate_credentials (agent, candidate);
  priv_assign_foundation (agent, candidate);
747

748
  result = priv_add_local_candidate_pruned (agent, stream_id, component, candidate);
749
750
751
752
753
754
  if (result) {
    agent_signal_new_candidate (agent, candidate);
  }
  else {
    /* error: duplicate candidate */
    nice_candidate_free (candidate), candidate = NULL;
755
756
757
758
759
  }

  return candidate;
}

760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
/*
 * Creates a server reflexive candidate for 'component_id' of stream
 * 'stream_id' for each TCP_PASSIVE and TCP_ACTIVE candidates for each
 * base address.
 *
 * @return pointer to the created candidate, or NULL on error
 */
void
discovery_discover_tcp_server_reflexive_candidates (
  NiceAgent *agent,
  guint stream_id,
  guint component_id,
  NiceAddress *address,
  NiceSocket *base_socket)
{
775
  NiceComponent *component;
776
  NiceStream *stream;
777
778
779
780
781
782
783
784
785
786
787
788
789
  NiceAddress base_addr = base_socket->addr;
  GSList *i;

  if (!agent_find_component (agent, stream_id, component_id, &stream, &component))
    return;

  nice_address_set_port (&base_addr, 0);
  for (i = component->local_candidates; i; i = i ->next) {
    NiceCandidate *c = i->data;
    NiceAddress caddr;

    caddr = c->addr;
    nice_address_set_port (&caddr, 0);
790
791
    if (agent->force_relay == FALSE &&
        c->transport != NICE_CANDIDATE_TRANSPORT_UDP &&
792
793
794
795
796
797
798
799
800
801
802
803
804
805
        c->type == NICE_CANDIDATE_TYPE_HOST &&
        nice_address_equal (&base_addr, &caddr)) {
      nice_address_set_port (address, nice_address_get_port (&c->addr));
      discovery_add_server_reflexive_candidate (
          agent,
          stream_id,
          component_id,
          address,
          c->transport,
          c->sockptr,
          FALSE);
    }
  }
}
806

807
/*
808
809
810
811
812
 * Creates a server reflexive candidate for 'component_id' of stream
 * 'stream_id'.
 *
 * @return pointer to the created candidate, or NULL on error
 */
813
NiceCandidate*
814
815
816
817
818
discovery_add_relay_candidate (
  NiceAgent *agent,
  guint stream_id,
  guint component_id,
  NiceAddress *address,
819
  NiceCandidateTransport transport,
820
821
  NiceSocket *base_socket,
  TurnServer *turn)
822
823
{
  NiceCandidate *candidate;
824
  NiceComponent *component;
825
  NiceStream *stream;
826
  NiceSocket *relay_socket = NULL;
827
828
829
830
831

  if (!agent_find_component (agent, stream_id, component_id, &stream, &component))
    return NULL;

  candidate = nice_candidate_new (NICE_CANDIDATE_TYPE_RELAYED);
832
833
834
835
836
  candidate->transport = transport;
  candidate->stream_id = stream_id;
  candidate->component_id = component_id;
  candidate->addr = *address;
  candidate->turn = turn_server_ref (turn);
837

838
839
840
841
842
843
844
845
846
847
848
  /* step: link to the base candidate+socket */
  relay_socket = nice_udp_turn_socket_new (agent->main_context, address,
      base_socket, &turn->server,
      turn->username, turn->password,
      agent_to_turn_socket_compatibility (agent));
  if (!relay_socket)
    goto errors;

  candidate->sockptr = relay_socket;
  candidate->base_addr = base_socket->addr;

849
850
  if (agent->compatibility == NICE_COMPATIBILITY_GOOGLE) {
    candidate->priority = nice_candidate_jingle_priority (candidate);
Jakub Adam's avatar
Jakub Adam committed
851
852
  } else if (agent->compatibility == NICE_COMPATIBILITY_MSN ||
             agent->compatibility == NICE_COMPATIBILITY_OC2007)  {
853
    candidate->priority = nice_candidate_msn_priority (candidate);
854
855
856
  } else if (agent->compatibility == NICE_COMPATIBILITY_OC2007R2) {
    candidate->priority =  nice_candidate_ms_ice_priority (candidate,
        agent->reliable, FALSE);
857
  } else {
858
859
    candidate->priority =  nice_candidate_ice_priority (candidate,
        agent->reliable, FALSE);
860
861
  }

862
  candidate->priority = ensure_unique_priority (stream, component,
863
      candidate->priority);
864
  priv_generate_candidate_credentials (agent, candidate);
865

866
867
868
869
  /* Google uses the turn username as the candidate username */
  if (agent->compatibility == NICE_COMPATIBILITY_GOOGLE) {
    g_free (candidate->username);
    candidate->username = g_strdup (turn->username);
870
871
  }

872
873
  priv_assign_foundation (agent, candidate);

874
  if (!priv_add_local_candidate_pruned (agent, stream_id, component, candidate))
875
876
    goto errors;

877
  nice_component_attach_socket (component, relay_socket);
878
879
  agent_signal_new_candidate (agent, candidate);

880
  return candidate;
881
882
883
884
885
886

errors:
  nice_candidate_free (candidate);
  if (relay_socket)
    nice_socket_free (relay_socket);
  return NULL;
887
888
}

889
/*
890
891
892
893
894
 * Creates a peer reflexive candidate for 'component_id' of stream
 * 'stream_id'.
 *
 * @return pointer to the created candidate, or NULL on error
 */
895
NiceCandidate*
896
897
898
899
900
discovery_add_peer_reflexive_candidate (
  NiceAgent *agent,
  guint stream_id,
  guint component_id,
  NiceAddress *address,
901
  NiceSocket *base_socket,
902
903
  NiceCandidate *local,
  NiceCandidate *remote)
904
905
{
  NiceCandidate *candidate;
906
  NiceComponent *component;
907
  NiceStream *stream;
908
  gboolean result;
909
910
911
912
913

  if (!agent_find_component (agent, stream_id, component_id, &stream, &component))
    return NULL;

  candidate = nice_candidate_new (NICE_CANDIDATE_TYPE_PEER_REFLEXIVE);
Youness Alaoui's avatar
Youness Alaoui committed
914
915
916
917
918
919
920
921
922
923
924
  if (local)
    candidate->transport = local->transport;
  else if (remote)
    candidate->transport = conn_check_match_transport (remote->transport);
  else {
    if (base_socket->type == NICE_SOCKET_TYPE_UDP_BSD ||
        base_socket->type == NICE_SOCKET_TYPE_UDP_TURN)
      candidate->transport = NICE_CANDIDATE_TRANSPORT_UDP;
    else
      candidate->transport = NICE_CANDIDATE_TRANSPORT_TCP_PASSIVE;
  }
925
926
927
  candidate->stream_id = stream_id;
  candidate->component_id = component_id;
  candidate->addr = *address;
Youness Alaoui's avatar
Youness Alaoui committed
928
  candidate->sockptr = base_socket;
929
  candidate->base_addr = base_socket->addr;
930

931
932
  if (agent->compatibility == NICE_COMPATIBILITY_GOOGLE) {
    candidate->priority = nice_candidate_jingle_priority (candidate);
Jakub Adam's avatar
Jakub Adam committed
933
934
  } else if (agent->compatibility == NICE_COMPATIBILITY_MSN ||
             agent->compatibility == NICE_COMPATIBILITY_OC2007)  {
935
    candidate->priority = nice_candidate_msn_priority (candidate);
936
937
938
  } else if (agent->compatibility == NICE_COMPATIBILITY_OC2007R2) {
    candidate->priority =  nice_candidate_ms_ice_priority (candidate,
        agent->reliable, FALSE);
939
  } else {
940
941
    candidate->priority = nice_candidate_ice_priority (candidate,
        agent->reliable, FALSE);
942
  }
943

944
  candidate->priority = ensure_unique_priority (stream, component,
945
      candidate->priority);
946
  priv_assign_foundation (agent, candidate);
947

Jakub Adam's avatar
Jakub Adam committed
948
949
  if ((agent->compatibility == NICE_COMPATIBILITY_MSN ||
       agent->compatibility == NICE_COMPATIBILITY_OC2007) &&
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
      remote && local) {
    guchar *new_username = NULL;
    guchar *decoded_local = NULL;
    guchar *decoded_remote = NULL;
    gsize local_size;
    gsize remote_size;
    g_free(candidate->username);
    g_free(candidate->password);

    decoded_local = g_base64_decode (local->username, &local_size);
    decoded_remote = g_base64_decode (remote->username, &remote_size);

    new_username = g_new0(guchar, local_size + remote_size);
    memcpy(new_username, decoded_local, local_size);
    memcpy(new_username + local_size, decoded_remote, remote_size);

    candidate->username = g_base64_encode (new_username, local_size + remote_size);
    g_free(new_username);
    g_free(decoded_local);
    g_free(decoded_remote);

    candidate->password = g_strdup(local->password);
  } else if (local) {
    g_free(candidate->username);
    g_free(candidate->password);

    candidate->username = g_strdup(local->username);
    candidate->password = g_strdup(local->password);
  }
979

980
  result = priv_add_local_candidate_pruned (agent, stream_id, component, candidate);
981
  if (result != TRUE) {
982
    /* error: memory allocation, or duplicate candidate */
983
    nice_candidate_free (candidate), candidate = NULL;
984
985
986
987
988
989
  }

  return candidate;
}


990
/*
991
992
993
994
 * Adds a new peer reflexive candidate to the list of known
 * remote candidates. The candidate is however not paired with
 * existing local candidates.
 *
995
 * See ICE sect 7.2.1.3 "Learning Peer Reflexive Candidates" (ID-19).
996
997
998
999
1000
 *
 * @return pointer to the created candidate, or NULL on error
 */
NiceCandidate *discovery_learn_remote_peer_reflexive_candidate (
  NiceAgent *agent,
1001
  NiceStream *stream,
1002
  NiceComponent *component,
1003
  guint32 priority,
1004
  const NiceAddress *remote_address,
1005
  NiceSocket *nicesock,
1006
1007
  NiceCandidate *local,
  NiceCandidate *remote)
1008
1009
1010
1011
{
  NiceCandidate *candidate;

  candidate = nice_candidate_new (NICE_CANDIDATE_TYPE_PEER_REFLEXIVE);
1012
1013
1014

  candidate->addr = *remote_address;
  candidate->base_addr = *remote_address;
1015
1016
1017
1018
1019
1020
  if (remote)
    candidate->transport = remote->transport;
  else if (local)
    candidate->transport = conn_check_match_transport (local->transport);
  else {
    if (nicesock->type == NICE_SOCKET_TYPE_UDP_BSD ||
1021
        nicesock->type == NICE_SOCKET_TYPE_UDP_TURN)
1022
1023
1024
1025
      candidate->transport = NICE_CANDIDATE_TRANSPORT_UDP;
    else
      candidate->transport = NICE_CANDIDATE_TRANSPORT_TCP_ACTIVE;
  }
Youness Alaoui's avatar
Youness Alaoui committed
1026
  candidate->sockptr = nicesock;
1027
1028
  candidate->stream_id = stream->id;
  candidate->component_id = component->id;
1029
1030
1031
1032
1033
1034
1035

  /* if the check didn't contain the PRIORITY attribute, then the priority will
   * be 0, which is invalid... */
  if (priority != 0) {
    candidate->priority = priority;
  } else if (agent->compatibility == NICE_COMPATIBILITY_GOOGLE) {
    candidate->priority = nice_candidate_jingle_priority (candidate);
Jakub Adam's avatar
Jakub Adam committed
1036
1037
  } else if (agent->compatibility == NICE_COMPATIBILITY_MSN ||
             agent->compatibility == NICE_COMPATIBILITY_OC2007)  {
1038
    candidate->priority = nice_candidate_msn_priority (candidate);
1039
1040
1041
  } else if (agent->compatibility == NICE_COMPATIBILITY_OC2007R2) {
    candidate->priority =  nice_candidate_ms_ice_priority (candidate,
        agent->reliable, FALSE);
1042
  } else {
1043
1044
    candidate->priority = nice_candidate_ice_priority (candidate,
        agent->reliable, FALSE);
1045
  }
1046

1047
  priv_assign_remote_foundation (agent, candidate);
1048

Jakub Adam's avatar
Jakub Adam committed
1049
1050
  if ((agent->compatibility == NICE_COMPATIBILITY_MSN ||
       agent->compatibility == NICE_COMPATIBILITY_OC2007) &&
1051
1052
1053
1054
1055
1056
1057
1058
      remote && local) {
    guchar *new_username = NULL;
    guchar *decoded_local = NULL;
    guchar *decoded_remote = NULL;
    gsize local_size;
    gsize remote_size;
    g_free(candidate->username);
    g_free (candidate->password);
1059

1060
1061
    decoded_local = g_base64_decode (local->username, &local_size);
    decoded_remote = g_base64_decode (remote->username, &remote_size);
1062

1063
1064
1065
    new_username = g_new0(guchar, local_size + remote_size);
    memcpy(new_username, decoded_remote, remote_size);
    memcpy(new_username + remote_size, decoded_local, local_size);
1066

1067
1068
1069
1070
    candidate->username = g_base64_encode (new_username, local_size + remote_size);
    g_free(new_username);
    g_free(decoded_local);
    g_free(decoded_remote);
1071

1072
1073
1074
1075
1076
1077
1078
    candidate->password = g_strdup(remote->password);
  } else if (remote) {
    g_free (candidate->username);
    g_free (candidate->password);
    candidate->username = g_strdup(remote->username);
    candidate->password = g_strdup(remote->password);
  }
1079

1080
1081
  /* note: candidate username and password are left NULL as stream 
     level ufrag/password are used */
1082

1083
1084
  component->remote_candidates = g_slist_append (component->remote_candidates,
      candidate);
1085

1086
  agent_signal_new_remote_candidate (agent, candidate);
1087
1088

  return candidate;
1089
}
1090

1091
/* 
1092
1093
1094
1095
1096
1097
1098
1099
 * Timer callback that handles scheduling new candidate discovery
 * processes (paced by the Ta timer), and handles running of the 
 * existing discovery processes.
 *
 * This function is designed for the g_timeout_add() interface.
 *
 * @return will return FALSE when no more pending timers.
 */