conncheck.c 162 KB
Newer Older
1
2
3
/*
 * This file is part of the Nice GLib ICE library.
 *
4
5
6
 * (C) 2006-2009 Collabora Ltd.
 *  Contact: Youness Alaoui
 * (C) 2006-2009 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:
 *   Kai Vehmanen, Nokia
26
 *   Youness Alaoui, Collabora Ltd.
27
28
29
30
31
32
33
34
35
36
37
38
39
 *   Dafydd Harries, Collabora Ltd.
 *
 * Alternatively, the contents of this file may be used under the terms of the
 * the GNU Lesser General Public License Version 2.1 (the "LGPL"), in which
 * case the provisions of LGPL are applicable instead of those above. If you
 * wish to allow use of your version of this file only under the terms of the
 * LGPL and not to allow others to use your version of this file under the
 * MPL, indicate your decision by deleting the provisions above and replace
 * them with the notice and other provisions required by the LGPL. If you do
 * not delete the provisions above, a recipient may use your version of this
 * file under either the MPL or the LGPL.
 */

40
/*
41
42
43
44
45
46
47
48
 * @file conncheck.c
 * @brief ICE connectivity checks
 */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

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

#include <glib.h>

54
55
#include "debug.h"

56
57
58
59
#include "agent.h"
#include "agent-priv.h"
#include "conncheck.h"
#include "discovery.h"
Jakub Adam's avatar
Jakub Adam committed
60
#include "stun/stun5389.h"
61
#include "stun/usages/ice.h"
62
63
#include "stun/usages/bind.h"
#include "stun/usages/turn.h"
64

65
static void priv_update_check_list_failed_components (NiceAgent *agent, NiceStream *stream);
66
static void priv_update_check_list_state_for_ready (NiceAgent *agent, NiceStream *stream, NiceComponent *component);
67
static guint priv_prune_pending_checks (NiceAgent *agent, NiceStream *stream, guint component_id);
68
static gboolean priv_schedule_triggered_check (NiceAgent *agent, NiceStream *stream, NiceComponent *component, NiceSocket *local_socket, NiceCandidate *remote_cand);
69
static void priv_mark_pair_nominated (NiceAgent *agent, NiceStream *stream, NiceComponent *component, NiceCandidate *localcand, NiceCandidate *remotecand);
70
static size_t priv_create_username (NiceAgent *agent, NiceStream *stream,
71
72
    guint component_id, NiceCandidate *remote, NiceCandidate *local,
    uint8_t *dest, guint dest_len, gboolean inbound);
73
static size_t priv_get_password (NiceAgent *agent, NiceStream *stream,
74
    NiceCandidate *remote, uint8_t **password);
75
76
static void candidate_check_pair_free (NiceAgent *agent,
    CandidateCheckPair *pair);
77
78
79
static CandidateCheckPair *priv_conn_check_add_for_candidate_pair_matched (
    NiceAgent *agent, guint stream_id, NiceComponent *component,
    NiceCandidate *local, NiceCandidate *remote, NiceCheckState initial_state);
80
81
static gboolean priv_update_selected_pair (NiceAgent *agent,
    NiceComponent *component, CandidateCheckPair *pair);
82

83
static int priv_timer_expired (GTimeVal *timer, GTimeVal *now)
84
85
86
87
88
{
  return (now->tv_sec == timer->tv_sec) ?
    now->tv_usec >= timer->tv_usec :
    now->tv_sec >= timer->tv_sec;
}
89

90
91
92
93
94
95
96
97
98
99
100
static unsigned int priv_timer_remainder (GTimeVal *timer, GTimeVal *now)
{
  unsigned int delay;
  if (now->tv_sec > timer->tv_sec ||
      (now->tv_sec == timer->tv_sec && now->tv_usec > timer->tv_usec))
    return 0;
  delay = (timer->tv_sec - now->tv_sec) * 1000;
  delay += ((signed long)(timer->tv_usec - now->tv_usec)) / 1000;
  return delay;
}

101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
static gchar
priv_state_to_gchar (NiceCheckState state)
{
  switch (state) {
    case NICE_CHECK_WAITING:
      return 'W';
    case NICE_CHECK_IN_PROGRESS:
      return 'I';
    case NICE_CHECK_SUCCEEDED:
      return 'S';
    case NICE_CHECK_FAILED:
      return 'F';
    case NICE_CHECK_FROZEN:
      return 'Z';
    case NICE_CHECK_DISCOVERED:
      return 'D';
    default:
      g_assert_not_reached ();
  }
}

122
123
124
125
126
static const gchar *
priv_state_to_string (NiceCheckState state)
{
  switch (state) {
    case NICE_CHECK_WAITING:
127
      return "WAITING";
128
    case NICE_CHECK_IN_PROGRESS:
129
      return "IN_PROGRESS";
130
    case NICE_CHECK_SUCCEEDED:
131
      return "SUCCEEDED";
132
    case NICE_CHECK_FAILED:
133
      return "FAILED";
134
    case NICE_CHECK_FROZEN:
135
      return "FROZEN";
136
    case NICE_CHECK_DISCOVERED:
137
      return "DISCOVERED";
138
139
140
141
142
    default:
      g_assert_not_reached ();
  }
}

143
144
145
146
147
148
149
#define SET_PAIR_STATE( a, p, s ) G_STMT_START{\
  g_assert (p); \
  p->state = s; \
  nice_debug ("Agent %p : pair %p state %s (%s)", \
      a, p, priv_state_to_string (s), G_STRFUNC); \
}G_STMT_END

150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
static const gchar *
priv_ice_return_to_string (StunUsageIceReturn ice_return)
{
  switch (ice_return) {
    case STUN_USAGE_ICE_RETURN_SUCCESS:
      return "success";
    case STUN_USAGE_ICE_RETURN_ERROR:
      return "error";
    case STUN_USAGE_ICE_RETURN_INVALID:
      return "invalid";
    case STUN_USAGE_ICE_RETURN_ROLE_CONFLICT:
      return "role conflict";
    case STUN_USAGE_ICE_RETURN_INVALID_REQUEST:
      return "invalid request";
    case STUN_USAGE_ICE_RETURN_INVALID_METHOD:
      return "invalid method";
    case STUN_USAGE_ICE_RETURN_MEMORY_ERROR:
      return "memory error";
    case STUN_USAGE_ICE_RETURN_INVALID_ADDRESS:
      return "invalid address";
    case STUN_USAGE_ICE_RETURN_NO_MAPPED_ADDRESS:
      return "no mapped address";
    default:
      g_assert_not_reached ();
  }
}

