ice.c 128 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
/*
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

Ghislain MARY's avatar
Ghislain MARY committed
29 30
#include <inttypes.h>

Ghislain MARY's avatar
Ghislain MARY committed
31
#include "mediastreamer2/ice.h"
32
#include "ortp/ortp.h"
Ghislain MARY's avatar
Ghislain MARY committed
33 34


35 36 37
#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
38 39
#define ICE_MIN_COMPONENTID		1
#define ICE_MAX_COMPONENTID		256
40
#define ICE_INVALID_COMPONENTID		0
Ghislain MARY's avatar
Ghislain MARY committed
41 42
#define ICE_MAX_UFRAG_LEN		256
#define ICE_MAX_PWD_LEN			256
Ghislain MARY's avatar
Ghislain MARY committed
43 44
#define ICE_DEFAULT_TA_DURATION		40	/* In milliseconds */
#define ICE_DEFAULT_RTO_DURATION	200	/* In milliseconds */
Ghislain MARY's avatar
Ghislain MARY committed
45
#define ICE_DEFAULT_KEEPALIVE_TIMEOUT   15	/* In seconds */
Simon Morlat's avatar
Simon Morlat committed
46
#define ICE_GATHERING_CANDIDATES_TIMEOUT	5000	/* In milliseconds */
47
#define ICE_NOMINATION_DELAY		1000	/* In milliseconds */
48
#define ICE_MAX_RETRANSMISSIONS		7
49
#define ICE_MAX_STUN_REQUEST_RETRANSMISSIONS	7
Ghislain MARY's avatar
Ghislain MARY committed
50

51

52 53 54 55 56
typedef struct _Type_ComponentID {
	IceCandidateType type;
	uint16_t componentID;
} Type_ComponentID;

57 58
typedef struct _Foundation_Pair_Priority_ComponentID {
	const IcePairFoundation *foundation;
59 60 61
	IceCandidatePair *pair;
	uint64_t priority;
	uint16_t componentID;
62
} Foundation_Pair_Priority_ComponentID;
63

64 65
typedef struct _CheckList_RtpSession {
	IceCheckList *cl;
66
	const RtpSession *rtp_session;
67 68
} CheckList_RtpSession;

69 70
typedef struct _CheckList_RtpSession_Time {
	IceCheckList *cl;
71
	const RtpSession *rtp_session;
Ghislain MARY's avatar
Ghislain MARY committed
72
	MSTimeSpec time;
73 74
} CheckList_RtpSession_Time;

75 76 77 78 79
typedef struct _CheckList_Bool {
	IceCheckList *cl;
	bool_t result;
} CheckList_Bool;

80
typedef struct _CheckList_MSListPtr {
81
	const IceCheckList *cl;
82 83 84
	MSList **list;
} CheckList_MSListPtr;

85 86 87 88 89
typedef struct _LocalCandidate_RemoteCandidate {
	IceCandidate *local;
	IceCandidate *remote;
} LocalCandidate_RemoteCandidate;

90
typedef struct _Addr_Ports {
91 92
	char *rtp_addr;
	char *rtcp_addr;
93 94 95 96 97
	int addr_len;
	int *rtp_port;
	int *rtcp_port;
} Addr_Ports;

98
typedef struct _Time_Bool {
Ghislain MARY's avatar
Ghislain MARY committed
99
	MSTimeSpec time;
100 101 102
	bool_t result;
} Time_Bool;

103 104 105 106 107
typedef struct _Session_Index {
	IceSession *session;
	int index;
} Session_Index;

108 109 110 111 112 113
typedef struct _LosingRemoteCandidate_InProgress_Failed {
	const IceCandidate *losing_remote_candidate;
	bool_t in_progress_candidates;
	bool_t failed_candidates;
} LosingRemoteCandidate_InProgress_Failed;

114 115 116 117 118
typedef struct _StunRequestRoundTripTime {
	int nb_responses;
	int sum;
} StunRequestRoundTripTime;

119

