ice.c 67.3 KB
Newer Older
Ghislain MARY's avatar
Ghislain MARY committed
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
/*
mediastreamer2 library - modular sound and video processing and streaming
Copyright (C) 2006  Belledonne Communications

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/


#if !defined(WIN32) && !defined(_WIN32_WCE)
#ifdef __APPLE__
#include <sys/types.h>
#endif
#include <sys/socket.h>
#include <netdb.h>
#endif

#include "mediastreamer2/msticker.h"
#include "mediastreamer2/ice.h"


33 34 35
#define ICE_MAX_NB_CANDIDATES		10
#define ICE_MAX_NB_CANDIDATE_PAIRS	(ICE_MAX_NB_CANDIDATES*ICE_MAX_NB_CANDIDATES)

Ghislain MARY's avatar
Ghislain MARY committed
36 37
#define ICE_MIN_COMPONENTID		1
#define ICE_MAX_COMPONENTID		256
38
#define ICE_INVALID_COMPONENTID		0
Ghislain MARY's avatar
Ghislain MARY committed
39 40
#define ICE_MAX_UFRAG_LEN		256
#define ICE_MAX_PWD_LEN			256
41 42 43
#define ICE_DEFAULT_TA_DURATION		20
#define ICE_DEFAULT_RTO_DURATION	100
#define ICE_MAX_RETRANSMISSIONS		7
Ghislain MARY's avatar
Ghislain MARY committed
44

45

46 47 48 49 50 51 52 53 54 55 56 57
typedef struct _Type_ComponentID {
	IceCandidateType type;
	uint16_t componentID;
} Type_ComponentID;

typedef struct _Foundations_Pair_Priority_ComponentID {
	MSList *foundations;
	IceCandidatePair *pair;
	uint64_t priority;
	uint16_t componentID;
} Foundations_Pair_Priority_ComponentID;

58 59 60 61 62
typedef struct _CheckList_RtpSession {
	IceCheckList *cl;
	RtpSession *rtp_session;
} CheckList_RtpSession;

63 64 65 66 67 68
typedef struct _CheckList_RtpSession_Time {
	IceCheckList *cl;
	RtpSession *rtp_session;
	uint64_t time;
} CheckList_RtpSession_Time;

69 70 71 72 73
typedef struct _CheckList_Bool {
	IceCheckList *cl;
	bool_t result;
} CheckList_Bool;

74 75 76 77 78
typedef struct _LocalCandidate_RemoteCandidate {
	IceCandidate *local;
	IceCandidate *remote;
} LocalCandidate_RemoteCandidate;

79

80
static int ice_compare_transport_addresses(const IceTransportAddress *ta1, const IceTransportAddress *ta2);
81 82
static int ice_compare_pair_priorities(const IceCandidatePair *p1, const IceCandidatePair *p2);
static void ice_pair_set_state(IceCandidatePair *pair, IceCandidatePairState state);
83
static void ice_compute_candidate_foundation(IceCandidate *candidate, IceCheckList *cl);
Ghislain MARY's avatar
Ghislain MARY committed
84
static void ice_set_credentials(char **ufrag, char **pwd, const char *ufrag_str, const char *pwd_str);
85
static void ice_conclude_processing(IceCheckList *cl, RtpSession *rtp_session);
Ghislain MARY's avatar
Ghislain MARY committed
86 87


88 89 90 91
/******************************************************************************
 * CONSTANTS DEFINITIONS                                                      *
 *****************************************************************************/

92 93
uint32_t stun_magic_cookie = 0x2112A442;

Ghislain MARY's avatar
Ghislain MARY committed
94 95 96 97 98
static const char * const role_values[] = {
	"Controlling",	/* IR_Controlling */
	"Controlled",	/* IR_Controlled */
};

99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
static const char * const candidate_type_values[] = {
	"host",		/* ICT_HostCandidate */
	"srflx",	/* ICT_ServerReflexiveCandidate */
	"prflx",	/* ICT_PeerReflexiveCandidate */
	"relay"		/* ICT_RelayedCandidate */
};

/**
 * ICE candidate type preference values as recommended in 4.1.1.2.
 */
static const uint8_t type_preference_values[] = {
	126,	/* ICT_HostCandidate */
	100,	/* ICT_ServerReflexiveCandidate */
	110,	/* ICT_PeerReflexiveCandidate */
	0	/* ICT_RelayedCandidate */
};

116 117 118 119 120 121 122 123 124 125
static const char * const candidate_pair_state_values[] = {
	"Waiting",	/* ICP_Waiting */
	"In-Progress",	/* ICP_InProgress */
	"Succeeded",	/* ICP_Succeeded */
	"Failed",	/* ICP_Failed */
	"Frozen"	/* ICP_Frozen */
};


/******************************************************************************
Ghislain MARY's avatar
Ghislain MARY committed
126 127 128 129 130 131 132 133
 * SESSION INITIALISATION AND DEINITIALISATION                                *
 *****************************************************************************/

static void ice_session_init(IceSession *session)
{
	session->streams = NULL;
	session->role = IR_Controlling;
	session->tie_breaker = (random() << 32) | (random() & 0xffffffff);
134
	session->ta = ICE_DEFAULT_TA_DURATION;
Ghislain MARY's avatar
Ghislain MARY committed
135
	session->max_connectivity_checks = ICE_MAX_NB_CANDIDATE_PAIRS;
Ghislain MARY's avatar
Ghislain MARY committed
136 137 138 139 140 141 142 143
	session->local_ufrag = ms_malloc(9);
	sprintf(session->local_ufrag, "%08lx", random());
	session->local_ufrag[8] = '\0';
	session->local_pwd = ms_malloc(25);
	sprintf(session->local_pwd, "%08lx%08lx%08lx", random(), random(), random());
	session->local_pwd[24] = '\0';
	session->remote_ufrag = NULL;
	session->remote_pwd = NULL;
Ghislain MARY's avatar
Ghislain MARY committed
144 145 146 147
}

IceSession * ice_session_new(void)
{
148
	MSTickerParams params;
Ghislain MARY's avatar
Ghislain MARY committed
149 150
	IceSession *session = ms_new(IceSession, 1);
	if (session == NULL) {
151 152 153 154 155 156 157 158 159
		ms_error("ice: Memory allocation of ICE session failed");
		return NULL;
	}
	params.name = "ICE Ticker";
	params.prio = MS_TICKER_PRIO_NORMAL;
	session->ticker = ms_ticker_new_with_params(&params);
	if (session->ticker == NULL) {
		ms_error("ice: Creation of ICE ticker failed");
		ice_session_destroy(session);
Ghislain MARY's avatar
Ghislain MARY committed
160 161 162 163 164 165 166 167
		return NULL;
	}
	ice_session_init(session);
	return session;
}

