linphonecall.c 83.9 KB
Newer Older
1 2 3

/*
linphone
4
Copyright (C) 2010  Belledonne Communications SARL
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 (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.
*/
21 22 23
#ifdef WIN32
#include <time.h>
#endif
24 25 26 27
#include "linphonecore.h"
#include "sipsetup.h"
#include "lpconfig.h"
#include "private.h"
28
#include <ortp/event.h>
29
#include <ortp/b64.h>
Yann Diorcet's avatar
Yann Diorcet committed
30
#include <math.h>
31

32 33 34
#include "mediastreamer2/mediastream.h"
#include "mediastreamer2/msvolume.h"
#include "mediastreamer2/msequalizer.h"
35
#include "mediastreamer2/msfileplayer.h"
36
#include "mediastreamer2/msjpegwriter.h"
37
#include "mediastreamer2/mseventqueue.h"
38
#include "mediastreamer2/mssndcard.h"
39

Simon Morlat's avatar
Simon Morlat committed
40
#ifdef VIDEO_ENABLED
41 42 43
static MSWebCam *get_nowebcam_device(){
	return ms_web_cam_manager_get_cam(ms_web_cam_manager_get(),"StaticImage: Static picture");
}
Simon Morlat's avatar
Simon Morlat committed
44
#endif
45

46 47 48
static bool_t generate_b64_crypto_key(int key_length, char* key_out) {
	int b64_size;
	uint8_t* tmp = (uint8_t*) malloc(key_length);			
49
	if (ortp_crypto_get_random(tmp, key_length)!=0) {
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
		ms_error("Failed to generate random key");
		free(tmp);
		return FALSE;
	}
	
	b64_size = b64_encode((const char*)tmp, key_length, NULL, 0);
	if (b64_size == 0) {
		ms_error("Failed to b64 encode key");
		free(tmp);
		return FALSE;
	}
	key_out[b64_size] = '\0';
	b64_encode((const char*)tmp, key_length, key_out, 40);
	free(tmp);
	return TRUE;
}

67 68 69 70
LinphoneCore *linphone_call_get_core(const LinphoneCall *call){
	return call->core;
}

71
const char* linphone_call_get_authentication_token(LinphoneCall *call){
72
	return call->auth_token;
73 74 75
}

bool_t linphone_call_get_authentication_token_verified(LinphoneCall *call){
76
	return call->auth_token_verified;
77
}
Simon Morlat's avatar
Simon Morlat committed
78 79

static bool_t linphone_call_are_all_streams_encrypted(LinphoneCall *call) {
80
	// Check ZRTP encryption in audiostream
81
	if (!call->audiostream_encrypted) {
82 83 84 85 86 87
		return FALSE;
	}

#ifdef VIDEO_ENABLED
	// If video enabled, check ZRTP encryption in videostream
	const LinphoneCallParams *params=linphone_call_get_current_params(call);
88
	if (params->has_video && !call->videostream_encrypted) {
89 90 91 92 93 94 95
		return FALSE;
	}
#endif

	return TRUE;
}

96
void propagate_encryption_changed(LinphoneCall *call){
Simon Morlat's avatar
Simon Morlat committed
97
	LinphoneCore *lc=call->core;
98
	if (!linphone_call_are_all_streams_encrypted(call)) {
99
		ms_message("Some streams are not encrypted");
Simon Morlat's avatar
Simon Morlat committed
100
		call->current_params.media_encryption=LinphoneMediaEncryptionNone;
Simon Morlat's avatar
Simon Morlat committed
101 102
		if (lc->vtable.call_encryption_changed)
			lc->vtable.call_encryption_changed(call->core, call, FALSE, call->auth_token);
103
	} else {
104
		ms_message("All streams are encrypted");
Simon Morlat's avatar
Simon Morlat committed
105 106 107
		call->current_params.media_encryption=LinphoneMediaEncryptionZRTP;
		if (lc->vtable.call_encryption_changed)
			lc->vtable.call_encryption_changed(call->core, call, TRUE, call->auth_token);
108 109 110 111 112 113 114 115
	}
}

#ifdef VIDEO_ENABLED
static void linphone_call_videostream_encryption_changed(void *data, bool_t encrypted){
	ms_message("Video stream is %s", encrypted ? "encrypted" : "not encrypted");

	LinphoneCall *call = (LinphoneCall *)data;
116
	call->videostream_encrypted=encrypted;
117 118 119 120 121
	propagate_encryption_changed(call);
}
#endif

static void linphone_call_audiostream_encryption_changed(void *data, bool_t encrypted) {
122
	char status[255]={0};
123 124 125
	ms_message("Audio stream is %s ", encrypted ? "encrypted" : "not encrypted");

	LinphoneCall *call = (LinphoneCall *)data;
126
	call->audiostream_encrypted=encrypted;
Simon Morlat's avatar
Simon Morlat committed
127
	
128 129 130 131 132
	if (encrypted && call->core->vtable.display_status != NULL) {
		snprintf(status,sizeof(status)-1,_("Authentication token is %s"),call->auth_token);
		 call->core->vtable.display_status(call->core, status);
	}

133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
	propagate_encryption_changed(call);


#ifdef VIDEO_ENABLED
	// Enable video encryption
	const LinphoneCallParams *params=linphone_call_get_current_params(call);
	if (params->has_video) {
		ms_message("Trying to enable encryption on video stream");
		OrtpZrtpParams params;
		params.zid_file=NULL; //unused
		video_stream_enable_zrtp(call->videostream,call->audiostream,&params);
	}
#endif
}