Ghislain MARY's avatar
Ghislain MARY committed
120 121
static MSTimeSpec ice_current_time(void);
static MSTimeSpec ice_add_ms(MSTimeSpec orig, uint32_t ms);
122
static int32_t ice_compare_time(MSTimeSpec ts1, MSTimeSpec ts2);
123
static char * ice_inet_ntoa(struct sockaddr *addr, int addrlen, char *dest, int destlen);
Ghislain MARY's avatar
Ghislain MARY committed
124
static void transactionID2string(const UInt96 *tr_id, char *tr_id_str);
125
static void ice_send_stun_server_binding_request(ortp_socket_t sock, const struct sockaddr *server, socklen_t addrlen, IceStunServerCheck *check);
126
static int ice_compare_transport_addresses(const IceTransportAddress *ta1, const IceTransportAddress *ta2);
127
static int ice_compare_pair_priorities(const IceCandidatePair *p1, const IceCandidatePair *p2);
128 129
static int ice_compare_pairs(const IceCandidatePair *p1, const IceCandidatePair *p2);
static int ice_compare_candidates(const IceCandidate *c1, const IceCandidate *c2);
130
static int ice_find_host_candidate(const IceCandidate *candidate, const uint16_t *componentID);
131
static int ice_find_candidate_from_type_and_componentID(const IceCandidate *candidate, const Type_ComponentID *tc);
132
static int ice_find_use_candidate_valid_pair_from_componentID(const IceValidCandidatePair* valid_pair, const uint16_t* componentID);
133
static int ice_find_nominated_valid_pair_from_componentID(const IceValidCandidatePair* valid_pair, const uint16_t* componentID);
134
static int ice_find_selected_valid_pair_from_componentID(const IceValidCandidatePair* valid_pair, const uint16_t* componentID);
135
static void ice_find_selected_valid_pair_for_componentID(const uint16_t *componentID, CheckList_Bool *cb);
136
static int ice_find_pair_in_valid_list(IceValidCandidatePair *valid_pair, IceCandidatePair *pair);
137
static void ice_pair_set_state(IceCandidatePair *pair, IceCandidatePairState state);
138
static void ice_compute_candidate_foundation(IceCandidate *candidate, IceCheckList *cl);
Ghislain MARY's avatar
Ghislain MARY committed
139
static void ice_set_credentials(char **ufrag, char **pwd, const char *ufrag_str, const char *pwd_str);
140
static void ice_conclude_processing(IceCheckList* cl, RtpSession* rtp_session);
Ghislain MARY's avatar
Ghislain MARY committed
141 142


143 144 145 146
/******************************************************************************
 * CONSTANTS DEFINITIONS                                                      *
 *****************************************************************************/

147 148
uint32_t stun_magic_cookie = 0x2112A442;

Ghislain MARY's avatar
Ghislain MARY committed
149 150 151 152 153
static const char * const role_values[] = {
	"Controlling",	/* IR_Controlling */
	"Controlled",	/* IR_Controlled */
};

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
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 */
};

171 172 173 174 175 176 177 178 179 180
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
181 182 183
 * SESSION INITIALISATION AND DEINITIALISATION                                *
 *****************************************************************************/

Ghislain MARY's avatar
Ghislain MARY committed
184 185 186 187 188 189 190 191
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);
192
	sprintf(ufrag, "%08x", (int)random());
Ghislain MARY's avatar
Ghislain MARY committed
193 194 195 196 197 198 199
	ufrag[8] = '\0';
	return ufrag;
}

static char * generate_pwd(void)
{
	char *pwd = ms_malloc(25);
200
	sprintf(pwd, "%08x%08x%08x", (int)random(), (int)random(), (int)random());
Ghislain MARY's avatar
Ghislain MARY committed
201 202 203 204
	pwd[24] = '\0';
	return pwd;
}

Ghislain MARY's avatar
Ghislain MARY committed
205 206
static void ice_session_init(IceSession *session)
{
207
	memset(&session->streams, 0, sizeof(session->streams));
Ghislain MARY's avatar
Ghislain MARY committed
208
	session->state = IS_Stopped;
Ghislain MARY's avatar
Ghislain MARY committed
209
	session->role = IR_Controlling;
Ghislain MARY's avatar
Ghislain MARY committed
210
	session->tie_breaker = generate_tie_breaker();
211
	session->ta = ICE_DEFAULT_TA_DURATION;
Ghislain MARY's avatar
Ghislain MARY committed
212
	session->keepalive_timeout = ICE_DEFAULT_KEEPALIVE_TIMEOUT;
Ghislain MARY's avatar
Ghislain MARY committed
213
	session->max_connectivity_checks = ICE_MAX_NB_CANDIDATE_PAIRS;
Ghislain MARY's avatar
Ghislain MARY committed
214 215
	session->local_ufrag = generate_ufrag();
	session->local_pwd = generate_pwd();
Ghislain MARY's avatar
Ghislain MARY committed
216 217
	session->remote_ufrag = NULL;
	session->remote_pwd = NULL;
Ghislain MARY's avatar
Ghislain MARY committed
218
	memset(&session->event_time, 0, sizeof(session->event_time));
219
	session->send_event = FALSE;
220 221
	session->gathering_start_ts.tv_sec = session->gathering_start_ts.tv_nsec = -1;
	session->gathering_end_ts.tv_sec = session->gathering_end_ts.tv_nsec = -1;
Ghislain MARY's avatar
Ghislain MARY committed
222 223 224 225 226 227
}

