call-session.cpp 32.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*
 * call-session.cpp
 * Copyright (C) 2017  Belledonne Communications SARL
 *
 * 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 3 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, see <http://www.gnu.org/licenses/>.
 */

19
#include <bctoolbox/defs.h>
20

21
#include "c-wrapper/c-wrapper.h"
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

#include "address/address-p.h"
#include "conference/session/call-session-p.h"
#include "call/call-p.h"
#include "conference/params/call-session-params-p.h"

#include "conference/session/call-session.h"

#include "logger/logger.h"

#include "linphone/core.h"

#include "private.h"

using namespace std;
37 38 39 40 41

LINPHONE_BEGIN_NAMESPACE

// =============================================================================

42
CallSessionPrivate::CallSessionPrivate (const Conference &conference, const CallSessionParams *params, CallSessionListener *listener)
43 44
	: conference(conference), listener(listener) {
	if (params)
45 46
		this->params = new CallSessionParams(*params);
	currentParams = new CallSessionParams();
47
	core = conference.getCore();
48 49 50 51
	ei = linphone_error_info_new();
}

CallSessionPrivate::~CallSessionPrivate () {
52 53 54 55 56 57
	if (currentParams)
		delete currentParams;
	if (params)
		delete params;
	if (remoteParams)
		delete remoteParams;
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
	if (ei)
		linphone_error_info_unref(ei);
	if (log)
		linphone_call_log_unref(log);
	if (op)
		sal_op_release(op);
}

// -----------------------------------------------------------------------------

int CallSessionPrivate::computeDuration () const {
	if (log->connected_date_time == 0)
		return 0;
	return (int)(ms_time(nullptr) - log->connected_date_time);
}

/*
 * Initialize call parameters according to incoming call parameters. This is to avoid to ask later (during reINVITEs) for features that the remote
 * end apparently does not support. This features are: privacy, video...
 */
void CallSessionPrivate::initializeParamsAccordingToIncomingCallParams () {
	currentParams->setPrivacy((LinphonePrivacyMask)sal_op_get_privacy(op));
}

void CallSessionPrivate::setState(LinphoneCallState newState, const string &message) {
83
	L_Q();
84 85 86 87 88 89 90 91 92 93 94 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 147 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
	if (state != newState){
		prevState = state;

		/* Make sanity checks with call state changes. Any bad transition can result in unpredictable results
		   or irrecoverable errors in the application. */
		if ((state == LinphoneCallEnd) || (state == LinphoneCallError)) {
			if (newState != LinphoneCallReleased) {
				lFatal() << "Abnormal call resurection from " << linphone_call_state_to_string(state) <<
					" to " << linphone_call_state_to_string(newState) << " , aborting";
				return;
			}
		} else if ((newState == LinphoneCallReleased) && (prevState != LinphoneCallError) && (prevState != LinphoneCallEnd)) {
			lFatal() << "Attempt to move CallSession [" << q << "] to Released state while it was not previously in Error or End state, aborting";
			return;
		}
		lInfo() << "CallSession [" << q << "] moving from state " << linphone_call_state_to_string(state) << " to " << linphone_call_state_to_string(newState);

		if (newState != LinphoneCallRefered) {
			/* LinphoneCallRefered is rather an event, not a state.
			   Indeed it does not change the state of the call (still paused or running). */
			state = newState;
		}

		switch (newState) {
			case LinphoneCallOutgoingInit:
			case LinphoneCallIncomingReceived:
#ifdef __ANDROID__
				lInfo() << "CallSession [" << q << "] acquires both wifi and multicast lock";
				linphone_core_wifi_lock_acquire(core);
				linphone_core_multicast_lock_acquire(core); /* Does no affect battery more than regular rtp traffic */
#endif
				break;
			case LinphoneCallEnd:
			case LinphoneCallError:
				switch (linphone_error_info_get_reason(q->getErrorInfo())) {
					case LinphoneReasonDeclined:
						log->status = LinphoneCallDeclined;
						break;
					case LinphoneReasonNotAnswered:
						if (log->dir == LinphoneCallIncoming)
							log->status = LinphoneCallMissed;
						break;
					case LinphoneReasonNone:
						if (log->dir == LinphoneCallIncoming) {
							if (ei) {
								int code = linphone_error_info_get_protocol_code(ei);
								if ((code >= 200) && (code < 300))
									log->status = LinphoneCallAcceptedElsewhere;
							}
						}
						break;
					case LinphoneReasonDoNotDisturb:
						if (log->dir == LinphoneCallIncoming) {
							if (ei) {
								int code = linphone_error_info_get_protocol_code(ei);
								if ((code >= 600) && (code < 700))
									log->status = LinphoneCallDeclinedElsewhere;
							}
						}
						break;
					default:
						break;
				}
				setTerminated();
				break;
			case LinphoneCallConnected:
				log->status = LinphoneCallSuccess;
				log->connected_date_time = ms_time(nullptr);
				break;
			case LinphoneCallReleased:
#ifdef __ANDROID__
				lInfo() << "CallSession [" << q << "] releases wifi/multicast lock";
				linphone_core_wifi_lock_release(core);
				linphone_core_multicast_lock_release(core);
#endif
				break;
			default:
				break;
		}

		if (newState != LinphoneCallStreamsRunning) {
#if 0 // TODO
			if (call->dtmfs_timer!=NULL){
				/*cancelling DTMF sequence, if any*/
				linphone_call_cancel_dtmfs(call);
			}
#endif
		}
		if (message.empty()) {
			lError() << "You must fill a reason when changing call state (from " <<
				linphone_call_state_to_string(prevState) << " to " << linphone_call_state_to_string(state) << ")";
		}
		if (listener)
177
			listener->onCallSessionStateChanged(*q, state, message);
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
		if (newState == LinphoneCallReleased)
			setReleased(); /* Shall be performed after app notification */
	}
}

