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

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

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

48 49 50 51 52 53 54 55 56 57
#include <errno.h>
#include <string.h>

#include <glib.h>

#include "agent.h"
#include "agent-priv.h"
#include "conncheck.h"
#include "discovery.h"

58 59 60 61 62
static void priv_update_check_list_failed_components (NiceAgent *agent, Stream *stream);
static void priv_prune_pending_checks (Stream *stream, guint component_id);
static gboolean priv_schedule_triggered_check (NiceAgent *agent, Stream *stream, Component *component, NiceUDPSocket *local_socket, NiceCandidate *remote_cand, gboolean use_candidate);
static void priv_mark_pair_nominated (NiceAgent *agent, Stream *stream, Component *component, NiceCandidate *remotecand);

63 64 65 66 67 68
static inline int priv_timer_expired (GTimeVal *restrict timer, GTimeVal *restrict now)
{
  return (now->tv_sec == timer->tv_sec) ?
    now->tv_usec >= timer->tv_usec :
    now->tv_sec >= timer->tv_sec;
}
69 70 71 72 73 74 75 76

/**
 * Finds the next connectivity check in WAITING state.
 */
static CandidateCheckPair *priv_conn_check_find_next_waiting (GSList *conn_check_list)
{
  GSList *i;

77 78
  /* note: list is sorted in priority order to first waiting check has
   *       the highest priority */
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95

  for (i = conn_check_list; i ; i = i->next) {
    CandidateCheckPair *p = i->data;
    if (p->state == NICE_CHECK_WAITING)
      return p;
  }

  return NULL;
}

/**
 * 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)
{
96 97 98 99
  /* XXX: from ID-16 onwards, the checks should not be sent
   * immediately, but be put into the "triggered queue",
   * see  "7.2.1.4 Triggered Checks"
   */
100
  g_get_current_time (&pair->next_tick);
101
  g_time_val_add (&pair->next_tick, agent->timer_ta * 1000);
102 103 104 105 106 107 108
  pair->state = NICE_CHECK_IN_PROGRESS;
  conn_check_send (agent, pair);
  return TRUE;
}

/**
 * Unfreezes the next connectivity check in the list. Follows the
109
 * algorithm (2.) defined in 5.7.4 (Computing States) of the ICE spec
110
 * (ID-19), with some exceptions (see comments in code).
111 112 113
 *
 * See also sect 7.1.2.2.3 (Updating Pair States), and
 * priv_conn_check_unfreeze_related().
114 115 116
 * 
 * @return TRUE on success, and FALSE if no frozen candidates were found.
 */
117
static gboolean priv_conn_check_unfreeze_next (NiceAgent *agent)
118 119
{
  CandidateCheckPair *pair = NULL;
120
  GSList *i, *j;
121

122 123 124 125 126 127 128
  /* XXX: the unfreezing is implemented a bit differently than in the
   *      current ICE spec, but should still be interoperate:
   *   - checks are not grouped by foundation
   *   - one frozen check is unfrozen (lowest component-id, highest
   *     priority)
   */

129 130 131 132
  for (i = agent->streams; i; i = i->next) {
    Stream *stream = i->data;
    guint64 max_frozen_priority = 0;

133

134 135 136 137 138 139 140 141 142 143
    for (j = stream->conncheck_list; j ; j = j->next) {
      CandidateCheckPair *p = j->data;

      /* XXX: the prio check could be removed as the pairs are sorted
       *       already */

      if (p->state == NICE_CHECK_FROZEN) {
	if (p->priority > max_frozen_priority) {
	  max_frozen_priority = p->priority;
	  pair = p;
144
	}
145 146
      }
    }
147 148 149

    if (pair) 
      break;
150 151 152
  }
  
  if (pair) {
153
    g_debug ("Agent %p : Pair %p with s/c-id %u/%u (%s) unfrozen.", agent, pair, pair->stream_id, pair->component_id, pair->foundation);
154 155 156 157 158 159 160
    pair->state = NICE_CHECK_WAITING;
    return TRUE;
  }

  return FALSE;
}

161 162 163 164
/**
 * Unfreezes the next next connectivity check in the list after
 * check 'success_check' has succesfully completed.
 *
165
 * See sect 7.1.2.2.3 (Updating Pair States) of ICE spec (ID-19).
166 167 168 169 170 171
 * 
 * @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.
 */
172
static void priv_conn_check_unfreeze_related (NiceAgent *agent, Stream *stream, CandidateCheckPair *ok_check)
173 174 175 176 177 178
{
  GSList *i, *j;
  guint unfrozen = 0;

  g_assert (ok_check);
  g_assert (ok_check->state == NICE_CHECK_SUCCEEDED);
179 180
  g_assert (stream);
  g_assert (stream->id == ok_check->stream_id);
181 182

  /* step: perform the step (1) of 'Updating Pair States' */
183
  for (i = stream->conncheck_list; i ; i = i->next) {
184 185 186 187 188
    CandidateCheckPair *p = i->data;
   
    if (p->stream_id == ok_check->stream_id) {
      if (p->state == NICE_CHECK_FROZEN &&
	  strcmp (p->foundation, ok_check->foundation) == 0) {
189
	g_debug ("Agent %p : Unfreezing check %p (after succesful check %p).", agent, p, ok_check);
190
	p->state = NICE_CHECK_WAITING;
191
	++unfrozen;
192 193 194 195 196 197 198 199 200 201
      }
    }
  }

  /* step: perform the step (2) of 'Updating Pair States' */
  stream = agent_find_stream (agent, ok_check->stream_id);
  if (stream_all_components_ready (stream)) {
    /* step: unfreeze checks from other streams */
    for (i = agent->streams; i ; i = i->next) {
      Stream *s = i->data;
202
      for (j = stream->conncheck_list; j ; j = j->next) {
203 204 205 206 207 208
	CandidateCheckPair *p = j->data;

	if (p->stream_id == s->id &&
	    p->stream_id != ok_check->stream_id) {
	  if (p->state == NICE_CHECK_FROZEN &&
	      strcmp (p->foundation, ok_check->foundation) == 0) {
209
	    g_debug ("Agent %p : Unfreezing check %p from stream %u (after succesful check %p).", agent, p, s->id, ok_check);
210 211 212 213 214 215 216 217 218 219 220 221 222
	    p->state = NICE_CHECK_WAITING;
	    ++unfrozen;
					    
	  }
	}
      }
      /* note: only unfreeze check from one stream at a time */
      if (unfrozen)
	break;
    }
  }    

  if (unfrozen == 0) 
223
    priv_conn_check_unfreeze_next (agent);
224 225
}

