ice.c 44.2 KB
Newer Older
aymeric's avatar
aymeric 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
/*
mediastreamer2 library - modular sound and video processing and streaming
Copyright (C) 2006  Simon MORLAT (simon.morlat@linphone.org)

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

28
#include "mediastreamer2/msticker.h"
aymeric's avatar
aymeric committed
29 30 31 32
#include "mediastreamer2/ice.h"
#include "mediastreamer2/mscommon.h"

static void 
33
ice_sendtest( struct IceCheckList *checklist, struct CandidatePair *remote_candidate, Socket myFd, StunAddress4 *dest, 
aymeric's avatar
aymeric committed
34
              const StunAtrString *username, const StunAtrString *password, 
aymeric's avatar
aymeric committed
35
              UInt96 *tid)
aymeric's avatar
aymeric committed
36 37 38 39 40 41
{	
   StunMessage req;
   char buf[STUN_MAX_MESSAGE_SIZE];
   int len = STUN_MAX_MESSAGE_SIZE;
   
   memset(&req, 0, sizeof(StunMessage));
42

aymeric's avatar
aymeric committed
43
   stunBuildReqSimple( &req, username, FALSE, FALSE, 1);
44 45
   req.hasMessageIntegrity=TRUE;

aymeric's avatar
aymeric committed
46 47 48 49
   /* 7.1.1.1
   The attribute MUST be set equal to the priority that would be
   assigned, based on the algorithm in Section 4.1.2, to a peer
   reflexive candidate, should one be learned as a consequence of this
aymeric's avatar
aymeric committed
50
   check */
51
   req.hasPriority = TRUE;
aymeric's avatar
aymeric committed
52

53
   req.priority.priority = (110 << 24) | (255 << 16) | (255 << 8)
aymeric's avatar
aymeric committed
54
	   | (256 - remote_candidate->remote_candidate.component_id);
55 56

   /* TODO: put this parameter only for the candidate selected */
aymeric's avatar
aymeric committed
57
   if (remote_candidate->nominated_pair==1)
58 59 60 61 62
	   req.hasUseCandidate = TRUE;

   if (remote_candidate->rem_controlling==1)
	   {
		   req.hasIceControlled = TRUE;
63
		   req.iceControlled.value = checklist->tiebreak_value;
64 65 66 67
	   }
   else
	   {
		   req.hasIceControlling = TRUE;
68
		   req.iceControlling.value	= checklist->tiebreak_value;
69 70 71 72 73
	   }

   /* TODO: not yet implemented? */
   req.hasFingerprint = TRUE;
   
aymeric's avatar
aymeric committed
74
   len = stunEncodeMessage( &req, buf, len, password );
aymeric's avatar
aymeric committed
75

aymeric's avatar
aymeric committed
76
   memcpy(tid , &(req.msgHdr.tr_id), sizeof(req.msgHdr.tr_id));
aymeric's avatar
aymeric committed
77

aymeric's avatar
aymeric committed
78
   sendMessage( myFd, buf, len, dest->addr, dest->port );	
aymeric's avatar
aymeric committed
79 80
}

81
static int ice_restart(struct IceCheckList *checklist)
aymeric's avatar
aymeric committed
82
{
aymeric's avatar
aymeric committed
83 84 85 86 87
	struct CandidatePair *remote_candidates = NULL;
	int pos;

	int count_waiting=0;
	int count=0;
aymeric's avatar
aymeric committed
88

89 90
	if (checklist==NULL)
		return 0;
aymeric's avatar
aymeric committed
91
	remote_candidates = checklist->cand_pairs;
aymeric's avatar
aymeric committed
92 93 94
	if (remote_candidates==NULL)
		return 0;

aymeric's avatar
aymeric committed
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
	for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++)
	{
		if (strcasecmp(remote_candidates[pos].local_candidate.cand_type, "srflx")==0)
		{
			/* search for a highest priority "equivalent" pair */
			int pos2;
			for (pos2=0;pos2<pos && remote_candidates[pos2].remote_candidate.conn_addr[0]!='\0';pos2++)
			{
				/* same "base" address (origin of STUN connectivity check to the remote candidate */
				if (strcasecmp(remote_candidates[pos].local_candidate.rel_addr, /* base address for "reflexive" address */
					remote_candidates[pos2].local_candidate.conn_addr)==0) /* base address for "host" address */
				{
					/* if same target remote candidate: -> remove the one with lowest priority */
					if (strcasecmp(remote_candidates[pos].remote_candidate.conn_addr,
						remote_candidates[pos2].remote_candidate.conn_addr)==0)
					{    
						/* useless cpair */                 
						ms_message("ice.c: Removing useless pair (idx=%i)", pos);
						remote_candidates[pos].connectivity_check = ICE_PRUNED;

					}

				}

			}
		}
	}

	/* no currently nominated pair */
	checklist->nominated_pair_index = -1;

	for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++)
	{
		if (remote_candidates[pos].connectivity_check == ICE_PRUNED)
			continue;
		if (remote_candidates[pos].connectivity_check == ICE_FROZEN)
			remote_candidates[pos].connectivity_check = ICE_WAITING;
	}

	checklist->Ta = 40;
	for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++)
	{
		if (remote_candidates[pos].connectivity_check == ICE_PRUNED)
			continue;
		if (remote_candidates[pos].connectivity_check == ICE_WAITING)
			count_waiting++;
		count++;
	}
	checklist->RTO = MAX(200, count*checklist->Ta*count_waiting);
	return 0;
}

