ice.c 107 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
/*
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"
31
#include "ortp/ortp.h"
Ghislain MARY's avatar
Ghislain MARY committed
32 33


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

37 38
#define ICE_MIN_COMPONENTID		1
#define ICE_MAX_COMPONENTID		256
39
#define ICE_INVALID_COMPONENTID		0
Ghislain MARY's avatar
Ghislain MARY committed
40 41
#define ICE_MAX_UFRAG_LEN		256
#define ICE_MAX_PWD_LEN			256
Ghislain MARY's avatar
Ghislain MARY committed
42 43 44
#define ICE_DEFAULT_TA_DURATION		20	/* In milliseconds */
#define ICE_DEFAULT_RTO_DURATION	100	/* In milliseconds */
#define ICE_DEFAULT_KEEPALIVE_TIMEOUT   15	/* In seconds */
45
#define ICE_GATHERING_CANDIDATES_TIMEOUT	2500	/* In milliseconds */
46
#define ICE_MAX_RETRANSMISSIONS		7
47

48

49 50 51 52 53
typedef struct _Type_ComponentID {
	IceCandidateType type;
	uint16_t componentID;
} Type_ComponentID;

54 55
typedef struct _Foundation_Pair_Priority_ComponentID {
	const IcePairFoundation *foundation;
56 57 58
	IceCandidatePair *pair;
	uint64_t priority;
	uint16_t componentID;
59
} Foundation_Pair_Priority_ComponentID;
60

61 62
typedef struct _CheckList_RtpSession {
	IceCheckList *cl;
63
	const RtpSession *rtp_session;
64 65
} CheckList_RtpSession;

66 67
typedef struct _CheckList_RtpSession_Time {
	IceCheckList *cl;
68
	const RtpSession *rtp_session;
69 70 71
	uint64_t time;
} CheckList_RtpSession_Time;

72 73 74 75 76
typedef struct _CheckList_Bool {
	IceCheckList *cl;
	bool_t result;
} CheckList_Bool;

77
typedef struct _CheckList_MSListPtr {
78
	const IceCheckList *cl;
79 80 81
	MSList **list;
} CheckList_MSListPtr;

82 83 84 85 86
typedef struct _LocalCandidate_RemoteCandidate {
	IceCandidate *local;
	IceCandidate *remote;
} LocalCandidate_RemoteCandidate;

87
typedef struct _Addr_Ports {
88 89
	char *rtp_addr;
	char *rtcp_addr;
90 91 92 93 94
	int addr_len;
	int *rtp_port;
	int *rtcp_port;
} Addr_Ports;

95 96 97 98 99
typedef struct _Time_Bool {
	uint64_t time;
	bool_t result;
} Time_Bool;

100 101 102 103 104
typedef struct _Session_Index {
	IceSession *session;
	int index;
} Session_Index;

105 106 107 108 109 110
typedef struct _LosingRemoteCandidate_InProgress_Failed {
	const IceCandidate *losing_remote_candidate;
	bool_t in_progress_candidates;
	bool_t failed_candidates;
} LosingRemoteCandidate_InProgress_Failed;

111

112
// WARNING: We need this function to push events in the rtp event queue but it should not be made public in oRTP.
113 114 115
extern void rtp_session_dispatch_event(RtpSession *session, OrtpEvent *ev);


116
static void ice_send_stun_server_binding_request(ortp_socket_t sock, const struct sockaddr *server, socklen_t addrlen, UInt96 *transactionID, uint8_t nb_transmissions, int id);
117
static int ice_compare_transport_addresses(const IceTransportAddress *ta1, const IceTransportAddress *ta2);
118
static int ice_compare_pair_priorities(const IceCandidatePair *p1, const IceCandidatePair *p2);
119 120
static int ice_compare_pairs(const IceCandidatePair *p1, const IceCandidatePair *p2);
static int ice_compare_candidates(const IceCandidate *c1, const IceCandidate *c2);
121
static int ice_find_host_candidate(const IceCandidate *candidate, const uint16_t *componentID);
122
static int ice_find_nominated_valid_pair_from_componentID(const IceValidCandidatePair* valid_pair, const uint16_t* componentID);
123
static int ice_find_selected_valid_pair_from_componentID(const IceValidCandidatePair* valid_pair, const uint16_t* componentID);
124
static int ice_find_running_check_list(const IceCheckList *cl);
125
static void ice_pair_set_state(IceCandidatePair *pair, IceCandidatePairState state);
126
static void ice_compute_candidate_foundation(IceCandidate *candidate, IceCheckList *cl);
Ghislain MARY's avatar
Ghislain MARY committed
127
static void ice_set_credentials(char **ufrag, char **pwd, const char *ufrag_str, const char *pwd_str);
128
static void ice_conclude_processing(IceCheckList* cl, RtpSession* rtp_session);
Ghislain MARY's avatar
Ghislain MARY committed
129 130


131 132 133 134
/******************************************************************************
 * CONSTANTS DEFINITIONS                                                      *
 *****************************************************************************/

135 136
uint32_t stun_magic_cookie = 0x2112A442;

Ghislain MARY's avatar
Ghislain MARY committed
137 138 139 140 141
static const char * const role_values[] = {
	"Controlling",	/* IR_Controlling */
	"Controlled",	/* IR_Controlled */
};

142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
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 */
};

159 160 161 162 163 164 165 166 167 168
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
169 170 171
 * SESSION INITIALISATION AND DEINITIALISATION                                *
 *****************************************************************************/

172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
static uint64_t generate_tie_breaker(void)
{
	return (((uint64_t)random()) << 32) | (((uint64_t)random()) & 0xffffffff);
}

static char * generate_ufrag(void)
{
	char *ufrag = ms_malloc(9);
	sprintf(ufrag, "%08lx", random());
	ufrag[8] = '\0';
	return ufrag;
}

static char * generate_pwd(void)
{
	char *pwd = ms_malloc(25);
	sprintf(pwd, "%08lx%08lx%08lx", random(), random(), random());
	pwd[24] = '\0';
	return pwd;
}

Ghislain MARY's avatar
Ghislain MARY committed
193 194 195
static void ice_session_init(IceSession *session)
{
	session->streams = NULL;
Ghislain MARY's avatar
Ghislain MARY committed
196
	session->state = IS_Stopped;
Ghislain MARY's avatar
Ghislain MARY committed
197
	session->role = IR_Controlling;
198
	session->tie_breaker = generate_tie_breaker();
199
	session->ta = ICE_DEFAULT_TA_DURATION;
Ghislain MARY's avatar
Ghislain MARY committed
200
	session->keepalive_timeout = ICE_DEFAULT_KEEPALIVE_TIMEOUT;
Ghislain MARY's avatar
Ghislain MARY committed
201
	session->max_connectivity_checks = ICE_MAX_NB_CANDIDATE_PAIRS;
202 203
	session->local_ufrag = generate_ufrag();
	session->local_pwd = generate_pwd();
Ghislain MARY's avatar
Ghislain MARY committed
204 205
	session->remote_ufrag = NULL;
	session->remote_pwd = NULL;
206 207
	session->event_time = 0;
	session->send_event = FALSE;
Ghislain MARY's avatar
Ghislain MARY committed
208 209 210 211
}