226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
/**
 * 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.
 */
static gboolean priv_conn_check_tick_stream (Stream *stream, NiceAgent *agent, GTimeVal *now)
{
  gboolean keep_timer_going = FALSE;
  guint s_inprogress = 0, s_succeeded = 0, s_nominated = 0, s_waiting_for_nomination = 0;
  guint frozen = 0, waiting = 0;
  GSList *i, *k;

  for (i = stream->conncheck_list; i ; i = i->next) {
    CandidateCheckPair *p = i->data;
      
    if (p->state == NICE_CHECK_IN_PROGRESS) {
      if (p->stun_ctx == NULL) {
246
	g_debug ("Agent %p : STUN connectivity check was cancelled, marking as done.", agent);
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
	p->state = NICE_CHECK_FAILED;
      }
      else if (priv_timer_expired (&p->next_tick, now)) {
	int res = stun_bind_elapse (p->stun_ctx);
	if (res == EAGAIN) {
	  /* case: not ready, so schedule a new timeout */
	  unsigned int timeout = stun_bind_timeout (p->stun_ctx);
	  
	  /* note: convert from milli to microseconds for g_time_val_add() */
	  p->next_tick = *now;
	  g_time_val_add (&p->next_tick, timeout * 1000);
	  
	  keep_timer_going = TRUE;
	  p->traffic_after_tick = TRUE; /* for keepalive timer */
	}
	else {
	  /* case: error, abort processing */
264
	  g_debug ("Agent %p : Retransmissions failed, giving up on connectivity check %p", agent, p);
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
	  p->state = NICE_CHECK_FAILED;
	  p->stun_ctx = NULL;
	}
      }
    }
    
    if (p->state == NICE_CHECK_FROZEN)
      ++frozen;
    else if (p->state == NICE_CHECK_IN_PROGRESS)
      ++s_inprogress;
    else if (p->state == NICE_CHECK_WAITING)
      ++waiting;
    else if (p->state == NICE_CHECK_SUCCEEDED)
      ++s_succeeded;
    
    if (p->state == NICE_CHECK_SUCCEEDED && p->nominated)
      ++s_nominated;
    else if (p->state == NICE_CHECK_SUCCEEDED && !p->nominated)
      ++s_waiting_for_nomination;
    }
    
    /* note: keep the timer going as long as there is work to be done */
  if (s_inprogress)
    keep_timer_going = TRUE;
  
    /* note: if some components have established connectivity,
     *       but yet no nominated pair, keep timer going */
  if (s_nominated < stream->n_components &&
      s_waiting_for_nomination) {
    keep_timer_going = TRUE;
    if (agent->controlling_mode) {
      guint n;
      for (n = 0; n < stream->n_components; n++) {
	for (k = stream->conncheck_list; k ; k = k->next) {
	  CandidateCheckPair *p = k->data;
	  /* note: highest priority item selected (list always sorted) */
	  if (p->state == NICE_CHECK_SUCCEEDED ||
	      p->state == NICE_CHECK_DISCOVERED) {
303
	    g_debug ("Agent %p : restarting check %p as the nominated pair.", agent, p);
304 305 306 307 308 309 310 311 312 313 314 315 316
	    p->nominated = TRUE;
	    priv_conn_check_initiate (agent, p);	
	    break; /* move to the next component */
	  }
	}
      }
    }
  }
  
#ifndef NDEBUG
  {
    static int tick_counter = 0;
    if (tick_counter++ % 50 == 0 || keep_timer_going != TRUE)
317
      g_debug ("Agent %p : timer(%p) tick #%u: %u frozen, %u in-progress, %u waiting, %u succeeded, %u nominated, %u waiting-for-nom.", agent, 
318 319 320 321 322 323 324 325
	       agent, tick_counter, frozen, s_inprogress, waiting, s_succeeded, s_nominated, s_waiting_for_nomination);
  }
#endif

  return keep_timer_going;

}

Youness Alaoui's avatar
Youness Alaoui committed
326

327 328 329 330 331 332 333 334
/**
 * 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.
 */