147
static int ice_sound_send_stun_request(RtpSession *session, struct IceCheckList *checklist, uint64_t ctime)
aymeric's avatar
aymeric committed
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
{
	struct CandidatePair *remote_candidates = NULL;

	if (checklist==NULL)
		return 0;
	remote_candidates = checklist->cand_pairs;
	if (remote_candidates==NULL)
		return 0;

	{
		struct CandidatePair *cand_pair;
		int media_socket = rtp_session_get_rtp_socket(session);
		StunAddress4 stunServerAddr;
		StunAtrString username;
		StunAtrString password;
		bool_t res;
		int pos;

		/* prepare ONCE tie-break value */
		if (checklist->tiebreak_value==0) {
			checklist->tiebreak_value = random() * (0x7fffffffffffffff/0x7fff);
		}

		cand_pair=NULL;
		for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++)
		{
			cand_pair = &remote_candidates[pos];
			if (cand_pair->connectivity_check == ICE_PRUNED)
			{
				cand_pair=NULL;
				continue;
			}
			if (cand_pair->connectivity_check == ICE_WAITING)
				break;
			if (cand_pair->connectivity_check == ICE_IN_PROGRESS)
				break;
			if (cand_pair->connectivity_check == ICE_SUCCEEDED)
				break;
			cand_pair=NULL;
		}

		if (cand_pair==NULL)
			return 0; /* nothing to do: every pair is FAILED, FROZEN or PRUNED */

		/* start first WAITING pair */
		cand_pair=NULL;
		for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++)
		{
			cand_pair = &remote_candidates[pos];
			if (cand_pair->connectivity_check == ICE_PRUNED)
			{
				cand_pair=NULL;
				continue;
			}
			if (cand_pair->connectivity_check == ICE_WAITING)
				break;
			cand_pair=NULL;
		}

		if (cand_pair!=NULL)
		{
			cand_pair->connectivity_check = ICE_IN_PROGRESS;
			cand_pair->retransmission_number=0;
			cand_pair->retransmission_time=ctime+checklist->RTO;
			/* keep same rem_controlling for retransmission */
			cand_pair->rem_controlling = checklist->rem_controlling;
		}

		/* try no nominate a pair if we are ready */
		if (cand_pair==NULL && checklist->nominated_pair_index<0)
		{
			for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++)
			{
				cand_pair = &remote_candidates[pos];
				if (cand_pair->connectivity_check == ICE_PRUNED)
				{
					cand_pair=NULL;
					continue;
				}
				if (cand_pair->connectivity_check == ICE_SUCCEEDED)
				{
					break;
				}
				cand_pair=NULL;
			}

			/* ALWAYS accept "host" candidate that have succeeded */
			if (cand_pair!=NULL
				&& (strcasecmp(cand_pair->remote_candidate.cand_type, "host")==0))
			{
				checklist->nominated_pair_index = pos;
				cand_pair->nominated_pair = 1;
				cand_pair->connectivity_check = ICE_IN_PROGRESS;
				cand_pair->retransmission_number=0;
				cand_pair->retransmission_time=ctime+checklist->RTO;
				/* keep same rem_controlling for retransmission */
				cand_pair->rem_controlling = checklist->rem_controlling;
				/* send a new STUN with USE-CANDIDATE */
aymeric's avatar
aymeric committed
246 247 248 249 250 251 252 253 254
				ms_message("ice.c: nominating pair -> %i (%s:%i:%s -> %s:%i:%s) nominated=%s",
					pos,
					cand_pair->local_candidate.conn_addr,
					cand_pair->local_candidate.conn_port,
					cand_pair->local_candidate.cand_type,
					cand_pair->remote_candidate.conn_addr,
					cand_pair->remote_candidate.conn_port,
					cand_pair->remote_candidate.cand_type,
					cand_pair->nominated_pair==0?"FALSE":"TRUE");
aymeric's avatar
aymeric committed
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
				checklist->keepalive_time=ctime+15*1000;
			}
			else if (cand_pair!=NULL)
			{
				struct CandidatePair *cand_pair2;
				int pos2;
				for (pos2=0;pos2<pos && remote_candidates[pos2].remote_candidate.conn_addr[0]!='\0';pos2++)
				{
					cand_pair2 = &remote_candidates[pos2];
					if (cand_pair2->connectivity_check == ICE_PRUNED)
					{
						cand_pair2=NULL;
						continue;
					}
					if (cand_pair2->connectivity_check == ICE_IN_PROGRESS
						||cand_pair2->connectivity_check == ICE_WAITING)
					{
						break;
					}
					cand_pair2=NULL;
				}

				if (cand_pair2!=NULL)
				{
					/* a better candidate is still tested */
					cand_pair=NULL;
				}
				else
				{
					checklist->nominated_pair_index = pos;
					cand_pair->nominated_pair = 1;
					cand_pair->connectivity_check = ICE_IN_PROGRESS;
					cand_pair->retransmission_number=0;
					cand_pair->retransmission_time=ctime+checklist->RTO;
					/* keep same rem_controlling for retransmission */
					cand_pair->rem_controlling = checklist->rem_controlling;
					/* send a new STUN with USE-CANDIDATE */
aymeric's avatar
aymeric committed
292 293 294 295 296 297 298 299 300
					ms_message("ice.c: nominating pair -> %i (%s:%i:%s -> %s:%i:%s) nominated=%s",
						pos,
						cand_pair->local_candidate.conn_addr,
						cand_pair->local_candidate.conn_port,
						cand_pair->local_candidate.cand_type,
						cand_pair->remote_candidate.conn_addr,
						cand_pair->remote_candidate.conn_port,
						cand_pair->remote_candidate.cand_type,
						cand_pair->nominated_pair==0?"FALSE":"TRUE");
aymeric's avatar
aymeric committed
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
					checklist->keepalive_time=ctime+15*1000;
				}
			}
		}

		if (cand_pair==NULL)
		{
			/* no WAITING pair: retransmit after RTO */
			for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++)
			{
				cand_pair = &remote_candidates[pos];
				if (cand_pair->connectivity_check == ICE_PRUNED)
				{
					cand_pair=NULL;
					continue;
				}
				if (cand_pair->connectivity_check == ICE_IN_PROGRESS
					&& ctime > cand_pair->retransmission_time)
				{
					if (cand_pair->retransmission_number>7)
					{
						ms_message("ice.c: ICE_FAILED for candidate pair! %s:%i -> %s:%i",
							cand_pair->local_candidate.conn_addr,
							cand_pair->local_candidate.conn_port,
							cand_pair->remote_candidate.conn_addr,
							cand_pair->remote_candidate.conn_port);

						cand_pair->connectivity_check = ICE_FAILED;
						cand_pair=NULL;
						continue;
					}

					cand_pair->retransmission_number++;
					cand_pair->retransmission_time=ctime+checklist->RTO;
					break;
				}
				cand_pair=NULL;
			}
		}

		if (cand_pair==NULL)
		{
			if (checklist->nominated_pair_index<0)
				return 0;

			/* send STUN indication each 15 seconds: keepalive */
			if (ctime>checklist->keepalive_time)
			{
				checklist->keepalive_time=ctime+15*1000;
				for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++)
				{
					cand_pair = &remote_candidates[pos];
					if (cand_pair->connectivity_check == ICE_SUCCEEDED)
					{
						res = stunParseServerName(cand_pair->remote_candidate.conn_addr,
							&stunServerAddr);
						if ( res == TRUE )
						{
							StunMessage req;
							char buf[STUN_MAX_MESSAGE_SIZE];
							int len = STUN_MAX_MESSAGE_SIZE;
							stunServerAddr.port = cand_pair->remote_candidate.conn_port;
							memset(&req, 0, sizeof(StunMessage));
							stunBuildReqSimple( &req, NULL, FALSE, FALSE, 1);
							req.msgHdr.msgType = (STUN_METHOD_BINDING|STUN_INDICATION);
aymeric's avatar
aymeric committed
366
							req.hasFingerprint = TRUE;
aymeric's avatar
aymeric committed
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
							len = stunEncodeMessage( &req, buf, len, NULL);
							sendMessage( media_socket, buf, len, stunServerAddr.addr, stunServerAddr.port );
						}
					}
				}
			}

			return 0;
		}

		username.sizeValue = 0;
		password.sizeValue = 0;

		/* username comes from "ice-ufrag" (rfrag:lfrag) */
		/* ufrag and pwd are in first row only */
		snprintf(username.value, sizeof(username.value), "%s:%s",
			checklist->rem_ice_ufrag,
			checklist->loc_ice_ufrag);
		username.sizeValue = (UInt16)strlen(username.value);


		snprintf(password.value, sizeof(password.value), "%s",
			checklist->rem_ice_pwd);
		password.sizeValue = (UInt16)strlen(password.value);


		res = stunParseServerName(cand_pair->remote_candidate.conn_addr,
			&stunServerAddr);
		if ( res == TRUE )
		{
aymeric's avatar
aymeric committed
397
			ms_message("ice.c: STUN REQ (%s) -> %i (%s:%i:%s -> %s:%i:%s) nominated=%s",
aymeric's avatar
aymeric committed
398
				cand_pair->nominated_pair==0?"":"USE-CANDIDATE",
aymeric's avatar
aymeric committed
399 400 401 402 403 404 405 406
				pos,
				cand_pair->local_candidate.conn_addr,
				cand_pair->local_candidate.conn_port,
				cand_pair->local_candidate.cand_type,
				cand_pair->remote_candidate.conn_addr,
				cand_pair->remote_candidate.conn_port,
				cand_pair->remote_candidate.cand_type,
				cand_pair->nominated_pair==0?"FALSE":"TRUE");
aymeric's avatar
aymeric committed
407
			stunServerAddr.port = cand_pair->remote_candidate.conn_port;
aymeric's avatar
aymeric committed
408
			ice_sendtest(checklist, cand_pair, media_socket, &stunServerAddr, &username, &password,
aymeric's avatar
aymeric committed
409 410 411 412 413
				&(cand_pair->tid));
		}
	}

	return 0;