void ice_session_destroy(IceSession *session)
{
168
	if (session->ticker) ms_ticker_destroy(session->ticker);
Ghislain MARY's avatar
Ghislain MARY committed
169 170 171 172
	if (session->local_ufrag) ms_free(session->local_ufrag);
	if (session->local_pwd) ms_free(session->local_pwd);
	if (session->remote_ufrag) ms_free(session->remote_ufrag);
	if (session->remote_pwd) ms_free(session->remote_pwd);
Ghislain MARY's avatar
Ghislain MARY committed
173 174 175 176 177 178 179
	ms_list_free(session->streams);
	ms_free(session);
}


/******************************************************************************
 * CHECK LIST INITIALISATION AND DEINITIALISATION                             *
180
 *****************************************************************************/
181

182 183
static void ice_check_list_init(IceCheckList *cl)
{
Ghislain MARY's avatar
Ghislain MARY committed
184
	cl->session = NULL;
Ghislain MARY's avatar
Ghislain MARY committed
185
	cl->remote_ufrag = cl->remote_pwd = NULL;
186
	cl->local_candidates = cl->remote_candidates = cl->pairs = cl->triggered_checks_queue = cl->check_list = cl->valid_list = NULL;
187
	cl->componentIDs = cl->foundations = NULL;
188
	cl->state = ICL_Running;
189
	cl->ta_time = 0;
190
	cl->foundation_generator = 1;
191 192
}

193 194 195 196 197 198 199 200 201 202 203
IceCheckList * ice_check_list_new(void)
{
	IceCheckList *cl = ms_new(IceCheckList, 1);
	if (cl == NULL) {
		ms_error("ice_check_list_new: Memory allocation failed");
		return NULL;
	}
	ice_check_list_init(cl);
	return cl;
}

204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
static void ice_compute_pair_priority(IceCandidatePair *pair, IceRole *role)
{
	/* Use formula defined in 5.7.2 to compute pair priority. */
	uint64_t G;
	uint64_t D;

	switch (*role) {
		case IR_Controlling:
			G = pair->local->priority;
			D = pair->remote->priority;
			break;
		case IR_Controlled:
			G = pair->remote->priority;
			D = pair->local->priority;
			break;
	}
	pair->priority = (MIN(G, D) << 32) | (MAX(G, D) << 1) | (G > D ? 1 : 0);
}

static IceCandidatePair *ice_pair_new(IceCheckList *cl, IceCandidate* local_candidate, IceCandidate *remote_candidate)
{
	IceCandidatePair *pair = ms_new(IceCandidatePair, 1);
	pair->local = local_candidate;
	pair->remote = remote_candidate;
	ice_pair_set_state(pair, ICP_Frozen);
	pair->is_default = FALSE;
	pair->is_nominated = FALSE;
	if ((pair->local->is_default == TRUE) && (pair->remote->is_default == TRUE)) pair->is_default = TRUE;
	else pair->is_default = FALSE;
	memset(&pair->transactionID, 0, sizeof(pair->transactionID));
	pair->rto = ICE_DEFAULT_RTO_DURATION;
	pair->retransmissions = 0;
	pair->role = cl->session->role;
	ice_compute_pair_priority(pair, &cl->session->role);
	return pair;
}

241 242 243 244 245
static void ice_free_pair_foundation(IcePairFoundation *foundation)
{
	ms_free(foundation);
}

246 247 248 249 250
static void ice_free_valid_pair(IceValidCandidatePair *valid_pair)
{
	ms_free(valid_pair);
}

Ghislain MARY's avatar
Ghislain MARY committed
251 252 253 254 255
static void ice_free_candidate_pair(IceCandidatePair *pair)
{
	ms_free(pair);
}

256 257 258 259 260
static void ice_free_candidate(IceCandidate *candidate)
{
	ms_free(candidate);
}

261 262
void ice_check_list_destroy(IceCheckList *cl)
{
Ghislain MARY's avatar
Ghislain MARY committed
263 264
	if (cl->remote_ufrag) ms_free(cl->remote_ufrag);
	if (cl->remote_pwd) ms_free(cl->remote_pwd);
265
	ms_list_for_each(cl->foundations, (void (*)(void*))ice_free_pair_foundation);
266
	ms_list_for_each(cl->valid_list, (void (*)(void*))ice_free_valid_pair);
267 268 269 270
	ms_list_for_each(cl->pairs, (void (*)(void*))ice_free_candidate_pair);
	ms_list_for_each(cl->remote_candidates, (void (*)(void*))ice_free_candidate);
	ms_list_for_each(cl->local_candidates, (void (*)(void*))ice_free_candidate);
	ms_list_free(cl->foundations);
271
	ms_list_free(cl->componentIDs);
Ghislain MARY's avatar
Ghislain MARY committed
272
	ms_list_free(cl->valid_list);
273
	ms_list_free(cl->check_list);
274
	ms_list_free(cl->triggered_checks_queue);
275 276 277 278 279 280 281
	ms_list_free(cl->pairs);
	ms_list_free(cl->remote_candidates);
	ms_list_free(cl->local_candidates);
	ms_free(cl);
}


282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
/******************************************************************************
 * CANDIDATE PAIR ACCESSORS                                                   *
 *****************************************************************************/

static void ice_pair_set_state(IceCandidatePair *pair, IceCandidatePairState state)
{
	if (pair->state != state) {
		pair->state = state;
		switch (state) {
			case ICP_Failed:
			case ICP_Waiting:
				memset(&pair->transactionID, 0, sizeof(pair->transactionID));
				break;
			case ICP_InProgress:
			case ICP_Succeeded:
			case ICP_Frozen:
				break;
		}
	}
}


304 305 306 307 308 309 310 311 312
/******************************************************************************
 * CHECK LIST ACCESSORS                                                       *
 *****************************************************************************/

IceCheckListState ice_check_list_state(IceCheckList *cl)
{
	return cl->state;
}

Ghislain MARY's avatar
Ghislain MARY committed
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
const char * ice_check_list_local_ufrag(IceCheckList *cl)
{
	/* Do not handle media specific ufrag for the moment, so use the session local ufrag. */
	return cl->session->local_ufrag;
}

const char * ice_check_list_local_pwd(IceCheckList *cl)
{
	/* Do not handle media specific pwd for the moment, so use the session local pwd. */
	return cl->session->local_pwd;
}