bool CallSessionPrivate::startPing () {
	if (core->sip_conf.ping_with_options) {
		/* Defer the start of the call after the OPTIONS ping for outgoing call or
		 * send an option request back to the caller so that we get a chance to discover our nat'd address
		 * before answering for incoming call */
		pingReplied = false;
		pingOp = sal_op_new(core->sal);
		if (direction == LinphoneCallIncoming) {
			const char *from = sal_op_get_from(pingOp);
			const char *to = sal_op_get_to(pingOp);
			linphone_configure_op(core, pingOp, log->from, nullptr, false);
			sal_op_set_route(pingOp, sal_op_get_network_origin(op));
			sal_ping(pingOp, from, to);
		} else if (direction == LinphoneCallOutgoing) {
			char *from = linphone_address_as_string(log->from);
			char *to = linphone_address_as_string(log->to);
			sal_ping(pingOp, from, to);
			ms_free(from);
			ms_free(to);
		}
		sal_op_set_user_pointer(pingOp, this);
		return true;
	}
	return false;
}

// -----------------------------------------------------------------------------

211 212 213 214 215
void CallSessionPrivate::abort (const string &errorMsg) {
	sal_call_terminate(op);
	setState(LinphoneCallError, errorMsg);
}

216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
void CallSessionPrivate::accepted () {
	/* Immediately notify the connected state, even if errors occur after */
	switch (state) {
		case LinphoneCallOutgoingProgress:
		case LinphoneCallOutgoingRinging:
		case LinphoneCallOutgoingEarlyMedia:
			/* Immediately notify the connected state */
			setState(LinphoneCallConnected, "Connected");
			break;
		default:
			break;
	}
	currentParams->setPrivacy((LinphonePrivacyMask)sal_op_get_privacy(op));
}

void CallSessionPrivate::ackBeingSent (LinphoneHeaders *headers) {
232
	L_Q();
233
	if (listener)
234
		listener->onAckBeingSent(*q, headers);
235 236 237
}

void CallSessionPrivate::ackReceived (LinphoneHeaders *headers) {
238
	L_Q();
239
	if (listener)
240
		listener->onAckReceived(*q, headers);
241 242 243
}

bool CallSessionPrivate::failure () {
244
	L_Q();
245 246 247 248 249 250 251 252 253 254 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 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
	const SalErrorInfo *ei = sal_op_get_error_info(op);
	switch (ei->reason) {
		case SalReasonRedirect:
			if ((state == LinphoneCallOutgoingInit) || (state == LinphoneCallOutgoingProgress)
				|| (state == LinphoneCallOutgoingRinging) /* Push notification case */ || (state == LinphoneCallOutgoingEarlyMedia)) {
				const SalAddress *redirectionTo = sal_op_get_remote_contact_address(op);
				if (redirectionTo) {
					char *url = sal_address_as_string(redirectionTo);
					lWarning() << "Redirecting CallSession [" << q << "] to " << url;
					if (log->to)
						linphone_address_unref(log->to);
					log->to = linphone_address_new(url);
					ms_free(url);
#if 0
					linphone_call_restart_invite(call);
#endif
					return true;
				}
			}
			break;
		default:
			break;
	}

	/* Some call errors are not fatal */
	switch (state) {
		case LinphoneCallUpdating:
		case LinphoneCallPausing:
		case LinphoneCallResuming:
			if (ei->reason != SalReasonNoMatch) {
				lInfo() << "Call error on state [" << linphone_call_state_to_string(state) << "], restoring previous state [" << linphone_call_state_to_string(prevState) << "]";
				setState(prevState, ei->full_string);
				return true;
			}
		default:
			break;
	}

	if ((state != LinphoneCallEnd) && (state != LinphoneCallError)) {
		if (ei->reason == SalReasonDeclined)
			setState(LinphoneCallEnd, "Call declined");
		else {
			if (linphone_call_state_is_early(state))
				setState(LinphoneCallError, ei->full_string);
			else
				setState(LinphoneCallEnd, ei->full_string);
		}
#if 0 // TODO: handle in Call class
		if (ei->reason != SalReasonNone)
			linphone_core_play_call_error_tone(core, linphone_reason_from_sal(ei->reason));
#endif
	}
#if 0
	LinphoneCall *referer=call->referer;
	if (referer){
		/*notify referer of the failure*/
		linphone_core_notify_refer_state(lc,referer,call);
		/*schedule automatic resume of the call. This must be done only after the notifications are completed due to dialog serialization of requests.*/
		linphone_core_queue_task(lc,(belle_sip_source_func_t)resume_call_after_failed_transfer,linphone_call_ref(referer),"Automatic call resuming after failed transfer");
	}
#endif
	return false;
}