aymeric's avatar
aymeric committed
414 415 416 417 418
}

static int
_ice_get_localip_for (struct sockaddr_storage *saddr, size_t saddr_len, char *loc, int size)
{
aymeric's avatar
aymeric committed
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
	int err, tmp;
	int sock;
	struct sockaddr_storage addr;
	socklen_t addr_len;

	strcpy (loc, "127.0.0.1");    /* always fallback to local loopback */

	sock = socket (saddr->ss_family, SOCK_DGRAM, 0);
	tmp = 1;
	err = setsockopt (sock, SOL_SOCKET, SO_REUSEADDR, (const char *) &tmp, sizeof (int));
	if (err < 0)
	{
		ms_error("ice.c: Error in setsockopt");
		closesocket (sock);
		return -1;
	}
	err = connect (sock, (struct sockaddr*)saddr, saddr_len);
	if (err < 0)
	{
		ms_error("ice.c: Error in connect");
		closesocket (sock);
		return -1;
	}
	addr_len = sizeof (addr);
	err = getsockname (sock, (struct sockaddr *) &addr, (socklen_t*)&addr_len);
	if (err != 0)
	{
		ms_error("ice.c: Error in getsockname");
		closesocket (sock);
		return -1;
	}

	err = getnameinfo ((struct sockaddr *) &addr, addr_len, loc, size, NULL, 0, NI_NUMERICHOST);
	if (err != 0)
	{
		ms_error("ice.c: Error in getnameinfo");
		closesocket (sock);
		return -1;
	}
	closesocket (sock);
	/* ms_message("ice.c: Outgoing interface for sending STUN answer is %s", loc); */
	return 0;
aymeric's avatar
aymeric committed
461 462
}

463 464 465
static void
_ice_createErrorResponse(StunMessage *response, int cl, int number, const char* msg)
{
aymeric's avatar
aymeric committed
466 467 468 469 470 471
	response->msgHdr.msgType = (STUN_METHOD_BINDING | STUN_ERR_RESP);
	response->hasErrorCode = TRUE;
	response->errorCode.errorClass = cl;
	response->errorCode.number = number;
	strcpy(response->errorCode.reason, msg);
	response->errorCode.sizeReason = strlen(msg);
aymeric's avatar
aymeric committed
472
	response->hasFingerprint = TRUE;
473 474
}

475
static int ice_process_stun_message(RtpSession *session, struct IceCheckList *checklist, OrtpEvent *evt)
aymeric's avatar
aymeric committed
476
{
aymeric's avatar
aymeric committed
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
	struct CandidatePair *remote_candidates = NULL;
	StunMessage msg;
	bool_t res;
	int highest_priority_success=-1;
	OrtpEventData *evt_data = ortp_event_get_data(evt);
	mblk_t *mp = evt_data->packet;
	struct sockaddr_in *udp_remote;
	char src6host[NI_MAXHOST];
	int recvport = 0;
	int i;

	udp_remote = (struct sockaddr_in*)&evt_data->ep->addr;

	memset( &msg, 0 , sizeof(msg) );
	res = stunParseMessage((char*)mp->b_rptr, mp->b_wptr-mp->b_rptr, &msg);
	if (!res)
	{
		ms_error("ice.c: Malformed STUN packet.");
		return -1;
	}
aymeric's avatar
aymeric committed
497

aymeric's avatar
aymeric committed
498
	if (checklist==NULL)
499
	{
aymeric's avatar
aymeric committed
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
		ms_error("ice.c: dropping STUN packet: ice is not configured");
		return -1;
	}

	remote_candidates = checklist->cand_pairs;
	if (remote_candidates==NULL)
	{
		ms_error("ice.c: dropping STUN packet: ice is not configured");
		return -1;
	}

	/* prepare ONCE tie-break value */
	if (checklist->tiebreak_value==0) {
		checklist->tiebreak_value = random() * (0x7fffffffffffffff/0x7fff);
	}

	memset (src6host, 0, sizeof (src6host));

	{
		struct sockaddr_storage *aaddr = (struct sockaddr_storage *)&evt_data->ep->addr;
		if (aaddr->ss_family==AF_INET)
			recvport = ntohs (((struct sockaddr_in *) udp_remote)->sin_port);
		else
			recvport = ntohs (((struct sockaddr_in6 *) &evt_data->ep->addr)->sin6_port);
	}
	i = getnameinfo ((struct sockaddr*)&evt_data->ep->addr, evt_data->ep->addrlen,
		src6host, NI_MAXHOST,
		NULL, 0, NI_NUMERICHOST);
	if (i != 0)
	{
		ms_error("ice.c: Error with getnameinfo");
		return -1;
	}
aymeric's avatar
aymeric committed
533

534
	if (STUN_IS_REQUEST(msg.msgHdr.msgType))
aymeric's avatar
aymeric committed
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
		ms_message("ice.c: STUN_CONNECTIVITYCHECK: Request received from: %s:%i",
		src6host, recvport);
	else if (STUN_IS_INDICATION(msg.msgHdr.msgType))
		ms_message("ice.c: SUN_INDICATION: Request Indication received from: %s:%i",
		src6host, recvport);
	else
		ms_message("ice.c: STUN_ANSWER: Answer received from: %s:%i",
		src6host, recvport);

	{
		int pos;
		for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++)
		{
			struct CandidatePair *cand_pair = &remote_candidates[pos];

			if (cand_pair->connectivity_check == ICE_SUCCEEDED)
			{
				highest_priority_success=pos;
				break;
			}
		}
	}

	if (STUN_IS_INDICATION(msg.msgHdr.msgType))