IceSession * ice_session_new(void)
{
	IceSession *session = ms_new(IceSession, 1);
	if (session == NULL) {
228 229 230
		ms_error("ice: Memory allocation of ICE session failed");
		return NULL;
	}
Ghislain MARY's avatar
Ghislain MARY committed
231 232 233 234 235 236
	ice_session_init(session);
	return session;
}

void ice_session_destroy(IceSession *session)
{
237
	int i;
238
	if (session != NULL) {
239 240 241 242 243 244
		for (i = 0; i < ICE_SESSION_MAX_CHECK_LISTS; i++) {
			if (session->streams[i] != NULL) {
				ice_check_list_destroy(session->streams[i]);
				session->streams[i] = NULL;
			}
		}
245 246 247 248 249 250
		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_free(session);
	}
Ghislain MARY's avatar
Ghislain MARY committed
251 252 253 254 255
}


/******************************************************************************
 * CHECK LIST INITIALISATION AND DEINITIALISATION                             *
256
 *****************************************************************************/
257

258 259
static void ice_check_list_init(IceCheckList *cl)
{
Ghislain MARY's avatar
Ghislain MARY committed
260
	cl->session = NULL;
261
	cl->rtp_session = NULL;
Ghislain MARY's avatar
Ghislain MARY committed
262
	cl->remote_ufrag = cl->remote_pwd = NULL;
263
	cl->stun_server_checks = NULL;
Ghislain MARY's avatar
Ghislain MARY committed
264
	cl->local_candidates = cl->remote_candidates = cl->pairs = cl->losing_pairs = cl->triggered_checks_queue = cl->check_list = cl->valid_list = cl->transaction_list = NULL;
Ghislain MARY's avatar
Ghislain MARY committed
265
	cl->local_componentIDs = cl->remote_componentIDs = cl->foundations = NULL;
266
	cl->state = ICL_Running;
267
	cl->foundation_generator = 1;
Ghislain MARY's avatar
Ghislain MARY committed
268
	cl->mismatch = FALSE;
269
	cl->gathering_candidates = FALSE;
270
	cl->gathering_finished = FALSE;
271 272 273 274 275
	cl->nomination_delay_running = FALSE;
	memset(&cl->ta_time, 0, sizeof(cl->ta_time));
	memset(&cl->keepalive_time, 0, sizeof(cl->keepalive_time));
	memset(&cl->gathering_start_time, 0, sizeof(cl->gathering_start_time));
	memset(&cl->nomination_delay_start_time, 0, sizeof(cl->nomination_delay_start_time));
276 277
}

278
IceCheckList * ice_check_list_new(void)
279 280 281 282 283 284 285
{
	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);
286 287 288
	return cl;
}

289
static void ice_compute_pair_priority(IceCandidatePair *pair, const IceRole *role)
290 291
{
	/* Use formula defined in 5.7.2 to compute pair priority. */
Ghislain MARY's avatar
Ghislain MARY committed
292 293
	uint64_t G = 0;
	uint64_t D = 0;
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309

	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)
{
310
	IceCandidatePair *pair = ms_new0(IceCandidatePair, 1);
311 312
	pair->local = local_candidate;
	pair->remote = remote_candidate;
313
	pair->state = ICP_Frozen;
314 315
	pair->is_default = FALSE;
	pair->is_nominated = FALSE;
316
	pair->use_candidate = FALSE;
317
	pair->wait_transaction_timeout = FALSE;
318 319 320 321 322 323 324 325 326
	if ((pair->local->is_default == TRUE) && (pair->remote->is_default == TRUE)) pair->is_default = TRUE;
	else pair->is_default = FALSE;
	pair->rto = ICE_DEFAULT_RTO_DURATION;
	pair->retransmissions = 0;
	pair->role = cl->session->role;
	ice_compute_pair_priority(pair, &cl->session->role);
	return pair;
}

327 328 329 330 331
static void ice_free_stun_server_check_transaction(IceStunServerCheckTransaction *transaction)
{
	ms_free(transaction);
}

332 333
static void ice_free_stun_server_check(IceStunServerCheck *check)
{
334
	ms_list_for_each(check->transactions, (void (*)(void*))ice_free_stun_server_check_transaction);
335 336 337
	ms_free(check);
}