void CallSessionPrivate::pingReply () {
310
	L_Q();
311 312 313
	if (state == LinphoneCallOutgoingInit) {
		pingReplied = true;
		if (isReadyForInvite())
314
			q->startInvite(nullptr, "");
315 316 317 318
	}
}

void CallSessionPrivate::remoteRinging () {
319
	L_Q();
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
	/* Set privacy */
	q->getCurrentParams()->setPrivacy((LinphonePrivacyMask)sal_op_get_privacy(op));
#if 0
	if (lc->ringstream == NULL) start_remote_ring(lc, call);
#endif
	lInfo() << "Remote ringing...";
	setState(LinphoneCallOutgoingRinging, "Remote ringing");
}

void CallSessionPrivate::terminated () {
	switch (state) {
		case LinphoneCallEnd:
		case LinphoneCallError:
			lWarning() << "terminated: already terminated, ignoring";
			return;
		case LinphoneCallIncomingReceived:
		case LinphoneCallIncomingEarlyMedia:
			if (!sal_op_get_reason_error_info(op)->protocol || strcmp(sal_op_get_reason_error_info(op)->protocol, "") == 0) {
				linphone_error_info_set(ei, nullptr, LinphoneReasonNotAnswered, 0, "Incoming call cancelled", nullptr);
				nonOpError = true;
			}
			break;
		default:
			break;
	}
#if 0
	if (call->refer_pending)
		linphone_core_start_refered_call(lc,call,NULL);
	//we stop the call only if we have this current call or if we are in call
	if ((bctbx_list_size(lc->calls)  == 1) || linphone_core_in_call(lc)) {
		linphone_core_stop_ringing(lc);
	}
#endif
	setState(LinphoneCallEnd, "Call ended");
}

void CallSessionPrivate::updated (bool isUpdate) {
357
	deferUpdate = !!lp_config_get_int(linphone_core_get_config(core), "sip", "defer_update_default", FALSE);
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 403
	SalErrorInfo sei;
	memset(&sei, 0, sizeof(sei));
	switch (state) {
		case LinphoneCallPausedByRemote:
			updatedByRemote();
			break;
		/* SIP UPDATE CASE */
		case LinphoneCallOutgoingRinging:
		case LinphoneCallOutgoingEarlyMedia:
		case LinphoneCallIncomingEarlyMedia:
			if (isUpdate) {
				setState(LinphoneCallEarlyUpdatedByRemote, "EarlyUpdatedByRemote");
				acceptUpdate(nullptr, prevState, linphone_call_state_to_string(prevState));
			}
			break;
		case LinphoneCallStreamsRunning:
		case LinphoneCallConnected:
		case LinphoneCallUpdatedByRemote: /* Can happen on UAC connectivity loss */
			updatedByRemote();
			break;
		case LinphoneCallPaused:
			/* We'll remain in pause state but accept the offer anyway according to default parameters */
			acceptUpdate(nullptr, state, linphone_call_state_to_string(state));
			break;
		case LinphoneCallUpdating:
		case LinphoneCallPausing:
		case LinphoneCallResuming:
			sal_error_info_set(&sei, SalReasonInternalError, "SIP", 0, nullptr, nullptr);
			sal_call_decline_with_error_info(op, &sei, nullptr);
			BCTBX_NO_BREAK; /* no break */
		case LinphoneCallIdle:
		case LinphoneCallOutgoingInit:
		case LinphoneCallEnd:
		case LinphoneCallIncomingReceived:
		case LinphoneCallOutgoingProgress:
		case LinphoneCallRefered:
		case LinphoneCallError:
		case LinphoneCallReleased:
		case LinphoneCallEarlyUpdatedByRemote:
		case LinphoneCallEarlyUpdating:
			lWarning() << "Receiving reINVITE or UPDATE while in state [" << linphone_call_state_to_string(state) << "], should not happen";
		break;
	}
}