Youness Alaoui's avatar
Youness Alaoui committed
335
static gboolean priv_conn_check_tick_unlocked (gpointer pointer)
336 337 338 339
{
  CandidateCheckPair *pair = NULL;
  NiceAgent *agent = pointer;
  gboolean keep_timer_going = FALSE;
340
  GSList *i, *j;
341
  GTimeVal now;
342 343 344

  /* step: process ongoing STUN transactions */
  g_get_current_time (&now);
345

346 347 348 349 350 351 352 353 354
  /* step: find the highest priority waiting check and send it */
  for (i = agent->streams; i ; i = i->next) {
    Stream *stream = i->data;
  
    pair = priv_conn_check_find_next_waiting (stream->conncheck_list);  

    if (pair)
      break;
  }
355 356 357 358 359

  if (pair) {
    priv_conn_check_initiate (agent, pair);
    keep_timer_going = TRUE;
  }
360 361
  else 
    priv_conn_check_unfreeze_next (agent);
362

363 364
  for (j = agent->streams; j; j = j->next) {
    Stream *stream = j->data;
365 366 367 368
    gboolean res =
      priv_conn_check_tick_stream (stream, agent, &now);
    if (res)
      keep_timer_going = res;
369 370 371
  }
  
  /* step: stop timer if no work left */
372
  if (keep_timer_going != TRUE) {
373
    g_debug ("Agent %p : %s: stopping conncheck timer", agent, G_STRFUNC);
374 375
    for (i = agent->streams; i; i = i->next) {
      Stream *stream = i->data;
376
      priv_update_check_list_failed_components (agent, stream);
377
      stream->conncheck_state = NICE_CHECKLIST_COMPLETED;
378 379
    }
    conn_check_free (agent);
380
    /* XXX: what to signal, is all processing now really done? */
381
    g_debug ("Agent %p : changing conncheck state to COMPLETED.", agent);
382 383 384 385 386
  }

  return keep_timer_going;
}

Youness Alaoui's avatar
Youness Alaoui committed
387 388 389 390 391
static gboolean priv_conn_check_tick (gpointer pointer)
{
  NiceAgent *agent = pointer;
  gboolean ret;

392
  g_static_rec_mutex_lock (&agent->mutex);
Youness Alaoui's avatar
Youness Alaoui committed
393
  ret = priv_conn_check_tick_unlocked (pointer);
394
  g_static_rec_mutex_unlock (&agent->mutex);
Youness Alaoui's avatar
Youness Alaoui committed
395 396 397 398

  return ret;
}

399 400 401 402 403 404 405 406 407 408 409
/**
 * 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.
 */
static gboolean priv_conn_keepalive_tick (gpointer pointer)
{
  NiceAgent *agent = pointer;
410
  GSList *i, *j;
411
  int errors = 0;
412
  gboolean ret = FALSE;
413

414
  g_static_rec_mutex_lock (&agent->mutex);
Youness Alaoui's avatar
Youness Alaoui committed
415

416
  /* case 1: session established and media flowing
417
   *         (ref ICE sect 10 "Keepalives" ID-19)  */
418
  for (i = agent->streams; i; i = i->next) {
419

420
    Stream *stream = i->data;
421 422 423 424 425 426 427
    for (j = stream->components; j; j = j->next) {
      Component *component = j->data;
      if (component->selected_pair.local != NULL &&
	  component->media_after_tick != TRUE) {
	CandidatePair *p = &component->selected_pair;
	struct sockaddr sockaddr;
	int res;
Youness Alaoui's avatar
Youness Alaoui committed
428

429 430
	memset (&sockaddr, 0, sizeof (sockaddr));
	nice_address_copy_to_sockaddr (&p->remote->addr, &sockaddr);
Youness Alaoui's avatar
Youness Alaoui committed
431

432
	res = stun_bind_keepalive (p->local->sockptr->fileno,
433 434
				   &sockaddr, sizeof (sockaddr),
                                   agent->compatibility);
435
	g_debug ("Agent %p : stun_bind_keepalive for pair %p res %d (%s).", agent, p, res, strerror (res));
436 437 438 439
	if (res < 0)
	  ++errors;
      }
      component->media_after_tick = FALSE;
440 441
    }
  }
Youness Alaoui's avatar
Youness Alaoui committed
442

443
  /* case 2: connectivity establishment ongoing
444
   *         (ref ICE sect 4.1.1.4 "Keeping Candidates Alive" ID-19)  */
445 446 447
  for (i = agent->streams; i; i = i->next) {
    Stream *stream = i->data;
    if (stream->conncheck_state == NICE_CHECKLIST_RUNNING) {
448 449
      for (j = stream->conncheck_list; j ; j = j->next) {
	CandidateCheckPair *p = j->data;
Youness Alaoui's avatar
Youness Alaoui committed
450

451
	if (p->traffic_after_tick != TRUE) {
452
	  g_debug ("Agent %p : resending STUN-CC to keep the candidate alive (pair %p).", agent, p);
453 454 455
	  conn_check_send (agent, p);
	}
	p->traffic_after_tick = FALSE;
456 457 458
      }
    }
  }
Youness Alaoui's avatar
Youness Alaoui committed
459

460
  if (errors) {
461
    g_debug ("Agent %p : %s: stopping keepalive timer", agent, G_STRFUNC);
462
    goto done;
463 464
  }

465 466 467
  ret = TRUE;

 done:
468
  g_static_rec_mutex_unlock (&agent->mutex);
469
  return ret;
470 471
}

472 473
/**
 * Initiates the next pending connectivity check.
474 475
 * 
 * @return TRUE if a pending check was scheduled
476
 */
477
gboolean conn_check_schedule_next (NiceAgent *agent)
478
{
479
  gboolean res = priv_conn_check_unfreeze_next (agent);
480
  g_debug ("Agent %p : priv_conn_check_unfreeze_next returned %d", agent, res);
481

482
  if (agent->discovery_unsched_items > 0)
483
    g_debug ("Agent %p : WARN: starting conn checks before local candidate gathering is finished.", agent);
484

485
  if (res == TRUE) {
486
    /* step: call once imediately */
Youness Alaoui's avatar
Youness Alaoui committed
487
    res = priv_conn_check_tick_unlocked ((gpointer) agent);
488
    g_debug ("Agent %p : priv_conn_check_tick_unlocked returned %d", agent, res);
489 490

    /* step: schedule timer if not running yet */
491
    if (res && agent->conncheck_timer_id == 0) {
492
      agent->conncheck_timer_id = agent_timeout_add_with_context (agent, agent->timer_ta, priv_conn_check_tick, agent);
493
    }
494 495

    /* step: also start the keepalive timer */
496
    if (agent->keepalive_timer_id == 0) {
497
      agent->keepalive_timer_id = agent_timeout_add_with_context (agent, NICE_AGENT_TIMER_TR_DEFAULT, priv_conn_keepalive_tick, agent);
498
    }
499

500
  }
501

502
  g_debug ("Agent %p : conn_check_schedule_next returning %d", agent, res);
503
  return res;
504 505
}