static void linphone_call_audiostream_auth_token_ready(void *data, const char* auth_token, bool_t verified) {
	LinphoneCall *call=(LinphoneCall *)data;
151 152
	if (call->auth_token != NULL)
		ms_free(call->auth_token);
153

154 155
	call->auth_token=ms_strdup(auth_token);
	call->auth_token_verified=verified;
156 157 158 159

	ms_message("Authentication token is %s (%s)", auth_token, verified?"verified":"unverified");
}

Simon Morlat's avatar
Simon Morlat committed
160 161 162 163
void linphone_call_set_authentication_token_verified(LinphoneCall *call, bool_t verified){
	if (call->audiostream==NULL){
		ms_error("linphone_call_set_authentication_token_verified(): No audio stream");
	}
Ghislain MARY's avatar
Ghislain MARY committed
164
	if (call->audiostream->ms.zrtp_context==NULL){
Simon Morlat's avatar
Simon Morlat committed
165 166 167
		ms_error("linphone_call_set_authentication_token_verified(): No zrtp context.");
	}
	if (!call->auth_token_verified && verified){
Ghislain MARY's avatar
Ghislain MARY committed
168
		ortp_zrtp_sas_verified(call->audiostream->ms.zrtp_context);
Simon Morlat's avatar
Simon Morlat committed
169
	}else if (call->auth_token_verified && !verified){
Ghislain MARY's avatar
Ghislain MARY committed
170
		ortp_zrtp_sas_reset_verified(call->audiostream->ms.zrtp_context);
Simon Morlat's avatar
Simon Morlat committed
171 172 173 174
	}
	call->auth_token_verified=verified;
	propagate_encryption_changed(call);
}
175

176
static MSList *make_codec_list(LinphoneCore *lc, const MSList *codecs, int bandwidth_limit,int* max_sample_rate, int nb_codecs_limit){
177 178
	MSList *l=NULL;
	const MSList *it;
179
	int nb = 0;
180
	if (max_sample_rate) *max_sample_rate=0;
181 182
	for(it=codecs;it!=NULL;it=it->next){
		PayloadType *pt=(PayloadType*)it->data;
183 184 185 186 187 188 189
		if (pt->flags & PAYLOAD_TYPE_ENABLED){
			if (bandwidth_limit>0 && !linphone_core_is_payload_type_usable_for_bandwidth(lc,pt,bandwidth_limit)){
				ms_message("Codec %s/%i eliminated because of audio bandwidth constraint.",pt->mime_type,pt->clock_rate);
				continue;
			}
			if (linphone_core_check_payload_type_usability(lc,pt)){
				l=ms_list_append(l,payload_type_clone(pt));
190
				nb++;
191
				if (max_sample_rate && payload_type_get_rate(pt)>*max_sample_rate) *max_sample_rate=payload_type_get_rate(pt);
192
			}
193
		}
194
		if ((nb_codecs_limit > 0) && (nb >= nb_codecs_limit)) break;
195 196 197 198
	}
	return l;
}

199
static void update_media_description_from_stun(SalMediaDescription *md, const StunCandidate *ac, const StunCandidate *vc){
200 201 202 203 204 205 206 207 208 209 210 211
	int i;
	for (i = 0; i < md->n_active_streams; i++) {
		if ((md->streams[i].type == SalAudio) && (ac->port != 0)) {
			strcpy(md->streams[0].rtp_addr,ac->addr);
			md->streams[0].rtp_port=ac->port;
			if ((ac->addr[0]!='\0' && vc->addr[0]!='\0' && strcmp(ac->addr,vc->addr)==0) || md->n_active_streams==1){
				strcpy(md->addr,ac->addr);
			}
		}
		if ((md->streams[i].type == SalVideo) && (vc->port != 0)) {
			strcpy(md->streams[1].rtp_addr,vc->addr);
			md->streams[1].rtp_port=vc->port;
212 213 214 215
		}
	}
}