const char * ice_check_list_remote_ufrag(IceCheckList *cl)
{
	if (cl->remote_ufrag) return cl->remote_ufrag;
	else return cl->session->remote_ufrag;
}

const char * ice_check_list_remote_pwd(IceCheckList *cl)
{
	if (cl->remote_pwd) return cl->remote_pwd;
	else return cl->session->remote_pwd;
}

void ice_check_list_set_remote_credentials(IceCheckList *cl, const char *ufrag, const char *pwd)
{
	ice_set_credentials(&cl->remote_ufrag, &cl->remote_pwd, ufrag, pwd);
}

342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
static void ice_check_list_queue_triggered_check(IceCheckList *cl, IceCandidatePair *pair)
{
	MSList *elem = ms_list_find(cl->triggered_checks_queue, pair);
	if (elem != NULL) {
		/* The pair is already in the triggered checks queue, do not add it again. */
	} else {
		cl->triggered_checks_queue = ms_list_append(cl->triggered_checks_queue, pair);
	}
}

static IceCandidatePair * ice_check_list_pop_triggered_check(IceCheckList *cl)
{
	IceCandidatePair *pair;

	if (ms_list_size(cl->triggered_checks_queue) == 0) return NULL;
	pair = ms_list_nth_data(cl->triggered_checks_queue, 0);
	if (pair != NULL) {
		/* Remove the first element in the triggered checks queue. */
		cl->triggered_checks_queue = ms_list_remove_link(cl->triggered_checks_queue, cl->triggered_checks_queue);
	}
	return pair;
}

Ghislain MARY's avatar
Ghislain MARY committed
365 366 367 368 369

/******************************************************************************
 * SESSION ACCESSORS                                                          *
 *****************************************************************************/

Ghislain MARY's avatar
Ghislain MARY committed
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
const char * ice_session_local_ufrag(IceSession *session)
{
	return session->local_ufrag;
}

const char * ice_session_local_pwd(IceSession *session)
{
	return session->local_pwd;
}

const char * ice_session_remote_ufrag(IceSession *session)
{
	return session->remote_ufrag;
}

const char * ice_session_remote_pwd(IceSession *session)
{
	return session->remote_pwd;
}

390 391 392 393 394 395 396 397 398 399
static void ice_check_list_compute_pair_priorities(IceCheckList *cl)
{
	ms_list_for_each2(cl->pairs, (void (*)(void*,void*))ice_compute_pair_priority, &cl->session->role);
}

static void ice_session_compute_pair_priorities(IceSession *session)
{
	ms_list_for_each(session->streams, (void (*)(void*))ice_check_list_compute_pair_priorities);
}

Ghislain MARY's avatar
Ghislain MARY committed
400 401
void ice_session_set_role(IceSession *session, IceRole role)
{
402 403 404 405 406
	if (session->role != role) {
		/* Compute new candidate pair priorities if the role changes. */
		session->role = role;
		ice_session_compute_pair_priorities(session);
	}
Ghislain MARY's avatar
Ghislain MARY committed
407 408
}

Ghislain MARY's avatar
Ghislain MARY committed
409 410 411 412 413 414 415 416 417 418
void ice_session_set_local_credentials(IceSession *session, const char *ufrag, const char *pwd)
{
	ice_set_credentials(&session->local_ufrag, &session->local_pwd, ufrag, pwd);
}

void ice_session_set_remote_credentials(IceSession *session, const char *ufrag, const char *pwd)
{
	ice_set_credentials(&session->remote_ufrag, &session->remote_pwd, ufrag, pwd);
}

Ghislain MARY's avatar
Ghislain MARY committed
419 420 421 422 423 424 425 426 427 428 429
void ice_session_set_max_connectivity_checks(IceSession *session, uint8_t max_connectivity_checks)
{
	session->max_connectivity_checks = max_connectivity_checks;
}


/******************************************************************************
 * SESSION HANDLING                                                           *
 *****************************************************************************/

void ice_session_add_check_list(IceSession *session, IceCheckList *cl)
430
{
Ghislain MARY's avatar
Ghislain MARY committed
431 432
	session->streams = ms_list_append(session->streams, cl);
	cl->session = session;
433 434 435 436 437 438 439
}


/******************************************************************************
 * STUN PACKETS HANDLING                                                      *
 *****************************************************************************/

440
/* Send a STUN binding request for ICE connectivity checks according to 7.1.2. */
441
static void ice_send_binding_request(IceCheckList *cl, IceCandidatePair *pair, RtpSession *rtp_session)
442 443 444
{
	StunMessage msg;
	StunAddress4 dest;
445 446
	StunAtrString username;
	StunAtrString password;
447 448 449 450
	char buf[STUN_MAX_MESSAGE_SIZE];
	int len = STUN_MAX_MESSAGE_SIZE;
	int socket = 0;

451 452 453 454 455 456 457 458 459
	if (pair->state == ICP_InProgress) {
		/* This is a retransmission: update the number of retransmissions, the retransmission timer value, and the transmission time. */
		pair->retransmissions++;
		if (pair->retransmissions > ICE_MAX_RETRANSMISSIONS) {
			/* Too much retransmissions, stop sending connectivity checks for this pair. */
			ice_pair_set_state(pair, ICP_Failed);
			return;
		}
		pair->rto = pair->rto << 1;
460
		pair->transmission_time = cl->session->ticker->time;
461 462
	}

463
	if (pair->local->componentID == 1) {
464
		socket = rtp_session_get_rtp_socket(rtp_session);
465
	} else if (pair->local->componentID == 2) {
466
		socket = rtp_session_get_rtcp_socket(rtp_session);
467 468
	} else return;

469 470 471 472 473 474
	// TODO: Check size of username.value because "RFRAG:LFRAG" can be up to 513 bytes!
	snprintf(username.value, sizeof(username.value) - 1, "%s:%s", ice_check_list_remote_ufrag(cl), ice_check_list_local_ufrag(cl));
	username.sizeValue = strlen(username.value);
	snprintf(password.value, sizeof(password.value) - 1, "%s", ice_check_list_remote_pwd(cl));
	password.sizeValue = strlen(password.value);

475 476
	stunParseHostName(pair->remote->taddr.ip, &dest.addr, &dest.port, pair->remote->taddr.port);
	memset(&msg, 0, sizeof(msg));
477
	stunBuildReqSimple(&msg, &username, FALSE, FALSE, 1);	// TODO: Should the id always be 1???
478
	msg.hasMessageIntegrity = TRUE;
479
	msg.hasFingerprint = TRUE;
480 481 482 483 484 485

	/* Set the PRIORITY attribute as defined in 7.1.2.1. */
	msg.hasPriority = TRUE;
	msg.priority.priority = (pair->local->priority & 0x00ffffff) | (type_preference_values[ICT_PeerReflexiveCandidate] << 24);

	/* Include the USE-CANDIDATE attribute if the pair is nominated and the agent has the controlling role, as defined in 7.1.2.1. */
486
	if ((cl->session->role == IR_Controlling) && (pair->is_nominated == TRUE)) {
487 488 489
		msg.hasUseCandidate = TRUE;
	}

490
	/* Include the ICE-CONTROLLING or ICE-CONTROLLED attribute depending on the role of the agent, as defined in 7.1.2.2. */
491
	switch (cl->session->role) {
492 493
		case IR_Controlling:
			msg.hasIceControlling = TRUE;
494
			msg.iceControlling.value = cl->session->tie_breaker;
495 496 497
			break;
		case IR_Controlled:
			msg.hasIceControlled = TRUE;
498
			msg.iceControlled.value = cl->session->tie_breaker;
499 500
			break;
	}
501

502
	len = stunEncodeMessage(&msg, buf, len, &password);
503 504 505 506
	if (len > 0) {
		/* Save the generated transaction ID to match the response to the request, and send the request. */
		memcpy(&pair->transactionID, &msg.msgHdr.tr_id, sizeof(pair->transactionID));
		sendMessage(socket, buf, len, dest.addr, dest.port);
Ghislain MARY's avatar
Ghislain MARY committed
507

508
		/* Save the role of the agent. */
509
		pair->role = cl->session->role;
510

511
		if (pair->state != ICP_InProgress) {
512 513 514 515 516 517
			/* First transmission of the request, initialize the retransmission timer. */
			pair->rto = ICE_DEFAULT_RTO_DURATION;
			pair->retransmissions = 0;
			/* Change the state of the pair. */
			ice_pair_set_state(pair, ICP_InProgress);
		}
518 519 520
	}
}