506 507 508 509 510 511 512 513 514 515 516 517 518 519
/** 
 * Compares two connectivity check items. Checkpairs are sorted
 * in descending priority order, with highest priority item at
 * the start of the list.
 */
gint conn_check_compare (const CandidateCheckPair *a, const CandidateCheckPair *b)
{
  if (a->priority > b->priority)
    return -1;
  else if (a->priority < b->priority)
    return 1;
  return 0;
}

520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
/**
 * Preprocesses a new connectivity check by going through list 
 * of a any stored early incoming connectivity checks from 
 * the remote peer. If a matching incoming check has been already
 * received, update the state of the new outgoing check 'pair'.
 * 
 * @param agent context pointer
 * @param stream which stream (of the agent)
 * @param component pointer to component object to which 'pair'has been added
 * @param pair newly added connectivity check
 */
static void priv_preprocess_conn_check_pending_data (NiceAgent *agent, Stream *stream, Component *component, CandidateCheckPair *pair)
{
  GSList *i;
  for (i = component->incoming_checks; i; i = i->next) {
    IncomingCheck *icheck = i->data;
    if (nice_address_equal (&icheck->from, &pair->remote->addr) &&
	icheck->local_socket == pair->local->sockptr) {
538
      g_debug ("Agent %p : Updating check %p with stored early-icheck %p, %p/%u/%u (agent/stream/component).", agent, pair, icheck, agent, stream->id, component->id);
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
      if (icheck->use_candidate)
	priv_mark_pair_nominated (agent, stream, component, pair->remote);
      priv_schedule_triggered_check (agent, stream, component, icheck->local_socket, pair->remote, icheck->use_candidate);
    }
  }
}

/**
 * Handle any processing steps for connectivity checks after
 * remote candidates have been set. This function handles
 * the special case where answerer has sent us connectivity
 * checks before the answer (containing candidate information),
 * reaches us. The special case is documented in sect 7.2 
 * if ICE spec (ID-19).
 */
void conn_check_remote_candidates_set(NiceAgent *agent)
{
  GSList *i, *j, *k, *l;
  for (i = agent->streams; i ; i = i->next) {
    Stream *stream = i->data;
    for (j = stream->conncheck_list; j ; j = j->next) {
      CandidateCheckPair *pair = j->data;
      Component *component = stream_find_component_by_id (stream, pair->component_id);
      gboolean match = FALSE;
      
      /* performn delayed processing of spec steps section 7.2.1.4,
	 and section 7.2.1.5 */
      priv_preprocess_conn_check_pending_data (agent, stream, component, pair);

      for (k = component->incoming_checks; k; k = k->next) {
	IncomingCheck *icheck = k->data;
	/* sect 7.2.1.3., "Learning Peer Reflexive Candidates", has to 
	 * be handled separately */
	for (l = component->remote_candidates; l; l = l->next) {
	  NiceCandidate *cand = l->data;
	  if (nice_address_equal (&icheck->from, &cand->addr)) {
	    match = TRUE;
	    break;
	  }
	}
	if (match != TRUE) {
	  /* note: we have gotten an incoming connectivity check from 
	   *       an address that is not a known remote candidate */
	  NiceCandidate *candidate = 
	    discovery_learn_remote_peer_reflexive_candidate (agent, 
							     stream, 
							     component, 
							     icheck->priority, 
							     &icheck->from, 
							     icheck->local_socket);
	  if (candidate) {
	    priv_schedule_triggered_check (agent, stream, component, icheck->local_socket, candidate, icheck->use_candidate);
	  }
	}
      }
    }
  }
}

598 599
/** 
 * Enforces the upper limit for connectivity checks as described
600
 * in ICE spec section 5.7.3 (ID-19). See also 
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
 * conn_check_add_for_candidate().
 */
static GSList *priv_limit_conn_check_list_size (GSList *conncheck_list, guint upper_limit)
{
  guint list_len = g_slist_length (conncheck_list);
  guint c = 0;
  GSList *result = conncheck_list;

  if (list_len > upper_limit) {
    c = list_len - upper_limit;
    if (c == list_len) {
      /* case: delete whole list */
      g_slist_foreach (conncheck_list, conn_check_free_item, NULL);
      g_slist_free (conncheck_list),
	result = NULL;
    }
    else {
      /* case: remove 'c' items from list end (lowest priority) */
      GSList *i, *tmp;

      g_assert (c > 0);
      i = g_slist_nth (conncheck_list, c - 1);

      tmp = i->next;
      i->next = NULL;

      if (tmp) {
	/* delete the rest of the connectivity check list */
	g_slist_foreach (tmp, conn_check_free_item, NULL);
	g_slist_free (tmp);
      }
    }
  }

  return result;
}

638 639 640 641 642 643 644 645 646 647
/**
 * Changes the selected pair for the component if 'pair' is nominated
 * and has higher priority than the currently selected pair. See
 * ICE sect 11.1.1. "Procedures for Full Implementations" (ID-19).
 */ 