559
	{
aymeric's avatar
aymeric committed
560
		ms_message("ice.c: STUN INDICATION <- (?:?:? <- %s:%i:?)", src6host, recvport);
aymeric's avatar
aymeric committed
561 562 563 564 565 566 567 568
		return 0;
	}
	else if (STUN_IS_REQUEST(msg.msgHdr.msgType))
	{
		StunMessage resp;
		StunAtrString hmacPassword;
		StunAddress4 remote_addr;
		int rtp_socket;
aymeric's avatar
aymeric committed
569

570
		memset( &resp, 0 , sizeof(resp));
aymeric's avatar
aymeric committed
571 572 573 574
		remote_addr.addr = ntohl(udp_remote->sin_addr.s_addr);
		remote_addr.port = ntohs(udp_remote->sin_port);

		rtp_socket = rtp_session_get_rtp_socket(session);
aymeric's avatar
aymeric committed
575

576 577
		resp.msgHdr.magic_cookie = ntohl(msg.msgHdr.magic_cookie);
		for (i=0; i<12; i++ )
aymeric's avatar
aymeric committed
578 579 580 581
		{
			resp.msgHdr.tr_id.octet[i] = msg.msgHdr.tr_id.octet[i];
		}

582
		/* check mandatory params */
aymeric's avatar
aymeric committed
583

584
		if (!msg.hasUsername)
aymeric's avatar
aymeric committed
585 586 587
		{
			char buf[STUN_MAX_MESSAGE_SIZE];
			int len = sizeof(buf);
aymeric's avatar
aymeric committed
588
			ms_error("ice.c: STUN REQ <- Missing USERNAME attribute in connectivity check");
aymeric's avatar
aymeric committed
589 590 591 592 593 594
			_ice_createErrorResponse(&resp, 4, 32, "Missing USERNAME attribute");
			len = stunEncodeMessage(&resp, buf, len, &hmacPassword );
			if (len)
				sendMessage( rtp_socket, buf, len, remote_addr.addr, remote_addr.port);
			return -1;
		}
595
		if (!msg.hasMessageIntegrity)
aymeric's avatar
aymeric committed
596 597 598
		{
			char buf[STUN_MAX_MESSAGE_SIZE];
			int len = sizeof(buf);
aymeric's avatar
aymeric committed
599
			ms_error("ice.c: STUN REQ <- Missing MESSAGEINTEGRITY attribute in connectivity check");
aymeric's avatar
aymeric committed
600 601 602 603 604 605 606 607 608 609 610
			_ice_createErrorResponse(&resp, 4, 1, "Missing MESSAGEINTEGRITY attribute");
			len = stunEncodeMessage(&resp, buf, len, &hmacPassword );
			if (len)
				sendMessage( rtp_socket, buf, len, remote_addr.addr, remote_addr.port);
			return -1;
		}

		/*
		The password associated with that transport address ID is used to verify
		the MESSAGE-INTEGRITY attribute, if one was present in the request.
		*/
aymeric's avatar
aymeric committed
611
		{
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
			char hmac[20];
			/* remove length of fingerprint if present */
			if (msg.hasFingerprint==TRUE)
			{
				char *lenpos = (char *)mp->b_rptr + sizeof(UInt16);
				UInt16 newlen = htons(msg.msgHdr.msgLength-8); /* remove fingerprint size */
				memcpy(lenpos, &newlen, sizeof(UInt16));
				stunCalculateIntegrity_shortterm(hmac, (char*)mp->b_rptr, mp->b_wptr-mp->b_rptr-24-8, checklist->loc_ice_pwd);
			}
			else
				stunCalculateIntegrity_shortterm(hmac, (char*)mp->b_rptr, mp->b_wptr-mp->b_rptr-24, checklist->loc_ice_pwd);
			if (memcmp(msg.messageIntegrity.hash, hmac, 20)!=0)
			{
				char buf[STUN_MAX_MESSAGE_SIZE];
				int len = sizeof(buf);
				ms_error("ice.c: STUN REQ <- Wrong MESSAGEINTEGRITY attribute in connectivity check");
				_ice_createErrorResponse(&resp, 4, 1, "Wrong MESSAGEINTEGRITY attribute");
				len = stunEncodeMessage(&resp, buf, len, &hmacPassword );
				if (len)
					sendMessage( rtp_socket, buf, len, remote_addr.addr, remote_addr.port);
				return -1;
			}
			if (msg.hasFingerprint==TRUE)
			{
				char *lenpos = (char *)mp->b_rptr + sizeof(UInt16);
				UInt16 newlen = htons(msg.msgHdr.msgLength); /* add back fingerprint size */
				memcpy(lenpos, &newlen, sizeof(UInt16));
			}
aymeric's avatar
aymeric committed
640
		}
641 642 643 644 645


		/* 7.2.1.1. Detecting and Repairing Role Conflicts */
		/* TODO */
		if (!msg.hasIceControlling && !msg.hasIceControlled)
aymeric's avatar
aymeric committed
646 647 648
		{
			char buf[STUN_MAX_MESSAGE_SIZE];
			int len = sizeof(buf);
aymeric's avatar
aymeric committed
649
			ms_error("ice.c: STUN REQ <- Missing either ICE-CONTROLLING or ICE-CONTROLLED attribute");
aymeric's avatar
aymeric committed
650 651 652 653 654 655 656 657
			_ice_createErrorResponse(&resp, 4, 87, "Missing either ICE-CONTROLLING or ICE-CONTROLLED attribute");
			len = stunEncodeMessage(&resp, buf, len, &hmacPassword );
			if (len)
				sendMessage( rtp_socket, buf, len, remote_addr.addr, remote_addr.port);
			return -1;
		}

		if (checklist->rem_controlling==0 && msg.hasIceControlling) {
aymeric's avatar
aymeric committed
658
			/* If the agent's tie-breaker is larger than or equal
aymeric's avatar
aymeric committed
659 660 661 662 663
			to the contents of the ICE-CONTROLLING attribute
			-> send 487, and do not change ROLE */
			if (checklist->tiebreak_value >= msg.iceControlling.value) {
				char buf[STUN_MAX_MESSAGE_SIZE];
				int len = sizeof(buf);
aymeric's avatar
aymeric committed
664
				ms_error("ice.c: STUN REQ <- 487 Role Conflict");
aymeric's avatar
aymeric committed
665 666 667 668 669 670 671 672 673 674 675
				_ice_createErrorResponse(&resp, 4, 87, "Role Conflict");
				len = stunEncodeMessage(&resp, buf, len, &hmacPassword );
				if (len)
					sendMessage( rtp_socket, buf, len, remote_addr.addr, remote_addr.port);
				return -1;
			}
			else {
				int pos;
				for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++)
				{
					/* controller agent */
aymeric's avatar
aymeric committed
676
					uint64_t G = remote_candidates[pos].remote_candidate.priority;
aymeric's avatar
aymeric committed
677
					/* controlled agent */	
aymeric's avatar
aymeric committed
678 679
					uint64_t D = remote_candidates[pos].local_candidate.priority;
					remote_candidates[pos].pair_priority = (MIN(G, D))<<32 | (MAX(G, D))<<1 | (G>D?1:0);
aymeric's avatar
aymeric committed
680 681 682
				}
				checklist->rem_controlling = 1;
				/* reset all to initial WAITING state? */
aymeric's avatar
aymeric committed
683
				ms_message("ice.c: STUN REQ <- tiebreaker -> reset all to ICE_WAITING state");
aymeric's avatar
aymeric committed
684 685 686 687 688 689 690 691 692
				for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++)
				{
					if (remote_candidates[pos].connectivity_check == ICE_PRUNED)
						continue;
					remote_candidates[pos].connectivity_check = ICE_WAITING;
					memset(&remote_candidates[pos].tid , 0, sizeof(remote_candidates[pos].tid));
					remote_candidates[pos].retransmission_time = 0;
					remote_candidates[pos].retransmission_number = 0;
				}
693
			}
aymeric's avatar
aymeric committed
694 695 696
		}

		if (checklist->rem_controlling==1 && msg.hasIceControlled) {
aymeric's avatar
aymeric committed
697

aymeric's avatar
aymeric committed
698 699 700 701 702 703 704 705
			/* If the agent's tie-breaker is larger than or equal
			to the contents of the ICE-CONTROLLED attribute
			-> change ROLE */
			if (checklist->tiebreak_value >= msg.iceControlled.value) {
				int pos;
				for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++)
				{
					/* controller agent */
aymeric's avatar
aymeric committed
706
					uint64_t G = remote_candidates[pos].local_candidate.priority;
aymeric's avatar
aymeric committed
707
					/* controlled agent */	
aymeric's avatar
aymeric committed
708 709
					uint64_t D = remote_candidates[pos].remote_candidate.priority;
					remote_candidates[pos].pair_priority = (MIN(G, D))<<32 | (MAX(G, D))<<1 | (G>D?1:0);
aymeric's avatar
aymeric committed
710 711 712
				}
				checklist->rem_controlling = 0;
				/* reset all to initial WAITING state? */
aymeric's avatar
aymeric committed
713
				ms_message("ice.c: STUN REQ <- tiebreaker -> reset all to ICE_WAITING state");
aymeric's avatar
aymeric committed
714 715 716 717 718 719 720 721 722 723 724 725 726
				for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++)
				{
					if (remote_candidates[pos].connectivity_check == ICE_PRUNED)
						continue;
					remote_candidates[pos].connectivity_check = ICE_WAITING;
					memset(&remote_candidates[pos].tid , 0, sizeof(remote_candidates[pos].tid));
					remote_candidates[pos].retransmission_time = 0;
					remote_candidates[pos].retransmission_number = 0;
				}
			}
			else {
				char buf[STUN_MAX_MESSAGE_SIZE];
				int len = sizeof(buf);
aymeric's avatar
aymeric committed
727
				ms_error("ice.c: STUN REQ <- 487 Role Conflict");
aymeric's avatar
aymeric committed
728 729 730 731 732 733 734
				_ice_createErrorResponse(&resp, 4, 87, "Role Conflict");
				len = stunEncodeMessage(&resp, buf, len, &hmacPassword );
				if (len)
					sendMessage( rtp_socket, buf, len, remote_addr.addr, remote_addr.port);
				return -1;
			}
		}