void CallSessionPrivate::updatedByRemote () {
404
	L_Q();
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
	setState(LinphoneCallUpdatedByRemote,"Call updated by remote");
	if (deferUpdate) {
		if (state == LinphoneCallUpdatedByRemote)
			lInfo() << "CallSession [" << q << "]: UpdatedByRemoted was signaled but defered. LinphoneCore expects the application to call linphone_core_accept_call_update() later.";
	} else {
		if (state == LinphoneCallUpdatedByRemote)
			q->acceptUpdate(nullptr);
		else {
			/* Otherwise it means that the app responded by linphone_core_accept_call_update
			 * within the callback, so job is already done. */
		}
	}
}

void CallSessionPrivate::updating (bool isUpdate) {
	updated(isUpdate);
}

// -----------------------------------------------------------------------------

425
void CallSessionPrivate::accept (const CallSessionParams *params) {
426
	L_Q();
427 428 429
	/* Try to be best-effort in giving real local or routable contact address */
	setContactOp();
	if (params) {
430 431
		this->params = new CallSessionParams(*params);
		sal_op_set_sent_custom_header(op, this->params->getPrivate()->getCustomHeaders());
432 433 434 435
	}

	sal_call_accept(op);
	if (listener)
436
		listener->onSetCurrentSession(*q);
437 438 439
	setState(LinphoneCallConnected, "Connected");
}

440
LinphoneStatus CallSessionPrivate::acceptUpdate (const CallSessionParams *csp, LinphoneCallState nextState, const string &stateInfo) {
441 442 443 444
	return startAcceptUpdate(nextState, stateInfo);
}

LinphoneStatus CallSessionPrivate::checkForAcceptation () const {
445
	L_Q();
446 447 448 449 450 451 452 453
	switch (state) {
		case LinphoneCallIncomingReceived:
		case LinphoneCallIncomingEarlyMedia:
			break;
		default:
			lError() << "checkForAcceptation() CallSession [" << q << "] is in state [" << linphone_call_state_to_string(state) << "], operation not permitted";
			return -1;
	}
454 455
	if (listener)
		listener->onCheckForAcceptation(*q);
456 457 458 459 460 461 462 463 464 465 466 467 468 469

	/* Check if this call is supposed to replace an already running one */
	SalOp *replaced = sal_call_get_replaces(op);
	if (replaced) {
		CallSession *session = reinterpret_cast<CallSession *>(sal_op_get_user_pointer(replaced));
		if (session) {
			lInfo() << "CallSession " << q << " replaces CallSession " << session << ". This last one is going to be terminated automatically";
			session->terminate();
		}
	}
	return 0;
}

void CallSessionPrivate::handleIncomingReceivedStateInIncomingNotification () {
470
	L_Q();
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
	/* Try to be best-effort in giving real local or routable contact address for 100Rel case */
	setContactOp();
	sal_call_notify_ringing(op, false);
	if (sal_call_get_replaces(op) && lp_config_get_int(linphone_core_get_config(core), "sip", "auto_answer_replacing_calls", 1))
		q->accept();
}

bool CallSessionPrivate::isReadyForInvite () const {
	bool pingReady = false;
	if (pingOp) {
		if (pingReplied)
			pingReady = true;
	} else
		pingReady = true;
	return pingReady;
}

bool CallSessionPrivate::isUpdateAllowed (LinphoneCallState &nextState) const {
	switch (state) {
		case LinphoneCallIncomingReceived:
		case LinphoneCallIncomingEarlyMedia:
		case LinphoneCallOutgoingRinging:
		case LinphoneCallOutgoingEarlyMedia:
			nextState = LinphoneCallEarlyUpdating;
			break;
		case LinphoneCallStreamsRunning:
		case LinphoneCallPausedByRemote:
		case LinphoneCallUpdatedByRemote:
			nextState = LinphoneCallUpdating;
			break;
		case LinphoneCallPaused:
			nextState = LinphoneCallPausing;
			break;
		case LinphoneCallOutgoingProgress:
		case LinphoneCallPausing:
		case LinphoneCallResuming:
		case LinphoneCallUpdating:
			nextState = state;
			break;
		default:
			lError() << "Update is not allowed in [" << linphone_call_state_to_string(state) << "] state";
			return false;
	}
	return true;
}

/*
 * Called internally when reaching the Released state, to perform cleanups to break circular references.
**/
void CallSessionPrivate::setReleased () {
521
	L_Q();
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
	if (op) {
		/* Transfer the last error so that it can be obtained even in Released state */
		if (!nonOpError)
			linphone_error_info_from_sal_op(ei, op);
		/* So that we cannot have anymore upcalls for SAL concerning this call */
		sal_op_release(op);
		op = nullptr;
	}
#if 0
	/* It is necessary to reset pointers to other call to prevent circular references that would result in memory never freed */
	if (call->referer){
		linphone_call_unref(call->referer);
		call->referer=NULL;
	}
	if (call->transfer_target){
		linphone_call_unref(call->transfer_target);
		call->transfer_target=NULL;
	}
	if (call->chat_room){
		linphone_chat_room_unref(call->chat_room);
		call->chat_room = NULL;
	}
#endif
	if (listener)
546
		listener->onCallSessionSetReleased(*q);
547 548 549 550 551 552 553 554
}