static gboolean priv_update_selected_pair (NiceAgent *agent, Component *component, CandidateCheckPair *pair)
{
  g_assert (component);
  g_assert (pair);
  if (pair->priority > component->selected_pair.priority) {
648
    g_debug ("Agent %p : changing SELECTED PAIR for component %u: %s:%s (prio:%lu).", agent, 
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 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 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
	     component->id, pair->local->foundation, pair->remote->foundation, (long unsigned)pair->priority);
    component->selected_pair.local = pair->local;
    component->selected_pair.remote = pair->remote;
    component->selected_pair.priority = pair->priority;

    agent_signal_new_selected_pair (agent, pair->stream_id, component->id, pair->local->foundation, pair->remote->foundation);
  }

  return TRUE;
}

/**
 * Updates the check list state.
 *
 * Implements parts of the algorithm described in 
 * ICE sect 8.1.2. "Updating States" (ID-19): if for any 
 * component, all checks have been completed and have
 * failed, mark that component's state to NICE_CHECK_FAILED.
 *
 * Sends a component state changesignal via 'agent'.
 */
static void priv_update_check_list_failed_components (NiceAgent *agent, Stream *stream)
{
  GSList *i;
  /* note: emitting a signal might cause the client 
   *       to remove the stream, thus the component count
   *       must be fetched before entering the loop*/
  guint c, components = stream->n_components;

  /* note: iterate the conncheck list for each component separately */
  for (c = 0; c < components; c++) {
    for (i = stream->conncheck_list; i; i = i->next) {
      CandidateCheckPair *p = i->data;
      
      if (p->stream_id == stream->id &&
	  p->component_id == (c + 1)) {
	
	if (p->state != NICE_CHECK_FAILED)
	  break;
      }
    }

    /* note: all checks have failed */
    if (i == NULL)
      agent_signal_component_state_change (agent, 
					   stream->id,
					   (c + 1), /* component-id */
					   NICE_COMPONENT_STATE_FAILED);
  }
}

/**
 * Updates the check list state for a stream component.
 *
 * Implements the algorithm described in ICE sect 8.1.2 
 * "Updating States" (ID-19) as it applies to checks of 
 * a certain component. If there are any nominated pairs, 
 * ICE processing may be concluded, and component state is 
 * changed to READY.
 *
 * Sends a component state changesignal via 'agent'.
 */
static void priv_update_check_list_state_for_ready (NiceAgent *agent, Stream *stream, Component *component)
{
  GSList *i;
  guint succeeded = 0, nominated = 0;

  g_assert (component);

  /* step: search for at least one nominated pair */
  for (i = stream->conncheck_list; i; i = i->next) {
    CandidateCheckPair *p = i->data;
    if (p->component_id == component->id) {
      if (p->state == NICE_CHECK_SUCCEEDED ||
	  p->state == NICE_CHECK_DISCOVERED) {
	++succeeded;
	if (p->nominated == TRUE) {
	  priv_prune_pending_checks (stream, p->component_id);
	  agent_signal_component_state_change (agent,
					       p->stream_id,
					       p->component_id,
					       NICE_COMPONENT_STATE_READY);
	}
      }
    }
  }
  
736
  g_debug ("Agent %p : conn.check list status: %u nominated, %u succeeded, c-id %u.", agent, nominated, succeeded, component->id);
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
}

/**
 * The remote party has signalled that the candidate pair
 * described by 'component' and 'remotecand' is nominated
 * for use.
 */
static void priv_mark_pair_nominated (NiceAgent *agent, Stream *stream, Component *component, NiceCandidate *remotecand)
{
  GSList *i;

  g_assert (component);

  /* step: search for at least one nominated pair */
  for (i = stream->conncheck_list; i; i = i->next) {
    CandidateCheckPair *pair = i->data;
    /* XXX: hmm, how to figure out to which local candidate the 
     *      check was sent to? let's mark all matching pairs
     *      as nominated instead */
    if (pair->remote == remotecand) {
757
      g_debug ("Agent %p : marking pair %p (%s) as nominated", agent, pair, pair->foundation);
758 759 760 761 762 763 764 765 766
      pair->nominated = TRUE;
      if (pair->state == NICE_CHECK_SUCCEEDED ||
	  pair->state == NICE_CHECK_DISCOVERED)
	priv_update_selected_pair (agent, component, pair);
      priv_update_check_list_state_for_ready (agent, stream, component);
    }
  }
}

767 768 769 770
/**
 * Creates a new connectivity check pair and adds it to
 * the agent's list of checks.
 */
771 772 773
static gboolean priv_add_new_check_pair (NiceAgent *agent, guint stream_id, Component *component, NiceCandidate *local, NiceCandidate *remote, NiceCheckState initial_state, gboolean use_candidate)
{
  gboolean result = FALSE;
774
  Stream *stream = agent_find_stream (agent, stream_id);
775 776
  CandidateCheckPair *pair = g_slice_new0 (CandidateCheckPair);
  if (pair) {
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
    GSList *modified_list = 
      g_slist_insert_sorted (stream->conncheck_list, pair, (GCompareFunc)conn_check_compare);
    if (modified_list) {
      /* step: allocation and addition succesful, do rest of the work */

      pair->agent = agent;
      pair->stream_id = stream_id;
      pair->component_id = component->id;;
      pair->local = local; 
      pair->remote = remote;
      g_snprintf (pair->foundation, NICE_CANDIDATE_PAIR_MAX_FOUNDATION, "%s:%s", local->foundation, remote->foundation);

      pair->priority = agent_candidate_pair_priority (agent, local, remote);
      pair->state = initial_state;
      pair->nominated = use_candidate;
      pair->controlling = agent->controlling_mode;
      
      /* note: for the first added check */
      if (!stream->conncheck_list)
	stream->conncheck_state = NICE_CHECKLIST_RUNNING;
      stream->conncheck_list = modified_list;

      result = TRUE;
800
      g_debug ("Agent %p : added a new conncheck %p with foundation of '%s' to list %u.", agent, pair, pair->foundation, stream_id);
801 802 803 804 805 806

      /* implement the hard upper limit for number of 
	 checks (see sect 5.7.3 ICE ID-19): */
      stream->conncheck_list = 
	priv_limit_conn_check_list_size (stream->conncheck_list, agent->max_conn_checks);
      if (!stream->conncheck_list) {
807
	stream->conncheck_state = NICE_CHECKLIST_FAILED;  
808
	result = FALSE;
809
      }
810 811 812 813 814 815
    }
    else {
      /* memory alloc failed: list insert */
      conn_check_free_item (pair, NULL);
      stream->conncheck_state = NICE_CHECKLIST_FAILED;  
    }
816 817
  }
  else { /* memory alloc failed: new pair */
818
    stream->conncheck_state = NICE_CHECKLIST_FAILED;
819 820 821 822 823
  }

  return result;
}