Simon Morlat's avatar
Simon Morlat committed
216
void linphone_call_make_local_media_description(LinphoneCore *lc, LinphoneCall *call){
217 218
	MSList *l;
	PayloadType *pt;
Simon Morlat's avatar
Simon Morlat committed
219
	SalMediaDescription *old_md=call->localdesc;
220
	int i;
221 222 223
	const char *me=linphone_core_get_identity(lc);
	LinphoneAddress *addr=linphone_address_new(me);
	const char *username=linphone_address_get_username (addr);
224
	SalMediaDescription *md=sal_media_description_new();
Simon Morlat's avatar
Simon Morlat committed
225
	bool_t keep_srtp_keys=lp_config_get_int(lc->config,"sip","keep_srtp_keys",0);
226

227
	linphone_core_adapt_to_network(lc,call->ping_time,&call->params);
228

Simon Morlat's avatar
Simon Morlat committed
229 230
	md->session_id=(old_md ? old_md->session_id : (rand() & 0xfff));
	md->session_ver=(old_md ? (old_md->session_ver+1) : (rand() & 0xfff));
231 232
	md->n_total_streams=(old_md ? old_md->n_total_streams : 1);
	md->n_active_streams=1;
233
	strncpy(md->addr,call->localip,sizeof(md->addr));
234
	strncpy(md->username,username,sizeof(md->username));
235 236 237 238
	
	if (call->params.down_bw)
		md->bandwidth=call->params.down_bw;
	else md->bandwidth=linphone_core_get_download_bandwidth(lc);
239

240
	/*set audio capabilities */
241
	strncpy(md->streams[0].rtp_addr,call->localip,sizeof(md->streams[0].rtp_addr));
242
	strncpy(md->streams[0].rtcp_addr,call->localip,sizeof(md->streams[0].rtcp_addr));
243
	md->streams[0].rtp_port=call->audio_port;
244
	md->streams[0].rtcp_port=call->audio_port+1;
245 246
	md->streams[0].proto=(call->params.media_encryption == LinphoneMediaEncryptionSRTP) ? 
		SalProtoRtpSavp : SalProtoRtpAvp;
247
	md->streams[0].type=SalAudio;
248 249 250
	if (call->params.down_ptime)
		md->streams[0].ptime=call->params.down_ptime;
	else
251
		md->streams[0].ptime=linphone_core_get_download_ptime(lc);
252
	l=make_codec_list(lc,lc->codecs_conf.audio_codecs,call->params.audio_bw,&md->streams[0].max_rate,-1);
Simon Morlat's avatar
Simon Morlat committed
253
	pt=payload_type_clone(rtp_profile_get_payload_from_mime(lc->default_profile,"telephone-event"));
254 255 256
	l=ms_list_append(l,pt);
	md->streams[0].payloads=l;

Simon Morlat's avatar
Simon Morlat committed
257
	if (call->params.has_video){
258
		md->n_active_streams++;
259
		md->streams[1].rtp_port=call->video_port;
260
		md->streams[1].rtcp_port=call->video_port+1;
261
		md->streams[1].proto=md->streams[0].proto;
262
		md->streams[1].type=SalVideo;
263
		l=make_codec_list(lc,lc->codecs_conf.video_codecs,0,NULL,-1);
264 265
		md->streams[1].payloads=l;
	}
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
	if (md->n_total_streams < md->n_active_streams)
		md->n_total_streams = md->n_active_streams;

	/* Deactivate inactive streams. */
	for (i = md->n_active_streams; i < md->n_total_streams; i++) {
		md->streams[i].rtp_port = 0;
		md->streams[i].rtcp_port = 0;
		md->streams[i].proto = SalProtoRtpAvp;
		md->streams[i].type = old_md->streams[i].type;
		md->streams[i].dir = SalStreamInactive;
		l = make_codec_list(lc, lc->codecs_conf.video_codecs, 0, NULL, 1);
		md->streams[i].payloads = l;
	}

	for(i=0; i<md->n_active_streams; i++) {
281
		if (md->streams[i].proto == SalProtoRtpSavp) {
Simon Morlat's avatar
Simon Morlat committed
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
			if (keep_srtp_keys && old_md && old_md->streams[i].proto==SalProtoRtpSavp){
				int j;
				for(j=0;j<SAL_CRYPTO_ALGO_MAX;++j){
					memcpy(&md->streams[i].crypto[j],&old_md->streams[i].crypto[j],sizeof(SalSrtpCryptoAlgo));
				}
			}else{
				md->streams[i].crypto[0].tag = 1;
				md->streams[i].crypto[0].algo = AES_128_SHA1_80;
				if (!generate_b64_crypto_key(30, md->streams[i].crypto[0].master_key))
					md->streams[i].crypto[0].algo = 0;
				md->streams[i].crypto[1].tag = 2;
				md->streams[i].crypto[1].algo = AES_128_SHA1_32;
				if (!generate_b64_crypto_key(30, md->streams[i].crypto[1].master_key))
					md->streams[i].crypto[1].algo = 0;
				md->streams[i].crypto[2].algo = 0;
			}
298
		}
299
	}
300
	update_media_description_from_stun(md,&call->ac,&call->vc);
301 302
	if (call->ice_session != NULL) {
		linphone_core_update_local_media_description_from_ice(md, call->ice_session);
303
		linphone_core_update_ice_state_in_call_stats(call);
304
	}
Yann Diorcet's avatar
Yann Diorcet committed
305 306 307
#ifdef BUILD_UPNP
	if(call->upnp_session != NULL) {
		linphone_core_update_local_media_description_from_upnp(md, call->upnp_session);
Yann Diorcet's avatar
Yann Diorcet committed
308
		linphone_core_update_upnp_state_in_call_stats(call);
Yann Diorcet's avatar
Yann Diorcet committed
309
	}
310
#endif  //BUILD_UPNP
311
	linphone_address_destroy(addr);
Simon Morlat's avatar
Simon Morlat committed
312 313
	call->localdesc=md;
	if (old_md) sal_media_description_unref(old_md);
314 315
}