177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
static const gchar *
priv_candidate_type_to_string (NiceCandidateType type)
{
  switch (type) {
    case NICE_CANDIDATE_TYPE_HOST:
      return "host";
    case NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE:
      return "srflx";
    case NICE_CANDIDATE_TYPE_PEER_REFLEXIVE:
      return "prflx";
    case NICE_CANDIDATE_TYPE_RELAYED:
      return "relay";
    default:
      g_assert_not_reached ();
  }
}

194
static const gchar *
195
196
197
priv_candidate_transport_to_string (NiceCandidateTransport transport)
{
  switch (transport) {
198
199
200
201
202
203
204
205
206
207
208
209
210
    case NICE_CANDIDATE_TRANSPORT_UDP:
      return "udp";
    case NICE_CANDIDATE_TRANSPORT_TCP_ACTIVE:
      return "tcp-act";
    case NICE_CANDIDATE_TRANSPORT_TCP_PASSIVE:
      return "tcp-pass";
    case NICE_CANDIDATE_TRANSPORT_TCP_SO:
      return "tcp-so";
    default:
      g_assert_not_reached ();
  }
}

211
static const gchar *
212
213
214
priv_socket_type_to_string (NiceSocketType type)
{
  switch (type) {
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
    case NICE_SOCKET_TYPE_UDP_BSD:
      return "udp";
    case NICE_SOCKET_TYPE_TCP_BSD:
      return "tcp";
    case NICE_SOCKET_TYPE_PSEUDOSSL:
      return "ssl";
    case NICE_SOCKET_TYPE_HTTP:
      return "http";
    case NICE_SOCKET_TYPE_SOCKS5:
      return "socks";
    case NICE_SOCKET_TYPE_UDP_TURN:
      return "udp-turn";
    case NICE_SOCKET_TYPE_UDP_TURN_OVER_TCP:
      return "tcp-turn";
    case NICE_SOCKET_TYPE_TCP_ACTIVE:
      return "tcp-act";
    case NICE_SOCKET_TYPE_TCP_PASSIVE:
      return "tcp-pass";
    case NICE_SOCKET_TYPE_TCP_SO:
      return "tcp-so";
    default:
      g_assert_not_reached ();
  }
}

/*
 * Dump the component list of incoming checks
 */
static void
print_component_incoming_checks (NiceAgent *agent, NiceStream *stream,
  NiceComponent *component)
{
  GList *i;

  for (i = component->incoming_checks.head; i; i = i->next) {
    IncomingCheck *icheck = i->data;
    gchar tmpbuf1[INET6_ADDRSTRLEN] = {0};
    gchar tmpbuf2[INET6_ADDRSTRLEN] = {0};

    nice_address_to_string (&icheck->local_socket->addr, tmpbuf1);
    nice_address_to_string (&icheck->from, tmpbuf2);
    nice_debug ("Agent %p : *** sc=%d/%d : icheck %p : "
      "sock %s [%s]:%u > [%s]:%u",
      agent, stream->id, component->id, icheck,
      priv_socket_type_to_string (icheck->local_socket->type),
      tmpbuf1, nice_address_get_port (&icheck->local_socket->addr),
      tmpbuf2, nice_address_get_port (&icheck->from));
  }
}

265
266
267
268
269
270
/*
 * Dump the conncheck lists of the agent
 */
static void
priv_print_conn_check_lists (NiceAgent *agent, const gchar *where, const gchar *detail)
{
271
272
  GSList *i, *k, *l;
  guint j, m;
273
  GTimeVal now;
274
275
276
277

  if (!nice_debug_is_verbose ())
    return;

278
279
  g_get_current_time (&now);

280
281
282
283
284
285
286
#define PRIORITY_LEN 32

  nice_debug ("Agent %p : *** conncheck list DUMP (called from %s%s)",
      agent, where, detail ? detail : "");
  for (i = agent->streams; i ; i = i->next) {
    NiceStream *stream = i->data;
    for (j = 1; j <= stream->n_components; j++) {
287
      NiceComponent *component;
288
289
290
291
292
293
294
295
296
297
      for (k = stream->conncheck_list; k ; k = k->next) {
        CandidateCheckPair *pair = k->data;
        if (pair->component_id == j) {
          gchar local_addr[INET6_ADDRSTRLEN];
          gchar remote_addr[INET6_ADDRSTRLEN];

          nice_address_to_string (&pair->local->addr, local_addr);
          nice_address_to_string (&pair->remote->addr, remote_addr);

          nice_debug ("Agent %p : *** sc=%d/%d : pair %p : "
298
299
              "f=%s t=%s:%s sock=%s "
              "%s:[%s]:%u > %s:[%s]:%u state=%c%s%s%s",
300
301
302
303
              agent, pair->stream_id, pair->component_id, pair,
              pair->foundation,
              priv_candidate_type_to_string (pair->local->type),
              priv_candidate_type_to_string (pair->remote->type),
304
305
              priv_socket_type_to_string (pair->sockptr->type),
              priv_candidate_transport_to_string (pair->local->transport),
306
              local_addr, nice_address_get_port (&pair->local->addr),
307
              priv_candidate_transport_to_string (pair->remote->transport),
308
309
310
311
312
              remote_addr, nice_address_get_port (&pair->remote->addr),
              priv_state_to_gchar (pair->state),
              pair->valid ? "V" : "",
              pair->nominated ? "N" : "",
              g_slist_find (agent->triggered_check_queue, pair) ? "T" : "");
313
314
315

          for (l = pair->stun_transactions, m = 0; l; l = l->next, m++) {
            StunTransaction *stun = l->data;
316
            nice_debug ("Agent %p : *** sc=%d/%d : pair %p :   "
317
318
319
320
321
322
323
324
                "stun#=%d timer=%d/%d %d/%dms buf=%p %s",
                agent, pair->stream_id, pair->component_id, pair, m,
                stun->timer.retransmissions, stun->timer.max_retransmissions,
                stun->timer.delay - priv_timer_remainder (&stun->next_tick, &now),
                stun->timer.delay,
                stun->message.buffer,
                (m == 0 && pair->retransmit) ? "(R)" : "");
          }
325
326
        }
      }
327
328
      if (agent_find_component (agent, stream->id, j, NULL, &component))
        print_component_incoming_checks (agent, stream, component);
329
330
331
332
    }
  }
}

333
334
335
336
337
338
339
/* Add the pair to the triggered checks list, if not already present
 */
static void
priv_add_pair_to_triggered_check_queue (NiceAgent *agent, CandidateCheckPair *pair)
{
  g_assert (pair);

340
  SET_PAIR_STATE (agent, pair, NICE_CHECK_IN_PROGRESS);
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
  if (agent->triggered_check_queue == NULL ||
      g_slist_find (agent->triggered_check_queue, pair) == NULL)
    agent->triggered_check_queue = g_slist_append (agent->triggered_check_queue, pair);
}