521 522 523 524 525 526 527 528 529 530 531
static int ice_get_socket_from_rtp_session(RtpSession *rtp_session, OrtpEventData *evt_data)
{
	if (evt_data->info.socket_type == OrtpRTPSocket) {
		return rtp_session_get_rtp_socket(rtp_session);
	} else if (evt_data->info.socket_type == OrtpRTCPSocket) {
		return rtp_session_get_rtcp_socket(rtp_session);
	}
	return -1;
}

static void ice_send_binding_response(RtpSession *rtp_session, OrtpEventData *evt_data, const StunMessage *msg, const StunAddress4 *dest)
532 533 534 535 536
{
	StunMessage response;
	StunAtrString password;
	char buf[STUN_MAX_MESSAGE_SIZE];
	int len = STUN_MAX_MESSAGE_SIZE;
537
	int socket = ice_get_socket_from_rtp_session(rtp_session, evt_data);
538

539
	if (socket < 0) return;
540 541 542 543 544 545 546 547 548 549 550 551 552 553
	memset(&response, 0, sizeof(response));

	/* Copy magic cookie and transaction ID from the request. */
	response.msgHdr.magic_cookie = ntohl(msg->msgHdr.magic_cookie);
	memcpy(&response.msgHdr.tr_id, &msg->msgHdr.tr_id, sizeof(response.msgHdr.tr_id));

	/* Create the binding response. */
	response.msgHdr.msgType = (STUN_METHOD_BINDING | STUN_SUCCESS_RESP);
	response.hasMessageIntegrity = TRUE;
	response.hasFingerprint = TRUE;
	response.hasUsername = TRUE;
	memcpy(response.username.value, msg->username.value, msg->username.sizeValue);
	response.username.sizeValue = msg->username.sizeValue;

554 555 556 557 558
	/* Add the mapped address to the response. */
	response.hasXorMappedAddress = TRUE;
	response.xorMappedAddress.ipv4.port = dest->port ^ (stun_magic_cookie >> 16);
	response.xorMappedAddress.ipv4.addr = dest->addr ^ stun_magic_cookie;

559 560 561 562 563 564
	len = stunEncodeMessage(&response, buf, len, &password);
	if (len > 0) {
		sendMessage(socket, buf, len, dest->addr, dest->port);
	}
}

565
static void ice_send_error_response(RtpSession *rtp_session, OrtpEventData *evt_data, const StunMessage *msg, uint8_t err_class, uint8_t err_num, const StunAddress4 *dest, const char *error)
566 567 568 569 570
{
	StunMessage response;
	StunAtrString password;
	char buf[STUN_MAX_MESSAGE_SIZE];
	int len = STUN_MAX_MESSAGE_SIZE;
571
	int socket = ice_get_socket_from_rtp_session(rtp_session, evt_data);
572

573
	if (socket < 0) return;
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
	memset(&response, 0, sizeof(response));

	/* Copy magic cookie and transaction ID from the request. */
	response.msgHdr.magic_cookie = ntohl(msg->msgHdr.magic_cookie);
	memcpy(&response.msgHdr.tr_id, &msg->msgHdr.tr_id, sizeof(response.msgHdr.tr_id));

	/* Create the error response. */
	response.msgHdr.msgType = (STUN_METHOD_BINDING | STUN_ERR_RESP);
	response.hasErrorCode = TRUE;
	response.errorCode.errorClass = err_class;
	response.errorCode.number = err_num;
	strcpy(response.errorCode.reason, error);
	response.errorCode.sizeReason = strlen(error);
	response.hasFingerprint = TRUE;

	len = stunEncodeMessage(&response, buf, len, &password);
	if (len > 0) {
		sendMessage(socket, buf, len, dest->addr, dest->port);
	}
}

595 596 597 598 599
static int ice_find_candidate_from_transport_address(IceCandidate *candidate, IceTransportAddress *taddr)
{
	return ice_compare_transport_addresses(&candidate->taddr, taddr);
}