735

aymeric's avatar
aymeric committed
736
		{
737 738 739 740
			struct CandidatePair *cand_pair;
			int pos;
			cand_pair=NULL;
			for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++)
741
			{
742 743 744 745 746 747
				cand_pair = &remote_candidates[pos]; 
				/* connectivity check is coming from a known remote candidate?
				we should also check the port...
				*/
				if (strcmp(cand_pair->remote_candidate.conn_addr, src6host)==0
					&& cand_pair->remote_candidate.conn_port==recvport)
aymeric's avatar
aymeric committed
748
				{
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
					ms_message("ice.c: STUN REQ (%s) <- %i (%s:%i:%s <- %s:%i:%s) from known peer",
						msg.hasUseCandidate==0?"":"USE-CANDIDATE",
						pos,
						cand_pair->local_candidate.conn_addr,
						cand_pair->local_candidate.conn_port,
						cand_pair->local_candidate.cand_type,
						cand_pair->remote_candidate.conn_addr,
						cand_pair->remote_candidate.conn_port,
						cand_pair->remote_candidate.cand_type);
					if (cand_pair->connectivity_check==ICE_FROZEN
						|| cand_pair->connectivity_check==ICE_IN_PROGRESS
						|| cand_pair->connectivity_check==ICE_FAILED)
					{
						cand_pair->connectivity_check = ICE_WAITING;
						if (msg.hasUseCandidate==TRUE && checklist->rem_controlling==0)
							cand_pair->nominated_pair = 1;
					}
					else if (cand_pair->connectivity_check==ICE_SUCCEEDED)
767
					{
768 769 770
						if (msg.hasUseCandidate==TRUE && checklist->rem_controlling==0)
						{
							cand_pair->nominated_pair = 1;
aymeric's avatar
aymeric committed
771

772 773 774 775 776 777 778 779 780 781 782 783 784
							/* USE-CANDIDATE is in STUN request and we already succeeded on that link */
							ms_message("ice.c: ICE CONCLUDED == %i (%s:%i:%s <- %s:%i:%s nominated=%s)",
								pos,
								cand_pair->local_candidate.conn_addr,
								cand_pair->local_candidate.conn_port,
								cand_pair->local_candidate.cand_type,
								cand_pair->remote_candidate.conn_addr,
								cand_pair->remote_candidate.conn_port,
								cand_pair->remote_candidate.cand_type,
								cand_pair->nominated_pair==0?"FALSE":"TRUE");
							memcpy(&session->rtp.rem_addr, &evt_data->ep->addr, evt_data->ep->addrlen);
							session->rtp.rem_addrlen=evt_data->ep->addrlen;
						}
785
					}
786
					break;
aymeric's avatar
aymeric committed
787
				}
788
				cand_pair=NULL;
aymeric's avatar
aymeric committed
789
			}
790 791 792 793
			if (cand_pair==NULL)
			{
				struct CandidatePair new_pair;
				memset(&new_pair, 0, sizeof(struct CandidatePair));
aymeric's avatar
aymeric committed
794

795 796
				ms_message("ice.c: STUN REQ <- connectivity check received from an unknow candidate (%s:%i)", src6host, recvport);
				/* TODO: add the peer-reflexive candidate */
aymeric's avatar
aymeric committed
797

798
				memcpy(&new_pair.local_candidate, &remote_candidates[0].local_candidate, sizeof(new_pair.local_candidate));
aymeric's avatar
aymeric committed
799

800 801
				new_pair.remote_candidate.foundation = 6;
				new_pair.remote_candidate.component_id = remote_candidates[0].remote_candidate.component_id;
aymeric's avatar
aymeric committed
802

803
				/* -> no known base address for peer */
aymeric's avatar
aymeric committed
804

805 806 807
				new_pair.remote_candidate.conn_port = recvport;
				snprintf(new_pair.remote_candidate.conn_addr, sizeof(new_pair.remote_candidate.conn_addr),
					"%s", src6host);
aymeric's avatar
aymeric committed
808

809 810 811 812 813 814 815 816 817 818
				/* take it from PRIORITY STUN attr */
				new_pair.remote_candidate.priority = msg.priority.priority;
				if (new_pair.remote_candidate.priority==0)
				{
					uint32_t type_preference = 110;
					uint32_t interface_preference = 255;
					uint32_t stun_priority=255;
					new_pair.remote_candidate.priority = (type_preference << 24) | (interface_preference << 16) | (stun_priority << 8)
						| (256 - new_pair.remote_candidate.component_id);
				}
aymeric's avatar
aymeric committed
819

820 821 822 823 824
				snprintf(new_pair.remote_candidate.cand_type, sizeof(cand_pair->remote_candidate.cand_type),
					"prflx");
				snprintf (new_pair.remote_candidate.transport,
								sizeof (new_pair.remote_candidate.transport),
								"UDP");
aymeric's avatar
aymeric committed
825

826
				if (checklist->rem_controlling==0)
aymeric's avatar
aymeric committed
827
				{
828 829 830 831 832 833 834 835 836 837 838
					uint64_t G = new_pair.local_candidate.priority;
					/* controlled agent */	
					uint64_t D = new_pair.remote_candidate.priority;
					new_pair.pair_priority = (MIN(G, D))<<32 | (MAX(G, D))<<1 | (G>D?1:0);
				}
				else
				{
					uint64_t G = new_pair.remote_candidate.priority;
					/* controlled agent */	
					uint64_t D = new_pair.local_candidate.priority;
					new_pair.pair_priority = (MIN(G, D))<<32 | (MAX(G, D))<<1 | (G>D?1:0);
aymeric's avatar
aymeric committed
839
				}
840 841 842
				new_pair.connectivity_check = ICE_WAITING;
				/* insert new pair candidate */
				if (msg.hasUseCandidate==TRUE && checklist->rem_controlling==0)
aymeric's avatar
aymeric committed
843
				{
844 845
					new_pair.nominated_pair = 1;
				}
aymeric's avatar
aymeric committed
846

847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
				for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++)
				{
					if (pos==9)
					{
						ms_message("ice.c: STUN REQ (%s) <- X (%s:%i:%s <- %s:%i:%s) no room for new remote reflexive candidate",
							msg.hasUseCandidate==0?"":"USE-CANDIDATE",
							new_pair.local_candidate.conn_addr,
							new_pair.local_candidate.conn_port,
							new_pair.local_candidate.cand_type,
							new_pair.remote_candidate.conn_addr,
							new_pair.remote_candidate.conn_port,
							new_pair.remote_candidate.cand_type);
						break;
					}
					if (new_pair.pair_priority > remote_candidates[pos].pair_priority)
					{
						/* move upper data */
						memmove(&remote_candidates[pos+1], &remote_candidates[pos], sizeof(struct CandidatePair)*(10-pos-1));
						memcpy(&remote_candidates[pos], &new_pair, sizeof(struct CandidatePair));

						if (checklist->nominated_pair_index>=pos)
							checklist->nominated_pair_index++;
						ms_message("ice.c: STUN REQ (%s) <- %i (%s:%i:%s <- %s:%i:%s) new learned remote reflexive candidate",
							msg.hasUseCandidate==0?"":"USE-CANDIDATE",
							pos,
							new_pair.local_candidate.conn_addr,
							new_pair.local_candidate.conn_port,
							new_pair.local_candidate.cand_type,
							new_pair.remote_candidate.conn_addr,
							new_pair.remote_candidate.conn_port,
							new_pair.remote_candidate.cand_type);
						break;
					}
aymeric's avatar
aymeric committed
880 881 882 883
				}
			}
		}