IceSession * ice_session_new(void)
{
212
	MSTickerParams params;
Ghislain MARY's avatar
Ghislain MARY committed
213 214
	IceSession *session = ms_new(IceSession, 1);
	if (session == NULL) {
215 216 217 218 219 220 221 222 223
		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
224 225 226 227 228 229 230 231
		return NULL;
	}
	ice_session_init(session);
	return session;
}

void ice_session_destroy(IceSession *session)
{
232 233 234 235 236 237 238 239 240 241
	if (session != NULL) {
		ms_list_for_each(session->streams, (void (*)(void*))ice_check_list_destroy);
		if (session->ticker) ms_ticker_destroy(session->ticker);
		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);
		ms_list_free(session->streams);
		ms_free(session);
	}
Ghislain MARY's avatar
Ghislain MARY committed
242 243 244 245 246
}


/******************************************************************************
 * CHECK LIST INITIALISATION AND DEINITIALISATION                             *
247
 *****************************************************************************/
248

249 250
static void ice_check_list_init(IceCheckList *cl)
{
Ghislain MARY's avatar
Ghislain MARY committed
251
	cl->session = NULL;
252
	cl->rtp_session = NULL;
Ghislain MARY's avatar
Ghislain MARY committed
253
	cl->remote_ufrag = cl->remote_pwd = NULL;
254
	cl->stun_server_checks = NULL;
255
	cl->local_candidates = cl->remote_candidates = cl->pairs = cl->losing_pairs = cl->triggered_checks_queue = cl->check_list = cl->valid_list = NULL;
Ghislain MARY's avatar
Ghislain MARY committed
256
	cl->local_componentIDs = cl->remote_componentIDs = cl->foundations = NULL;
257
	cl->state = ICL_Running;
258
	cl->ta_time = 0;
Ghislain MARY's avatar
Ghislain MARY committed
259
	cl->keepalive_time = 0;
260
	cl->foundation_generator = 1;
Ghislain MARY's avatar
Ghislain MARY committed
261
	cl->mismatch = FALSE;
262
	cl->gathering_candidates = FALSE;
263 264
}

265
IceCheckList * ice_check_list_new(void)
266 267 268 269 270 271 272
{
	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);
273 274 275
	return cl;
}

276
static void ice_compute_pair_priority(IceCandidatePair *pair, const IceRole *role)
277 278
{
	/* Use formula defined in 5.7.2 to compute pair priority. */
Ghislain MARY's avatar
Ghislain MARY committed
279 280
	uint64_t G = 0;
	uint64_t D = 0;
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302

	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;
303
	pair->use_candidate = FALSE;
304
	pair->wait_transaction_timeout = FALSE;
305 306 307 308 309 310 311 312 313 314
	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;
}

315 316 317 318 319
static void ice_free_stun_server_check(IceStunServerCheck *check)
{
	ms_free(check);
}

320 321 322 323 324
static void ice_free_pair_foundation(IcePairFoundation *foundation)
{
	ms_free(foundation);
}

325 326 327 328 329
static void ice_free_valid_pair(IceValidCandidatePair *valid_pair)
{
	ms_free(valid_pair);
}

330 331 332 333 334
static void ice_free_candidate_pair(IceCandidatePair *pair)
{
	ms_free(pair);
}

335 336 337 338 339
static void ice_free_candidate(IceCandidate *candidate)
{
	ms_free(candidate);
}

340 341
void ice_check_list_destroy(IceCheckList *cl)
{
Ghislain MARY's avatar
Ghislain MARY committed
342 343
	if (cl->remote_ufrag) ms_free(cl->remote_ufrag);
	if (cl->remote_pwd) ms_free(cl->remote_pwd);
344
	ms_list_for_each(cl->stun_server_checks, (void (*)(void*))ice_free_stun_server_check);
345
	ms_list_for_each(cl->foundations, (void (*)(void*))ice_free_pair_foundation);
346
	ms_list_for_each(cl->valid_list, (void (*)(void*))ice_free_valid_pair);
347 348 349
	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);
350
	ms_list_free(cl->stun_server_checks);
351
	ms_list_free(cl->foundations);
Ghislain MARY's avatar
Ghislain MARY committed
352 353
	ms_list_free(cl->local_componentIDs);
	ms_list_free(cl->remote_componentIDs);
354
	ms_list_free(cl->valid_list);
355
	ms_list_free(cl->check_list);
356
	ms_list_free(cl->triggered_checks_queue);
357
	ms_list_free(cl->losing_pairs);
358 359 360 361 362 363 364
	ms_list_free(cl->pairs);
	ms_list_free(cl->remote_candidates);
	ms_list_free(cl->local_candidates);
	ms_free(cl);
}


365 366 367 368
/******************************************************************************
 * CANDIDATE ACCESSORS                                                        *
 *****************************************************************************/

369
const char *ice_candidate_type(const IceCandidate *candidate)
370 371 372 373
{
	return candidate_type_values[candidate->type];
}

374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
/******************************************************************************
 * 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;
		}
	}
}


396 397 398 399
/******************************************************************************
 * CHECK LIST ACCESSORS                                                       *
 *****************************************************************************/

400
IceCheckListState ice_check_list_state(const IceCheckList* cl)
401 402 403 404
{
	return cl->state;
}

405 406 407 408 409
static int ice_find_non_failed_check_list(const IceCheckList *cl)
{
	return (cl->state == ICL_Failed);
}

410 411 412
void ice_check_list_set_state(IceCheckList *cl, IceCheckListState state)
{
	cl->state = state;
413
	if (ms_list_find_custom(cl->session->streams, (MSCompareFunc)ice_find_non_failed_check_list, NULL) == NULL) {
414 415 416
		/* Set the state of the session to Failed if all the check lists are in the Failed state. */
		cl->session->state = IS_Failed;
	}
417 418
}

419 420 421 422 423
void ice_check_list_set_rtp_session(IceCheckList *cl, RtpSession *rtp_session)
{
	cl->rtp_session = rtp_session;
}

424
const char * ice_check_list_local_ufrag(const IceCheckList* cl)
Ghislain MARY's avatar
Ghislain MARY committed
425 426 427 428 429
{
	/* Do not handle media specific ufrag for the moment, so use the session local ufrag. */
	return cl->session->local_ufrag;
}