Ghislain MARY's avatar
Ghislain MARY committed
338 339 340 341 342
static void ice_free_transaction(IceTransaction *transaction)
{
	ms_free(transaction);
}

343 344 345 346 347
static void ice_free_pair_foundation(IcePairFoundation *foundation)
{
	ms_free(foundation);
}

348 349 350 351 352
static void ice_free_valid_pair(IceValidCandidatePair *valid_pair)
{
	ms_free(valid_pair);
}

353
static void ice_free_candidate_pair(IceCandidatePair *pair, IceCheckList *cl)
Ghislain MARY's avatar
Ghislain MARY committed
354
{
355 356 357 358 359 360
	MSList *elem;
	while ((elem = ms_list_find(cl->check_list, pair)) != NULL) {
		cl->check_list = ms_list_remove(cl->check_list, pair);
	}
	while ((elem = ms_list_find_custom(cl->valid_list, (MSCompareFunc)ice_find_pair_in_valid_list, pair)) != NULL) {
		ice_free_valid_pair(elem->data);
361
		cl->valid_list = ms_list_remove_link(cl->valid_list, elem);
362
	}
Ghislain MARY's avatar
Ghislain MARY committed
363 364 365
	ms_free(pair);
}

366 367 368 369 370
static void ice_free_candidate(IceCandidate *candidate)
{
	ms_free(candidate);
}

371 372
void ice_check_list_destroy(IceCheckList *cl)
{
Ghislain MARY's avatar
Ghislain MARY committed
373 374
	if (cl->remote_ufrag) ms_free(cl->remote_ufrag);
	if (cl->remote_pwd) ms_free(cl->remote_pwd);
375
	ms_list_for_each(cl->stun_server_checks, (void (*)(void*))ice_free_stun_server_check);
Ghislain MARY's avatar
Ghislain MARY committed
376
	ms_list_for_each(cl->transaction_list, (void (*)(void*))ice_free_transaction);
377
	ms_list_for_each(cl->foundations, (void (*)(void*))ice_free_pair_foundation);
378
	ms_list_for_each2(cl->pairs, (void (*)(void*,void*))ice_free_candidate_pair, cl);
379
	ms_list_for_each(cl->valid_list, (void (*)(void*))ice_free_valid_pair);
380 381
	ms_list_for_each(cl->remote_candidates, (void (*)(void*))ice_free_candidate);
	ms_list_for_each(cl->local_candidates, (void (*)(void*))ice_free_candidate);
382
	ms_list_free(cl->stun_server_checks);
Ghislain MARY's avatar
Ghislain MARY committed
383
	ms_list_free(cl->transaction_list);
384
	ms_list_free(cl->foundations);
Ghislain MARY's avatar
Ghislain MARY committed
385 386
	ms_list_free(cl->local_componentIDs);
	ms_list_free(cl->remote_componentIDs);
Ghislain MARY's avatar
Ghislain MARY committed
387
	ms_list_free(cl->valid_list);
388
	ms_list_free(cl->check_list);
389
	ms_list_free(cl->triggered_checks_queue);
390
	ms_list_free(cl->losing_pairs);
391 392 393
	ms_list_free(cl->pairs);
	ms_list_free(cl->remote_candidates);
	ms_list_free(cl->local_candidates);
394
	memset(cl, 0, sizeof(IceCheckList));
395 396 397 398
	ms_free(cl);
}


399 400 401 402
/******************************************************************************
 * CANDIDATE ACCESSORS                                                        *
 *****************************************************************************/

403
const char *ice_candidate_type(const IceCandidate *candidate)
404 405 406 407
{
	return candidate_type_values[candidate->type];
}

408 409 410 411 412 413 414 415 416 417 418 419
/******************************************************************************
 * CANDIDATE PAIR ACCESSORS                                                   *
 *****************************************************************************/

static void ice_pair_set_state(IceCandidatePair *pair, IceCandidatePairState state)
{
	if (pair->state != state) {
		pair->state = state;
	}
}


420 421 422 423
/******************************************************************************
 * CHECK LIST ACCESSORS                                                       *
 *****************************************************************************/

424
IceCheckListState ice_check_list_state(const IceCheckList* cl)
425 426 427 428
{
	return cl->state;
}

429
static IceCheckList * ice_find_check_list_from_state(const IceSession *session, IceCheckListState state)
430
{
431 432
	int i;
	for (i = 0; i < ICE_SESSION_MAX_CHECK_LISTS; i++) {
Simon Morlat's avatar
Simon Morlat committed
433
		if (session->streams[i] && ice_check_list_state(session->streams[i]) == state) return session->streams[i];
434 435
	}
	return NULL;
436 437
}