884 885 886 887 888 889
		{
			UInt32 cookie = 0x2112A442;
			resp.hasXorMappedAddress = TRUE;
			resp.xorMappedAddress.ipv4.port = remote_addr.port^(cookie>>16);
			resp.xorMappedAddress.ipv4.addr = remote_addr.addr^cookie;
		}
aymeric's avatar
aymeric committed
890

891
		resp.msgHdr.msgType = (STUN_METHOD_BINDING | STUN_SUCCESS_RESP);
aymeric's avatar
aymeric committed
892

893 894 895 896 897 898 899
		resp.hasUsername = TRUE;
		memcpy(resp.username.value, msg.username.value, msg.username.sizeValue );
		resp.username.sizeValue = msg.username.sizeValue;

		/* ? any messageintegrity in response? */
		resp.hasMessageIntegrity = TRUE;

900 901 902 903 904 905
		{
			const char serverName[] = "mediastreamer2 " STUN_VERSION;
			resp.hasSoftware = TRUE;
			memcpy( resp.softwareName.value, serverName, sizeof(serverName));
			resp.softwareName.sizeValue = sizeof(serverName);
		}
aymeric's avatar
aymeric committed
906

aymeric's avatar
aymeric committed
907 908
		resp.hasFingerprint = TRUE;

aymeric's avatar
aymeric committed
909 910 911 912 913
		{
			char buf[STUN_MAX_MESSAGE_SIZE];
			int len = sizeof(buf);
			len = stunEncodeMessage( &resp, buf, len, &hmacPassword );
			if (len)
914
				sendMessage( rtp_socket, buf, len, remote_addr.addr, remote_addr.port);
aymeric's avatar
aymeric committed
915
		}
916
	}