/* Remove the pair from the triggered checks list
 */
static void
priv_remove_pair_from_triggered_check_queue (NiceAgent *agent, CandidateCheckPair *pair)
{
  g_assert (pair);
  agent->triggered_check_queue = g_slist_remove (agent->triggered_check_queue, pair);
}

/* Get the pair from the triggered checks list
 */
static CandidateCheckPair *
priv_get_pair_from_triggered_check_queue (NiceAgent *agent)
{
  CandidateCheckPair *pair = NULL;

  if (agent->triggered_check_queue) {
    pair = (CandidateCheckPair *)agent->triggered_check_queue->data;
    priv_remove_pair_from_triggered_check_queue (agent, pair);
  }
  return pair;
}

369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/*
 * Check if the conncheck list if Active according to
 * ICE spec, 5.7.4 (Computing States)
 *
 * note: the ICE spec in unclear about that, but the check list should
 * be considered active when there is at least a pair in Waiting state
 * OR a pair in In-Progress state.
 */
static gboolean
priv_is_checklist_active (NiceStream *stream)
{
  GSList *i;

  for (i = stream->conncheck_list; i ; i = i->next) {
    CandidateCheckPair *p = i->data;
    if (p->state == NICE_CHECK_WAITING || p->state == NICE_CHECK_IN_PROGRESS)
      return TRUE;
  }
  return FALSE;
}

/*
 * Check if the conncheck list if Frozen according to
 * ICE spec, 5.7.4 (Computing States)
 */
static gboolean
priv_is_checklist_frozen (NiceStream *stream)
{
  GSList *i;

  if (stream->conncheck_list == NULL)
    return FALSE;

  for (i = stream->conncheck_list; i ; i = i->next) {
    CandidateCheckPair *p = i->data;
    if (p->state != NICE_CHECK_FROZEN)
      return FALSE;
  }
  return TRUE;
}

/*
 * Check if all components of the stream have
 * a valid pair (used for ICE spec, 7.1.3.2.3, point 2.)
 */
static gboolean
priv_all_components_have_valid_pair (NiceStream *stream)
{
  guint i;
  GSList *j;

  for (i = 1; i <= stream->n_components; i++) {
    for (j = stream->conncheck_list; j ; j = j->next) {
      CandidateCheckPair *p = j->data;
      if (p->component_id == i && p->valid)
        break;
    }
    if (j == NULL)
      return FALSE;
  }
  return TRUE;
}

/*
 * Check if the foundation in parameter matches the foundation
 * of a valid pair in the conncheck list [of stream] (used for ICE spec,
 * 7.1.3.2.3, point 2.)
 */
static gboolean
priv_foundation_matches_a_valid_pair (const gchar *foundation, NiceStream *stream)
{
  GSList *i;

  for (i = stream->conncheck_list; i ; i = i->next) {
    CandidateCheckPair *p = i->data;
    if (p->valid &&
        strncmp (p->foundation, foundation,
            NICE_CANDIDATE_PAIR_MAX_FOUNDATION) == 0)
      return TRUE;
  }
  return FALSE;
}

452
/*
453
454
455
456
457
458
 * Finds the next connectivity check in WAITING state.
 */
static CandidateCheckPair *priv_conn_check_find_next_waiting (GSList *conn_check_list)
{
  GSList *i;

459
460
  /* note: list is sorted in priority order to first waiting check has
   *       the highest priority */
461
462
463
464
465
466
467
468
469
  for (i = conn_check_list; i ; i = i->next) {
    CandidateCheckPair *p = i->data;
    if (p->state == NICE_CHECK_WAITING)
      return p;
  }

  return NULL;
}

470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
/*
 * Finds the next connectivity check in FROZEN state.
 */
static CandidateCheckPair *
priv_conn_check_find_next_frozen (GSList *conn_check_list)
{
  GSList *i;

  /* note: list is sorted in priority order to first frozen check has
   *       the highest priority */
  for (i = conn_check_list; i ; i = i->next) {
    CandidateCheckPair *p = i->data;
    if (p->state == NICE_CHECK_FROZEN)
      return p;
  }

  return NULL;
}

/*
 * Returns the number of active check lists of the agent
 */
static guint
priv_number_of_active_check_lists (NiceAgent *agent)
{
  guint n = 0;
  GSList *i;

  for (i = agent->streams; i ; i = i->next)
    if (priv_is_checklist_active (i->data))
      n++;
  return n;
}

/*
 * Returns the first stream of the agent having a Frozen
 * connection check list
 */
static NiceStream *
priv_find_first_frozen_check_list (NiceAgent *agent)
{
  GSList *i;

  for (i = agent->streams; i ; i = i->next) {
    NiceStream *stream = i->data;
    if (priv_is_checklist_frozen (stream))
      return stream;
  }
  return NULL;
}

521
/*
522
523
524
525
526
527
 * Initiates a new connectivity check for a ICE candidate pair.
 *
 * @return TRUE on success, FALSE on error
 */
static gboolean priv_conn_check_initiate (NiceAgent *agent, CandidateCheckPair *pair)
{
528
  SET_PAIR_STATE (agent, pair, NICE_CHECK_IN_PROGRESS);
529
  if (conn_check_send (agent, pair)) {
530
    SET_PAIR_STATE (agent, pair, NICE_CHECK_FAILED);
531
532
    return FALSE;
  }
533
534
535
  return TRUE;
}

536
/*
537
 * Unfreezes the next connectivity check in the list. Follows the
538
 * algorithm (2.) defined in 5.7.4 (Computing States) of the ICE spec
539
 * (RFC5245)
540
541
542
 *
 * See also sect 7.1.2.2.3 (Updating Pair States), and
 * priv_conn_check_unfreeze_related().
543
544
545
 * 
 * @return TRUE on success, and FALSE if no frozen candidates were found.
 */