438 439
void ice_check_list_set_state(IceCheckList *cl, IceCheckListState state)
{
440 441
	if (cl->state != state) {
		cl->state = state;
442 443
		if (ice_find_check_list_from_state(cl->session, ICL_Running) == NULL) {
			if (ice_find_check_list_from_state(cl->session, ICL_Failed) != NULL) {
444 445 446 447 448 449 450
				/* Set the state of the session to Failed if at least one check list is in the Failed state. */
				cl->session->state = IS_Failed;
			} else {
				/* All the check lists are in the Completed state, set the state of the session to Completed. */
				cl->session->state = IS_Completed;
			}
		}
451
	}
452 453
}

454 455 456 457 458
void ice_check_list_set_rtp_session(IceCheckList *cl, RtpSession *rtp_session)
{
	cl->rtp_session = rtp_session;
}

459
const char * ice_check_list_local_ufrag(const IceCheckList* cl)
Ghislain MARY's avatar
Ghislain MARY committed
460 461 462 463 464
{
	/* Do not handle media specific ufrag for the moment, so use the session local ufrag. */
	return cl->session->local_ufrag;
}

465
const char * ice_check_list_local_pwd(const IceCheckList* cl)
Ghislain MARY's avatar
Ghislain MARY committed
466 467 468 469 470
{
	/* Do not handle media specific pwd for the moment, so use the session local pwd. */
	return cl->session->local_pwd;
}

471
const char * ice_check_list_remote_ufrag(const IceCheckList* cl)
Ghislain MARY's avatar
Ghislain MARY committed
472 473 474 475 476
{
	if (cl->remote_ufrag) return cl->remote_ufrag;
	else return cl->session->remote_ufrag;
}

477
const char * ice_check_list_remote_pwd(const IceCheckList* cl)
Ghislain MARY's avatar
Ghislain MARY committed
478 479 480 481 482
{
	if (cl->remote_pwd) return cl->remote_pwd;
	else return cl->session->remote_pwd;
}

483
static int ice_find_default_local_candidate(const IceCandidate *candidate, const uint16_t *componentID)
484
{
485
	return !((candidate->componentID == *componentID) && (candidate->is_default == TRUE));
486 487
}

488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
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;
}

506 507 508 509 510
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);
}

511
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)
512 513
{
	IceCandidate *candidate = NULL;
514 515 516 517 518 519 520 521 522 523 524 525 526
	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);

	candidate = (IceCandidate *)rtp_elem->data;
	if (rtp_addr != NULL) *rtp_addr = candidate->taddr.ip;
	if (rtp_port != NULL) *rtp_port = candidate->taddr.port;
527 528 529 530
	if (rtcp_elem == NULL) {
		if ((rtcp_addr != NULL) || (rtcp_port != NULL)) return FALSE;
		else return TRUE;
	}
531 532 533 534
	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;
535 536
}

537
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
538 539
{
	IceCandidate *candidate = NULL;
540 541 542 543 544 545
	IceValidCandidatePair *valid_pair = NULL;
	uint16_t componentID;
	MSList *rtp_elem;
	MSList *rtcp_elem;

	componentID = 1;
546
	rtp_elem = ms_list_find_custom(cl->valid_list, (MSCompareFunc)ice_find_selected_valid_pair_from_componentID, &componentID);
547 548
	if (rtp_elem == NULL) return FALSE;
	componentID = 2;
549
	rtcp_elem = ms_list_find_custom(cl->valid_list, (MSCompareFunc)ice_find_selected_valid_pair_from_componentID, &componentID);
550 551 552 553 554

	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;
555 556 557 558
	if (rtcp_elem == NULL) {
		if ((rtcp_addr != NULL) || (rtcp_port != NULL)) return FALSE;
		else return TRUE;
	}
559 560 561 562 563
	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
564 565
}

566
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)
567 568 569 570 571 572 573 574
{
	IceCandidate *candidate = NULL;
	IceValidCandidatePair *valid_pair = NULL;
	uint16_t componentID;
	MSList *rtp_elem;
	MSList *rtcp_elem;

	componentID = 1;
575
	rtp_elem = ms_list_find_custom(cl->valid_list, (MSCompareFunc)ice_find_selected_valid_pair_from_componentID, &componentID);
576 577
	if (rtp_elem == NULL) return FALSE;
	componentID = 2;
578
	rtcp_elem = ms_list_find_custom(cl->valid_list, (MSCompareFunc)ice_find_selected_valid_pair_from_componentID, &componentID);
579 580 581 582 583 584 585 586 587 588 589 590 591

	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;
}