aymeric's avatar
aymeric committed
917 918 919 920 921 922 923 924 925 926
	else if (STUN_IS_SUCCESS_RESP(msg.msgHdr.msgType))
	{
		/* set state to RECV-VALID or VALID */
		StunMessage resp;
		StunAddress4 mappedAddr;
		memset(&resp, 0, sizeof(StunMessage));
		res = stunParseMessage((char*)mp->b_rptr, mp->b_wptr-mp->b_rptr,
			&resp );
		if (!res)
		{
aymeric's avatar
aymeric committed
927
			ms_error("ice.c: STUN RESP <- Bad format for STUN answer.");
aymeric's avatar
aymeric committed
928 929 930 931 932
			return -1;
		}

		if (resp.hasXorMappedAddress!=TRUE)
		{
aymeric's avatar
aymeric committed
933
			ms_error("ice.c: STUN RESP <- Missing XOR-MAPPED-ADDRESS in STUN answer.");		  
aymeric's avatar
aymeric committed
934 935 936 937
			return -1;
		}

		{
938 939 940 941
			UInt32 cookie = 0x2112A442;
			UInt16 cookie16 = 0x2112A442 >> 16;
			mappedAddr.port = resp.xorMappedAddress.ipv4.port^cookie16;
			mappedAddr.addr = resp.xorMappedAddress.ipv4.addr^cookie;
aymeric's avatar
aymeric committed
942 943 944
		}

		{
945 946 947 948 949 950 951 952 953
			struct in_addr inaddr;
			char mapped_addr[64];
			struct CandidatePair *cand_pair;
			int pos;
			inaddr.s_addr = htonl (mappedAddr.addr);
			snprintf(mapped_addr, sizeof(mapped_addr),
				"%s", inet_ntoa (inaddr));

			for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++)
aymeric's avatar
aymeric committed
954
			{
955
				cand_pair = &remote_candidates[pos];
aymeric's avatar
aymeric committed
956

957
				if (memcmp(&(cand_pair->tid), &(resp.msgHdr.tr_id), sizeof(resp.msgHdr.tr_id))==0)
aymeric's avatar
aymeric committed
958
				{
959
					break;
aymeric's avatar
aymeric committed
960
				}
961 962
				cand_pair = NULL;
			}
aymeric's avatar
aymeric committed
963

964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
			if (cand_pair==NULL)
			{
				ms_message("ice.c: STUN RESP (%s) <- no transaction for STUN answer?",
					msg.hasUseCandidate==0?"":"USE-CANDIDATE");
			}
			else if (strcmp(src6host, cand_pair->remote_candidate.conn_addr)!=0
				|| recvport!=cand_pair->remote_candidate.conn_port)
			{
				/* 7.1.2.2.  Success Cases
				-> must be a security issue: refuse non-symmetric answer */
				ms_message("ice.c: STUN RESP (%s) <- %i (%s:%i:%s <- %s:%i:%s nominated=%s) refused because non-symmetric",
					msg.hasUseCandidate==0?"":"USE-CANDIDATE",
					pos,
					cand_pair->local_candidate.conn_addr,
					cand_pair->local_candidate.conn_port,
					cand_pair->local_candidate.cand_type,
					cand_pair->remote_candidate.conn_addr,
					cand_pair->remote_candidate.conn_port,
					cand_pair->remote_candidate.cand_type,
					cand_pair->nominated_pair==0?"FALSE":"TRUE");
aymeric's avatar
aymeric committed
984
				cand_pair->connectivity_check = ICE_FAILED;
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
			}
			else
			{
				/* Youhouhouhou */
				ms_message("ice.c: STUN RESP (%s) <- %i (%s:%i:%s <- %s:%i:%s nominated=%s)",
					msg.hasUseCandidate==0?"":"USE-CANDIDATE",
					pos,
					cand_pair->local_candidate.conn_addr,
					cand_pair->local_candidate.conn_port,
					cand_pair->local_candidate.cand_type,
					cand_pair->remote_candidate.conn_addr,
					cand_pair->remote_candidate.conn_port,
					cand_pair->remote_candidate.cand_type,
					cand_pair->nominated_pair==0?"FALSE":"TRUE");
				if (cand_pair->connectivity_check != ICE_SUCCEEDED)
aymeric's avatar
aymeric committed
1000
				{
1001
					if (checklist->rem_controlling==1 && cand_pair->nominated_pair>0)
aymeric's avatar
aymeric committed
1002
					{
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
						/* USE-CANDIDATE was in previous STUN request sent */
						ms_message("ice.c: ICE CONCLUDED == %i (%s:%i:%s <- %s:%i:%s nominated=%s)",
							pos,
							cand_pair->local_candidate.conn_addr,
							cand_pair->local_candidate.conn_port,
							cand_pair->local_candidate.cand_type,
							cand_pair->remote_candidate.conn_addr,
							cand_pair->remote_candidate.conn_port,
							cand_pair->remote_candidate.cand_type,
							cand_pair->nominated_pair==0?"FALSE":"TRUE");
						memcpy(&session->rtp.rem_addr, &evt_data->ep->addr, evt_data->ep->addrlen);
						session->rtp.rem_addrlen=evt_data->ep->addrlen;
aymeric's avatar
aymeric committed
1015
					}
1016 1017

					if (cand_pair->nominated_pair>0 && checklist->rem_controlling==0)
aymeric's avatar
aymeric committed
1018
					{
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
						/* USE-CANDIDATE is in STUN request and we already succeeded on that link */
						ms_message("ice.c: ICE CONCLUDED == %i (%s:%i:%s <- %s:%i:%s nominated=%s)",
							pos,
							cand_pair->local_candidate.conn_addr,
							cand_pair->local_candidate.conn_port,
							cand_pair->local_candidate.cand_type,
							cand_pair->remote_candidate.conn_addr,
							cand_pair->remote_candidate.conn_port,
							cand_pair->remote_candidate.cand_type,
							cand_pair->nominated_pair==0?"FALSE":"TRUE");
						memcpy(&session->rtp.rem_addr, &evt_data->ep->addr, evt_data->ep->addrlen);
						session->rtp.rem_addrlen=evt_data->ep->addrlen;
					}

					cand_pair->connectivity_check = ICE_FAILED;
					if (mappedAddr.port == cand_pair->local_candidate.conn_port
						&& strcmp(mapped_addr, cand_pair->local_candidate.conn_addr)==0)
					{
						/* no peer-reflexive candidate was discovered */
						cand_pair->connectivity_check = ICE_SUCCEEDED;
					}
					else
					{
						int pos2;
aymeric's avatar
aymeric committed
1043 1044
						for (pos2=0;pos2<10 && remote_candidates[pos2].remote_candidate.conn_addr[0]!='\0';pos2++)
						{
1045 1046 1047 1048
							if (mappedAddr.port == remote_candidates[pos2].local_candidate.conn_port
								&& strcmp(mapped_addr, remote_candidates[pos2].local_candidate.conn_addr)==0
								&& cand_pair->remote_candidate.conn_port == remote_candidates[pos2].remote_candidate.conn_port
								&& strcmp(cand_pair->remote_candidate.conn_addr, remote_candidates[pos2].remote_candidate.conn_addr)==0)
aymeric's avatar
aymeric committed
1049
							{
1050 1051 1052 1053 1054 1055 1056
								if (remote_candidates[pos2].connectivity_check==ICE_PRUNED
									||remote_candidates[pos2].connectivity_check==ICE_FROZEN
									||remote_candidates[pos2].connectivity_check==ICE_FAILED
									|| remote_candidates[pos2].connectivity_check==ICE_IN_PROGRESS)
									remote_candidates[pos2].connectivity_check = ICE_WAITING; /* trigger check */
								/*
								ms_message("ice.c: STUN RESP (%s) <- %i (%s:%i:%s <- %s:%i:%s) found candidate pair matching XOR-MAPPED-ADDRESS",
aymeric's avatar
aymeric committed
1057
									msg.hasUseCandidate==0?"":"USE-CANDIDATE",
1058 1059 1060 1061 1062 1063 1064 1065
									pos,
									cand_pair->local_candidate.conn_addr,
									cand_pair->local_candidate.conn_port,
									cand_pair->local_candidate.cand_type,
									cand_pair->remote_candidate.conn_addr,
									cand_pair->remote_candidate.conn_port,
									cand_pair->remote_candidate.cand_type);
									*/
aymeric's avatar
aymeric committed
1066
								break;
aymeric's avatar
aymeric committed
1067
							}
1068 1069 1070 1071 1072
						}
						if (pos2==10 || remote_candidates[pos2].remote_candidate.conn_addr[0]=='\0')
						{
							struct CandidatePair new_pair;
							memset(&new_pair, 0, sizeof(struct CandidatePair));
aymeric's avatar
aymeric committed
1073

1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
							/* 7.1.2.2.1.  Discovering Peer Reflexive Candidates */
							/* If IP & port were different than mappedAddr, there was A NAT
							between me and remote destination. */
							memcpy(&new_pair.remote_candidate, &cand_pair->remote_candidate, sizeof(new_pair.remote_candidate));

							new_pair.local_candidate.foundation = 6;
							new_pair.local_candidate.component_id = cand_pair->local_candidate.component_id;

							/* what is my base address? */
							new_pair.local_candidate.rel_port = cand_pair->local_candidate.conn_port;
							snprintf(new_pair.local_candidate.rel_addr, sizeof(new_pair.local_candidate.rel_addr),
								"%s", cand_pair->local_candidate.conn_addr);

							new_pair.local_candidate.conn_port = mappedAddr.port;
							snprintf(new_pair.local_candidate.conn_addr, sizeof(new_pair.local_candidate.conn_addr),
								"%s", mapped_addr);

							new_pair.remote_candidate.priority = (110 << 24) | (255 << 16) | (255 << 8)
								| (256 - new_pair.remote_candidate.component_id);

							snprintf(new_pair.local_candidate.cand_type, sizeof(cand_pair->local_candidate.cand_type),
								"prflx");
							snprintf (new_pair.local_candidate.transport,
											sizeof (new_pair.local_candidate.transport),
											"UDP");

							if (checklist->rem_controlling==0)
							{
								uint64_t G = new_pair.local_candidate.priority;
								/* controlled agent */	
								uint64_t D = new_pair.remote_candidate.priority;
								new_pair.pair_priority = (MIN(G, D))<<32 | (MAX(G, D))<<1 | (G>D?1:0);
							}
							else
							{
								uint64_t G = new_pair.remote_candidate.priority;
								/* controlled agent */	
								uint64_t D = new_pair.local_candidate.priority;
								new_pair.pair_priority = (MIN(G, D))<<32 | (MAX(G, D))<<1 | (G>D?1:0);
							}
							new_pair.connectivity_check = ICE_WAITING;
							/* insert new pair candidate */
							for (pos2=0;pos2<10 && remote_candidates[pos2].remote_candidate.conn_addr[0]!='\0';pos2++)
							{
								if (pos2==9)
								{
									ms_message("ice.c: STUN RESP (%s) <- %i (%s:%i:%s <- %s:%i:%s) no room for new local peer-reflexive candidate",
										msg.hasUseCandidate==0?"":"USE-CANDIDATE",
										pos2,
										new_pair.local_candidate.conn_addr,
										new_pair.local_candidate.conn_port,
										new_pair.local_candidate.cand_type,
										new_pair.remote_candidate.conn_addr,
										new_pair.remote_candidate.conn_port,
										new_pair.remote_candidate.cand_type);
									break;
								}
								if (new_pair.pair_priority > remote_candidates[pos2].pair_priority)
								{
									/* move upper data */
									memmove(&remote_candidates[pos2+1], &remote_candidates[pos2], sizeof(struct CandidatePair)*(10-pos2-1));
									memcpy(&remote_candidates[pos2], &new_pair, sizeof(struct CandidatePair));

									if (checklist->nominated_pair_index>=pos2)
										checklist->nominated_pair_index++;
									ms_message("ice.c: STUN RESP (%s) <- %i (%s:%i:%s <- %s:%i:%s) new discovered local peer-reflexive candidate",
										msg.hasUseCandidate==0?"":"USE-CANDIDATE",
										pos2,
										new_pair.local_candidate.conn_addr,
										new_pair.local_candidate.conn_port,
										new_pair.local_candidate.cand_type,
										new_pair.remote_candidate.conn_addr,
										new_pair.remote_candidate.conn_port,
										new_pair.remote_candidate.cand_type);
									break;
								}
aymeric's avatar
aymeric committed
1150 1151 1152 1153 1154 1155
							}
						}
					}
				}
			}
		}
aymeric's avatar
aymeric committed
1156
	}