546
static gboolean priv_conn_check_unfreeze_next (NiceAgent *agent, NiceStream *stream)
547
{
548
  GSList *i, *j;
549
550
  GSList *found_list = NULL;
  gboolean result = FALSE;
551

552
553
  priv_print_conn_check_lists (agent, G_STRFUNC, NULL);

554
555
556
557
558
  for (i = stream->conncheck_list; i ; i = i->next) {
    CandidateCheckPair *p1 = i->data;
    CandidateCheckPair *pair = NULL;
    guint lowest_component_id = stream->n_components + 1;
    guint64 highest_priority = 0;
559

560
561
562
    if (g_slist_find_custom (found_list, p1->foundation, (GCompareFunc)strcmp))
      continue;
    found_list = g_slist_prepend (found_list, p1->foundation);
563

564
    for (j = stream->conncheck_list; j ; j = j->next) {
565
566
567
568
569
570
571
572
573
574
      CandidateCheckPair *p2 = i->data;
      if (strncmp (p2->foundation, p1->foundation,
              NICE_CANDIDATE_PAIR_MAX_FOUNDATION) == 0) {
        if (p2->component_id < lowest_component_id ||
            (p2->component_id == lowest_component_id &&
             p2->priority > highest_priority)) {
          pair = p2;
          lowest_component_id = p2->component_id;
          highest_priority = p2->priority;
        }
575
576
      }
    }
577

578
579
580
    if (pair) {
      nice_debug ("Agent %p : Pair %p with s/c-id %u/%u (%s) unfrozen.",
          agent, pair, pair->stream_id, pair->component_id, pair->foundation);
581
      SET_PAIR_STATE (agent, pair, NICE_CHECK_WAITING);
582
583
      result = TRUE;
    }
584
  }
585
586
  g_slist_free (found_list);
  return result;
587
588
}

589
/*
590
 * Unfreezes the next next connectivity check in the list after
Youness Alaoui's avatar
Youness Alaoui committed
591
 * check 'success_check' has successfully completed.
592
 *
593
 * See sect 7.1.2.2.3 (Updating Pair States) of ICE spec (ID-19).
594
595
596
597
598
599
 * 
 * @param agent context
 * @param ok_check a connectivity check that has just completed
 *
 * @return TRUE on success, and FALSE if no frozen candidates were found.
 */
600
static void priv_conn_check_unfreeze_related (NiceAgent *agent, NiceStream *stream, CandidateCheckPair *ok_check)
601
602
603
604
605
{
  GSList *i, *j;

  g_assert (ok_check);
  g_assert (ok_check->state == NICE_CHECK_SUCCEEDED);
606
607
  g_assert (stream);
  g_assert (stream->id == ok_check->stream_id);
608

609
610
  priv_print_conn_check_lists (agent, G_STRFUNC, NULL);

611
  /* step: perform the step (1) of 'Updating Pair States' */
612
  for (i = stream->conncheck_list; i ; i = i->next) {
613
614
615
616
    CandidateCheckPair *p = i->data;
   
    if (p->stream_id == ok_check->stream_id) {
      if (p->state == NICE_CHECK_FROZEN &&
617
618
          strncmp (p->foundation, ok_check->foundation,
              NICE_CANDIDATE_PAIR_MAX_FOUNDATION) == 0) {
Youness Alaoui's avatar
Youness Alaoui committed
619
	nice_debug ("Agent %p : Unfreezing check %p (after successful check %p).", agent, p, ok_check);
620
	SET_PAIR_STATE (agent, p, NICE_CHECK_WAITING);
621
622
623
624
625
626
      }
    }
  }

  /* step: perform the step (2) of 'Updating Pair States' */
  stream = agent_find_stream (agent, ok_check->stream_id);
627
  if (priv_all_components_have_valid_pair (stream)) {
628
    for (i = agent->streams; i ; i = i->next) {
629
630
631
      /* the agent examines the check list for each other
       * media stream in turn
       */
632
      NiceStream *s = i->data;
633
634
635
636
637
638
639
640
641
      if (s->id == ok_check->stream_id)
        continue;
      if (priv_is_checklist_active (s)) {
        /* checklist is Active
         */
        for (j = s->conncheck_list; j ; j = j->next) {
	  CandidateCheckPair *p = j->data;
          if (p->state == NICE_CHECK_FROZEN &&
              priv_foundation_matches_a_valid_pair (p->foundation, stream)) {
Youness Alaoui's avatar
Youness Alaoui committed
642
	    nice_debug ("Agent %p : Unfreezing check %p from stream %u (after successful check %p).", agent, p, s->id, ok_check);
643
	    SET_PAIR_STATE (agent, p, NICE_CHECK_WAITING);
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
          }
        }
      } else if (priv_is_checklist_frozen (s)) {
        /* checklist is Frozen
         */
        gboolean match_found = FALSE;
        /* check if there is one pair in the check list whose
         * foundation matches a pair in the valid list under
         * consideration
         */
        for (j = s->conncheck_list; j ; j = j->next) {
	  CandidateCheckPair *p = j->data;
          if (priv_foundation_matches_a_valid_pair (p->foundation, stream)) {
            match_found = TRUE;
            nice_debug ("Agent %p : Unfreezing check %p from stream %u (after successful check %p).", agent, p, s->id, ok_check);
659
            SET_PAIR_STATE (agent, p, NICE_CHECK_WAITING);
660
661
662
663
664
665
666
667
668
          }
        }

        if (!match_found) {
          /* set the pair with the lowest component ID
           * and highest priority to Waiting
           */
          priv_conn_check_unfreeze_next (agent, s);
        }
669
670
671
672
673
      }
    }
  }    
}

674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
/*
 * Create a new STUN transaction and add it to the list
 * of ongoing stun transactions of a pair.
 *
 * @pair the pair the new stun transaction should be added to.
 * @return the created stun transaction.
 */
static StunTransaction *
priv_add_stun_transaction (CandidateCheckPair *pair)
{
  StunTransaction *stun = g_slice_new0 (StunTransaction);
  pair->stun_transactions = g_slist_prepend (pair->stun_transactions, stun);
  pair->retransmit = TRUE;
  return stun;
}

/*
 * Forget a STUN transaction.
 *
 * @data the stun transaction to be forgotten.
 * @user_data the component contained the concerned stun agent.
 */
696
static void
697
priv_forget_stun_transaction (gpointer data, gpointer user_data)
698
{
699
700
  StunTransaction *stun = data;
  NiceComponent *component = user_data;
701
702
  StunTransactionId id;

703
704
  if (stun->message.buffer != NULL) {
    stun_message_id (&stun->message, id);
705
706
    stun_agent_forget_transaction (&component->stun_agent, id);
  }
707
}
708

709
710
711
712
static void
priv_free_stun_transaction (gpointer data)
{
  g_slice_free (StunTransaction, data);
713
714
}

715
/*
716
717
 * Remove a STUN transaction from a pair, and forget it
 * from the related component stun agent.
718
 *
719
720
721
722
 * @pair the pair the stun transaction should be removed from.
 * @stun the stun transaction to be removed.
 * @component the component containing the stun agent used to
 * forget the stun transaction.
723
 */
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
static void
priv_remove_stun_transaction (CandidateCheckPair *pair,
  StunTransaction *stun, NiceComponent *component)
{
  priv_forget_stun_transaction (stun, component);
  pair->stun_transactions = g_slist_remove (pair->stun_transactions, stun);
  priv_free_stun_transaction (stun);
}