430
const char * ice_check_list_local_pwd(const IceCheckList* cl)
Ghislain MARY's avatar
Ghislain MARY committed
431 432 433 434 435
{
	/* Do not handle media specific pwd for the moment, so use the session local pwd. */
	return cl->session->local_pwd;
}

436
const char * ice_check_list_remote_ufrag(const IceCheckList* cl)
Ghislain MARY's avatar
Ghislain MARY committed
437 438 439 440 441
{
	if (cl->remote_ufrag) return cl->remote_ufrag;
	else return cl->session->remote_ufrag;
}

442
const char * ice_check_list_remote_pwd(const IceCheckList* cl)
Ghislain MARY's avatar
Ghislain MARY committed
443 444 445 446 447
{
	if (cl->remote_pwd) return cl->remote_pwd;
	else return cl->session->remote_pwd;
}

448
static int ice_find_default_local_candidate(const IceCandidate *candidate, const uint16_t *componentID)
449
{
450
	return !((candidate->componentID == *componentID) && (candidate->is_default == TRUE));
451 452
}

453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
bool_t ice_check_list_remote_credentials_changed(IceCheckList *cl, const char *ufrag, const char *pwd)
{
	const char *old_ufrag;
	const char *old_pwd;
	if ((cl->remote_ufrag == NULL) || (cl->remote_pwd == NULL)) {
		if (cl->remote_ufrag == NULL) old_ufrag = cl->session->remote_ufrag;
		else old_ufrag = cl->remote_ufrag;
		if ((strlen(ufrag) != strlen(old_ufrag)) || (strcmp(ufrag, old_ufrag) != 0)) return TRUE;
		if (cl->remote_pwd == NULL) old_pwd = cl->session->remote_pwd;
		else old_pwd = cl->remote_pwd;
		if ((strlen(pwd) != strlen(old_pwd)) || (strcmp(pwd, old_pwd) != 0)) return TRUE;
		return FALSE;
	}
	if (strlen(ufrag) != strlen(cl->remote_ufrag) || (strcmp(ufrag, cl->remote_ufrag) != 0)) return TRUE;
	if (strlen(pwd) != strlen(cl->remote_pwd) || (strcmp(pwd, cl->remote_pwd) != 0)) return TRUE;
	return FALSE;
}

471 472 473 474 475
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);
}

476
bool_t ice_check_list_default_local_candidate(const IceCheckList *cl, const char **rtp_addr, int *rtp_port, const char **rtcp_addr, int *rtcp_port)
477 478
{
	IceCandidate *candidate = NULL;
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
	uint16_t componentID;
	MSList *rtp_elem;
	MSList *rtcp_elem;

	componentID = 1;
	rtp_elem = ms_list_find_custom(cl->local_candidates, (MSCompareFunc)ice_find_default_local_candidate, &componentID);
	if (rtp_elem == NULL) return FALSE;
	componentID = 2;
	rtcp_elem = ms_list_find_custom(cl->local_candidates, (MSCompareFunc)ice_find_default_local_candidate, &componentID);
	if ((rtcp_elem == NULL) && ((rtcp_addr != NULL) || (rtcp_port != NULL))) return FALSE;

	candidate = (IceCandidate *)rtp_elem->data;
	if (rtp_addr != NULL) *rtp_addr = candidate->taddr.ip;
	if (rtp_port != NULL) *rtp_port = candidate->taddr.port;
	candidate = (IceCandidate *)rtcp_elem->data;
	if (rtcp_addr != NULL) *rtcp_addr = candidate->taddr.ip;
	if (rtcp_port != NULL) *rtcp_port = candidate->taddr.port;
	return TRUE;
497 498
}

499
bool_t ice_check_list_selected_valid_local_candidate(const IceCheckList *cl, const char **rtp_addr, int *rtp_port, const char **rtcp_addr, int *rtcp_port)
Ghislain MARY's avatar
Ghislain MARY committed
500 501
{
	IceCandidate *candidate = NULL;
502 503 504 505 506 507
	IceValidCandidatePair *valid_pair = NULL;
	uint16_t componentID;
	MSList *rtp_elem;
	MSList *rtcp_elem;

	componentID = 1;
508
	rtp_elem = ms_list_find_custom(cl->valid_list, (MSCompareFunc)ice_find_selected_valid_pair_from_componentID, &componentID);
509 510
	if (rtp_elem == NULL) return FALSE;
	componentID = 2;
511
	rtcp_elem = ms_list_find_custom(cl->valid_list, (MSCompareFunc)ice_find_selected_valid_pair_from_componentID, &componentID);
512 513 514 515 516 517 518 519 520 521 522
	if ((rtcp_elem == NULL) && ((rtcp_addr != NULL) || (rtcp_port != NULL))) return FALSE;

	valid_pair = (IceValidCandidatePair *)rtp_elem->data;
	candidate = valid_pair->valid->local;
	if (rtp_addr != NULL) *rtp_addr = candidate->taddr.ip;
	if (rtp_port != NULL) *rtp_port = candidate->taddr.port;
	valid_pair = (IceValidCandidatePair *)rtcp_elem->data;
	candidate = valid_pair->valid->local;
	if (rtcp_addr != NULL) *rtcp_addr = candidate->taddr.ip;
	if (rtcp_port != NULL) *rtcp_port = candidate->taddr.port;
	return TRUE;
Ghislain MARY's avatar
Ghislain MARY committed
523 524
}

525
bool_t ice_check_list_selected_valid_remote_candidate(const IceCheckList *cl, const char **rtp_addr, int *rtp_port, const char **rtcp_addr, int *rtcp_port)
526 527 528 529 530 531 532 533
{
	IceCandidate *candidate = NULL;
	IceValidCandidatePair *valid_pair = NULL;
	uint16_t componentID;
	MSList *rtp_elem;
	MSList *rtcp_elem;

	componentID = 1;
534
	rtp_elem = ms_list_find_custom(cl->valid_list, (MSCompareFunc)ice_find_selected_valid_pair_from_componentID, &componentID);
535 536
	if (rtp_elem == NULL) return FALSE;
	componentID = 2;
537
	rtcp_elem = ms_list_find_custom(cl->valid_list, (MSCompareFunc)ice_find_selected_valid_pair_from_componentID, &componentID);
538 539 540 541 542 543 544 545 546 547 548 549 550

	valid_pair = (IceValidCandidatePair *)rtp_elem->data;
	candidate = valid_pair->valid->remote;
	if (rtp_addr != NULL) *rtp_addr = candidate->taddr.ip;
	if (rtp_port != NULL) *rtp_port = candidate->taddr.port;
	if (rtcp_elem == NULL) return FALSE;
	valid_pair = (IceValidCandidatePair *)rtcp_elem->data;
	candidate = valid_pair->valid->remote;
	if (rtcp_addr != NULL) *rtcp_addr = candidate->taddr.ip;
	if (rtcp_port != NULL) *rtcp_port = candidate->taddr.port;
	return TRUE;
}