/* This method is called internally to get rid of a call that was notified to the application,
 * because it reached the end or error state. It performs the following tasks:
 * - remove the call from the internal list of calls
 * - update the call logs accordingly
 */
void CallSessionPrivate::setTerminated() {
555
	L_Q();
556 557
	completeLog();
	if (listener)
558
		listener->onCallSessionSetTerminated(*q);
559 560
}

Ronan's avatar
Ronan committed
561
LinphoneStatus CallSessionPrivate::startAcceptUpdate (LinphoneCallState nextState, const string &stateInfo) {
562 563 564 565 566 567
	sal_call_accept(op);
	setState(nextState, stateInfo);
	return 0;
}

LinphoneStatus CallSessionPrivate::startUpdate () {
568
	L_Q();
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
	string subject;
	if (q->getParams()->getPrivate()->getInConference())
		subject = "Conference";
	else if (q->getParams()->getPrivate()->getInternalCallUpdate())
		subject = "ICE processing concluded";
	else if (q->getParams()->getPrivate()->getNoUserConsent())
		subject = "Refreshing";
	else
		subject = "Media change";
	if (destProxy && destProxy->op) {
		/* Give a chance to update the contact address if connectivity has changed */
		sal_op_set_contact_address(op, sal_op_get_contact_address(destProxy->op));
	} else
		sal_op_set_contact_address(op, nullptr);
	return sal_call_update(op, subject.c_str(), q->getParams()->getPrivate()->getNoUserConsent());
}

void CallSessionPrivate::terminate () {
	if ((state == LinphoneCallIncomingReceived) && (linphone_error_info_get_reason(ei) != LinphoneReasonNotAnswered)) {
		linphone_error_info_set_reason(ei, LinphoneReasonDeclined);
		nonOpError = true;
	}
	setState(LinphoneCallEnd, "Call terminated");
}

594
void CallSessionPrivate::updateCurrentParams () const {}
595 596 597 598 599 600 601

// -----------------------------------------------------------------------------

void CallSessionPrivate::setContactOp () {
	SalAddress *salAddress = nullptr;
	LinphoneAddress *contact = getFixedContact();
	if (contact) {
602
		salAddress = const_cast<SalAddress *>(L_GET_PRIVATE_FROM_C_OBJECT(contact)->getInternalAddress());
603
		sal_op_set_contact_address(op, salAddress);
Ghislain MARY's avatar
Ghislain MARY committed
604
		linphone_address_unref(contact);
605 606 607 608 609 610 611 612
	}
}

// -----------------------------------------------------------------------------

void CallSessionPrivate::completeLog () {
	log->duration = computeDuration(); /* Store duration since connected */
	log->error_info = linphone_error_info_ref(ei);
613
	if (log->status == LinphoneCallMissed)
614 615 616 617 618
		core->missed_calls++;
	linphone_core_report_call_log(core, log);
}

void CallSessionPrivate::createOpTo (const LinphoneAddress *to) {
619
	L_Q();
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
	if (op)
		sal_op_release(op);
	op = sal_op_new(core->sal);
	sal_op_set_user_pointer(op, q);
#if 0
	if (linphone_call_params_get_referer(call->params))
		sal_call_set_referer(call->op,linphone_call_params_get_referer(call->params)->op);
#endif
	linphone_configure_op(core, op, to, q->getParams()->getPrivate()->getCustomHeaders(), false);
	if (q->getParams()->getPrivacy() != LinphonePrivacyDefault)
		sal_op_set_privacy(op, (SalPrivacyMask)q->getParams()->getPrivacy());
	/* else privacy might be set by proxy */
}

// -----------------------------------------------------------------------------

LinphoneAddress * CallSessionPrivate::getFixedContact () const {
	LinphoneAddress *result = nullptr;
	if (op && sal_op_get_contact_address(op)) {
		/* If already choosed, don't change it */
		return nullptr;
	} else if (pingOp && sal_op_get_contact_address(pingOp)) {
		/* If the ping OPTIONS request succeeded use the contact guessed from the received, rport */
		lInfo() << "Contact has been fixed using OPTIONS";
		char *addr = sal_address_as_string(sal_op_get_contact_address(pingOp));
		result = linphone_address_new(addr);
		ms_free(addr);
647
	} else if (destProxy && destProxy->op && _linphone_proxy_config_get_contact_without_params(destProxy)) {
648 649
		/* If using a proxy, use the contact address as guessed with the REGISTERs */
		lInfo() << "Contact has been fixed using proxy";
650
		result = linphone_address_clone(_linphone_proxy_config_get_contact_without_params(destProxy));
651 652 653 654 655 656 657 658 659 660 661 662 663 664
	} else {
		result = linphone_core_get_primary_contact_parsed(core);
		if (result) {
			/* Otherwise use supplied localip */
			linphone_address_set_domain(result, nullptr /* localip */);
			linphone_address_set_port(result, -1 /* linphone_core_get_sip_port(core) */);
			lInfo() << "Contact has not been fixed, stack will do";
		}
	}
	return result;
}