592 593 594 595 596 597 598 599 600 601
IceCandidateType ice_check_list_selected_valid_candidate_type(const IceCheckList *cl)
{
	MSList *elem;
	uint16_t componentID = 1;

	elem = ms_list_find_custom(cl->valid_list, (MSCompareFunc)ice_find_selected_valid_pair_from_componentID, &componentID);
	if (elem == NULL) return ICT_RelayedCandidate;
	return ((IceValidCandidatePair *)elem->data)->valid->remote->type;
}

602 603 604 605 606 607 608 609 610 611 612 613 614 615
void ice_check_list_check_completed(IceCheckList *cl)
{
	CheckList_Bool cb;

	if (cl->state != ICL_Completed) {
		cb.cl = cl;
		cb.result = TRUE;
		ms_list_for_each2(cl->local_componentIDs, (void (*)(void*,void*))ice_find_selected_valid_pair_for_componentID, &cb);
		if (cb.result == TRUE) {
			ice_check_list_set_state(cl, ICL_Completed);
		}
	}
}

616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
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;
}

639 640 641 642 643 644 645 646 647 648 649
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
650 651 652 653 654
bool_t ice_check_list_is_mismatch(const IceCheckList *cl)
{
	return cl->mismatch;
}

Ghislain MARY's avatar
Ghislain MARY committed
655 656 657 658 659

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

660 661
IceCheckList * ice_session_check_list(const IceSession *session, unsigned int n)
{
662 663
	if (n >= ICE_SESSION_MAX_CHECK_LISTS) return NULL;
	return session->streams[n];
664 665
}

666
const char * ice_session_local_ufrag(const IceSession *session)
Ghislain MARY's avatar
Ghislain MARY committed
667 668 669 670
{
	return session->local_ufrag;
}

671
const char * ice_session_local_pwd(const IceSession *session)
Ghislain MARY's avatar
Ghislain MARY committed
672 673 674 675
{
	return session->local_pwd;
}

676
const char * ice_session_remote_ufrag(const IceSession *session)
Ghislain MARY's avatar
Ghislain MARY committed
677 678 679 680
{
	return session->remote_ufrag;
}

681
const char * ice_session_remote_pwd(const IceSession *session)
Ghislain MARY's avatar
Ghislain MARY committed
682 683 684 685
{
	return session->remote_pwd;
}

686 687 688 689 690 691 692
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)
{
693 694 695 696 697
	int i;
	for (i = 0; i < ICE_SESSION_MAX_CHECK_LISTS; i++) {
		if (session->streams[i] != NULL)
			ice_check_list_compute_pair_priorities(session->streams[i]);
	}
698 699
}

700 701 702 703 704 705
IceSessionState ice_session_state(const IceSession *session)
{
	return session->state;
}

IceRole ice_session_role(const IceSession *session)
Ghislain MARY's avatar
Ghislain MARY committed
706 707 708 709
{
	return session->role;
}

Ghislain MARY's avatar
Ghislain MARY committed
710 711
void ice_session_set_role(IceSession *session, IceRole role)
{
712 713 714 715 716
	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
717 718
}

Ghislain MARY's avatar
Ghislain MARY committed
719 720 721 722 723
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);
}

724 725 726 727 728 729 730 731
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
732 733 734 735 736
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
737 738 739 740 741
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
742 743 744 745 746 747
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
748 749 750 751 752

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

753 754
int ice_session_nb_check_lists(IceSession *session)
{
755 756 757 758 759 760
	int i;
	int nb = 0;
	for (i = 0; i < ICE_SESSION_MAX_CHECK_LISTS; i++) {
		if (session->streams[i] != NULL) nb++;
	}
	return nb;
761 762 763 764
}

bool_t ice_session_has_completed_check_list(const IceSession *session)
{
765 766 767 768 769 770
	int i;
	for (i = 0; i < ICE_SESSION_MAX_CHECK_LISTS; i++) {
		if ((session->streams[i] != NULL) && (ice_check_list_state(session->streams[i]) == ICL_Completed))
			return TRUE;
	}
	return FALSE;
771 772
}

773
void ice_session_add_check_list(IceSession *session, IceCheckList *cl, unsigned int idx)
774
{
775 776 777 778 779 780 781 782 783
	if (idx >= ICE_SESSION_MAX_CHECK_LISTS) {
		ms_error("ice_session_add_check_list: Wrong idx parameter");
		return;
	}
	if (session->streams[idx] != NULL) {
		ms_error("ice_session_add_check_list: Existing check list at index %u, remove it first", idx);
		return;
	}
	session->streams[idx] = cl;
Ghislain MARY's avatar
Ghislain MARY committed
784
	cl->session = session;
785 786 787
	if (cl->state == ICL_Running) {
		session->state = IS_Running;
	}
788 789
}