551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
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;
}

574 575 576 577 578 579 580 581 582 583 584
static int ice_find_non_frozen_pair(const IceCandidatePair *pair, const void *dummy)
{
	return (pair->state == ICP_Frozen);
}

static bool_t ice_check_list_is_frozen(const IceCheckList *cl)
{
	MSList *elem = ms_list_find_custom(cl->check_list, (MSCompareFunc)ice_find_non_frozen_pair, NULL);
	return (elem == NULL);
}

Ghislain MARY's avatar
Ghislain MARY committed
585 586 587 588 589
bool_t ice_check_list_is_mismatch(const IceCheckList *cl)
{
	return cl->mismatch;
}

Ghislain MARY's avatar
Ghislain MARY committed
590 591 592 593 594

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

595 596 597 598 599
IceCheckList * ice_session_check_list(const IceSession *session, unsigned int n)
{
	return (IceCheckList *)ms_list_nth_data(session->streams, n);
}

600
const char * ice_session_local_ufrag(const IceSession *session)
Ghislain MARY's avatar
Ghislain MARY committed
601 602 603 604
{
	return session->local_ufrag;
}

605
const char * ice_session_local_pwd(const IceSession *session)
Ghislain MARY's avatar
Ghislain MARY committed
606 607 608 609
{
	return session->local_pwd;
}

610
const char * ice_session_remote_ufrag(const IceSession *session)
Ghislain MARY's avatar
Ghislain MARY committed
611 612 613 614
{
	return session->remote_ufrag;
}

615
const char * ice_session_remote_pwd(const IceSession *session)
Ghislain MARY's avatar
Ghislain MARY committed
616 617 618 619
{
	return session->remote_pwd;
}

620 621 622 623 624 625 626 627 628 629
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);
}

630 631 632 633 634 635
IceSessionState ice_session_state(const IceSession *session)
{
	return session->state;
}

IceRole ice_session_role(const IceSession *session)
Ghislain MARY's avatar
Ghislain MARY committed
636 637 638 639
{
	return session->role;
}

Ghislain MARY's avatar
Ghislain MARY committed
640 641
void ice_session_set_role(IceSession *session, IceRole role)
{
642 643 644 645 646
	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
647 648
}

Ghislain MARY's avatar
Ghislain MARY committed
649 650 651 652 653
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);
}

654 655 656 657 658 659 660 661
bool_t ice_session_remote_credentials_changed(IceSession *session, const char *ufrag, const char *pwd)
{
	if ((session->remote_ufrag == NULL) || (session->remote_pwd == NULL)) return TRUE;
	if (strlen(ufrag) != strlen(session->remote_ufrag) || (strcmp(ufrag, session->remote_ufrag) != 0)) return TRUE;
	if (strlen(pwd) != strlen(session->remote_pwd) || (strcmp(pwd, session->remote_pwd) != 0)) return TRUE;
	return FALSE;
}

Ghislain MARY's avatar
Ghislain MARY committed
662 663 664 665 666
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
667 668 669 670 671
void ice_session_set_max_connectivity_checks(IceSession *session, uint8_t max_connectivity_checks)
{
	session->max_connectivity_checks = max_connectivity_checks;
}

Ghislain MARY's avatar
Ghislain MARY committed
672 673 674 675 676 677
void ice_session_set_keepalive_timeout(IceSession *session, uint8_t timeout)
{
	if (timeout < ICE_DEFAULT_KEEPALIVE_TIMEOUT) timeout = ICE_DEFAULT_KEEPALIVE_TIMEOUT;
	session->keepalive_timeout = timeout;
}

Ghislain MARY's avatar
Ghislain MARY committed
678 679 680 681 682

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

683 684 685 686 687
int ice_session_nb_check_lists(IceSession *session)
{
	return ms_list_size(session->streams);
}

Ghislain MARY's avatar
Ghislain MARY committed
688
void ice_session_add_check_list(IceSession *session, IceCheckList *cl)
689
{
Ghislain MARY's avatar
Ghislain MARY committed
690 691
	session->streams = ms_list_append(session->streams, cl);
	cl->session = session;
692 693 694
	if (cl->state == ICL_Running) {
		session->state = IS_Running;
	}
695 696
}

697 698
void ice_session_remove_check_list(IceSession *session, IceCheckList *cl)
{
699
	if (cl == NULL) return;
700 701 702 703
	session->streams = ms_list_remove(session->streams, cl);
	ice_check_list_destroy(cl);
}

Ghislain MARY's avatar
Ghislain MARY committed
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
static int ice_find_default_candidate_from_componentID(const IceCandidate *candidate, const uint16_t *componentID)
{
	return !((candidate->is_default == TRUE) && (candidate->componentID == *componentID));
}

static void ice_find_default_remote_candidate_for_componentID(const uint16_t *componentID, IceCheckList *cl)
{
	MSList *elem = ms_list_find_custom(cl->remote_candidates, (MSCompareFunc)ice_find_default_candidate_from_componentID, componentID);
	if (elem == NULL) {
		cl->mismatch = TRUE;
		cl->state = ICL_Failed;
	}
}

static void ice_check_list_check_mismatch(IceCheckList *cl)
{
	ms_list_for_each2(cl->remote_componentIDs, (void (*)(void*,void*))ice_find_default_remote_candidate_for_componentID, cl);
}

void ice_session_check_mismatch(IceSession *session)
{
	ms_list_for_each(session->streams, (void (*)(void*))ice_check_list_check_mismatch);
}

728

729 730 731 732
/******************************************************************************
 * CANDIDATES GATHERING                                                       *
 *****************************************************************************/