600
/* Check that the mandatory attributes of a connectivity check binding request are present. */
601
static int ice_check_received_binding_request_attributes(RtpSession *rtp_session, OrtpEventData *evt_data, const StunMessage *msg, const StunAddress4 *remote_addr)
602 603 604
{
	if (!msg->hasMessageIntegrity) {
		ms_warning("ice: Received binding request missing MESSAGE-INTEGRITY attribute");
605
		ice_send_error_response(rtp_session, evt_data, msg, 4, 0, remote_addr, "Missing MESSAGE-INTEGRITY attribute");
606 607 608 609
		return -1;
	}
	if (!msg->hasUsername) {
		ms_warning("ice: Received binding request missing USERNAME attribute");
610
		ice_send_error_response(rtp_session, evt_data, msg, 4, 0, remote_addr, "Missing USERNAME attribute");
611 612 613 614
		return -1;
	}
	if (!msg->hasFingerprint) {
		ms_warning("ice: Received binding request missing FINGERPRINT attribute");
615
		ice_send_error_response(rtp_session, evt_data, msg, 4, 0, remote_addr, "Missing FINGERPRINT attribute");
616 617 618 619
		return -1;
	}
	if (!msg->hasPriority) {
		ms_warning("ice: Received binding request missing PRIORITY attribute");
620
		ice_send_error_response(rtp_session, evt_data, msg, 4, 0, remote_addr, "Missing PRIORITY attribute");
621 622 623 624
		return -1;
	}
	if (!msg->hasIceControlling && !msg->hasIceControlled) {
		ms_warning("ice: Received binding request missing ICE-CONTROLLING or ICE-CONTROLLED attribute");
625
		ice_send_error_response(rtp_session, evt_data ,msg, 4, 0, remote_addr, "Missing ICE-CONTROLLING or ICE-CONTROLLED attribute");
626 627 628 629 630
		return -1;
	}
	return 0;
}

631
static int ice_check_received_binding_request_integrity(IceCheckList *cl, RtpSession *rtp_session, OrtpEventData *evt_data, const StunMessage *msg, const StunAddress4 *remote_addr)
632 633
{
	char hmac[20];
634
	mblk_t *mp = evt_data->packet;
635 636 637 638 639 640 641 642 643 644 645

	/* Check the message integrity: first remove length of fingerprint... */
	char *lenpos = (char *)mp->b_rptr + sizeof(uint16_t);
	uint16_t newlen = htons(msg->msgHdr.msgLength - 8);
	memcpy(lenpos, &newlen, sizeof(uint16_t));
	stunCalculateIntegrity_shortterm(hmac, (char *)mp->b_rptr, mp->b_wptr - mp->b_rptr - 24 - 8, ice_check_list_local_pwd(cl));
	/* ... and then restore the length with fingerprint. */
	newlen = htons(msg->msgHdr.msgLength);
	memcpy(lenpos, &newlen, sizeof(uint16_t));
	if (memcmp(msg->messageIntegrity.hash, hmac, sizeof(hmac)) != 0) {
		ms_error("ice: Wrong MESSAGE-INTEGRITY in received binding request");
646
		ice_send_error_response(rtp_session, evt_data, msg, 4, 1, remote_addr, "Wrong MESSAGE-INTEGRITY attribute");
647 648 649 650 651
		return -1;
	}
	return 0;
}

652
static int ice_check_received_binding_request_username(IceCheckList *cl, RtpSession *rtp_session, OrtpEventData *evt_data, const StunMessage *msg, const StunAddress4 *remote_addr)
653 654 655 656 657 658 659 660 661 662
{
	char username[256];
	char *colon;

	/* Check if the username is valid. */
	memset(username, '\0', sizeof(username));
	memcpy(username, msg->username.value, msg->username.sizeValue);
	colon = strchr(username, ':');
	if ((colon == NULL) || (strncmp(username, ice_check_list_local_ufrag(cl), colon - username) != 0)) {
		ms_error("ice: Wrong USERNAME attribute");
663
		ice_send_error_response(rtp_session, evt_data, msg, 4, 1, remote_addr, "Wrong USERNAME attribute");
664 665 666 667 668
		return -1;
	}
	return 0;
}

669
static int ice_check_received_binding_request_role_conflict(IceCheckList *cl, RtpSession *rtp_session, OrtpEventData *evt_data, const StunMessage *msg, const StunAddress4 *remote_addr)
670 671 672 673 674
{
	/* Detect and repair role conflicts according to 7.2.1.1. */
	if ((cl->session->role == IR_Controlling) && (msg->hasIceControlling)) {
		ms_warning("ice: Role conflict, both agents are CONTROLLING");
		if (cl->session->tie_breaker >= msg->iceControlling.value) {
675
			ice_send_error_response(rtp_session, evt_data, msg, 4, 87, remote_addr, "Role Conflict");
676 677 678 679 680 681 682 683 684 685 686
			return -1;
		} else {
			ms_message("ice: Switch to the CONTROLLED role");
			ice_session_set_role(cl->session, IR_Controlled);
		}
	} else if ((cl->session->role == IR_Controlled) && (msg->hasIceControlled)) {
		ms_warning("ice: Role conflict, both agents are CONTROLLED");
		if (cl->session->tie_breaker >= msg->iceControlled.value) {
			ms_message("ice: Switch to the CONTROLLING role");
			ice_session_set_role(cl->session, IR_Controlling);
		} else {
687
			ice_send_error_response(rtp_session, evt_data, msg, 4, 87, remote_addr, "Role Conflict");
688 689 690 691 692 693
			return -1;
		}
	}
	return 0;
}

694 695 696 697 698 699 700
static void ice_fill_transport_address(IceTransportAddress *taddr, const char *ip, int port)
{
	memset(taddr, 0, sizeof(IceTransportAddress));
	strncpy(taddr->ip, ip, sizeof(taddr->ip));
	taddr->port = port;
}

701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
static int ice_find_candidate_from_foundation(IceCandidate *candidate, const char *foundation)
{
	return !((strlen(candidate->foundation) == strlen(foundation)) && (strcmp(candidate->foundation, foundation) == 0));
}

static void ice_generate_arbitrary_foundation(char *foundation, int len, MSList *list)
{
	long long unsigned int r;
	MSList *elem;

	do {
		r = (random() << 32) | random();
		snprintf(foundation, len, "%llx", r);
		elem = ms_list_find_custom(list, (MSCompareFunc)ice_find_candidate_from_foundation, foundation);
	} while (elem != NULL);
}

718
static IceCandidate * ice_learn_peer_reflexive_candidate(IceCheckList *cl, RtpSession *rtp_session, OrtpEventData *evt_data, const StunMessage *msg, const IceTransportAddress *taddr)
719
{
720 721 722
	char foundation[32];
	IceCandidate *candidate = NULL;
	MSList *elem;
723 724 725 726 727 728 729
	uint16_t componentID;

	if (evt_data->info.socket_type == OrtpRTPSocket) {
		componentID = 1;
	} else if (evt_data->info.socket_type == OrtpRTCPSocket) {
		componentID = 2;
	} else return NULL;
730

731
	elem = ms_list_find_custom(cl->remote_candidates, (MSCompareFunc)ice_find_candidate_from_transport_address, taddr);
732
	if (elem == NULL) {
733
		ms_message("ice: Learned peer reflexive candidate %s:%d", taddr->ip, taddr->port);
734 735 736
		/* Add peer reflexive candidate to the remote candidates list. */
		memset(foundation, '\0', sizeof(foundation));
		ice_generate_arbitrary_foundation(foundation, sizeof(foundation), cl->remote_candidates);
737
		candidate = ice_add_remote_candidate(cl, "prflx", taddr->ip, taddr->port, componentID, msg->priority.priority, foundation);
738 739 740 741
	}
	return candidate;
}