824 825 826
/**
 * Forms new candidate pairs by matching the new remote candidate
 * 'remote_cand' with all existing local candidates of 'component'.
Kai Vehmanen's avatar
Kai Vehmanen committed
827
 * Implements the logic described in ICE sect 5.7.1. "Forming Candidate
828
 * Pairs" (ID-19).
829 830 831 832 833
 *
 * @param agent context
 * @param component pointer to the component
 * @param remote remote candidate to match with
 *
834
 * @return number of checks added, negative on fatal errors
835 836 837 838
 */
int conn_check_add_for_candidate (NiceAgent *agent, guint stream_id, Component *component, NiceCandidate *remote)
{
  GSList *i;
839
  int added = 0; 
840 841 842 843 844

  for (i = component->local_candidates; i ; i = i->next) {

    NiceCandidate *local = i->data;

845 846
    /* note: match pairs only if transport and address family are the same */
    if (local->transport == remote->transport &&
847
	local->addr.s.addr.sa_family == remote->addr.s.addr.sa_family) {
848

849
      gboolean result;
850

851
      /* note: do not create pairs where local candidate is 
852
       *       a srv-reflexive (ICE 5.7.3. "Pruning the Pairs" ID-19) */
853 854
      if (local->type == NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE)
	continue;
855

856 857 858
      result = priv_add_new_check_pair (agent, stream_id, component, local, remote, NICE_CHECK_FROZEN, FALSE);
      if (result) {
	++added;
859 860 861 862
	agent_signal_component_state_change (agent, 
					     stream_id,
					     component->id,
					     NICE_COMPONENT_STATE_CONNECTING);
863 864 865 866 867
      }
      else {
	added = -1;
	break;
      }
868 869 870
    }
  }

871
  return added;
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
}

/**
 * Frees the CandidateCheckPair structure pointer to 
 * by 'user data'. Compatible with g_slist_foreach().
 */
void conn_check_free_item (gpointer data, gpointer user_data)
{
  CandidateCheckPair *pair = data;
  g_assert (user_data == NULL);
  if (pair->stun_ctx)
    stun_bind_cancel (pair->stun_ctx), 
      pair->stun_ctx = NULL;
  g_slice_free (CandidateCheckPair, pair);
}

/**
889
 * Frees all resources of all connectivity checks.
890 891 892
 */
void conn_check_free (NiceAgent *agent)
{
893 894 895 896 897 898 899 900 901 902
  GSList *i;
  for (i = agent->streams; i; i = i->next) {
    Stream *stream = i->data;

    if (stream->conncheck_list) {
      g_slist_foreach (stream->conncheck_list, conn_check_free_item, NULL);
      g_slist_free (stream->conncheck_list),
	stream->conncheck_list = NULL;
      stream->conncheck_state = NICE_CHECKLIST_NOT_STARTED;
    }
903
  }
904

905 906 907 908
  if (agent->conncheck_timer_id) {
    g_source_remove (agent->conncheck_timer_id),
      agent->conncheck_timer_id = 0;
  }
909 910 911 912 913 914 915 916
}

/**
 * Prunes the list of connectivity checks for items related
 * to stream 'stream_id'. 
 *
 * @return TRUE on success, FALSE on a fatal error
 */
917
gboolean conn_check_prune_stream (NiceAgent *agent, Stream *stream)
918 919 920 921
{
  CandidateCheckPair *pair;
  GSList *i;

922 923
  for (i = stream->conncheck_list; i ; ) {
    GSList *next = i->next;
924 925
    pair = i->data;

926 927 928 929 930 931 932 933
    g_assert (pair->stream_id == stream->id);

    stream->conncheck_list = 
      g_slist_remove (stream->conncheck_list, pair);
    conn_check_free_item (pair, NULL);
    i = next;
    if (!stream->conncheck_list)
      break;
934 935
  }

936 937
  if (!stream->conncheck_list) {
    stream->conncheck_state = NICE_CHECKLIST_NOT_STARTED;
938 939
    conn_check_free (agent);
  }
940 941

  /* return FALSE if there was a memory allocation failure */
942
  if (stream->conncheck_list == NULL && i != NULL)
943 944 945 946 947 948 949
    return FALSE;

  return TRUE;
}


/**
950 951 952
 * Fills 'dest' with a username string for use in an outbound connectivity
 * checks. No more than 'dest_len' characters (including terminating
 * NULL) is ever written to the 'dest'.
953
 */