733
static void ice_check_list_gather_candidates(IceCheckList *cl, Session_Index *si)
734 735 736
{
	IceStunServerCheck *check;
	ortp_socket_t sock = -1;
737
	uint64_t curtime = si->session->ticker->time;
738

739
	if ((cl->rtp_session != NULL) && (cl->gathering_candidates == FALSE) && (cl->state != ICL_Completed)) {
740
		cl->gathering_candidates = TRUE;
741
		cl->gathering_start_time = curtime;
742 743 744 745
		sock = rtp_session_get_rtp_socket(cl->rtp_session);
		if (sock > 0) {
			check = (IceStunServerCheck *)ms_new0(IceStunServerCheck, 1);
			check->sock = sock;
746
			if (si->index == 0) {
747 748
				check->transmission_time = curtime + ICE_DEFAULT_RTO_DURATION;
				check->nb_transmissions = 1;
749 750
				ice_send_stun_server_binding_request(sock, (struct sockaddr *)&cl->session->ss, cl->session->ss_len,
					&check->transactionID, check->nb_transmissions, check->sock);
751
			} else {
752
				check->transmission_time = curtime + 2 * si->index * ICE_DEFAULT_TA_DURATION;
753 754 755 756 757 758 759
			}
			cl->stun_server_checks = ms_list_append(cl->stun_server_checks, check);
		}
		sock = rtp_session_get_rtcp_socket(cl->rtp_session);
		if (sock > 0) {
			check = (IceStunServerCheck *)ms_new0(IceStunServerCheck, 1);
			check->sock = sock;
760
			check->transmission_time = curtime + 2 * si->index * ICE_DEFAULT_TA_DURATION + ICE_DEFAULT_TA_DURATION;
761 762
			cl->stun_server_checks = ms_list_append(cl->stun_server_checks, check);
		}
763
		si->index++;
764 765 766 767 768
	}
}

void ice_session_gather_candidates(IceSession *session, struct sockaddr_storage ss, socklen_t ss_len)
{
769
	Session_Index si;
770 771
	session->ss = ss;
	session->ss_len = ss_len;
772 773 774
	si.session = session;
	si.index = 0;
	ms_list_for_each2(session->streams, (void (*)(void*,void*))ice_check_list_gather_candidates, &si);
775 776 777
}


778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
/******************************************************************************
 * CANDIDATES SELECTION                                                       *
 *****************************************************************************/

static void ice_unselect_valid_pair(IceValidCandidatePair *valid_pair)
{
	valid_pair->selected = FALSE;
}

static void ice_check_list_select_candidates(IceCheckList *cl)
{
	IceValidCandidatePair *valid_pair = NULL;
	uint16_t componentID;
	MSList *elem;

	ms_list_for_each(cl->valid_list, (void (*)(void*))ice_unselect_valid_pair);
	for (componentID = 1; componentID <= 2; componentID++) {
		elem = ms_list_find_custom(cl->valid_list, (MSCompareFunc)ice_find_nominated_valid_pair_from_componentID, &componentID);
		if (elem == NULL) continue;
		valid_pair = (IceValidCandidatePair *)elem->data;
		valid_pair->selected = TRUE;
	}
}

void ice_session_select_candidates(IceSession *session)
{
	ms_list_for_each(session->streams, (void (*)(void*))ice_check_list_select_candidates);
}


808 809 810 811
/******************************************************************************
 * STUN PACKETS HANDLING                                                      *
 *****************************************************************************/

812
static void ice_send_stun_server_binding_request(ortp_socket_t sock, const struct sockaddr *server, socklen_t addrlen, UInt96 *transactionID, uint8_t nb_transmissions, int id)
813 814 815 816 817 818 819 820 821 822 823 824
{
	StunMessage msg;
	StunAtrString username;
	StunAtrString password;
	char buf[STUN_MAX_MESSAGE_SIZE];
	int len = STUN_MAX_MESSAGE_SIZE;
	const struct sockaddr_in *servaddr = (const struct sockaddr_in *)server;

	memset(&msg, 0, sizeof(StunMessage));
	memset(&username,0,sizeof(username));
	memset(&password,0,sizeof(password));
	stunBuildReqSimple(&msg, &username, FALSE, FALSE, id);
825 826 827 828
	if (nb_transmissions > 1) {
		/* Keep the same transaction ID for retransmissions. */
		memcpy(&msg.msgHdr.tr_id, transactionID, sizeof(msg.msgHdr.tr_id));
	}
829 830 831
	len = stunEncodeMessage(&msg, buf, len, &password);
	if (len > 0) {
		sendMessage(sock, buf, len, htonl(servaddr->sin_addr.s_addr), htons(servaddr->sin_port));
832
		memcpy(transactionID, &msg.msgHdr.tr_id, sizeof(*transactionID));
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
	}
}

static int ice_parse_stun_server_binding_response(const StunMessage *msg, char *addr, int addr_len, int *port)
{
	struct in_addr ia;

	if (msg->hasXorMappedAddress) {
		*port = msg->xorMappedAddress.ipv4.port;
		ia.s_addr = htonl(msg->xorMappedAddress.ipv4.addr);
	} else if (msg->hasMappedAddress) {
		*port = msg->mappedAddress.ipv4.port;
		ia.s_addr = htonl(msg->mappedAddress.ipv4.addr);
	} else return -1;

	strncpy(addr, inet_ntoa(ia), addr_len);
	return 0;
}

852
/* Send a STUN binding request for ICE connectivity checks according to 7.1.2. */
853
static void ice_send_binding_request(IceCheckList *cl, IceCandidatePair *pair, const RtpSession *rtp_session)
854 855 856
{
	StunMessage msg;
	StunAddress4 dest;
857 858
	StunAtrString username;
	StunAtrString password;
859 860 861 862
	char buf[STUN_MAX_MESSAGE_SIZE];
	int len = STUN_MAX_MESSAGE_SIZE;
	int socket = 0;

863
	if (pair->state == ICP_InProgress) {
864 865 866 867 868 869 870 871
		if (pair->wait_transaction_timeout == TRUE) {
			/* Special case where a binding response triggers a binding request for an InProgress pair. */
			/* In this case we wait for the transmission timeout before creating a new binding request for the pair. */
			pair->wait_transaction_timeout = FALSE;
			ice_pair_set_state(pair, ICP_Waiting);
			ice_check_list_queue_triggered_check(cl, pair);
			return;
		}
872 873 874 875 876 877 878 879 880
		/* 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;
	}
881
	pair->transmission_time = cl->session->ticker->time;
882

883
	if (pair->local->componentID == 1) {
884
		socket = rtp_session_get_rtp_socket(rtp_session);
885
	} else if (pair->local->componentID == 2) {
886
		socket = rtp_session_get_rtcp_socket(rtp_session);
887 888
	} else return;

889 890 891 892 893
	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);

894 895
	stunParseHostName(pair->remote->taddr.ip, &dest.addr, &dest.port, pair->remote->taddr.port);
	memset(&msg, 0, sizeof(msg));
Ghislain MARY's avatar
Ghislain MARY committed
896
	stunBuildReqSimple(&msg, &username, FALSE, FALSE, 1);
897
	msg.hasMessageIntegrity = TRUE;
898
	msg.hasFingerprint = TRUE;
899 900 901 902 903 904

	/* 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. */
905
	if ((cl->session->role == IR_Controlling) && (pair->use_candidate == TRUE)) {
906 907 908
		msg.hasUseCandidate = TRUE;
	}

909
	/* Include the ICE-CONTROLLING or ICE-CONTROLLED attribute depending on the role of the agent, as defined in 7.1.2.2. */
910
	switch (cl->session->role) {
911 912
		case IR_Controlling:
			msg.hasIceControlling = TRUE;
913
			msg.iceControlling.value = cl->session->tie_breaker;
914 915 916
			break;
		case IR_Controlled:
			msg.hasIceControlled = TRUE;
917
			msg.iceControlled.value = cl->session->tie_breaker;
918 919
			break;
	}
920

921 922 923 924 925
	/* Keep the same transaction ID for retransmission. */
	if (pair->state == ICP_InProgress) {
		memcpy(&msg.msgHdr.tr_id, &pair->transactionID, sizeof(msg.msgHdr.tr_id));
	}

926
	len = stunEncodeMessage(&msg, buf, len, &password);
927 928 929 930
	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);
931

932
		if (pair->state != ICP_InProgress) {
933 934 935
			/* First transmission of the request, initialize the retransmission timer. */
			pair->rto = ICE_DEFAULT_RTO_DURATION;
			pair->retransmissions = 0;
936 937
			/* Save the role of the agent. */
			pair->role = cl->session->role;
938 939 940
			/* Change the state of the pair. */
			ice_pair_set_state(pair, ICP_InProgress);
		}
941 942 943
	}
}