// =============================================================================

665
CallSession::CallSession (const Conference &conference, const CallSessionParams *params, CallSessionListener *listener)
666 667 668 669
	: Object(*new CallSessionPrivate(conference, params, listener)) {
	lInfo() << "New CallSession [" << this << "] initialized (LinphoneCore version: " << linphone_core_get_version() << ")";
}

670 671
CallSession::CallSession (CallSessionPrivate &p) : Object(p) {}

672 673
// -----------------------------------------------------------------------------

674
LinphoneStatus CallSession::accept (const CallSessionParams *csp) {
675
	L_D();
676 677 678 679 680 681
	LinphoneStatus result = d->checkForAcceptation();
	if (result < 0) return result;
	d->accept(csp);
	return 0;
}

682
LinphoneStatus CallSession::acceptUpdate (const CallSessionParams *csp) {
683
	L_D();
684 685 686 687 688 689 690 691
	if (d->state != LinphoneCallUpdatedByRemote) {
		lError() << "CallSession::acceptUpdate(): invalid state " << linphone_call_state_to_string(d->state) << " to call this method";
		return -1;
	}
	return d->acceptUpdate(csp, d->prevState, linphone_call_state_to_string(d->prevState));
}

void CallSession::configure (LinphoneCallDir direction, LinphoneProxyConfig *cfg, SalOp *op, const Address &from, const Address &to) {
692
	L_D();
693 694 695 696 697 698 699 700 701 702 703 704 705 706
	d->direction = direction;
	d->destProxy = cfg;
	LinphoneAddress *fromAddr = linphone_address_new(from.asString().c_str());
	LinphoneAddress *toAddr = linphone_address_new(to.asString().c_str());
	if (!d->destProxy) {
		/* Try to define the destination proxy if it has not already been done to have a correct contact field in the SIP messages */
		d->destProxy = linphone_core_lookup_known_proxy(d->core, toAddr);
	}
	d->log = linphone_call_log_new(direction, fromAddr, toAddr);

	if (op) {
		/* We already have an op for incoming calls */
		d->op = op;
		sal_op_set_user_pointer(d->op, this);
Ronan's avatar
Ronan committed
707
		sal_op_cnx_ip_to_0000_if_sendonly_enable(op, !!lp_config_get_default_int(linphone_core_get_config(d->core),
708 709 710 711 712 713 714
			"sip", "cnx_ip_to_0000_if_sendonly_enabled", 0));
		d->log->call_id = ms_strdup(sal_op_get_call_id(op)); /* Must be known at that time */
	}

	if (direction == LinphoneCallOutgoing) {
		d->startPing();
	} else if (direction == LinphoneCallIncoming) {
715
		d->params = new CallSessionParams();
716 717 718 719 720 721 722 723 724 725 726 727 728
		d->params->initDefault(d->core);
	}
}

LinphoneStatus CallSession::decline (LinphoneReason reason) {
	LinphoneErrorInfo *ei = linphone_error_info_new();
	linphone_error_info_set(ei, "SIP", reason, linphone_reason_to_error_code(reason), nullptr, nullptr);
	LinphoneStatus status = decline(ei);
	linphone_error_info_unref(ei);
	return status;
}

LinphoneStatus CallSession::decline (const LinphoneErrorInfo *ei) {
729
	L_D();
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
	SalErrorInfo sei;
	SalErrorInfo sub_sei;
	memset(&sei, 0, sizeof(sei));
	memset(&sub_sei, 0, sizeof(sub_sei));
	sei.sub_sei = &sub_sei;
	if ((d->state != LinphoneCallIncomingReceived) && (d->state != LinphoneCallIncomingEarlyMedia)) {
		lError() << "Cannot decline a CallSession that is in state " << linphone_call_state_to_string(d->state);
		return -1;
	}
	if (ei) {
		linphone_error_info_to_sal(ei, &sei);
		sal_call_decline_with_error_info(d->op, &sei , nullptr);
	} else
		sal_call_decline(d->op, SalReasonDeclined, nullptr);
	sal_error_info_reset(&sei);
	sal_error_info_reset(&sub_sei);
	d->terminate();
	return 0;
}