742 743 744 745 746 747
static int ice_find_pair_from_candidates(IceCandidatePair *pair, LocalCandidate_RemoteCandidate *candidates)
{
	return !((pair->local == candidates->local) && (pair->remote == candidates->remote));
}

/* Trigger checks as defined in 7.2.1.4. */
748
static IceCandidatePair * ice_trigger_connectivity_check_on_binding_request(IceCheckList *cl, RtpSession *rtp_session, OrtpEventData *evt_data, IceCandidate *prflx_candidate, const IceTransportAddress *remote_taddr)
749 750 751 752
{
	IceTransportAddress local_taddr;
	LocalCandidate_RemoteCandidate candidates;
	MSList *elem;
753
	IceCandidatePair *pair = NULL;
754 755 756 757 758 759 760
	int recv_port;

	if (evt_data->info.socket_type == OrtpRTPSocket) {
		recv_port = rtp_session->rtp.loc_port;
	} else if (evt_data->info.socket_type == OrtpRTCPSocket) {
		recv_port = rtp_session->rtp.loc_port + 1;
	} else return NULL;
761

762
	ice_fill_transport_address(&local_taddr, "192.168.0.147", recv_port);	// TODO: Get local IP address
763 764 765
	elem = ms_list_find_custom(cl->local_candidates, (MSCompareFunc)ice_find_candidate_from_transport_address, &local_taddr);
	if (elem == NULL) {
		ms_error("Local candidate %s:%d not found!", local_taddr.ip, local_taddr.port);
766
		return NULL;
767 768 769 770 771 772 773 774
	}
	candidates.local = (IceCandidate *)elem->data;
	if (prflx_candidate != NULL) {
		candidates.remote = prflx_candidate;
	} else {
		elem = ms_list_find_custom(cl->remote_candidates, (MSCompareFunc)ice_find_candidate_from_transport_address, remote_taddr);
		if (elem == NULL) {
			ms_error("Remote candidate %s:%d not found!", remote_taddr->ip, remote_taddr->port);
775
			return NULL;
776 777 778
		}
		candidates.remote = (IceCandidate *)elem->data;
	}
779
	elem = ms_list_find_custom(cl->check_list, (MSCompareFunc)ice_find_pair_from_candidates, &candidates);
780 781 782 783
	if (elem == NULL) {
		/* The pair is not in the check list yet. */
		ms_message("ice: Add new candidate pair in the check list");
		pair = ice_pair_new(cl, candidates.local, candidates.remote);
784 785
		cl->pairs = ms_list_append(cl->pairs, pair);
		cl->check_list = ms_list_insert_sorted(cl->check_list, pair, (MSCompareFunc)ice_compare_pair_priorities);
786 787
		/* Set the state of the pair to Waiting and trigger a check. */
		ice_pair_set_state(pair, ICP_Waiting);
788
		ice_check_list_queue_triggered_check(cl, pair);
789 790 791 792 793 794 795 796 797
	} else {
		/* The pair has been found in the check list. */
		pair = (IceCandidatePair *)elem->data;
		switch (pair->state) {
			case ICP_Waiting:
			case ICP_Frozen:
			case ICP_InProgress:
			case ICP_Failed:
				ice_pair_set_state(pair, ICP_Waiting);
798
				ice_check_list_queue_triggered_check(cl, pair);
799 800 801 802 803 804
				break;
			case ICP_Succeeded:
				/* Nothing to be done. */
				break;
		}
	}
805 806 807 808
	return pair;
}

/* Update the nominated flag of a candidate pair according to 7.2.1.5. */
809
static void ice_update_nominated_flag_on_binding_request(IceCheckList *cl, RtpSession *rtp_session, const StunMessage *msg, IceCandidatePair *pair)
810 811 812 813 814 815 816 817 818 819 820 821 822 823
{
	if (msg->hasUseCandidate && (cl->session->role == IR_Controlled)) {
		switch (pair->state) {
			case ICP_Succeeded:
				pair->is_nominated = TRUE;
				break;
			case ICP_Waiting:
			case ICP_Frozen:
			case ICP_InProgress:
			case ICP_Failed:
				/* Nothing to be done. */
				break;
		}
	}
824 825

	ice_conclude_processing(cl, rtp_session);
826 827
}

828
static void ice_handle_received_binding_request(IceCheckList *cl, RtpSession *rtp_session, OrtpEventData *evt_data, const StunMessage *msg, const StunAddress4 *remote_addr, const char *src6host)
829
{
830 831
	IceTransportAddress taddr;
	IceCandidate *prflx_candidate;
832
	IceCandidatePair *pair;
833

834 835 836 837
	if (ice_check_received_binding_request_attributes(rtp_session, evt_data, msg, remote_addr) < 0) return;
	if (ice_check_received_binding_request_integrity(cl, rtp_session, evt_data, msg, remote_addr) < 0) return;
	if (ice_check_received_binding_request_username(cl, rtp_session, evt_data, msg, remote_addr) < 0) return;
	if (ice_check_received_binding_request_role_conflict(cl, rtp_session, evt_data, msg, remote_addr) < 0) return;
838

839
	ice_fill_transport_address(&taddr, src6host, remote_addr->port);
840 841
	prflx_candidate = ice_learn_peer_reflexive_candidate(cl, rtp_session, evt_data, msg, &taddr);
	pair = ice_trigger_connectivity_check_on_binding_request(cl, rtp_session, evt_data, prflx_candidate, &taddr);
842
	if (pair != NULL) ice_update_nominated_flag_on_binding_request(cl, rtp_session, msg, pair);
843
	ice_send_binding_response(rtp_session, evt_data, msg, remote_addr);
844 845
}

Ghislain MARY's avatar
Ghislain MARY committed
846 847 848 849 850
static int ice_find_pair_from_transactionID(IceCandidatePair *pair, UInt96 *transactionID)
{
	return memcmp(&pair->transactionID, transactionID, sizeof(pair->transactionID));
}