316
static int find_port_offset(LinphoneCore *lc, SalStreamType type){
317 318
	int offset;
	MSList *elem;
319 320
	int tried_port;
	int existing_port;
321
	bool_t already_used=FALSE;
322
	for(offset=0;offset<100;offset+=2){
323 324 325 326 327 328 329 330 331
		switch (type) {
			default:
			case SalAudio:
				tried_port=linphone_core_get_audio_port (lc)+offset;
				break;
			case SalVideo:
				tried_port=linphone_core_get_video_port (lc)+offset;
				break;
		}
332 333 334
		already_used=FALSE;
		for(elem=lc->calls;elem!=NULL;elem=elem->next){
			LinphoneCall *call=(LinphoneCall*)elem->data;
335 336 337 338 339 340 341 342 343 344
			switch (type) {
				default:
				case SalAudio:
					existing_port = call->audio_port;
					break;
				case SalVideo:
					existing_port = call->video_port;
					break;
			}
			if (existing_port==tried_port) {
345 346 347 348 349 350 351 352 353 354 355 356 357
				already_used=TRUE;
				break;
			}
		}
		if (!already_used) break;
	}
	if (offset==100){
		ms_error("Could not find any free port !");
		return -1;
	}
	return offset;
}

358 359 360 361 362 363 364 365 366 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 397 398 399 400 401 402
static int select_random_port(LinphoneCore *lc, SalStreamType type) {
	MSList *elem;
	int nb_tries;
	int tried_port = 0;
	int existing_port = 0;
	int min_port = 0, max_port = 0;
	bool_t already_used = FALSE;

	switch (type) {
		default:
		case SalAudio:
			linphone_core_get_audio_port_range(lc, &min_port, &max_port);
			break;
		case SalVideo:
			linphone_core_get_video_port_range(lc, &min_port, &max_port);
			break;
	}
	tried_port = (rand() % (max_port - min_port) + min_port) & ~0x1;
	if (tried_port < min_port) tried_port = min_port + 2;
	for (nb_tries = 0; nb_tries < 100; nb_tries++) {
		for (elem = lc->calls; elem != NULL; elem = elem->next) {
			LinphoneCall *call = (LinphoneCall *)elem->data;
			switch (type) {
				default:
				case SalAudio:
					existing_port = call->audio_port;
					break;
				case SalVideo:
					existing_port = call->video_port;
					break;
			}
			if (existing_port == tried_port) {
				already_used = TRUE;
				break;
			}
		}
		if (!already_used) break;
	}
	if (nb_tries == 100) {
		ms_error("Could not find any free port!");
		return -1;
	}
	return tried_port;
}

403
static void linphone_call_init_common(LinphoneCall *call, LinphoneAddress *from, LinphoneAddress *to){
404
	int port_offset;
405
	int min_port, max_port;
406
	call->magic=linphone_call_magic;
407
	call->refcnt=1;
408
	call->state=LinphoneCallIdle;
409
	call->transfer_state = LinphoneCallIdle;
410 411 412
	call->start_time=time(NULL);
	call->media_start_time=0;
	call->log=linphone_call_log_new(call, from, to);
413
	call->owns_call_log=TRUE;
414
	linphone_core_notify_all_friends(call->core,LinphoneStatusOnThePhone);
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
	linphone_core_get_audio_port_range(call->core, &min_port, &max_port);
	if (min_port == max_port) {
		/* Used fixed RTP audio port. */
		port_offset=find_port_offset (call->core, SalAudio);
		if (port_offset==-1) return;
		call->audio_port=linphone_core_get_audio_port(call->core)+port_offset;
	} else {
		/* Select random RTP audio port in the specified range. */
		call->audio_port = select_random_port(call->core, SalAudio);
	}
	linphone_core_get_video_port_range(call->core, &min_port, &max_port);
	if (min_port == max_port) {
		/* Used fixed RTP video port. */
		port_offset=find_port_offset (call->core, SalVideo);
		if (port_offset==-1) return;
		call->video_port=linphone_core_get_video_port(call->core)+port_offset;
	} else {
		/* Select random RTP video port in the specified range. */
		call->video_port = select_random_port(call->core, SalVideo);
	}
Yann Diorcet's avatar
Yann Diorcet committed
435 436 437
	linphone_call_init_stats(&call->stats[LINPHONE_CALL_STATS_AUDIO], LINPHONE_CALL_STATS_AUDIO);
	linphone_call_init_stats(&call->stats[LINPHONE_CALL_STATS_VIDEO], LINPHONE_CALL_STATS_VIDEO);
}
438

Yann Diorcet's avatar
Yann Diorcet committed
439
void linphone_call_init_stats(LinphoneCallStats *stats, int type) {
Yann Diorcet's avatar
Yann Diorcet committed
440
	stats->type = type;
Yann Diorcet's avatar
Yann Diorcet committed
441 442
	stats->received_rtcp = NULL;
	stats->sent_rtcp = NULL;
443
	stats->ice_state = LinphoneIceStateNotActivated;
Yann Diorcet's avatar
Yann Diorcet committed
444 445 446 447 448
#ifdef BUILD_UPNP
	stats->upnp_state = LinphoneUpnpStateIdle;
#else
	stats->upnp_state = LinphoneUpnpStateNotAvailable;
#endif //BUILD_UPNP
449 450
}

451

452 453 454 455 456 457 458 459 460 461 462 463 464
static void discover_mtu(LinphoneCore *lc, const char *remote){
	int mtu;
	if (lc->net_conf.mtu==0	){
		/*attempt to discover mtu*/
		mtu=ms_discover_mtu(remote);
		if (mtu>0){
			ms_set_mtu(mtu);
			ms_message("Discovered mtu is %i, RTP payload max size is %i",
				mtu, ms_get_payload_max_size());
		}
	}
}