aymeric's avatar
aymeric committed
1157 1158
	else if (STUN_IS_ERR_RESP(msg.msgHdr.msgType))
	{
1159
		int pos;
aymeric's avatar
aymeric committed
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
		StunMessage resp;
		memset(&resp, 0, sizeof(StunMessage));
		res = stunParseMessage((char*)mp->b_rptr, mp->b_wptr-mp->b_rptr,
			&resp );
		if (!res)
		{
			ms_error("ice.c: ERROR_RESPONSE: Bad format for STUN answer.");
			return -1;
		}

		for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++)
		{
			struct CandidatePair *cand_pair = &remote_candidates[pos];

			if (memcmp(&(cand_pair->tid), &(resp.msgHdr.tr_id), sizeof(resp.msgHdr.tr_id))==0)
			{
				cand_pair->connectivity_check = ICE_FAILED;
				ms_message("ice.c: ERROR_RESPONSE: ICE_FAILED for candidate pair! %s:%i -> %s:%i",
					cand_pair->local_candidate.conn_addr,
					cand_pair->local_candidate.conn_port,
					cand_pair->remote_candidate.conn_addr,
					cand_pair->remote_candidate.conn_port);
				if (resp.hasErrorCode==TRUE && resp.errorCode.errorClass==4 && resp.errorCode.number==87)
				{
					if (remote_candidates[pos].rem_controlling==1)
					{
						int pos2;
						for (pos2=0;pos2<10 && remote_candidates[pos2].remote_candidate.conn_addr[0]!='\0';pos2++)
						{
							/* controller agent */
aymeric's avatar
aymeric committed
1190
							uint64_t G = remote_candidates[pos2].local_candidate.priority;
aymeric's avatar
aymeric committed
1191
							/* controlled agent */	
aymeric's avatar
aymeric committed
1192 1193
							uint64_t D = remote_candidates[pos2].remote_candidate.priority;
							remote_candidates[pos2].pair_priority = (MIN(G, D))<<32 | (MAX(G, D))<<1 | (G>D?1:0);
aymeric's avatar
aymeric committed
1194 1195 1196 1197 1198 1199 1200 1201 1202
						}
						checklist->rem_controlling=0;
					}
					else
					{
						int pos2;
						for (pos2=0;pos2<10 && remote_candidates[pos2].remote_candidate.conn_addr[0]!='\0';pos2++)
						{
							/* controller agent */
aymeric's avatar
aymeric committed
1203
							uint64_t G = remote_candidates[pos2].remote_candidate.priority;
aymeric's avatar
aymeric committed
1204
							/* controlled agent */	
aymeric's avatar
aymeric committed
1205 1206
							uint64_t D = remote_candidates[pos2].local_candidate.priority;
							remote_candidates[pos2].pair_priority = (MIN(G, D))<<32 | (MAX(G, D))<<1 | (G>D?1:0);
aymeric's avatar
aymeric committed
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
						}
						checklist->rem_controlling=1;
					}
					/* reset all to initial WAITING state? */
					ms_message("ice.c: ERROR_RESPONSE: 487 -> reset all to ICE_WAITING state");
					for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++)
					{
						if (remote_candidates[pos].connectivity_check == ICE_PRUNED)
							continue;
						remote_candidates[pos].connectivity_check = ICE_WAITING;
						memset(&remote_candidates[pos].tid , 0, sizeof(remote_candidates[pos].tid));
						remote_candidates[pos].retransmission_time = 0;
						remote_candidates[pos].retransmission_number = 0;
					}
				}
			}
		}
	}

	return 0;
aymeric's avatar
aymeric committed
1227 1228
}

1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382



struct IceData {
	RtpSession *session;
	OrtpEvQueue *ortp_event;
	struct IceCheckList *check_lists;	/* table of 10 cpair */
	int rate;
};

typedef struct IceData IceData;

static void ice_init(MSFilter * f)
{
	IceData *d = (IceData *)ms_new(IceData, 1);

	d->ortp_event = ortp_ev_queue_new();
	d->session = NULL;
	d->check_lists = NULL;
	d->rate = 8000;
	f->data = d;
}

static void ice_postprocess(MSFilter * f)
{
	IceData *d = (IceData *) f->data;
	if (d->session!=NULL && d->ortp_event!=NULL)
	  rtp_session_unregister_event_queue(d->session, d->ortp_event);
}

static void ice_uninit(MSFilter * f)
{
	IceData *d = (IceData *) f->data;
	if (d->ortp_event!=NULL)
	  ortp_ev_queue_destroy(d->ortp_event);
	ms_free(f->data);
}

static int ice_set_session(MSFilter * f, void *arg)
{
	IceData *d = (IceData *) f->data;
	RtpSession *s = (RtpSession *) arg;
	PayloadType *pt = rtp_profile_get_payload(rtp_session_get_profile(s),
											  rtp_session_get_recv_payload_type
											  (s));
	if (pt != NULL) {
		if (strcasecmp("g722", pt->mime_type)==0 )
			d->rate=8000;
		else d->rate = pt->clock_rate;
	} else {
		ms_warning("Receiving undefined payload type ?");
	}
	d->session = s;

	return 0;
}

static int ice_set_sdpcandidates(MSFilter * f, void *arg)
{
	IceData *d = (IceData *) f->data;
	struct IceCheckList *scs = NULL;

	if (d == NULL)
		return -1;

	scs = (struct IceCheckList *) arg;
	d->check_lists = scs;
	ice_restart(d->check_lists);
	return 0;
}

static void ice_preprocess(MSFilter * f){
	IceData *d = (IceData *) f->data;
	if (d->session!=NULL && d->ortp_event!=NULL)
		rtp_session_register_event_queue(d->session, d->ortp_event);
}

static void ice_process(MSFilter * f)
{
	IceData *d = (IceData *) f->data;

	if (d->session == NULL)
		return;

	/* check received STUN request */
	if (d->ortp_event!=NULL)
	{
		OrtpEvent *evt = ortp_ev_queue_get(d->ortp_event);

		while (evt != NULL) {
			if (ortp_event_get_type(evt) ==
				ORTP_EVENT_STUN_PACKET_RECEIVED) {
				ice_process_stun_message(d->session, d->check_lists, evt);
			}
			if (ortp_event_get_type(evt) ==
				ORTP_EVENT_TELEPHONE_EVENT) {
			}

			ortp_event_destroy(evt);
			evt = ortp_ev_queue_get(d->ortp_event);
		}
	}

#if !defined(_WIN32_WCE)
	ice_sound_send_stun_request(d->session, d->check_lists, f->ticker->time);
#else
	ice_sound_send_stun_request(d->session, d->check_lists, f->ticker->time));
#endif
}

static MSFilterMethod ice_methods[] = {
	{MS_ICE_SET_SESSION, ice_set_session},
	{MS_ICE_SET_CANDIDATEPAIRS, ice_set_sdpcandidates},
	{0, NULL}
};

#ifdef _MSC_VER

MSFilterDesc ms_ice_desc = {
	MS_ICE_ID,
	"MSIce",
	N_("ICE filter"),
	MS_FILTER_OTHER,
	NULL,
	0,
	0,
	ice_init,
	ice_preprocess,
	ice_process,
	ice_postprocess,
	ice_uninit,
	ice_methods
};

#else

MSFilterDesc ms_ice_desc = {
	.id = MS_ICE_ID,
	.name = "MSIce",
	.text = N_("ICE filter"),
	.category = MS_FILTER_OTHER,
	.ninputs = 0,
	.noutputs = 0,
	.init = ice_init,
	.preprocess = ice_preprocess,
	.process = ice_process,
	.postprocess=ice_postprocess,
	.uninit = ice_uninit,
	.methods = ice_methods
};

#endif

MS_FILTER_DESC_EXPORT(ms_ice_desc)