851
static int ice_check_received_binding_response_addresses(IceCandidatePair *pair, const StunAddress4 *remote_addr)
852 853 854 855 856 857 858 859 860
{
	StunAddress4 dest;

	stunParseHostName(pair->remote->taddr.ip, &dest.addr, &dest.port, pair->remote->taddr.port);
	if ((remote_addr->addr != dest.addr) || (remote_addr->port != dest.port)) {
		// TODO: Need to also check that the address/port on which we received the response match the local address/port of the pair
		/* Non-symmetric addresses, set the state of the pair to Failed as defined in 7.1.3.1. */
		ms_warning("ice: Non symmetric addresses, set state of pair %p to Failed", pair);
		ice_pair_set_state(pair, ICP_Failed);
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
		return -1;
	}
	return 0;
}

static int ice_check_received_binding_response_attributes(const StunMessage *msg, const StunAddress4 *remote_addr)
{
	if (!msg->hasUsername) {
		ms_warning("ice: Received binding response missing USERNAME attribute");
		return -1;
	}
	if (!msg->hasFingerprint) {
		ms_warning("ice: Received binding response missing FINGERPRINT attribute");
		return -1;
	}
	if (!msg->hasXorMappedAddress) {
		ms_warning("ice: Received binding response missing XOR-MAPPED-ADDRESS attribute");
		return -1;
879
	}
880 881 882 883 884 885 886 887 888 889 890 891 892 893
	return 0;
}

static IceCandidate * ice_discover_peer_reflexive_candidate(IceCheckList *cl, IceCandidatePair *pair, const StunMessage *msg)
{
	struct in_addr inaddr;
	IceTransportAddress taddr;
	IceCandidate *candidate = NULL;
	MSList *elem;

	memset(&taddr, 0, sizeof(taddr));
	inaddr.s_addr = htonl(msg->xorMappedAddress.ipv4.addr);
	snprintf(taddr.ip, sizeof(taddr.ip), "%s", inet_ntoa(inaddr));
	taddr.port = msg->xorMappedAddress.ipv4.port;
894
	elem = ms_list_find_custom(cl->local_candidates, (MSCompareFunc)ice_find_candidate_from_transport_address, &taddr);
895 896 897 898 899 900 901 902
	if (elem == NULL) {
		ms_message("ice: Discovered peer reflexive candidate %s:%d", taddr.ip, taddr.port);
		/* Add peer reflexive candidate to the local candidates list. */
		candidate = ice_add_local_candidate(cl, "prflx", taddr.ip, taddr.port, pair->local->componentID, pair->local);
		ice_compute_candidate_foundation(candidate, cl);
	}
	return candidate;
}
903

904 905 906 907 908 909 910 911 912 913
static int ice_compare_valid_pair_priorities(IceValidCandidatePair *vp1, IceValidCandidatePair *vp2)
{
	return ice_compare_pair_priorities(vp1->valid, vp2->valid);
}

static int ice_find_valid_pair(IceValidCandidatePair *vp1, IceValidCandidatePair *vp2)
{
	return !((vp1->valid == vp2->valid) && (vp1->generated_from == vp2->generated_from));
}

Ghislain MARY's avatar
Ghislain MARY committed
914
/* Construct a valid ICE candidate pair as defined in 7.1.3.2.2. */
915
static IceCandidatePair * ice_construct_valid_pair(IceCheckList *cl, RtpSession *rtp_session, OrtpEventData *evt_data, IceCandidate *prflx_candidate, IceCandidatePair *succeeded_pair)
Ghislain MARY's avatar
Ghislain MARY committed
916 917 918 919
{
	IceTransportAddress local_taddr;
	LocalCandidate_RemoteCandidate candidates;
	IceCandidatePair *pair = NULL;
920
	IceValidCandidatePair *valid_pair;
Ghislain MARY's avatar
Ghislain MARY committed
921
	MSList *elem;
922
	int recv_port;
Ghislain MARY's avatar
Ghislain MARY committed
923 924 925 926

	if (prflx_candidate != NULL) {
		candidates.local = prflx_candidate;
	} else {
927 928 929 930 931 932 933
		if (evt_data->info.socket_type == OrtpRTPSocket) {
			recv_port = rtp_session->rtp.loc_port;
		} else if (evt_data->info.socket_type == OrtpRTCPSocket) {
			recv_port = rtp_session->rtp.loc_port + 1;
		} else return NULL;

		ice_fill_transport_address(&local_taddr, "192.168.0.147", recv_port);	// TODO: Get local IP address
Ghislain MARY's avatar
Ghislain MARY committed
934 935 936 937 938 939 940
		elem = ms_list_find_custom(cl->local_candidates, (MSCompareFunc)ice_find_candidate_from_transport_address, &local_taddr);
		if (elem == NULL) {
			ms_error("Local candidate %s:%d not found!", local_taddr.ip, local_taddr.port);
			return NULL;
		}
		candidates.local = (IceCandidate *)elem->data;
	}
941
	candidates.remote = succeeded_pair->remote;
942
	elem = ms_list_find_custom(cl->check_list, (MSCompareFunc)ice_find_pair_from_candidates, &candidates);
Ghislain MARY's avatar
Ghislain MARY committed
943 944 945
	if (elem == NULL) {
		/* The candidate pair is not a known candidate pair, compute its priority and add it to the valid list. */
		pair = ice_pair_new(cl, candidates.local, candidates.remote);
946
		cl->pairs = ms_list_append(cl->pairs, pair);
Ghislain MARY's avatar
Ghislain MARY committed
947 948 949 950
	} else {
		/* The candidate pair is already in the check list, add it to the valid list. */
		pair = (IceCandidatePair *)elem->data;
	}
951 952 953 954 955 956 957 958 959
	valid_pair = ms_new(IceValidCandidatePair, 1);
	valid_pair->valid = pair;
	valid_pair->generated_from = succeeded_pair;
	elem = ms_list_find_custom(cl->valid_list, (MSCompareFunc)ice_find_valid_pair, valid_pair);
	if (elem == NULL) {
		cl->valid_list = ms_list_insert_sorted(cl->valid_list, valid_pair, (MSCompareFunc)ice_compare_valid_pair_priorities);
		ms_message("Added pair %p to the valid list", pair);
	} else {
		ms_message("Pair %p already in the valid list", pair);
960
		ms_free(valid_pair);
961
	}
Ghislain MARY's avatar
Ghislain MARY committed
962 963 964
	return pair;
}

965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
static int ice_compare_pair_foundations(IceCandidatePair *p1, IceCandidatePair *p2)
{
	return !((strlen(p1->local->foundation) == strlen(p2->local->foundation)) && (strcmp(p1->local->foundation, p2->local->foundation) == 0)
		&& ((strlen(p1->remote->foundation) == strlen(p2->remote->foundation)) && (strcmp(p1->remote->foundation, p2->remote->foundation) == 0)));
}