465
LinphoneCall * linphone_call_new_outgoing(struct _LinphoneCore *lc, LinphoneAddress *from, LinphoneAddress *to, const LinphoneCallParams *params)
466 467 468 469 470 471
{
	LinphoneCall *call=ms_new0(LinphoneCall,1);
	call->dir=LinphoneCallOutgoing;
	call->op=sal_op_new(lc->sal);
	sal_op_set_user_pointer(call->op,call);
	call->core=lc;
472
	linphone_core_get_local_ip(lc,NULL,call->localip);
473
	linphone_call_init_common(call,from,to);
Simon Morlat's avatar
Simon Morlat committed
474
	_linphone_call_params_copy(&call->params,params);
475
	sal_op_set_custom_header(call->op,call->params.custom_headers);
Simon Morlat's avatar
Simon Morlat committed
476
	call->params.custom_headers=NULL;
477
	
478
	if (linphone_core_get_firewall_policy(call->core) == LinphonePolicyUseIce) {
479 480
		call->ice_session = ice_session_new();
		ice_session_set_role(call->ice_session, IR_Controlling);
481
	}
482
	if (linphone_core_get_firewall_policy(call->core) == LinphonePolicyUseStun) {
483
		call->ping_time=linphone_core_run_stun_tests(call->core,call);
484
	}
Yann Diorcet's avatar
Yann Diorcet committed
485 486
#ifdef BUILD_UPNP
	if (linphone_core_get_firewall_policy(call->core) == LinphonePolicyUseUpnp) {
487 488 489
		if(!lc->rtp_conf.disable_upnp) {
			call->upnp_session = linphone_upnp_session_new(call);
		}
Yann Diorcet's avatar
Yann Diorcet committed
490 491
	}
#endif //BUILD_UPNP
492 493
	call->camera_active=params->has_video;
	
494
	discover_mtu(lc,linphone_address_get_domain (to));
495
	if (params->referer){
496
		sal_call_set_referer(call->op,params->referer->op);
497
		call->referer=linphone_call_ref(params->referer);
498
	}
499 500 501 502 503
	return call;
}