/*
 * Remove all STUN transactions from a pair, and forget them
 * from the related component stun agent.
 *
 * @pair the pair the stun list should be cleared.
 * @component the component containing the stun agent used to
 * forget the stun transactions.
 */
static void
priv_free_all_stun_transactions (CandidateCheckPair *pair,
  NiceComponent *component)
{
  if (component)
    g_slist_foreach (pair->stun_transactions, priv_forget_stun_transaction, component);
  g_slist_free_full (pair->stun_transactions, priv_free_stun_transaction);
  pair->stun_transactions = NULL;
}

static void
candidate_check_pair_fail (NiceStream *stream, NiceAgent *agent, CandidateCheckPair *p)
{
  NiceComponent *component;

  component = nice_stream_find_component_by_id (stream, p->component_id);
757
  SET_PAIR_STATE (agent, p, NICE_CHECK_FAILED);
758
  priv_free_all_stun_transactions (p, component);
759
760
}

761
/*
762
763
764
765
766
767
768
 * Helper function for connectivity check timer callback that
 * runs through the stream specific part of the state machine. 
 *
 * @param schedule if TRUE, schedule a new check
 *
 * @return will return FALSE when no more pending timers.
 */
769
static gboolean priv_conn_check_tick_stream (NiceStream *stream, NiceAgent *agent)
770
771
{
  gboolean keep_timer_going = FALSE;
772
  GSList *i, *j;
773
  CandidateCheckPair *pair;
774
  unsigned int timeout;
775
776
777
  GTimeVal now;

  g_get_current_time (&now);
778

779
  /* step: process ongoing STUN transactions */
780
781
  for (i = stream->conncheck_list; i ; i = i->next) {
    CandidateCheckPair *p = i->data;
782
783
    gchar tmpbuf1[INET6_ADDRSTRLEN], tmpbuf2[INET6_ADDRSTRLEN];
    NiceComponent *component;
784
785
786
787
    StunTransaction *stun;

    if (p->stun_transactions == NULL)
      continue;
788
789
790
791
792

    if (!agent_find_component (agent, p->stream_id, p->component_id,
        NULL, &component))
      continue;

793
794
795
796
    /* The first stun transaction of the list may eventually be
     * retransmitted, other stun transactions just have their
     * timer updated.
     */
797

798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
    j = p->stun_transactions->next;

    /* process all stun transactions except the first one */
    while (j) {
      StunTransaction *s = j->data;
      GSList *next = j->next;

      if (priv_timer_expired (&s->next_tick, &now))
        switch (stun_timer_refresh (&s->timer)) {
          case STUN_USAGE_TIMER_RETURN_TIMEOUT:
            priv_remove_stun_transaction (p, s, component);
            break;
          case STUN_USAGE_TIMER_RETURN_RETRANSMIT:
            timeout = stun_timer_remainder (&s->timer);
            s->next_tick = now;
            g_time_val_add (&s->next_tick, timeout * 1000);
            break;
          default:
            break;
      }
      j = next;
819
820
    }

821
    if (p->state != NICE_CHECK_IN_PROGRESS)
822
      continue;
823

824
825
826
827
    /* process the first stun transaction of the list */
    stun = p->stun_transactions->data;
    if (!priv_timer_expired (&stun->next_tick, &now))
      continue;
828

829
830
831
    switch (stun_timer_refresh (&stun->timer)) {
      case STUN_USAGE_TIMER_RETURN_TIMEOUT:
timer_return_timeout:
832
833
834
        /* case: error, abort processing */
        nice_address_to_string (&p->local->addr, tmpbuf1);
        nice_address_to_string (&p->remote->addr, tmpbuf2);
835
836
        nice_debug ("Agent %p : Retransmissions failed, giving up on pair %p",
            agent, p);
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
        nice_debug ("Agent %p : Failed pair is [%s]:%u --> [%s]:%u", agent,
            tmpbuf1, nice_address_get_port (&p->local->addr),
            tmpbuf2, nice_address_get_port (&p->remote->addr));
        candidate_check_pair_fail (stream, agent, p);
        priv_print_conn_check_lists (agent, G_STRFUNC,
            ", retransmission failed");

        /* perform a check if a transition state from connected to
         * ready can be performed. This may happen here, when the last
         * in-progress pair has expired its retransmission count
         * in priv_conn_check_tick_stream(), which is a condition to
         * make the transition connected to ready.
         */
        priv_update_check_list_state_for_ready (agent, stream, component);
        break;
      case STUN_USAGE_TIMER_RETURN_RETRANSMIT:
        /* case: retransmission stopped, due to the nomination of
         * a pair with a higher priority than this in-progress pair,
         * ICE spec, sect 8.1.2 "Updating States", item 2.2
         */
857
858
        if (!p->retransmit)
          goto timer_return_timeout;
859

860
        /* case: not ready, so schedule a new timeout */
861
        timeout = stun_timer_remainder (&stun->timer);
862

863
        nice_debug ("Agent %p :STUN transaction retransmitted on pair %p "
864
865
            "(timer=%d/%d %d/%dms).",
            agent, p,
866
867
            stun->timer.retransmissions, stun->timer.max_retransmissions,
            stun->timer.delay - timeout, stun->timer.delay);
868

869
        agent_socket_send (p->sockptr, &p->remote->addr,
870
871
            stun_message_length (&stun->message),
            (gchar *)stun->buffer);
872

873
        /* note: convert from milli to microseconds for g_time_val_add() */
874
875
        stun->next_tick = now;
        g_time_val_add (&stun->next_tick, timeout * 1000);
876

877
878
        return TRUE;
      case STUN_USAGE_TIMER_RETURN_SUCCESS:
879
        timeout = stun_timer_remainder (&stun->timer);
880

881
        /* note: convert from milli to microseconds for g_time_val_add() */
882
883
        stun->next_tick = now;
        g_time_val_add (&stun->next_tick, timeout * 1000);
Youness Alaoui's avatar
Youness Alaoui committed
884

885
886
887
888
889
        keep_timer_going = TRUE;
        break;
      default:
        /* Nothing to do. */
        break;
890
    }
891
  }
892
893
894
895
896
897
898

  /* step: perform an ordinary check, ICE spec, 5.8 "Scheduling Checks"
   * note: This code is executed when the triggered checks list is
   * empty, and when no STUN message has been sent (pacing constraint)
   */
  pair = priv_conn_check_find_next_waiting (stream->conncheck_list);
  if (pair) {
899
900
    priv_print_conn_check_lists (agent, G_STRFUNC,
        ", got a pair in Waiting state");
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
    priv_conn_check_initiate (agent, pair);
    return TRUE;
  }

  /* note: this is unclear in the ICE spec, but a check list in Frozen
   * state (where all pairs are in Frozen state) is not supposed to
   * change its state by an ordinary check, but only by the success of
   * checks in other check lists, in priv_conn_check_unfreeze_related().
   * The underlying idea is to concentrate the checks on a single check
   * list initially.
   */
  if (priv_is_checklist_frozen (stream))
    return keep_timer_going;

  /* step: ordinary check continued, if there's no pair in the waiting
   * state, pick a pair in the frozen state
   */
  pair = priv_conn_check_find_next_frozen (stream->conncheck_list);
  if (pair) {
920
921
    priv_print_conn_check_lists (agent, G_STRFUNC,
        ", got a pair in Frozen state");
922
    SET_PAIR_STATE (agent, pair, NICE_CHECK_WAITING);
923
924
925
926
927
928
929
930
931
932
    priv_conn_check_initiate (agent, pair);
    return TRUE;
  }
  return keep_timer_going;
}