790 791
void ice_session_remove_check_list(IceSession *session, IceCheckList *cl)
{
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
	int i;
	for (i = 0; i < ICE_SESSION_MAX_CHECK_LISTS; i++) {
		if ((session->streams[i] != NULL) && (session->streams[i] == cl)) {
			ice_check_list_destroy(cl);
			session->streams[i] = NULL;
			break;
		}
	}
}

void ice_session_remove_check_list_from_idx(IceSession *session, unsigned int idx) {
	if (idx >= ICE_SESSION_MAX_CHECK_LISTS) {
		ms_error("ice_session_remove_check_list_from_idx: Wrong idx parameter");
		return;
	}
	if (session->streams[idx] != NULL) {
		ice_check_list_destroy(session->streams[idx]);
		session->streams[idx] = NULL;
	}
811 812
}

Ghislain MARY's avatar
Ghislain MARY committed
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
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)
{
834 835 836 837 838
	int i;
	for (i = 0; i < ICE_SESSION_MAX_CHECK_LISTS; i++) {
		if (session->streams[i] != NULL)
			ice_check_list_check_mismatch(session->streams[i]);
	}
Ghislain MARY's avatar
Ghislain MARY committed
839 840
}

841

842 843 844 845
/******************************************************************************
 * CANDIDATES GATHERING                                                       *
 *****************************************************************************/

846 847 848
bool_t ice_check_list_candidates_gathered(const IceCheckList *cl)
{
	return cl->gathering_finished;
849 850 851 852
}

bool_t ice_session_candidates_gathered(const IceSession *session)
{
853 854 855 856 857 858
	int i;
	for (i = 0; i < ICE_SESSION_MAX_CHECK_LISTS; i++) {
		if ((session->streams[i] != NULL) && (ice_check_list_candidates_gathered(session->streams[i]) != TRUE))
			return FALSE;
	}
	return TRUE;
859 860
}

861
static bool_t ice_check_list_gathering_needed(const IceCheckList *cl)
862
{
863 864 865
	if (cl->gathering_finished == FALSE)
		return TRUE;
	return FALSE;
866 867
}

868
static void ice_check_list_gather_candidates(IceCheckList *cl, Session_Index *si)
869 870 871
{
	IceStunServerCheck *check;
	ortp_socket_t sock = -1;
Ghislain MARY's avatar
Ghislain MARY committed
872
	MSTimeSpec curtime = ice_current_time();
873

874
	if ((cl->rtp_session != NULL) && (cl->gathering_candidates == FALSE) && (cl->state != ICL_Completed) && (ice_check_list_candidates_gathered(cl) == FALSE)) {
875
		cl->gathering_candidates = TRUE;
876
		cl->gathering_start_time = curtime;
877 878 879 880
		sock = rtp_session_get_rtp_socket(cl->rtp_session);
		if (sock > 0) {
			check = (IceStunServerCheck *)ms_new0(IceStunServerCheck, 1);
			check->sock = sock;
881
			check->srcport = rtp_session_get_local_port(cl->rtp_session);
882
			if (si->index == 0) {
883 884
				check->next_transmission_time = ice_add_ms(curtime, ICE_DEFAULT_RTO_DURATION);
				ice_send_stun_server_binding_request(sock, (struct sockaddr *)&cl->session->ss, cl->session->ss_len, check);
885
			} else {
886
				check->next_transmission_time = ice_add_ms(curtime, 2 * si->index * ICE_DEFAULT_TA_DURATION);
887 888
			}
			cl->stun_server_checks = ms_list_append(cl->stun_server_checks, check);
jehan's avatar
jehan committed
889 890
		} else {
			ms_error("ice: no rtp socket found for session [%p]",cl->rtp_session);
891 892 893 894 895
		}
		sock = rtp_session_get_rtcp_socket(cl->rtp_session);
		if (sock > 0) {
			check = (IceStunServerCheck *)ms_new0(IceStunServerCheck, 1);
			check->sock = sock;
896
			check->srcport = rtp_session_get_local_rtcp_port(cl->rtp_session);
897
			check->next_transmission_time = ice_add_ms(curtime, 2 * si->index * ICE_DEFAULT_TA_DURATION + ICE_DEFAULT_TA_DURATION);
898
			cl->stun_server_checks = ms_list_append(cl->stun_server_checks, check);
jehan's avatar
jehan committed
899 900
		}else {
			ms_message("ice: no rtcp socket found for session [%p]",cl->rtp_session);
901
		}
902
		si->index++;
jehan's avatar
jehan committed
903 904
	} else {
		ms_message("ice: candidate gathering skipped for rtp session [%p] with check list [%p] in state [%s]",cl->rtp_session,cl,ice_check_list_state_to_string(cl->state));
905 906 907
	}
}