void CallSession::initiateIncoming () {}

bool CallSession::initiateOutgoing () {
753
	L_D();
754 755 756 757 758 759 760 761 762 763 764 765
	bool defer = false;
	d->setState(LinphoneCallOutgoingInit, "Starting outgoing call");
	d->log->start_date_time = ms_time(nullptr);
	if (!d->destProxy)
		defer = d->startPing();
 	if (d->direction == LinphoneCallOutgoing) {
		d->createOpTo(d->log->to);
	}
	return defer;
}

void CallSession::iterate (time_t currentRealTime, bool oneSecondElapsed) {
766
	L_D();
767 768 769
	int elapsed = (int)(currentRealTime - d->log->start_date_time);
	if ((d->state == LinphoneCallOutgoingInit) && (elapsed >= d->core->sip_conf.delayed_timeout)) {
		/* Start the call even if the OPTIONS reply did not arrive */
770
		startInvite(nullptr, "");
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
	}
	if ((d->state == LinphoneCallIncomingReceived) || (d->state == LinphoneCallIncomingEarlyMedia)) {
		if (oneSecondElapsed)
			lInfo() << "Incoming call ringing for " << elapsed << " seconds";
		if (elapsed > d->core->sip_conf.inc_timeout) {
			lInfo() << "Incoming call timeout (" << d->core->sip_conf.inc_timeout << ")";
#if 0
			LinphoneReason declineReason = (core->current_call != call) ? LinphoneReasonBusy : LinphoneReasonDeclined;
#endif
			d->log->status = LinphoneCallMissed;
#if 0
			call->non_op_error = TRUE;
			linphone_error_info_set(call->ei, NULL, decline_reason, linphone_reason_to_error_code(decline_reason), "Not answered", NULL);
			linphone_call_decline(call, decline_reason);
#endif
		}
	}
	if ((d->core->sip_conf.in_call_timeout > 0) && (d->log->connected_date_time != 0)
		&& ((currentRealTime - d->log->connected_date_time) > d->core->sip_conf.in_call_timeout)) {
		lInfo() << "In call timeout (" << d->core->sip_conf.in_call_timeout << ")";
		terminate();
	}
}

void CallSession::startIncomingNotification () {
796
	L_D();
797
	if (d->listener)
798
		d->listener->onCallSessionAccepted(*this);
799
	/* Prevent the CallSession from being destroyed while we are notifying, if the user declines within the state callback */
800
	shared_ptr<CallSession> ref = static_pointer_cast<CallSession>(shared_from_this());
801 802 803 804
#if 0
	call->bg_task_id=sal_begin_background_task("liblinphone call notification", NULL, NULL);
#endif
	if (d->deferIncomingNotification) {
805
		lInfo() << "Defer incoming notification";
806 807 808 809
		return;
	}

	if (d->listener)
810
		d->listener->onIncomingCallSessionStarted(*this);
811

812
	d->setState(LinphoneCallIncomingReceived, "Incoming CallSession");
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827

	/* From now on, the application is aware of the call and supposed to take background task or already submitted notification to the user.
	 * We can then drop our background task. */
#if 0
	if (call->bg_task_id!=0) {
		sal_end_background_task(call->bg_task_id);
		call->bg_task_id=0;
	}
#endif

	if (d->state == LinphoneCallIncomingReceived) {
		d->handleIncomingReceivedStateInIncomingNotification();
	}
}

828
int CallSession::startInvite (const Address *destination, const string &subject) {
829
	L_D();
830 831 832 833 834 835 836 837 838 839 840 841 842
	/* Try to be best-effort in giving real local or routable contact address */
	d->setContactOp();
	string destinationStr;
	char *realUrl = nullptr;
	if (destination)
		destinationStr = destination->asString();
	else {
		realUrl = linphone_address_as_string(d->log->to);
		destinationStr = realUrl;
		ms_free(realUrl);
	}
	char *from = linphone_address_as_string(d->log->from);
	/* Take a ref because sal_call() may destroy the CallSession if no SIP transport is available */
843
	shared_ptr<CallSession> ref = static_pointer_cast<CallSession>(shared_from_this());
844
	int result = sal_call(d->op, from, destinationStr.c_str(), subject.empty() ? nullptr : subject.c_str());
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
	ms_free(from);
	if (result < 0) {
		if ((d->state != LinphoneCallError) && (d->state != LinphoneCallReleased)) {
			/* sal_call() may invoke call_failure() and call_released() SAL callbacks synchronously,
			   in which case there is no need to perform a state change here. */
			d->setState(LinphoneCallError, "Call failed");
		}
	} else {
		d->log->call_id = ms_strdup(sal_op_get_call_id(d->op)); /* Must be known at that time */
		d->setState(LinphoneCallOutgoingProgress, "Outgoing call in progress");
	}
	return result;
}