944 945 946 947 948 949 950 951 952 953 954
static int ice_get_componentID_from_rtp_session(const OrtpEventData *evt_data)
{
	if (evt_data->info.socket_type == OrtpRTPSocket) {
		return 1;
	} else if (evt_data->info.socket_type == OrtpRTCPSocket) {
		return 2;
	}
	return -1;
}


955
static int ice_get_socket_from_rtp_session(const RtpSession *rtp_session, const OrtpEventData *evt_data)
956 957 958 959 960 961 962 963 964
{
	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;
}

965
static int ice_get_recv_port_from_rtp_session(const RtpSession *rtp_session, const OrtpEventData *evt_data)
966 967 968 969 970 971 972 973
{
	if (evt_data->info.socket_type == OrtpRTPSocket) {
		return rtp_session->rtp.loc_port;
	} else if (evt_data->info.socket_type == OrtpRTCPSocket) {
		return rtp_session->rtp.loc_port + 1;
	} else return -1;
}

974
static void ice_send_binding_response(const RtpSession *rtp_session, const OrtpEventData *evt_data, const StunMessage *msg, const StunAddress4 *dest)
975 976 977 978 979
{
	StunMessage response;
	StunAtrString password;
	char buf[STUN_MAX_MESSAGE_SIZE];
	int len = STUN_MAX_MESSAGE_SIZE;
980
	int socket = ice_get_socket_from_rtp_session(rtp_session, evt_data);
981

982
	if (socket < 0) return;
983 984 985 986 987 988 989 990 991 992 993 994 995 996
	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;

997 998 999 1000 1001
	/* 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;

1002 1003 1004 1005 1006 1007
	len = stunEncodeMessage(&response, buf, len, &password);
	if (len > 0) {
		sendMessage(socket, buf, len, dest->addr, dest->port);
	}
}

1008
static void ice_send_error_response(const RtpSession *rtp_session, const OrtpEventData *evt_data, const StunMessage *msg, uint8_t err_class, uint8_t err_num, const StunAddress4 *dest, const char *error)
1009 1010 1011 1012 1013
{
	StunMessage response;
	StunAtrString password;
	char buf[STUN_MAX_MESSAGE_SIZE];
	int len = STUN_MAX_MESSAGE_SIZE;
1014
	int socket = ice_get_socket_from_rtp_session(rtp_session, evt_data);
Ghislain MARY's avatar
Ghislain MARY committed
1015 1016
	int recvport = ice_get_recv_port_from_rtp_session(rtp_session, evt_data);
	struct in_addr dest_addr;
1017

1018
	if (socket < 0) return;
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
	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) {
Ghislain MARY's avatar
Ghislain MARY committed
1036 1037
		dest_addr.s_addr = htonl(dest->addr);
		ms_message("ice: Sending error response to %s:%u from %s:%u", inet_ntoa(dest_addr), dest->port, inet_ntoa(evt_data->packet->ipi_addr), recvport);
1038 1039 1040 1041
		sendMessage(socket, buf, len, dest->addr, dest->port);
	}
}

1042
static void ice_send_indication(const IceCandidatePair *pair, const RtpSession *rtp_session)
Ghislain MARY's avatar
Ghislain MARY committed
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
{
	StunMessage indication;
	StunAddress4 dest;
	char buf[STUN_MAX_MESSAGE_SIZE];
	int len = STUN_MAX_MESSAGE_SIZE;
	int socket;

	if (pair->local->componentID == 1) {
		socket = rtp_session_get_rtp_socket(rtp_session);
	} else if (pair->local->componentID == 2) {
		socket = rtp_session_get_rtcp_socket(rtp_session);
	} else return;

	stunParseHostName(pair->remote->taddr.ip, &dest.addr, &dest.port, pair->remote->taddr.port);
	memset(&indication, 0, sizeof(indication));
	stunBuildReqSimple(&indication, NULL, FALSE, FALSE, 1);
	indication.msgHdr.msgType = (STUN_METHOD_BINDING|STUN_INDICATION);
	indication.hasFingerprint = TRUE;

	len = stunEncodeMessage(&indication, buf, len, NULL);
	if (len > 0) {
		sendMessage(socket, buf, len, dest.addr, dest.port);
	}
}

1068
static void ice_send_keepalive_packet_for_componentID(const uint16_t *componentID, const CheckList_RtpSession *cr)
Ghislain MARY's avatar
Ghislain MARY committed
1069
{
1070
	MSList *elem = ms_list_find_custom(cr->cl->valid_list, (MSCompareFunc)ice_find_selected_valid_pair_from_componentID, componentID);
Ghislain MARY's avatar
Ghislain MARY committed
1071 1072 1073 1074 1075 1076
	if (elem != NULL) {
		IceValidCandidatePair *valid_pair = (IceValidCandidatePair *)elem->data;
		ice_send_indication(valid_pair->valid, cr->rtp_session);
	}
}

1077
static void ice_send_keepalive_packets(IceCheckList *cl, const RtpSession *rtp_session)
Ghislain MARY's avatar
Ghislain MARY committed
1078 1079 1080 1081
{
	CheckList_RtpSession cr;
	cr.cl = cl;
	cr.rtp_session = rtp_session;
Ghislain MARY's avatar
Ghislain MARY committed
1082
	ms_list_for_each2(cl->local_componentIDs, (void (*)(void*,void*))ice_send_keepalive_packet_for_componentID, &cr);
Ghislain MARY's avatar
Ghislain MARY committed
1083 1084
}

1085
static int ice_find_candidate_from_transport_address(const IceCandidate *candidate, const IceTransportAddress *taddr)
1086 1087 1088 1089
{
	return ice_compare_transport_addresses(&candidate->taddr, taddr);
}

1090
/* Check that the mandatory attributes of a connectivity check binding request are present. */
1091
static int ice_check_received_binding_request_attributes(const RtpSession *rtp_session, const OrtpEventData *evt_data, const StunMessage *msg, const StunAddress4 *remote_addr)
1092 1093 1094
{
	if (!msg->hasMessageIntegrity) {
		ms_warning("ice: Received binding request missing MESSAGE-INTEGRITY attribute");
1095
		ice_send_error_response(rtp_session, evt_data, msg, 4, 0, remote_addr, "Missing MESSAGE-INTEGRITY attribute");
1096 1097 1098 1099
		return -1;
	}
	if (!msg->hasUsername) {
		ms_warning("ice: Received binding request missing USERNAME attribute");
1100
		ice_send_error_response(rtp_session, evt_data, msg, 4, 0, remote_addr, "Missing USERNAME attribute");
1101 1102 1103 1104
		return -1;
	}
	if (!msg->hasFingerprint) {
		ms_warning("ice: Received binding request missing FINGERPRINT attribute");
1105
		ice_send_error_response(rtp_session, evt_data, msg, 4, 0, remote_addr, "Missing FINGERPRINT attribute");
1106 1107 1108 1109
		return -1;
	}
	if (!msg->hasPriority) {
		ms_warning("ice: Received binding request missing PRIORITY attribute");
1110
		ice_send_error_response(rtp_session, evt_data, msg, 4, 0, remote_addr, "Missing PRIORITY attribute");
1111 1112 1113 1114
		return -1;
	}
	if (!msg->hasIceControlling && !msg->hasIceControlled) {
		ms_warning("ice: Received binding request missing ICE-CONTROLLING or ICE-CONTROLLED attribute");
1115
		ice_send_error_response(rtp_session, evt_data ,msg, 4, 0, remote_addr, "Missing ICE-CONTROLLING or ICE-CONTROLLED attribute");
1116 1117 1118 1119 1120
		return -1;
	}
	return 0;
}

1121
static int ice_check_received_binding_request_integrity(const IceCheckList *cl, const RtpSession *rtp_session, const OrtpEventData *evt_data, const StunMessage *msg, const StunAddress4 *remote_addr)
1122 1123
{
	char hmac[20];
1124
	mblk_t *mp = evt_data->packet;
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135

	/* 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");
1136
		ice_send_error_response(rtp_session, evt_data, msg, 4, 1, remote_addr, "Wrong MESSAGE-INTEGRITY attribute");
1137 1138 1139 1140 1141
		return -1;
	}
	return 0;
}

1142
static int ice_check_received_binding_request_username(const IceCheckList *cl, const RtpSession *rtp_session, const OrtpEventData *evt_data, const StunMessage *msg, const StunAddress4 *remote_addr)
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
{
	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");
1153
		ice_send_error_response(rtp_session, evt_data, msg, 4, 1, remote_addr, "Wrong USERNAME attribute");
1154 1155 1156 1157 1158
		return -1;
	}
	return 0;
}

1159
static int ice_check_received_binding_request_role_conflict(const IceCheckList *cl, const RtpSession *rtp_session, const OrtpEventData *evt_data, const StunMessage *msg, const StunAddress4 *remote_addr)
1160 1161 1162 1163 1164
{
	/* 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) {
1165
			ice_send_error_response(rtp_session, evt_data, msg, 4, 87, remote_addr, "Role Conflict");
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
			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 {
1177
			ice_send_error_response(rtp_session, evt_data, msg, 4, 87, remote_addr, "Role Conflict");
1178 1179 1180 1181 1182 1183
			return -1;
		}
	}
	return 0;
}

1184 1185 1186 1187 1188 1189 1190
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;
}

1191
static int ice_find_candidate_from_foundation(const IceCandidate *candidate, const char *foundation)
1192 1193 1194 1195 1196 1197
{
	return !((strlen(candidate->foundation) == strlen(foundation)) && (strcmp(candidate->foundation, foundation) == 0));
}

static void ice_generate_arbitrary_foundation(char *foundation, int len, MSList *list)
{
1198
	uint64_t r;
1199 1200 1201
	MSList *elem;

	do {
1202 1203
		r = (((uint64_t)random()) << 32) | (((uint64_t)random()) & 0xffffffff);
		snprintf(foundation, len, "%llx", (long long unsigned int)r);
1204 1205 1206 1207
		elem = ms_list_find_custom(list, (MSCompareFunc)ice_find_candidate_from_foundation, foundation);
	} while (elem != NULL);
}

1208
static IceCandidate * ice_learn_peer_reflexive_candidate(IceCheckList *cl, const OrtpEventData *evt_data, const StunMessage *msg, const IceTransportAddress *taddr)
1209
{
1210 1211 1212
	char foundation[32];
	IceCandidate *candidate = NULL;
	MSList *elem;
1213
	int componentID;
1214

1215 1216
	componentID = ice_get_componentID_from_rtp_session(evt_data);
	if (componentID < 0) return NULL;
1217

1218
	elem = ms_list_find_custom(cl->remote_candidates, (MSCompareFunc)ice_find_candidate_from_transport_address, taddr);
1219
	if (elem == NULL) {
1220
		ms_message("ice: Learned peer reflexive candidate %s:%d", taddr->ip, taddr->port);
1221 1222 1223
		/* Add peer reflexive candidate to the remote candidates list. */
		memset(foundation, '\0', sizeof(foundation));
		ice_generate_arbitrary_foundation(foundation, sizeof(foundation), cl->remote_candidates);
1224
		candidate = ice_add_remote_candidate(cl, "prflx", taddr->ip, taddr->port, componentID, msg->priority.priority, foundation, FALSE);
1225 1226 1227 1228
	}
	return candidate;
}