static gboolean
priv_conn_check_tick_stream_nominate (NiceStream *stream, NiceAgent *agent)
{
  gboolean keep_timer_going = FALSE;
933
  /* s_xxx counters are stream-wide */
934
935
936
937
938
939
  guint s_inprogress = 0;
  guint s_succeeded = 0;
  guint s_discovered = 0;
  guint s_nominated = 0;
  guint s_waiting_for_nomination = 0;
  guint s_valid = 0;
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
  guint s_frozen = 0;
  guint s_waiting = 0;
  CandidateCheckPair *other_stream_pair = NULL;
  GSList *i, *j;

  /* Search for a nominated pair (or selected to be nominated pair)
   * from another stream.
   */
  for (i = agent->streams; i ; i = i->next) {
    NiceStream *s = i->data;
    if (s->id == stream->id)
      continue;
    for (j = s->conncheck_list; j ; j = j->next) {
      CandidateCheckPair *p = j->data;
      if (p->nominated || p->use_candidate_on_next_check) {
        other_stream_pair = p;
        break;
      }
    }
    if (other_stream_pair)
      break;
  }
962

963
  /* we compute some stream-wide counter values */
964
965
  for (i = stream->conncheck_list; i ; i = i->next) {
    CandidateCheckPair *p = i->data;
966
    if (p->state == NICE_CHECK_FROZEN)
967
      s_frozen++;
968
    else if (p->state == NICE_CHECK_IN_PROGRESS)
969
      s_inprogress++;
970
    else if (p->state == NICE_CHECK_WAITING)
971
      s_waiting++;
972
    else if (p->state == NICE_CHECK_SUCCEEDED)
973
      s_succeeded++;
974
    else if (p->state == NICE_CHECK_DISCOVERED)
975
      s_discovered++;
976
    if (p->valid)
977
      s_valid++;
978

979
980
    if ((p->state == NICE_CHECK_SUCCEEDED || p->state == NICE_CHECK_DISCOVERED)
        && p->nominated)
981
      s_nominated++;
982
983
    else if ((p->state == NICE_CHECK_SUCCEEDED ||
            p->state == NICE_CHECK_DISCOVERED) && !p->nominated)
984
      s_waiting_for_nomination++;
985
  }
986

987
  /* note: keep the timer going as long as there is work to be done */
988
989
990
991
992
  if (s_inprogress)
    keep_timer_going = TRUE;
  
  if (s_nominated < stream->n_components &&
      s_waiting_for_nomination) {
993
994
    if (NICE_AGENT_IS_COMPATIBLE_WITH_RFC5245_OR_OC2007R2 (agent)) {
      if (agent->nomination_mode == NICE_NOMINATION_MODE_REGULAR &&
995
996
          agent->controlling_mode) {
#define NICE_MIN_NUMBER_OF_VALID_PAIRS 2
997
        /* ICE 8.1.1.1 Regular nomination
998
999
1000
1001
         * we choose to nominate the valid pair of a component if
         * - there is no pair left frozen, waiting or in-progress, or
         * - if there are at least two valid pairs, or
         * - if there is at least one valid pair of type HOST-HOST
1002
1003
1004
1005
1006
1007
         *
         * This is the "stopping criterion" described in 8.1.1.1, and is
         * a "local optimization" between accumulating more valid pairs,
         * and limiting the time spent waiting for in-progress connections
         * checks until they finally fail.
         */
1008
1009
1010
1011
        for (i = stream->components; i; i = i->next) {
          NiceComponent *component = i->data;
          CandidateCheckPair *other_component_pair = NULL;
          CandidateCheckPair *this_component_pair = NULL;
1012
1013
1014
          NiceCandidate *lcand1 = NULL;
          NiceCandidate *rcand1 = NULL;
          NiceCandidate *lcand2, *rcand2;
1015
          gboolean already_done = FALSE;
1016
1017
1018
1019
          gboolean found_other_component_pair = FALSE;
          gboolean found_other_stream_pair = FALSE;
          gboolean first_nomination = FALSE;
          gboolean stopping_criterion;
1020
          /* p_xxx counters are component-wide */
1021
1022
1023
1024
1025
          guint p_valid = 0;
          guint p_frozen = 0;
          guint p_waiting = 0;
          guint p_inprogress = 0;
          guint p_host_host_valid = 0;
1026

1027
1028
1029
          /* we compute some component-wide counter values */
          for (j = stream->conncheck_list; j ; j = j->next) {
            CandidateCheckPair *p = j->data;
1030
            if (p->component_id == component->id) {
1031
1032
1033
              /* verify that the choice of the pair to be nominated
               * has not already been done
               */
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
              if (p->use_candidate_on_next_check)
                already_done = TRUE;
              if (p->state == NICE_CHECK_FROZEN)
                p_frozen++;
              else if (p->state == NICE_CHECK_WAITING)
                p_waiting++;
              else if (p->state == NICE_CHECK_IN_PROGRESS)
                p_inprogress++;
              if (p->valid)
                p_valid++;
              if (p->valid &&
                  p->local->type == NICE_CANDIDATE_TYPE_HOST &&
                  p->remote->type == NICE_CANDIDATE_TYPE_HOST)
                p_host_host_valid++;
1048
1049
1050
            }
          }

1051
1052
1053
          if (already_done)
            continue;

1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
          /* Search for a nominated pair (or selected to be nominated pair)
           * from another component of this stream.
           */
          for (j = stream->conncheck_list; j ; j = j->next) {
            CandidateCheckPair *p = j->data;
            if (p->component_id == component->id)
              continue;
            if (p->nominated || p->use_candidate_on_next_check) {
              other_component_pair = p;
              break;
            }
          }
1066

1067
1068
1069
          if (other_stream_pair == NULL && other_component_pair == NULL)
            first_nomination = TRUE;

1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
          /* We choose a pair to be nominated in the list of valid
           * pairs.
           *
           * this pair will be the one with the highest priority,
           * when we don't have other nominated pairs in other
           * components and in other streams
           *
           * this pair will be a pair compatible with another nominated
           * pair from another component if we found one.
           *
           * else this pair will be a pair compatible with another
           * nominated pair from another stream if we found one.
           *
1083
           */
1084
1085
          for (j = stream->conncheck_list; j ; j = j->next) {
            CandidateCheckPair *p = j->data;
1086
1087
1088
1089
1090
            /* note: highest priority item selected (list always sorted) */
            if (p->component_id == component->id &&
                !p->nominated &&
                !p->use_candidate_on_next_check &&
                p->valid) {
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
              /* According a ICE spec, sect 8.1.1.1.  "Regular
               * Nomination", we enqueue the check that produced this
               * valid pair. When this pair has been discovered, we want
               * to test its parent pair instead.
               */
              if (p->succeeded_pair != NULL) {
                g_assert (p->state == NICE_CHECK_DISCOVERED);
                p = p->succeeded_pair;
              }
              g_assert (p->state == NICE_CHECK_SUCCEEDED);
1101
1102
1103
1104
1105

              if (this_component_pair == NULL)
                /* highest priority pair */
                this_component_pair = p;

1106
1107
1108
1109
              lcand1 = p->local;
              rcand1 = p->remote;

              if (first_nomination)
1110
1111
1112
                /* use the highest priority pair */
                break;

1113
1114
1115
1116
              if (other_component_pair) {
                lcand2 = other_component_pair->local;
                rcand2 = other_component_pair->remote;
              }
1117
              if (other_component_pair &&
1118
1119
1120
                  lcand1->transport == lcand2->transport &&
                  nice_address_equal_no_port (&lcand1->addr, &lcand2->addr) &&
                  nice_address_equal_no_port (&rcand1->addr, &rcand2->addr)) {
1121
1122
1123
1124
1125
                /* else continue the research with lower priority
                 * pairs, compatible with a nominated pair of
                 * another component
                 */
                this_component_pair = p;
1126
                found_other_component_pair = TRUE;
1127
1128
1129
                break;
              }

1130
1131
1132
1133
1134
1135
1136
1137
1138
              if (other_stream_pair) {
                lcand2 = other_stream_pair->local;
                rcand2 = other_stream_pair->remote;
              }
              if (other_stream_pair &&
                  other_component_pair == NULL &&
                  lcand1->transport == lcand2->transport &&
                  nice_address_equal_no_port (&lcand1->addr, &lcand2->addr) &&
                  nice_address_equal_no_port (&rcand1->addr, &rcand2->addr)) {
1139
1140
1141
1142
1143
                /* else continue the research with lower priority
                 * pairs, compatible with a nominated pair of
                 * another stream
                 */
                this_component_pair = p;
1144
                found_other_stream_pair = TRUE;
1145
1146
                break;
              }
1147
1148
            }
          }
1149
1150
1151
1152
1153
1154

          /* No valid pair for this component */
          if (this_component_pair == NULL)
            continue;

          /* The stopping criterion tries to select a set of pairs of
1155
           * the same kind (transport/type) for all components of a
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
           * stream, and for all streams, when possible (see last
           * paragraph).
           *
           * When no stream has nominated a pair yet, we apply the
           * following criterion :
           *   - stop if we have a valid host-host pair
           *   - or stop if we have at least "some* (2 in the current
           *     implementation) valid pairs, and select the best one
           *   - or stop if the conncheck cannot evolve more
           *
           * Else when the stream has a nominated pair in another
1167
1168
           * component we apply this criterion:
           *   - stop if we have a valid pair of the same kind than this
1169
1170
1171
1172
           *     other nominated pair.
           *   - or stop if the conncheck cannot evolve more
           *
           * Else when another stream has a nominated pair we apply the
1173
           * following criterion:
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
           *   - stop if we have a valid pair of the same kind than the
           *     other nominated pair.
           *   - or stop if the conncheck cannot evolve more
           *
           * When no further evolution of the conncheck is possible, we
           * prefer to select the best valid pair we have, *even* if it
           * is not compatible with the transport of another stream of
           * component. We think it's still a better choice than marking
           * this component 'failed'.
           */
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
          stopping_criterion = FALSE;
          if (first_nomination && p_host_host_valid > 0) {
            stopping_criterion = TRUE;
            nice_debug ("Agent %p : stopping criterion: "
                "valid host-host pair", agent);
          } else if (first_nomination &&
              p_valid >= NICE_MIN_NUMBER_OF_VALID_PAIRS) {
            stopping_criterion = TRUE;
            nice_debug ("Agent %p : stopping criterion: "
                "*some* valid pairs", agent);
          } else if (found_other_component_pair) {
            stopping_criterion = TRUE;
            nice_debug ("Agent %p : stopping criterion: "
                "matching pair in another component", agent);
          } else if (found_other_stream_pair) {
            stopping_criterion = TRUE;
            nice_debug ("Agent %p : stopping criterion: "
                "matching pair in another stream", agent);
          } else if (p_waiting == 0 && p_inprogress == 0 && p_frozen == 0) {
            stopping_criterion = TRUE;
            nice_debug ("Agent %p : stopping criterion: "
                "no more pairs to check", agent);
          }
1207

1208
1209
          if (!stopping_criterion)
            continue;
1210
1211
1212
1213
1214
1215
1216
1217

          /* when the stopping criterion is reached, we add the
           * selected pair for this component to the triggered checks
           * list
           */
          nice_debug ("Agent %p : restarting check of %s:%s pair %p with "
              "USE-CANDIDATE attrib (regular nomination) for "
              "stream %d component %d", agent,
1218
1219
              priv_candidate_transport_to_string (lcand1->transport),
              priv_candidate_transport_to_string (rcand1->transport),
1220
1221
1222
1223
              this_component_pair, stream->id, component->id);
          this_component_pair->use_candidate_on_next_check = TRUE;
          priv_add_pair_to_triggered_check_queue (agent, this_component_pair);
          keep_timer_going = TRUE;
1224
1225
1226
        }
      }
    } else if (agent->controlling_mode) {
1227
1228
      for (i = stream->components; i; i = i->next) {
        NiceComponent *component = i->data;
1229

1230
1231
	for (j = stream->conncheck_list; j ; j = j->next) {
	  CandidateCheckPair *p = j->data;
1232
	  /* note: highest priority item selected (list always sorted) */
1233
1234
1235
	  if (p->component_id == component->id &&
              (p->state == NICE_CHECK_SUCCEEDED ||
               p->state == NICE_CHECK_DISCOVERED)) {
1236
1237
	    nice_debug ("Agent %p : restarting check of pair %p as the "
                "nominated pair.", agent, p);
1238
	    p->nominated = TRUE;
1239
            priv_update_selected_pair (agent, component, p);
1240
            priv_add_pair_to_triggered_check_queue (agent, p);
1241
            keep_timer_going = TRUE;
1242
1243
1244
1245
1246
1247
	    break; /* move to the next component */
	  }
	}
      }
    }
  }
1248
  if (stream->tick_counter++ % 50 == 0)
1249
1250
1251
1252
1253
1254
    nice_debug ("Agent %p : stream %u: timer tick #%u: %u frozen, "
        "%u in-progress, %u waiting, %u succeeded, %u discovered, "
        "%u nominated, %u waiting-for-nom, %u valid",
        agent, stream->id, stream->tick_counter,
        s_frozen, s_inprogress, s_waiting, s_succeeded, s_discovered,
        s_nominated, s_waiting_for_nomination, s_valid);
1255
1256
1257
1258
1259

  return keep_timer_going;

}