908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
static bool_t ice_session_gathering_needed(const IceSession *session) {
	int i;
	for (i = 0; i < ICE_SESSION_MAX_CHECK_LISTS; i++) {
		if ((session->streams[i] != NULL) && (ice_check_list_gathering_needed(session->streams[i]) == TRUE))
			return TRUE;
	}
	return FALSE;
}

static IceCheckList * ice_session_first_check_list(const IceSession *session) {
	int i;
	for (i = 0; i < ICE_SESSION_MAX_CHECK_LISTS; i++) {
		if (session->streams[i] != NULL)
			return session->streams[i];
	}
	return NULL;
}

void ice_session_gather_candidates(IceSession *session, const struct sockaddr* ss, socklen_t ss_len)
927
{
928
	Session_Index si;
929
	OrtpEvent *ev;
930 931
	int i;

932
	memcpy(&session->ss,ss,ss_len);
933
	session->ss_len = ss_len;
934 935
	si.session = session;
	si.index = 0;
936
	ms_get_cur_time(&session->gathering_start_ts);
937 938 939 940 941
	if (ice_session_gathering_needed(session) == TRUE) {
		for (i = 0; i < ICE_SESSION_MAX_CHECK_LISTS; i++) {
			if (session->streams[i] != NULL)
				ice_check_list_gather_candidates(session->streams[i], &si);
		}
942 943 944 945 946
	} else {
		/* Notify end of gathering since it has already been done. */
		ev = ortp_event_new(ORTP_EVENT_ICE_GATHERING_FINISHED);
		ortp_event_get_data(ev)->info.ice_processing_successful = TRUE;
		session->gathering_end_ts = session->gathering_start_ts;
947
		rtp_session_dispatch_event(ice_session_first_check_list(session)->rtp_session, ev);
948
	}
949 950
}

951 952 953 954 955 956 957
int ice_session_gathering_duration(IceSession *session)
{
	if ((session->gathering_start_ts.tv_sec == -1) || (session->gathering_end_ts.tv_sec == -1)) return -1;
	return ((session->gathering_end_ts.tv_sec - session->gathering_start_ts.tv_sec) * 1000.0)
		+ ((session->gathering_end_ts.tv_nsec - session->gathering_start_ts.tv_nsec) / 1000000.0);
}

958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978
static void ice_transaction_sum_gathering_round_trip_time(const IceStunServerCheckTransaction *transaction, StunRequestRoundTripTime *rtt)
{
	if ((transaction->response_time.tv_sec != 0) && (transaction->response_time.tv_nsec != 0)) {
		rtt->nb_responses++;
		rtt->sum += ice_compare_time(transaction->response_time, transaction->request_time);
	}
}

static void ice_stun_server_check_sum_gathering_round_trip_time(const IceStunServerCheck *check, StunRequestRoundTripTime *rtt)
{
	ms_list_for_each2(check->transactions, (void (*)(void*,void*))ice_transaction_sum_gathering_round_trip_time, rtt);
}

static void ice_check_list_sum_gathering_round_trip_times(const IceCheckList *cl, StunRequestRoundTripTime *rtt)
{
	ms_list_for_each2(cl->stun_server_checks, (void (*)(void*,void*))ice_stun_server_check_sum_gathering_round_trip_time, rtt);
}

int ice_session_average_gathering_round_trip_time(IceSession *session)
{
	StunRequestRoundTripTime rtt;
979
	int i;
980 981 982

	if ((session->gathering_start_ts.tv_sec == -1) || (session->gathering_end_ts.tv_sec == -1)) return -1;
	memset(&rtt, 0, sizeof(rtt));
983 984 985 986
	for (i = 0; i < ICE_SESSION_MAX_CHECK_LISTS; i++) {
		if (session->streams[i] != NULL)
			ice_check_list_sum_gathering_round_trip_times(session->streams[i], &rtt);
	}
987 988 989 990
	if (rtt.nb_responses == 0) return -1;
	return (rtt.sum / rtt.nb_responses);
}

991

992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
/******************************************************************************
 * 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;

1007 1008
	if (