LinphoneStatus CallSession::terminate (const LinphoneErrorInfo *ei) {
860
	L_D();
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
	lInfo() << "Terminate CallSession [" << this << "] which is currently in state [" << linphone_call_state_to_string(d->state) << "]";
	SalErrorInfo sei;
	memset(&sei, 0, sizeof(sei));
	switch (d->state) {
		case LinphoneCallReleased:
		case LinphoneCallEnd:
		case LinphoneCallError:
			lWarning() << "No need to terminate CallSession [" << this << "] in state [" << linphone_call_state_to_string(d->state) << "]";
			return -1;
		case LinphoneCallIncomingReceived:
		case LinphoneCallIncomingEarlyMedia:
			return decline(ei);
		case LinphoneCallOutgoingInit:
			/* In state OutgoingInit, op has to be destroyed */
			sal_op_release(d->op);
			d->op = nullptr;
			break;
		default:
			if (ei) {
				linphone_error_info_to_sal(ei, &sei);
				sal_call_terminate_with_error(d->op, &sei);
				sal_error_info_reset(&sei);
			} else
				sal_call_terminate(d->op);
			break;
	}

	d->terminate();
	return 0;
}

892
LinphoneStatus CallSession::update (const CallSessionParams *csp) {
893
	L_D();
894 895 896 897
	LinphoneCallState nextState;
	LinphoneCallState initialState = d->state;
	if (!d->isUpdateAllowed(nextState))
		return -1;
898
	if (d->currentParams == csp)
899 900 901 902 903 904 905 906 907 908 909 910
		lWarning() << "CallSession::update() is given the current params, this is probably not what you intend to do!";
	LinphoneStatus result = d->startUpdate();
	if (result && (d->state != initialState)) {
		/* Restore initial state */
		d->setState(initialState, "Restore initial state");
	}
	return result;
}

// -----------------------------------------------------------------------------

LinphoneCallDir CallSession::getDirection () const {
911
	L_D();
912 913 914 915
	return d->direction;
}

int CallSession::getDuration () const {
916
	L_D();
917 918 919 920 921 922 923 924 925 926 927
	switch (d->state) {
		case LinphoneCallEnd:
		case LinphoneCallError:
		case LinphoneCallReleased:
			return d->log->duration;
		default:
			return d->computeDuration();
	}
}

const LinphoneErrorInfo * CallSession::getErrorInfo () const {
928
	L_D();
929 930 931 932 933 934
	if (!d->nonOpError)
		linphone_error_info_from_sal_op(d->ei, d->op);
	return d->ei;
}

LinphoneCallLog * CallSession::getLog () const {
935
	L_D();
936 937 938 939 940 941 942 943
	return d->log;
}

LinphoneReason CallSession::getReason () const {
	return linphone_error_info_get_reason(getErrorInfo());
}

const Address& CallSession::getRemoteAddress () const {
944
	L_D();
945
	return *L_GET_CPP_PTR_FROM_C_OBJECT((d->direction == LinphoneCallIncoming)
946
		? linphone_call_log_get_from(d->log) : linphone_call_log_get_to(d->log));
947 948 949 950 951 952 953
}

string CallSession::getRemoteAddressAsString () const {
	return getRemoteAddress().asString();
}

string CallSession::getRemoteContact () const {
954
	L_D();
955 956 957 958 959 960 961
	if (d->op) {
		/* sal_op_get_remote_contact preserves header params */
		return sal_op_get_remote_contact(d->op);
	}
	return string();
}

962
const CallSessionParams * CallSession::getRemoteParams () {
963
	L_D();
964 965 966 967 968
	if (d->op){
		const SalCustomHeader *ch = sal_op_get_recv_custom_header(d->op);
		if (ch) {
			/* Instanciate a remote_params only if a SIP message was received before (custom headers indicates this) */
			if (!d->remoteParams)
969
				d->remoteParams = new CallSessionParams();
970 971 972 973 974 975 976 977
			d->remoteParams->getPrivate()->setCustomHeaders(ch);
		}
		return d->remoteParams;
	}
	return nullptr;
}

LinphoneCallState CallSession::getState () const {
978
	L_D();
979 980 981 982 983 984
	return d->state;
}

// -----------------------------------------------------------------------------

string CallSession::getRemoteUserAgent () const {
985
	L_D();
986 987 988 989 990
	if (d->op)
		return sal_op_get_remote_ua(d->op);
	return string();
}

991
CallSessionParams * CallSession::getCurrentParams () const {
992
	L_D();
993 994 995 996 997 998
	d->updateCurrentParams();
	return d->currentParams;
}

// -----------------------------------------------------------------------------

999
const CallSessionParams * CallSession::getParams () const {
1000
	L_D();
1001 1002 1003
	return d->params;
}

1004
LINPHONE_END_NAMESPACE