954
static gboolean priv_create_check_username (NiceAgent *agent, CandidateCheckPair *pair, gchar *dest, guint dest_len)
955 956 957
{
  Stream *stream;

958 959
  stream = agent_find_stream (agent, pair->stream_id);

960
  if (pair &&
961 962 963 964 965 966 967 968 969 970 971 972 973
      pair->remote && pair->remote->username) {
    if (pair->local && pair->local->username) {
      g_snprintf (dest, dest_len, "%s%s%s", pair->remote->username,
          agent->compatibility == NICE_COMPATIBILITY_ID19 ? ":" : "",
          pair->local->username);
      return TRUE;
    } else if (stream) {
      g_snprintf (dest, dest_len, "%s%s%s", pair->remote->username,
          agent->compatibility == NICE_COMPATIBILITY_ID19 ? ":" : "",
          stream->local_ufrag);
      return TRUE;

    }
974
  }
975

976
  if (stream) {
977 978 979
    g_snprintf (dest, dest_len, "%s%s%s", stream->remote_ufrag,
        agent->compatibility == NICE_COMPATIBILITY_ID19 ? ":" : "",
        stream->local_ufrag);
980 981
    return TRUE;
  }
982

983
  return FALSE;
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
}

/**
 * Returns a password string for use in an outbound connectivity
 * check.
 */
static const gchar *priv_create_check_password (NiceAgent *agent, CandidateCheckPair *pair)
{
  Stream *stream;

  if (pair &&
      pair->remote && pair->remote->password)
    return pair->remote->password;

  stream = agent_find_stream (agent, pair->stream_id);
  if (stream)
    return stream->remote_password;

  return NULL;
}

/**
 * Sends a connectivity check over candidate pair 'pair'.
1007 1008
 *
 * @return zero on success, non-zero on error
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
 */
int conn_check_send (NiceAgent *agent, CandidateCheckPair *pair)
{

  /* note: following information is supplied:
   *  - username (for USERNAME attribute)
   *  - password (for MESSAGE-INTEGRITY)
   *  - priority (for PRIORITY)
   *  - ICE-CONTROLLED/ICE-CONTROLLING (for role conflicts)
   *  - USE-CANDIDATE (if sent by the controlling agent)
   */

  guint32 priority =
    nice_candidate_ice_priority_full (
      NICE_CANDIDATE_TYPE_PREF_PEER_REFLEXIVE,
      1,
      pair->local->component_id);
1026

1027
  gchar uname[NICE_STREAM_MAX_UNAME];
1028
  gboolean username_filled = 
1029
     priv_create_check_username (agent, pair, uname, sizeof (uname));
1030
  const gchar *password = priv_create_check_password (agent, pair);
1031

1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
  bool controlling = agent->controlling_mode;
 /* XXX: add API to support different nomination modes: */
  bool cand_use = controlling;

  struct sockaddr sockaddr;
  unsigned int timeout;

  memset (&sockaddr, 0, sizeof (sockaddr)); 

  nice_address_copy_to_sockaddr (&pair->remote->addr, &sockaddr);

1043 1044 1045 1046
#ifndef NDEBUG
  {
    gchar tmpbuf[INET6_ADDRSTRLEN];
    nice_address_to_string (&pair->remote->addr, tmpbuf);
1047
    g_debug ("Agent %p : STUN-CC REQ to '%s:%u', socket=%u, pair=%s (c-id:%u), tie=%llu, username='%s', password='%s', priority=%u.", agent, 
1048 1049 1050
	     tmpbuf,
	     ntohs(((struct sockaddr_in*)(&sockaddr))->sin_port), 
	     pair->local->sockptr->fileno,
1051
	     pair->foundation, pair->component_id,
1052
	     (unsigned long long)agent->tie_breaker,
1053
	     uname, password, priority);
1054 1055 1056

  }
#endif
1057 1058

  if (cand_use) 
1059
    pair->nominated = controlling;
1060

1061
  if (username_filled) {
1062

1063 1064
    if (pair->stun_ctx)
      stun_bind_cancel (pair->stun_ctx);
1065

1066 1067
    stun_conncheck_start (&pair->stun_ctx, pair->local->sockptr->fileno,
			  &sockaddr, sizeof (sockaddr),
1068
			  uname, password,
1069
			  cand_use, controlling, priority,
1070
			  agent->tie_breaker, agent->compatibility);
1071

1072 1073 1074
    timeout = stun_bind_timeout (pair->stun_ctx);
    /* note: convert from milli to microseconds for g_time_val_add() */
    g_get_current_time (&pair->next_tick);
1075
    g_time_val_add (&pair->next_tick, timeout * 1000);
1076 1077 1078
    pair->traffic_after_tick = TRUE; /* for keepalive timer */
  }
    
1079 1080 1081
  return 0;
}

1082
/**
Kai Vehmanen's avatar
Kai Vehmanen committed
1083
 * Implemented the pruning steps described in ICE sect 8.1.2
1084
 * "Updating States" (ID-19) after a pair has been nominated.
1085
 *
1086
 * @see priv_update_check_list_state_failed_components()
1087
 */
1088
static void priv_prune_pending_checks (Stream *stream, guint component_id)
1089 1090
{
  GSList *i;
1091

1092
  /* step: cancel all FROZEN and WAITING pairs for the component */
1093
  for (i = stream->conncheck_list; i; i = i->next) {
1094 1095 1096 1097 1098 1099
    CandidateCheckPair *p = i->data;
    if (p->component_id == component_id) {
      if (p->state == NICE_CHECK_FROZEN ||
	  p->state == NICE_CHECK_WAITING)
	p->state = NICE_CHECK_CANCELLED;
      
1100
      /* note: a SHOULD level req. in ICE 8.1.2. "Updating States" (ID-19) */
1101 1102 1103 1104 1105 1106 1107
      if (p->state == NICE_CHECK_IN_PROGRESS) {
	if (p->stun_ctx)
	  stun_bind_cancel (p->stun_ctx),
	    p->stun_ctx = NULL;
	p->state = NICE_CHECK_CANCELLED;
      }
    }
1108 1109 1110
  }
}