1260
1261
1262
1263
1264
1265
1266
1267
1268
static void
conn_check_stop (NiceAgent *agent)
{
  if (agent->conncheck_timer_source == NULL)
    return;

  g_source_destroy (agent->conncheck_timer_source);
  g_source_unref (agent->conncheck_timer_source);
  agent->conncheck_timer_source = NULL;
1269
  agent->conncheck_ongoing_idle_delay = 0;
1270
1271
}

Youness Alaoui's avatar
Youness Alaoui committed
1272

1273
/*
1274
1275
1276
1277
1278
1279
1280
 * Timer callback that handles initiating and managing connectivity
 * checks (paced by the Ta timer).
 *
 * This function is designed for the g_timeout_add() interface.
 *
 * @return will return FALSE when no more pending timers.
 */
1281
1282
static gboolean priv_conn_check_tick_agent_locked (NiceAgent *agent,
    gpointer user_data)
1283
1284
1285
{
  CandidateCheckPair *pair = NULL;
  gboolean keep_timer_going = FALSE;
1286
  GSList *i, *j;
1287

1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
  /* configure the initial state of the check lists of the agent
   * as described in ICE spec, 5.7.4
   *
   * if all pairs in all check lists are in frozen state, then
   * we are in the initial state (5.7.4, point 1.)
   */
  if (priv_number_of_active_check_lists (agent) == 0) {
    /* set some pairs of the first stream in the waiting state
     * ICE spec, 5.7.4, point 2.
     *
     * note: we adapt the ICE spec here, by selecting the first
     * frozen check list, which is not necessarily the check
     * list of the first stream (the first stream may be completed)
     */
    NiceStream *stream = priv_find_first_frozen_check_list (agent);
    if (stream)
      priv_conn_check_unfreeze_next (agent, stream);
1305
  }
1306

1307
1308
1309
1310
1311
  /* step: perform a test from the triggered checks list,
   * ICE spec, 5.8 "Scheduling Checks"
   */
  pair = priv_get_pair_from_triggered_check_queue (agent);

1312
  if (pair) {
1313
1314
    priv_print_conn_check_lists (agent, G_STRFUNC,
        ", got a pair from triggered check list");
1315
    if (conn_check_send (agent, pair)) {
1316
      SET_PAIR_STATE (agent, pair, NICE_CHECK_FAILED);
1317
1318
      return FALSE;
    }
1319
    return TRUE;
1320
1321
  }

1322
1323
  /* step: process ongoing STUN transactions and
   * perform an ordinary check, ICE spec, 5.8, "Scheduling Checks"
1324
1325
1326
   */
  for (i = agent->streams; i ; i = i->next) {
    NiceStream *stream = i->data;
1327
    if (priv_conn_check_tick_stream (stream, agent))
1328
1329
1330
      keep_timer_going = TRUE;
    if (priv_conn_check_tick_stream_nominate (stream, agent))
      keep_timer_going = TRUE;
1331
  }
1332

1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
  /* step: if no work left and a conncheck list of a stream is still
   * frozen, set the pairs to waiting, according to ICE SPEC, sect
   * 7.1.3.3.  "Check List and Timer State Updates"
   */
  if (!keep_timer_going) {
    for (i = agent->streams; i ; i = i->next) {
      NiceStream *stream = i->data;
      if (priv_is_checklist_frozen (stream)) {
        nice_debug ("Agent %p : stream %d conncheck list is still "
            "frozen, while other lists are completed. Unfreeze it.",
            agent, stream->id);
        keep_timer_going = priv_conn_check_unfreeze_next (agent, stream);
      }
Jakub Adam's avatar
Jakub Adam committed
1346
1347
1348
      if (!keep_timer_going && !stream->peer_gathering_done) {
        keep_timer_going = TRUE;
      }
1349
1350
1351
1352
1353
1354
1355
    }
  }

  /* note: we provide a grace period before declaring a component as
   * failed. Components marked connected, and then ready follow another
   * code path, and are not concerned by this grace period.
   */
1356
  if (!keep_timer_going && agent->conncheck_ongoing_idle_delay == 0)
1357
    nice_debug ("Agent %p : waiting %d msecs before checking "
1358
        "for failed components.", agent, agent->idle_timeout);
1359
1360

  if (keep_timer_going)
1361
    agent->conncheck_ongoing_idle_delay = 0;
1362
  else
1363
    agent->conncheck_ongoing_idle_delay += agent->timer_ta;
1364

1365
  /* step: stop timer if no work left */
1366
  if (!keep_timer_going &&
1367
      agent->conncheck_ongoing_idle_delay >= agent->idle_timeout) {
1368
    nice_debug ("Agent %p : checking for failed components now.", agent);
1369
    for (i = agent->streams; i; i = i->next) {
1370
      NiceStream *stream = i->data;
1371
      priv_update_check_list_failed_components (agent, stream);
1372
      for (j = stream->components; j; j = j->next) {
1373
        NiceComponent *component = j->data;
1374
1375
        priv_update_check_list_state_for_ready (agent, stream, component);
      }
1376
    }
1377