static void ice_change_state_of_frozen_pairs_to_waiting(IceCandidatePair *pair, IceCandidatePair *succeeded_pair)
{
	if ((pair != succeeded_pair) && (pair->state == ICP_Frozen) && (ice_compare_pair_foundations(pair, succeeded_pair) == 0)) {
		ms_message("Change state of pair %p from Frozen to Waiting", pair);
		ice_pair_set_state(pair, ICP_Waiting);
	}
}

/* Update the pair states according to 7.1.3.2.3. */
static void ice_update_pair_states_on_binding_response(IceCheckList *cl, IceCandidatePair *pair)
{
	/* Set the state of the pair that generated the check to Succeeded. */
	ice_pair_set_state(pair, ICP_Succeeded);

	/* Change the state of all Frozen pairs with the same foundation to Waiting. */
986
	ms_list_for_each2(cl->check_list, (void (*)(void*,void*))ice_change_state_of_frozen_pairs_to_waiting, pair);
987 988 989 990

	// TODO: If there is a pair in the valid list for every component of this media stream, unfreeze checks for other media streams
}

991
/* Update the nominated flag of a candidate pair according to 7.1.3.2.4. */
992
static void ice_update_nominated_flag_on_binding_response(IceCheckList *cl, RtpSession *rtp_session, IceCandidatePair *valid_pair, IceCandidatePair *succeeded_pair, IceCandidatePairState succeeded_pair_previous_state)
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
{
	switch (cl->session->role) {
		case IR_Controlling:
			if (succeeded_pair->is_nominated == TRUE) {
				valid_pair->is_nominated = TRUE;
			}
			break;
		case IR_Controlled:
			if (succeeded_pair_previous_state == ICP_InProgress) {
				valid_pair->is_nominated = TRUE;
			}
			break;
	}

1007
	ice_conclude_processing(cl, rtp_session);
1008 1009
}

1010 1011 1012 1013 1014
static int ice_find_not_failed_or_succeeded_pair(IceCandidatePair *pair, void *dummy)
{
	return !((pair->state != ICP_Failed) && (pair->state != ICP_Succeeded));
}

1015
static int ice_find_valid_pair_from_componentID(IceValidCandidatePair *valid_pair, uint16_t *componentID)
1016
{
1017
	return !(valid_pair->valid->local->componentID == *componentID);
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
}

static void ice_find_valid_pair_for_componentID(uint16_t *componentID, CheckList_Bool *cb)
{
	MSList *elem = ms_list_find_custom(cb->cl->valid_list, (MSCompareFunc)ice_find_valid_pair_from_componentID, componentID);
	if (elem == NULL) {
		/* This component ID is not present in the valid list. */
		cb->result = FALSE;
	}
}

1029 1030 1031
/* Update the check list state according to 7.1.3.3. */
static void ice_update_check_list_state(IceCheckList *cl)
{
1032
	CheckList_Bool cb;
1033
	MSList *elem = ms_list_find_custom(cl->check_list, (MSCompareFunc)ice_find_not_failed_or_succeeded_pair, NULL);
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
	if (elem == NULL) {
		/* All the pairs in the check list are now either in the Failed or Succeeded state. */
		cb.cl = cl;
		cb.result = TRUE;
		ms_list_for_each2(cl->componentIDs, (void (*)(void*,void*))ice_find_valid_pair_for_componentID, &cb);
		if (cb.result == TRUE) {
			/* There is a pair for every component IDs in the valid list. */
			// TODO: Activate an other check list if necessary
		} else {
			cl->state = ICL_Failed;
Ghislain MARY's avatar
Ghislain MARY committed
1044 1045 1046
			ms_message("Failed ICE check list processing!");
			ice_dump_valid_list(cl);
			// TODO: Call a callback function to notify the application of the end of the ICE processing for this check list
1047 1048
		}
	}
1049 1050
}

1051
static void ice_handle_received_binding_response(IceCheckList *cl, RtpSession *rtp_session, OrtpEventData *evt_data, const StunMessage *msg, const StunAddress4 *remote_addr)
1052
{
1053 1054
	IceCandidatePair *succeeded_pair;
	IceCandidatePair *valid_pair;
Ghislain MARY's avatar
Ghislain MARY committed
1055
	IceCandidate *prflx_candidate;
1056
	IceCandidatePairState succeeded_pair_previous_state;
1057
	MSList *elem = ms_list_find_custom(cl->check_list, (MSCompareFunc)ice_find_pair_from_transactionID, &msg->msgHdr.tr_id);
1058 1059 1060 1061 1062
	if (elem == NULL) {
		/* We received an error response concerning an unknown binding request, ignore it... */
		return;
	}

1063 1064
	succeeded_pair = (IceCandidatePair *)elem->data;
	if (ice_check_received_binding_response_addresses(succeeded_pair, remote_addr) < 0) return;
1065 1066
	if (ice_check_received_binding_response_attributes(msg, remote_addr) < 0) return;

1067 1068
	succeeded_pair_previous_state = succeeded_pair->state;
	prflx_candidate = ice_discover_peer_reflexive_candidate(cl, succeeded_pair, msg);
Ghislain MARY's avatar
Ghislain MARY committed
1069
	if (prflx_candidate != NULL) {
1070
		valid_pair = ice_construct_valid_pair(cl, rtp_session, evt_data, prflx_candidate, succeeded_pair);
Ghislain MARY's avatar
Ghislain MARY committed
1071
	} else {
1072
		valid_pair = ice_construct_valid_pair(cl, rtp_session, evt_data, NULL, succeeded_pair);
1073
	}
1074
	ice_update_pair_states_on_binding_response(cl, succeeded_pair);
1075
	ice_update_nominated_flag_on_binding_response(cl, rtp_session, valid_pair, succeeded_pair, succeeded_pair_previous_state);
1076
	ice_update_check_list_state(cl);
1077 1078
}

Ghislain MARY's avatar
Ghislain MARY committed
1079 1080 1081
static void ice_handle_received_error_response(IceCheckList *cl, const StunMessage *msg)
{
	IceCandidatePair *pair;
1082
	MSList *elem = ms_list_find_custom(cl->check_list, (MSCompareFunc)ice_find_pair_from_transactionID, &msg->msgHdr.tr_id);
Ghislain MARY's avatar
Ghislain MARY committed
1083 1084 1085 1086 1087 1088
	if (elem == NULL) {
		/* We received an error response concerning an unknown binding request, ignore it... */
		return;
	}

	pa