LinphoneCall * linphone_call_new_incoming(LinphoneCore *lc, LinphoneAddress *from, LinphoneAddress *to, SalOp *op){
	LinphoneCall *call=ms_new0(LinphoneCall,1);
504
	char *from_str;
505
	const SalMediaDescription *md;
506 507 508 509 510 511 512

	call->dir=LinphoneCallIncoming;
	sal_op_set_user_pointer(op,call);
	call->op=op;
	call->core=lc;

	if (lc->sip_conf.ping_with_options){
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
#ifdef BUILD_UPNP
		if (lc->upnp != NULL && linphone_core_get_firewall_policy(lc)==LinphonePolicyUseUpnp &&
			linphone_upnp_context_get_state(lc->upnp) == LinphoneUpnpStateOk) {
#else //BUILD_UPNP
		{
#endif //BUILD_UPNP
			/*the following sends an option request back to the caller so that
			 we get a chance to discover our nat'd address before answering.*/
			call->ping_op=sal_op_new(lc->sal);
			from_str=linphone_address_as_string_uri_only(from);
			sal_op_set_route(call->ping_op,sal_op_get_network_origin(op));
			sal_op_set_user_pointer(call->ping_op,call);
			sal_ping(call->ping_op,linphone_core_find_best_identity(lc,from,NULL),from_str);
			ms_free(from_str);
		}
528
	}
529

530
	linphone_address_clean(from);
531
	linphone_core_get_local_ip(lc,NULL,call->localip);
532
	linphone_call_init_common(call, from, to);
jehan's avatar
jehan committed
533
	call->log->call_id=ms_strdup(sal_op_get_call_id(op)); /*must be known at that time*/
534
	linphone_core_init_default_params(lc, &call->params);
535
	md=sal_call_get_remote_media_description(op);
536
	call->params.has_video &= !!lc->video_policy.automatically_accept;
537 538 539 540 541
	if (md) {
		// It is licit to receive an INVITE without SDP
		// In this case WE chose the media parameters according to policy.
		call->params.has_video &= linphone_core_media_description_contains_video_stream(md);
	}
542 543
	switch (linphone_core_get_firewall_policy(call->core)) {
		case LinphonePolicyUseIce:
544 545 546
			call->ice_session = ice_session_new();
			ice_session_set_role(call->ice_session, IR_Controlled);
			linphone_core_update_ice_from_remote_media_description(call, sal_call_get_remote_media_description(op));
547 548 549 550 551 552
			if (call->ice_session != NULL) {
				linphone_call_init_media_streams(call);
				linphone_call_start_media_streams_for_ice_gathering(call);
				if (linphone_core_gather_ice_candidates(call->core,call)<0) {
					/* Ice candidates gathering failed, proceed with the call anyway. */
					linphone_call_delete_ice_session(call);
553
					linphone_call_stop_media_streams_for_ice_gathering(call);
554
				}
555
			}
556
			break;
557
		case LinphonePolicyUseStun:
558
			call->ping_time=linphone_core_run_stun_tests(call->core,call);
559
			/* No break to also destroy ice session in this case. */
Yann Diorcet's avatar
Yann Diorcet committed
560 561 562
			break;
		case LinphonePolicyUseUpnp:
#ifdef BUILD_UPNP
563 564 565 566 567 568 569 570
			if(!lc->rtp_conf.disable_upnp) {
				call->upnp_session = linphone_upnp_session_new(call);
				if (call->upnp_session != NULL) {
					linphone_call_init_media_streams(call);
					if (linphone_core_update_upnp_from_remote_media_description(call, sal_call_get_remote_media_description(op))<0) {
						/* uPnP port mappings failed, proceed with the call anyway. */
						linphone_call_delete_upnp_session(call);
					}
571
				}
Yann Diorcet's avatar
Yann Diorcet committed
572 573 574
			}
#endif //BUILD_UPNP
			break;
575 576 577
		default:
			break;
	}
578 579
	call->camera_active=call->params.has_video;
	
580 581 582 583
	discover_mtu(lc,linphone_address_get_domain(from));
	return call;
}

Simon Morlat's avatar
Simon Morlat committed
584 585 586 587 588 589
/* this function is called internally to get rid of a call.
 It performs the following tasks:
 - remove the call from the internal list of calls
 - update the call logs accordingly
*/

590
static void linphone_call_set_terminated(LinphoneCall *call){
Simon Morlat's avatar
Simon Morlat committed
591
	LinphoneCore *lc=call->core;
592

Simon Morlat's avatar
Simon Morlat committed
593
	linphone_core_update_allocated_audio_bandwidth(lc);
594

595
	call->owns_call_log=FALSE;
596
	linphone_call_log_completed(call);
597 598


599 600 601
	if (call == lc->current_call){
		ms_message("Resetting the current call");
		lc->current_call=NULL;
602 603 604 605
	}

	if (linphone_core_del_call(lc,call) != 0){
		ms_error("Could not remove the call from the list !!!");
Simon Morlat's avatar
Simon Morlat committed
606
	}
607

608 609
	if (ms_list_size(lc->calls)==0)
		linphone_core_notify_all_friends(lc,lc->presence_mode);
610

611
	linphone_core_conference_check_uninit(lc);
612 613 614 615
	if (call->ringing_beep){
		linphone_core_stop_dtmf(lc);
		call->ringing_beep=FALSE;
	}
616 617 618 619
	if (call->referer){
		linphone_call_unref(call->referer);
		call->referer=NULL;
	}
620 621
}

622 623 624 625 626
void linphone_call_fix_call_parameters(LinphoneCall *call){
	call->params.has_video=call->current_params.has_video;
	call->params.media_encryption=call->current_params.media_encryption;
}

627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
const char *linphone_call_state_to_string(LinphoneCallState cs){
	switch (cs){
		case LinphoneCallIdle:
			return "LinphoneCallIdle";
		case LinphoneCallIncomingReceived:
			return "LinphoneCallIncomingReceived";
		case LinphoneCallOutgoingInit:
			return "LinphoneCallOutgoingInit";
		case LinphoneCallOutgoingProgress:
			return "LinphoneCallOutgoingProgress";
		case LinphoneCallOutgoingRinging:
			return "LinphoneCallOutgoingRinging";
		case LinphoneCallOutgoingEarlyMedia:
			return "LinphoneCallOutgoingEarlyMedia";
		case LinphoneCallConnected:
			return "LinphoneCallConnected";
		case LinphoneCallStreamsRunning:
			return "LinphoneCallStreamsRunning";
		case LinphoneCallPausing:
			return "LinphoneCallPausing";
		case LinphoneCallPaused:
			return "LinphoneCallPaused";
		case LinphoneCallResuming:
			return "LinphoneCallResuming";
		case LinphoneCallRefered:
			return "LinphoneCallRefered";
		case LinphoneCallError:
Simon Morlat's avatar
Simon Morlat committed
654
			return "LinphoneCallError";
655 656 657 658
		case LinphoneCallEnd:
			return "LinphoneCallEnd";
		case LinphoneCallPausedByRemote:
			return "LinphoneCallPausedByRemote";
659 660
		case LinphoneCallUpdatedByRemote:
			return "LinphoneCallUpdatedByRemote";
661 662
		case LinphoneCallIncomingEarlyMedia:
			return "LinphoneCallIncomingEarlyMedia";
663 664
		case LinphoneCallUpdating:
			return "LinphoneCallUpdating";
665 666
		case LinphoneCallReleased:
			return "LinphoneCallReleased";
667 668 669 670
	}
	return "undefined state";
}

671 672
void linphone_call_set_state(LinphoneCall *call, LinphoneCallState cstate, const char *message){
	LinphoneCore *lc=call->core;
673

674
	if (call->state!=cstate){
675 676 677
		if (call->state==LinphoneCallEnd || call->state==LinphoneCallError){
			if (cstate!=LinphoneCallReleased){
				ms_warning("Spurious call state change from %s to %s, ignored.",linphone_call_state_to_string(call->state),
678
				   linphone_call_state_to_string(cstate));
679 680 681
				return;
			}
		}
682 683
		ms_message("Call %p: moving from state %s to %s",call,linphone_call_state_to_string(call->state),
		           linphone_call_state_to_string(cstate));
684 685 686 687 688
		if (cstate!=LinphoneCallRefered){
			/*LinphoneCallRefered is rather an event, not a state.
			 Indeed it does not change the state of the call (still paused or running)*/
			call->state=cstate;
		}
689
		if (cstate==LinphoneCallEnd || cstate==LinphoneCallError){
Yann Diorcet's avatar
Yann Diorcet committed
690
			switch(call->reason){
691 692
				case LinphoneReasonDeclined:
					call->log->status=LinphoneCallDeclined;
jehan's avatar
jehan committed
693
					break;
694 695 696 697 698
				case LinphoneReasonNotAnswered:
					call->log->status=LinphoneCallMissed;
				break;
				default:
				break;
699 700
			}
			linphone_call_set_terminated (call);
701
		}
702 703
		if (cstate == LinphoneCallConnected) {
			call->log->status=LinphoneCallSuccess;
704
			call->media_start_time=time(NULL);
705
		}
706

707 708
		if (lc->vtable.call_state_changed)
			lc->vtable.call_state_changed(lc,call,cstate,message);
709 710 711 712 713 714 715
		if (cstate==LinphoneCallReleased){
			if (call->op!=NULL) {
				/* so that we cannot have anymore upcalls for SAL
				 concerning this call*/
				sal_op_release(call->op);
				call->op=NULL;
			}
716
			linphone_call_unref(call);
717
		}
718 719 720
	}
}

721 722
static void linphone_call_destroy(LinphoneCall *obj)
{
Yann Diorcet's avatar
Yann Diorcet committed
723 724 725
#ifdef BUILD_UPNP
	linphone_call_delete_upnp_session(obj);
#endif //BUILD_UPNP
726
	linphone_call_delete_ice_session(obj);
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
	if (obj->op!=NULL) {
		sal_op_release(obj->op);
		obj->op=NULL;
	}
	if (obj->resultdesc!=NULL) {
		sal_media_description_unref(obj->resultdesc);
		obj->resultdesc=NULL;
	}
	if (obj->localdesc!=NULL) {
		sal_media_description_unref(obj->localdesc);
		obj->localdesc=NULL;
	}
	if (obj->ping_op) {
		sal_op_release(obj->ping_op);
	}
742 743 744
	if (obj->refer_to){
		ms_free(obj->refer_to);
	}
745 746
	if (obj->owns_call_log)
		linphone_call_log_destroy(obj->log);
747 748 749
	if (obj->auth_token) {
		ms_free(obj->auth_token);
	}
750
	linphone_call_params_uninit(&obj->params);
751 752 753
	ms_free(obj);
}

Simon Morlat's avatar
Simon Morlat committed
754
/**
Simon Morlat's avatar
Simon Morlat committed
755
 * @addtogroup call_control
Simon Morlat's avatar
Simon Morlat committed
756 757 758 759 760 761 762 763 764 765
 * @{
**/

/**
 * Increments the call 's reference count.
 * An application that wishes to retain a pointer to call object
 * must use this function to unsure the pointer remains
 * valid. Once the application no more needs this pointer,
 * it must call linphone_call_unref().
**/
766
LinphoneCall * linphone_call_ref(LinphoneCall *obj){
767
	obj->refcnt++;
768
	return obj;
769 770
}

Simon Morlat's avatar
Simon Morlat committed
771 772 773 774
/**
 * Decrements the call object reference count.
 * See linphone_call_ref().
**/
775 776
void linphone_call_unref(LinphoneCall *obj){
	obj->refcnt--;
Simon Morlat's avatar
Simon Morlat committed
777
	if (obj->refcnt==0){
778
		linphone_call_destroy(obj);
Simon Morlat's avatar
Simon Morlat committed
779
	}
780 781
}

782 783 784
/**
 * Returns current parameters associated to the call.
**/
Simon Morlat's avatar
Simon Morlat committed
785 786 787
const LinphoneCallParams * linphone_call_get_current_params(LinphoneCall *call){
	if (call->params.record_file)
		call->current_params.record_file=call->params.record_file;
788
	return &call->current_params;
789 790
}

791
static bool_t is_video_active(const SalStreamDescription *sd){
792
	return sd->rtp_port!=0 && sd->dir!=SalStreamInactive;
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
}

/**
 * Returns call parameters proposed by remote.
 * 
 * This is useful when receiving an incoming call, to know whether the remote party
 * supports video, encryption or whatever.
**/
const LinphoneCallParams * linphone_call_get_remote_params(LinphoneCall *call){
	LinphoneCallParams *cp=&call->remote_params;
	memset(cp,0,sizeof(*cp));
	if (call->op){
		SalMediaDescription *md=sal_call_get_remote_media_description(call->op);
		if (md){
			SalStreamDescription *asd,*vsd,*secure_asd,*secure_vsd;

			asd=sal_media_description_find_stream(md,SalProtoRtpAvp,SalAudio);
			vsd=sal_media_description_find_stream(md,SalProtoRtpAvp,SalVideo);
			secure_asd=sal_media_description_find_stream(md,SalProtoRtpSavp,SalAudio);
			secure_vsd=sal_media_description_find_stream(md,SalProtoRtpSavp,SalVideo);
			if (secure_vsd){
				cp->has_video=is_video_active(secure_vsd);
				if (secure_asd || asd==NULL)
					cp->media_encryption=LinphoneMediaEncryptionSRTP;
			}else if (vsd){
				cp->has_video=is_video_active(vsd);
			}
820 821 822 823 824
			if (!cp->has_video){
				if (md->bandwidth>0 && md->bandwidth<=linphone_core_get_edge_bw(call->core)){
					cp->low_bandwidth=TRUE;
				}
			}
825
			cp->custom_headers=(SalCustomHeader*)sal_op_get_custom_header(call->op);
826 827 828 829 830 831
			return cp;
		}
	}
	return NULL;
}

Simon Morlat's avatar
Simon Morlat committed
832 833 834 835
/**
 * Returns the remote address associated to this call
 *
**/
836 837 838 839
const LinphoneAddress * linphone_call_get_remote_address(const LinphoneCall *call){
	return call->dir==LinphoneCallIncoming ? call->log->from : call->log->to;
}

Simon Morlat's avatar
Simon Morlat committed
840 841 842 843 844
/**
 * Returns the remote address associated to this call as a string.
 *
 * The result string must be freed by user using ms_free().
**/
845 846 847 848
char *linphone_call_get_remote_address_as_string(const LinphoneCall *call){
	return linphone_address_as_string(linphone_call_get_remote_address(call));
}

Simon Morlat's avatar
Simon Morlat committed
849 850 851
/**
 * Retrieves the call's current state.
**/
852 853 854 855
LinphoneCallState linphone_call_get_state(const LinphoneCall *call){
	return call->state;
}

856 857 858 859 860 861 862
/**
 * Returns the reason for a call termination (either error or normal termination)
**/
LinphoneReason linphone_call_get_reason(const LinphoneCall *call){
	return call->reason;
}

863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
/**
 * Get the user_pointer in the LinphoneCall
 *
 * @ingroup call_control
 *
 * return user_pointer an opaque user pointer that can be retrieved at any time
**/
void *linphone_call_get_user_pointer(LinphoneCall *call)
{
	return call->user_pointer;
}

/**
 * Set the user_pointer in the LinphoneCall
 *
 * @ingroup call_control
 *
 * the user_pointer is an opaque user pointer that can be retrieved at any time in the LinphoneCall
**/
void linphone_call_set_user_pointer(LinphoneCall *call, void *user_pointer)
{
	call->user_pointer = user_pointer;
}
Simon Morlat's avatar
Simon Morlat committed
886

887 888 889 890 891 892 893
/**
 * Returns the call log associated to this call.
**/
LinphoneCallLog *linphone_call_get_call_log(const LinphoneCall *call){
	return call->log;
}

Simon Morlat's avatar
Simon Morlat committed
894
/**
895
 * Returns the refer-to uri (if the call was transfered).
Simon Morlat's avatar
Simon Morlat committed
896 897 898 899 900
**/
const char *linphone_call_get_refer_to(const LinphoneCall *call){
	return call->refer_to;
}

901 902 903
/**
 * Returns direction of the call (incoming or outgoing).
**/
Simon Morlat's avatar
Simon Morlat committed
904 905 906
LinphoneCallDir linphone_call_get_dir(const LinphoneCall *call){
	return call->log->dir;
}
907

908 909 910 911 912 913 914 915 916 917
/**
 * Returns the far end's user agent description string, if available.
**/
const char *linphone_call_get_remote_user_agent(LinphoneCall *call){
	if (call->op){
		return sal_op_get_remote_ua (call->op);
	}
	return NULL;
}

918 919 920 921 922 923 924 925 926 927
/**
 * Returns the far end's sip contact as a string, if available.
**/
const char *linphone_call_get_remote_contact(LinphoneCall *call){
	if (call->op){
		return sal_op_get_remote_contact(call->op);
	}
	return NULL;
}

928 929 930 931 932
/**
 * Returns true if this calls has received a transfer that has not been
 * executed yet.
 * Pending transfers are executed when this call is being paused or closed,
 * locally or by remote endpoint.
933
 * If the call is already paused while receiving the transfer request, the
934 935 936 937 938 939
 * transfer immediately occurs.
**/
bool_t linphone_call_has_transfer_pending(const LinphoneCall *call){
	return call->refer_pending;
}

940 941 942 943 944 945 946 947
/**
 * Returns call's duration in seconds.
**/
int linphone_call_get_duration(const LinphoneCall *call){
	if (call->media_start_time==0) return 0;
	return time(NULL)-call->media_start_time;
}

948 949 950 951 952 953 954 955 956 957 958 959 960 961
/**
 * Returns the call object this call is replacing, if any.
 * Call replacement can occur during call transfers.
 * By default, the core automatically terminates the replaced call and accept the new one.
 * This function allows the application to know whether a new incoming call is a one that replaces another one.
**/
LinphoneCall *linphone_call_get_replaced_call(LinphoneCall *call){
	SalOp *op=sal_call_get_replaces(call->op);
	if (op){
		return (LinphoneCall*)sal_op_get_user_pointer(op);
	}
	return NULL;
}

962 963 964 965
/**
 * Indicate whether camera input should be sent to remote end.
**/
void linphone_call_enable_camera (LinphoneCall *call, bool_t enable){
Simon Morlat's avatar
Simon Morlat committed
966
#ifdef VIDEO_ENABLED
Ghislain MARY's avatar
Ghislain MARY committed
967
	if (call->videostream!=NULL && call->videostream->ms.ticker!=NULL){
968 969 970 971 972 973 974
		LinphoneCore *lc=call->core;
		MSWebCam *nowebcam=get_nowebcam_device();
		if (call->camera_active!=enable && lc->video_conf.device!=nowebcam){
			video_stream_change_camera(call->videostream,
			             enable ? lc->video_conf.device : nowebcam);
		}
	}
975
	call->camera_active=enable;
Simon Morlat's avatar
Simon Morlat committed
976
#endif
977 978
}

979 980 981 982 983 984 985 986 987 988 989 990