1111 1112
/**
 * Schedules a triggered check after a succesfully inbound 
1113
 * connectivity check. Implements ICE sect 7.2.1.4 "Triggered Checks" (ID-19).
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
 * 
 * @param agent self pointer
 * @param component the check is related to
 * @param local_socket socket from which the inbound check was received
 * @param remote_cand remote candidate from which the inbound check was sent
 * @param use_candidate whether the original check had USE-CANDIDATE attribute set
 */
static gboolean priv_schedule_triggered_check (NiceAgent *agent, Stream *stream, Component *component, NiceUDPSocket *local_socket, NiceCandidate *remote_cand, gboolean use_candidate)
{
  GSList *i;
1124
  gboolean result = FALSE;
1125

1126
  for (i = stream->conncheck_list; i ; i = i->next) {
1127 1128 1129 1130 1131
      CandidateCheckPair *p = i->data;
      if (p->component_id == component->id &&
	  p->remote == remote_cand &&
	  p->local->sockptr == local_socket) {

1132
	g_debug ("Agent %p : Found a matching pair %p for triggered check.", agent, p);
1133 1134 1135 1136 1137 1138
	
	if (p->state == NICE_CHECK_WAITING ||
	    p->state == NICE_CHECK_FROZEN)
	  priv_conn_check_initiate (agent, p);

	if (p->state == NICE_CHECK_IN_PROGRESS) {
1139
	  /* XXX: according to ICE 7.2.1.4 "Triggered Checks" (ID-19),
Kai Vehmanen's avatar
Kai Vehmanen committed
1140
	   * we should cancel the existing one, and send a new one...? :P */
1141
	  g_debug ("Agent %p : Skipping triggered check, already in progress..", agent);
1142 1143 1144
	}
	else if (p->state == NICE_CHECK_SUCCEEDED ||
		 p->state == NICE_CHECK_DISCOVERED) {
1145
	  g_debug ("Agent %p : Skipping triggered check, already completed..", agent); 
1146 1147
	  /* note: this is a bit unsure corner-case -- let's do the
	     same state update as for processing responses to our own checks */
1148
	  priv_update_check_list_state_for_ready (agent, stream, component);
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171

	  /* note: to take care of the controlling-controlling case in 
	   *       aggressive nomination mode, send a new triggered
	   *       check to nominate the pair */
	  if (agent->controlling_mode)
	    priv_conn_check_initiate (agent, p);
	}

	/* note: the spec says the we SHOULD retransmit in-progress
	 *       checks immediately, but we won't do that now */

	return TRUE;
      }
  }

  {
    NiceCandidate *local = NULL;

    for (i = component->local_candidates; i ; i = i->next) {
      local = i->data;
      if (local->sockptr == local_socket)
	break;
    }    
1172
    if (i) {
1173
      g_debug ("Agent %p : Adding a triggered check to conn.check list (local=%p).", agent, local);
1174 1175 1176
      result = priv_add_new_check_pair (agent, stream->id, component, local, remote_cand, NICE_CHECK_WAITING, use_candidate);
    }
    else
1177
      g_debug ("Agent %p : Didn't find a matching pair for triggered check (remote-cand=%p).", agent, remote_cand);
1178 1179
  }

1180
  return result;
1181 1182
}

1183

1184 1185 1186 1187
/**
 * Sends a reply to an succesfully received STUN connectivity 
 * check request. Implements parts of the ICE spec section 7.2 (STUN
 * Server Procedures).
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
 *
 * @param agent context pointer
 * @param stream which stream (of the agent)
 * @param component which component (of the stream)
 * @param rcand remote candidate from which the request came, if NULL,
 *        the response is sent immediately but no other processing is done
 * @param toaddr address to which reply is sent
 * @param udp_socket the socket over which the request came
 * @param rbuf_len length of STUN message to send
 * @param rbuf buffer containing the STUN message to send
 * @param use_candidate whether the request had USE_CANDIDATE attribute
 * 
 * @pre (rcand == NULL || nice_address_equal(rcand->addr, toaddr) == TRUE)
1201
 */
1202
static void priv_reply_to_conn_check (NiceAgent *agent, Stream *stream, Component *component, NiceCandidate *rcand, const NiceAddress *toaddr, NiceUDPSocket *udp_socket, size_t  rbuf_len, uint8_t *rbuf, gboolean use_candidate)
1203
{
1204 1205
  g_assert (rcand == NULL || nice_address_equal(&rcand->addr, toaddr) == TRUE);

1206 1207 1208
#ifndef NDEBUG
  {
    gchar tmpbuf[INET6_ADDRSTRLEN];
1209
    nice_address_to_string (toaddr, tmpbuf);
1210
    g_debug ("Agent %p : STUN-CC RESP to '%s:%u', socket=%u, len=%u, cand=%p (c-id:%u), use-cand=%d.", agent,
1211
	     tmpbuf,
1212
	     nice_address_get_port (toaddr),
1213
	     udp_socket->fileno,
1214
	     (unsigned)rbuf_len,
1215
	     rcand, component->id,
1216 1217 1218
	     (int)use_candidate);
  }
#endif
1219

1220
  nice_udp_socket_send (udp_socket, toaddr, rbuf_len, (const gchar*)rbuf);
1221
  
1222 1223 1224
  if (rcand) {
    if (use_candidate)
      priv_mark_pair_nominated (agent, stream, component, rcand);
1225