1229
static int ice_find_pair_from_candidates(const IceCandidatePair *pair, const LocalCandidate_RemoteCandidate *candidates)
1230 1231 1232 1233 1234
{
	return !((pair->local == candidates->local) && (pair->remote == candidates->remote));
}

/* Trigger checks as defined in 7.2.1.4. */
1235
static IceCandidatePair * ice_trigger_connectivity_check_on_binding_request(IceCheckList *cl, const RtpSession *rtp_session, const OrtpEventData *evt_data, IceCandidate *prflx_candidate, const IceTransportAddress *remote_taddr)
1236 1237 1238 1239
{
	IceTransportAddress local_taddr;
	LocalCandidate_RemoteCandidate candidates;
	MSList *elem;
1240
	IceCandidatePair *pair = NULL;
1241
	int recvport = ice_get_recv_port_from_rtp_session(rtp_session, evt_data);
1242

1243
	if (recvport < 0) return NULL;
1244

1245
	ice_fill_transport_address(&local_taddr, inet_ntoa(evt_data->packet->ipi_addr), recvport);
1246 1247
	elem = ms_list_find_custom(cl->local_candidates, (MSCompareFunc)ice_find_candidate_from_transport_address, &local_taddr);
	if (elem == NULL) {
Ghislain MARY's avatar
Ghislain MARY committed
1248
		ms_error("Local candidate %s:%u not found!", local_taddr.ip, local_taddr.port);
1249
		return NULL;
1250 1251 1252 1253 1254 1255 1256
	}
	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) {
Ghislain MARY's avatar
Ghislain MARY committed
1257
			ms_error("Remote candidate %s:%u not found!", remote_taddr->ip, remote_taddr->port);
1258
			return NULL;
1259 1260 1261
		}
		candidates.remote = (IceCandidate *)elem->data;
	}
1262
	elem = ms_list_find_custom(cl->check_list, (MSCompareFunc)ice_find_pair_from_candidates, &candidates);
1263 1264 1265
	if (elem == NULL) {
		/* The pair is not in the check list yet. */
		ms_message("ice: Add new candidate pair in the check list");
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
		/* Check if the pair is in the list of pairs even if it is not in the check list. */
		elem = ms_list_find_custom(cl->pairs, (MSCompareFunc)ice_find_pair_from_candidates, &candidates);
		if (elem == NULL) {
			pair = ice_pair_new(cl, candidates.local, candidates.remote);
			cl->pairs = ms_list_append(cl->pairs, pair);
		} else {
			pair = (IceCandidatePair *)elem->data;
		}
		elem = ms_list_find(cl->check_list, pair);
		if (elem == NULL) {
			cl->check_list = ms_list_insert_sorted(cl->check_list, pair, (MSCompareFunc)ice_compare_pair_priorities);
		}
1278 1279
		/* Set the state of the pair to Waiting and trigger a check. */
		ice_pair_set_state(pair, ICP_Waiting);
1280
		ice_check_list_queue_triggered_check(cl, pair);
1281 1282 1283 1284 1285 1286 1287 1288
	} 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_Failed:
				ice_pair_set_state(pair, ICP_Waiting);
1289
				ice_check_list_queue_triggered_check(cl, pair);
1290
				break;
1291 1292 1293 1294
			case ICP_InProgress:
				/* Wait transaction timeout before creating a new binding request for this pair. */
				pair->wait_transaction_timeout = TRUE;
				break;
1295 1296 1297 1298 1299
			case ICP_Succeeded:
				/* Nothing to be done. */
				break;
		}
	}
1300 1301 1302 1303
	return pair;
}

/* Update the nominated flag of a candidate pair according to 7.2.1.5. */
1304
static void ice_update_nominated_flag_on_binding_request(const IceCheckList *cl, const StunMessage *msg, IceCandidatePair *pair)
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
{
	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;
		}
	}
1319 1320
}

1321
static void ice_handle_received_binding_request(IceCheckList *cl, RtpSession *rtp_session, const OrtpEventData *evt_data, const StunMessage *msg, const StunAddress4 *remote_addr, const char *src6host)
1322
{
1323 1324
	IceTransportAddress taddr;
	IceCandidate *prflx_candidate;
1325
	IceCandidatePair *pair;
1326

1327 1328 1329 1330
	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;
1331

1332
	ice_fill_transport_address(&taddr, src6host, remote_addr->port);
1333
	prflx_candidate = ice_learn_peer_reflexive_candidate(cl, evt_data, msg, &taddr);
1334
	pair = ice_trigger_connectivity_check_on_binding_request(cl, rtp_session, evt_data, prflx_candidate, &taddr);
1335
	if (pair != NULL) ice_update_nominated_flag_on_binding_request(cl, msg, pair);
1336
	ice_send_binding_response(rtp_session, evt_data, msg, remote_addr);
1337
	ice_conclude_processing(cl, rtp_session);
1338 1339
}

1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
static int ice_find_stun_server_check(const IceStunServerCheck *check, const ortp_socket_t *sock)
{
	return !(check->sock == *sock);
}

static int ice_find_check_list_gathering_candidates(const IceCheckList *cl, const void *dummy)
{
	return (cl->gathering_candidates == FALSE);
}

1350
static int ice_find_pair_from_transactionID(const IceCandidatePair *pair, const UInt96 *transactionID)
1351 1352 1353 1354
{
	return memcmp(&pair->transactionID, transactionID, sizeof(pair->transactionID));
}

1355
static int ice_check_received_binding_response_addresses(const RtpSession *rtp_session, const OrtpEventData *evt_data, IceCandidatePair *pair, const StunAddress4 *remote_addr)
1356 1357
{
	StunAddress4 dest;
1358 1359
	StunAddress4 local;
	int recvport = ice_get_recv_port_from_rtp_session(rtp_session, evt_data);
1360

1361
	if (recvport < 0) return -1;
1362
	stunParseHostName(pair->remote->taddr.ip, &dest.addr, &dest.port, pair->remote->taddr.port);
1363 1364
	stunParseHostName(pair->local->taddr.ip, &local.addr, &local.port, recvport);
	if ((remote_addr->addr != dest.addr) || (remote_addr->port != dest.port) || (ntohl(evt_data->packet->ipi_addr.s_addr) != local.addr) || (local.port != pair->local->taddr.port)) {
1365 1366 1367
		/* 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);
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
		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;
1386
	}
1387 1388 1389
	return 0;
}

1390
static IceCandidate * ice_discover_peer_reflexive_candidate(IceCheckList *cl, const IceCandidatePair *pair, const StunMessage *msg)
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
{
	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;
1401
	elem = ms_list_find_custom(cl->local_candidates, (MSCompareFunc)ice_find_candidate_from_transport_address, &taddr);
1402 1403 1404 1405 1406
	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);
1407 1408
	} else {
		candidate = (IceCandidate *)elem->data;
1409 1410 1411
	}
	return candidate;
}
1412

1413
static int ice_compare_valid_pair_priorities(const IceValidCandidatePair *vp1, const IceValidCandidatePair *vp2)
1414 1415 1416 1417
{
	return ice_compare_pair_priorities(vp1->valid, vp2->valid);
}

1418
static int ice_find_valid_pair(const IceValidCandidatePair *vp1, const IceValidCandidatePair *vp2)
1419 1420 1421 1422
{
	return