call-session.cpp 44.4 KB
Newer Older
1 2
/*
 * call-session.cpp
Ghislain MARY's avatar
Ghislain MARY committed
3
 * Copyright (C) 2010-2017 Belledonne Communications SARL
4
 *
Ghislain MARY's avatar
Ghislain MARY committed
5 6 7 8
 * 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.
9 10 11 12 13 14 15
 *
 * 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
Ghislain MARY's avatar
Ghislain MARY committed
16 17
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 19
 */

20
#include <bctoolbox/defs.h>
21

22
#include "c-wrapper/c-wrapper.h"
23 24 25 26

#include "address/address-p.h"
#include "call/call-p.h"
#include "conference/params/call-session-params-p.h"
27
#include "conference/session/call-session-p.h"
28
#include "conference/session/call-session.h"
29
#include "core/core-p.h"
30 31 32 33 34 35 36 37

#include "logger/logger.h"

#include "linphone/core.h"

#include "private.h"

using namespace std;
38 39 40 41 42

LINPHONE_BEGIN_NAMESPACE

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

43 44 45 46 47 48 49 50 51 52 53
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 () {
54
	currentParams->setPrivacy((LinphonePrivacyMask)op->get_privacy());
55 56
}

57 58 59 60 61 62
void CallSessionPrivate::notifyReferState () {
	SalCallOp *refererOp = referer->getPrivate()->getOp();
	if (refererOp)
		refererOp->notify_refer_state(op);
}

63
void CallSessionPrivate::setState (CallSession::State newState, const string &message) {
64
	L_Q();
65 66 67 68 69
	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. */
70 71 72 73
		if ((state == CallSession::State::End) || (state == CallSession::State::Error)) {
			if (newState != CallSession::State::Released) {
				lFatal() << "Abnormal call resurection from " << Utils::toString(state) <<
					" to " << Utils::toString(newState) << " , aborting";
74 75
				return;
			}
76
		} else if ((newState == CallSession::State::Released) && (prevState != CallSession::State::Error) && (prevState != CallSession::State::End)) {
77 78 79
			lFatal() << "Attempt to move CallSession [" << q << "] to Released state while it was not previously in Error or End state, aborting";
			return;
		}
80
		lInfo() << "CallSession [" << q << "] moving from state " << Utils::toString(state) << " to " << Utils::toString(newState);
81

82 83
		if (newState != CallSession::State::Referred) {
			/* CallSession::State::Referred is rather an event, not a state.
84 85 86 87 88
			   Indeed it does not change the state of the call (still paused or running). */
			state = newState;
		}

		switch (newState) {
89 90
			case CallSession::State::OutgoingInit:
			case CallSession::State::IncomingReceived:
91 92 93
				getPlatformHelpers(q->getCore()->getCCore())->acquireWifiLock();
				getPlatformHelpers(q->getCore()->getCCore())->acquireMcastLock();
				getPlatformHelpers(q->getCore()->getCCore())->acquireCpuLock();
94
				break;
95 96
			case CallSession::State::End:
			case CallSession::State::Error:
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
				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;
128
			case CallSession::State::Connected:
129 130 131
				log->status = LinphoneCallSuccess;
				log->connected_date_time = ms_time(nullptr);
				break;
132
			case CallSession::State::Released:
133 134 135
				getPlatformHelpers(q->getCore()->getCCore())->acquireWifiLock();
				getPlatformHelpers(q->getCore()->getCCore())->acquireMcastLock();
				getPlatformHelpers(q->getCore()->getCCore())->acquireCpuLock();
136 137 138 139 140 141 142
				break;
			default:
				break;
		}

		if (message.empty()) {
			lError() << "You must fill a reason when changing call state (from " <<
143
				Utils::toString(prevState) << " to " << Utils::toString(state) << ")";
144 145
		}
		if (listener)
146
			listener->onCallSessionStateChanged(q->getSharedFromThis(), newState, message);
147
		if (newState == CallSession::State::Released)
148 149 150 151
			setReleased(); /* Shall be performed after app notification */
	}
}

152
void CallSessionPrivate::setTransferState (CallSession::State newState) {
153 154 155 156
	L_Q();
	if (newState == transferState)
		return;
	lInfo() << "Transfer state for CallSession [" << q << "] changed from ["
157
		<< Utils::toString(transferState) << "] to [" << Utils::toString(newState) << "]";
158 159 160 161 162
	transferState = newState;
	if (listener)
		listener->onCallSessionTransferStateChanged(q->getSharedFromThis(), newState);
}

Ghislain MARY's avatar
Ghislain MARY committed
163 164 165 166 167
void CallSessionPrivate::startIncomingNotification () {
	L_Q();
	if (listener)
		listener->onIncomingCallSessionStarted(q->getSharedFromThis());

168
	setState(CallSession::State::IncomingReceived, "Incoming CallSession");
Ghislain MARY's avatar
Ghislain MARY committed
169

170 171 172 173
	// 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 (listener)
		listener->onBackgroundTaskToBeStopped(q->getSharedFromThis());
Ghislain MARY's avatar
Ghislain MARY committed
174

175
	if (state == CallSession::State::IncomingReceived) {
Ghislain MARY's avatar
Ghislain MARY committed
176 177 178 179
		handleIncomingReceivedStateInIncomingNotification();
	}
}

180
bool CallSessionPrivate::startPing () {
181 182
	L_Q();
	if (q->getCore()->getCCore()->sip_conf.ping_with_options) {
183 184 185 186
		/* 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;
187
		pingOp = new SalOp(q->getCore()->getCCore()->sal);
188
		if (direction == LinphoneCallIncoming) {
189 190
			const char *from = pingOp->get_from();
			const char *to = pingOp->get_to();
191
			linphone_configure_op(q->getCore()->getCCore(), pingOp, log->from, nullptr, false);
192 193
			pingOp->set_route(op->get_network_origin());
			pingOp->ping(from, to);
194 195 196
		} else if (direction == LinphoneCallOutgoing) {
			char *from = linphone_address_as_string(log->from);
			char *to = linphone_address_as_string(log->to);
197
			pingOp->ping(from, to);
198 199 200
			ms_free(from);
			ms_free(to);
		}
201
		pingOp->set_user_pointer(this);
202 203 204 205 206 207 208
		return true;
	}
	return false;
}

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

209 210 211 212 213 214
void CallSessionPrivate::setParams (CallSessionParams *csp) {
	if (params)
		delete params;
	params = csp;
}

Ghislain MARY's avatar
Ghislain MARY committed
215 216 217 218
bool CallSessionPrivate::isInConference () const {
	return params->getPrivate()->getInConference();
}

219 220
// -----------------------------------------------------------------------------

221
void CallSessionPrivate::abort (const string &errorMsg) {
222
	op->terminate();
223
	setState(CallSession::State::Error, errorMsg);
224 225
}

226 227 228
void CallSessionPrivate::accepted () {
	/* Immediately notify the connected state, even if errors occur after */
	switch (state) {
229 230 231
		case CallSession::State::OutgoingProgress:
		case CallSession::State::OutgoingRinging:
		case CallSession::State::OutgoingEarlyMedia:
232
			/* Immediately notify the connected state */
233
			setState(CallSession::State::Connected, "Connected");
234 235 236 237
			break;
		default:
			break;
	}
238
	currentParams->setPrivacy((LinphonePrivacyMask)op->get_privacy());
239 240 241
}

void CallSessionPrivate::ackBeingSent (LinphoneHeaders *headers) {
242
	L_Q();
243
	if (listener)
244
		listener->onAckBeingSent(q->getSharedFromThis(), headers);
245 246 247
}

void CallSessionPrivate::ackReceived (LinphoneHeaders *headers) {
248
	L_Q();
249
	if (listener)
250
		listener->onAckReceived(q->getSharedFromThis(), headers);
251 252
}

253 254 255 256 257 258 259
void CallSessionPrivate::cancelDone () {
	if (reinviteOnCancelResponseRequested) {
		reinviteOnCancelResponseRequested = false;
		reinviteToRecoverFromConnectionLoss();
	}
}

260
bool CallSessionPrivate::failure () {
261
	L_Q();
262
	const SalErrorInfo *ei = op->get_error_info();
263 264
	switch (ei->reason) {
		case SalReasonRedirect:
265 266
			if ((state == CallSession::State::OutgoingInit) || (state == CallSession::State::OutgoingProgress)
				|| (state == CallSession::State::OutgoingRinging) /* Push notification case */ || (state == CallSession::State::OutgoingEarlyMedia)) {
267
				const SalAddress *redirectionTo = op->get_remote_contact_address();
268 269 270 271 272 273 274
				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);
275
					restartInvite();
276 277 278 279 280 281 282 283 284 285
					return true;
				}
			}
			break;
		default:
			break;
	}

	/* Some call errors are not fatal */
	switch (state) {
286 287 288
		case CallSession::State::Updating:
		case CallSession::State::Pausing:
		case CallSession::State::Resuming:
289
			if (ei->reason != SalReasonNoMatch) {
290
				lInfo() << "Call error on state [" << Utils::toString(state) << "], restoring previous state [" << Utils::toString(prevState) << "]";
291 292 293 294 295 296 297
				setState(prevState, ei->full_string);
				return true;
			}
		default:
			break;
	}

298
	if ((state != CallSession::State::End) && (state != CallSession::State::Error)) {
299
		if (ei->reason == SalReasonDeclined)
300
			setState(CallSession::State::End, "Call declined");
301
		else {
302 303
			if (CallSession::isEarlyState(state))
				setState(CallSession::State::Error, ei->full_string ? ei->full_string : "");
304
			else
305
				setState(CallSession::State::End, ei->full_string ? ei->full_string : "");
306
		}
307 308
		if ((ei->reason != SalReasonNone) && listener)
			listener->onPlayErrorTone(q->getSharedFromThis(), linphone_reason_from_sal(ei->reason));
309
	}
310 311 312
	if (referer) {
		// Notify referer of the failure
		notifyReferState();
313 314 315 316
	}
	return false;
}

317 318
void CallSessionPrivate::infoReceived (SalBodyHandler *bodyHandler) {
	L_Q();
319
	LinphoneInfoMessage *info = linphone_core_create_info_message(q->getCore()->getCCore());
320 321 322 323 324 325 326 327 328 329 330
	linphone_info_message_set_headers(info, op->get_recv_custom_header());
	if (bodyHandler) {
		LinphoneContent *content = linphone_content_from_sal_body_handler(bodyHandler);
		linphone_info_message_set_content(info, content);
		linphone_content_unref(content);
	}
	if (listener)
		listener->onInfoReceived(q->getSharedFromThis(), info);
	linphone_info_message_unref(info);
}

331
void CallSessionPrivate::pingReply () {
332
	L_Q();
333
	if (state == CallSession::State::OutgoingInit) {
334 335
		pingReplied = true;
		if (isReadyForInvite())
336
			q->startInvite(nullptr, "");
337 338 339
	}
}

340 341 342 343
void CallSessionPrivate::referred (const Address &referToAddr) {
	L_Q();
	referTo = referToAddr.asString();
	referPending = true;
344
	setState(CallSession::State::Referred, "Referred");
345 346 347 348
	if (referPending && listener)
		listener->onCallSessionStartReferred(q->getSharedFromThis());
}

349
void CallSessionPrivate::remoteRinging () {
350
	L_Q();
351
	/* Set privacy */
352
	currentParams->setPrivacy((LinphonePrivacyMask)op->get_privacy());
353 354
	if (listener)
		listener->onStartRinging(q->getSharedFromThis());
355
	lInfo() << "Remote ringing...";
356
	setState(CallSession::State::OutgoingRinging, "Remote ringing");
357 358
}

359 360 361
void CallSessionPrivate::replaceOp (SalCallOp *newOp) {
	L_Q();
	SalCallOp *oldOp = op;
362
	CallSession::State oldState = state;
363 364 365 366
	op = newOp;
	op->set_user_pointer(q);
	op->set_local_media_description(oldOp->get_local_media_description());
	switch (state) {
367 368 369
		case CallSession::State::IncomingEarlyMedia:
		case CallSession::State::IncomingReceived:
			op->notify_ringing((state == CallSession::State::IncomingEarlyMedia) ? true : false);
370
			break;
371 372
		case CallSession::State::Connected:
		case CallSession::State::StreamsRunning:
373 374 375
			op->accept();
			break;
		default:
376
			lWarning() << "CallSessionPrivate::replaceOp(): don't know what to do in state [" << Utils::toString(state) << "]";
377 378 379
			break;
	}
	switch (oldState) {
380 381
		case CallSession::State::IncomingEarlyMedia:
		case CallSession::State::IncomingReceived:
Ghislain MARY's avatar
Ghislain MARY committed
382
			oldOp->set_user_pointer(nullptr); // In order for the call session to not get terminated by terminating this op
383 384 385 386 387 388
			// Do not terminate a forked INVITE
			if (op->get_replaces())
				oldOp->terminate();
			else
				oldOp->kill_dialog();
			break;
389 390
		case CallSession::State::Connected:
		case CallSession::State::StreamsRunning:
391 392 393 394 395 396 397 398 399
			oldOp->terminate();
			oldOp->kill_dialog();
			break;
		default:
			break;
	}
	oldOp->release();
}

400
void CallSessionPrivate::terminated () {
401
	L_Q();
402
	switch (state) {
403 404
		case CallSession::State::End:
		case CallSession::State::Error:
405 406
			lWarning() << "terminated: already terminated, ignoring";
			return;
407 408
		case CallSession::State::IncomingReceived:
		case CallSession::State::IncomingEarlyMedia:
409
			if (!op->get_reason_error_info()->protocol || strcmp(op->get_reason_error_info()->protocol, "") == 0) {
410 411 412 413 414 415 416
				linphone_error_info_set(ei, nullptr, LinphoneReasonNotAnswered, 0, "Incoming call cancelled", nullptr);
				nonOpError = true;
			}
			break;
		default:
			break;
	}
417 418
	if (referPending && listener)
		listener->onCallSessionStartReferred(q->getSharedFromThis());
419 420
	if (listener)
		listener->onStopRingingIfInCall(q->getSharedFromThis());
421
	setState(CallSession::State::End, "Call ended");
422 423 424
}

void CallSessionPrivate::updated (bool isUpdate) {
425 426
	L_Q();
	deferUpdate = !!lp_config_get_int(linphone_core_get_config(q->getCore()->getCCore()), "sip", "defer_update_default", FALSE);
427 428 429
	SalErrorInfo sei;
	memset(&sei, 0, sizeof(sei));
	switch (state) {
430
		case CallSession::State::PausedByRemote:
431 432 433
			updatedByRemote();
			break;
		/* SIP UPDATE CASE */
434 435 436
		case CallSession::State::OutgoingRinging:
		case CallSession::State::OutgoingEarlyMedia:
		case CallSession::State::IncomingEarlyMedia:
437
			if (isUpdate) {
438 439
				setState(CallSession::State::EarlyUpdatedByRemote, "EarlyUpdatedByRemote");
				acceptUpdate(nullptr, prevState, Utils::toString(prevState));
440 441
			}
			break;
442 443 444
		case CallSession::State::StreamsRunning:
		case CallSession::State::Connected:
		case CallSession::State::UpdatedByRemote: /* Can happen on UAC connectivity loss */
445 446
			updatedByRemote();
			break;
447
		case CallSession::State::Paused:
448
			/* We'll remain in pause state but accept the offer anyway according to default parameters */
449
			acceptUpdate(nullptr, state, Utils::toString(state));
450
			break;
451 452 453
		case CallSession::State::Updating:
		case CallSession::State::Pausing:
		case CallSession::State::Resuming:
454
			sal_error_info_set(&sei, SalReasonInternalError, "SIP", 0, nullptr, nullptr);
455
			op->decline_with_error_info(&sei, nullptr);
456
			BCTBX_NO_BREAK; /* no break */
457 458 459 460 461 462 463 464 465 466 467
		case CallSession::State::Idle:
		case CallSession::State::OutgoingInit:
		case CallSession::State::End:
		case CallSession::State::IncomingReceived:
		case CallSession::State::OutgoingProgress:
		case CallSession::State::Referred:
		case CallSession::State::Error:
		case CallSession::State::Released:
		case CallSession::State::EarlyUpdatedByRemote:
		case CallSession::State::EarlyUpdating:
			lWarning() << "Receiving reINVITE or UPDATE while in state [" << Utils::toString(state) << "], should not happen";
468 469 470 471 472
		break;
	}
}

void CallSessionPrivate::updatedByRemote () {
473
	L_Q();
474
	setState(CallSession::State::UpdatedByRemote,"Call updated by remote");
475
	if (deferUpdate) {
476
		if (state == CallSession::State::UpdatedByRemote)
477 478
			lInfo() << "CallSession [" << q << "]: UpdatedByRemoted was signaled but defered. LinphoneCore expects the application to call linphone_core_accept_call_update() later.";
	} else {
479
		if (state == CallSession::State::UpdatedByRemote)
480 481 482 483 484 485 486 487 488 489 490 491 492 493
			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);
}

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

494 495 496 497 498 499 500
void CallSessionPrivate::init () {
	currentParams = new CallSessionParams();
	ei = linphone_error_info_new();
}

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

501
void CallSessionPrivate::accept (const CallSessionParams *csp) {
502
	L_Q();
503 504
	/* Try to be best-effort in giving real local or routable contact address */
	setContactOp();
505 506 507 508
	if (csp)
		setParams(new CallSessionParams(*csp));
	if (params)
		op->set_sent_custom_header(params->getPrivate()->getCustomHeaders());
509

510
	op->accept();
511
	if (listener)
512
		listener->onSetCurrentSession(q->getSharedFromThis());
513
	setState(CallSession::State::Connected, "Connected");
514 515
}

516
LinphoneStatus CallSessionPrivate::acceptUpdate (const CallSessionParams *csp, CallSession::State nextState, const string &stateInfo) {
517 518 519 520
	return startAcceptUpdate(nextState, stateInfo);
}

LinphoneStatus CallSessionPrivate::checkForAcceptation () const {
521
	L_Q();
522
	switch (state) {
523 524
		case CallSession::State::IncomingReceived:
		case CallSession::State::IncomingEarlyMedia:
525 526
			break;
		default:
527
			lError() << "checkForAcceptation() CallSession [" << q << "] is in state [" << Utils::toString(state) << "], operation not permitted";
528 529
			return -1;
	}
530
	if (listener)
531
		listener->onCheckForAcceptation(q->getSharedFromThis());
532 533

	/* Check if this call is supposed to replace an already running one */
534
	SalOp *replaced = op->get_replaces();
535
	if (replaced) {
536
		CallSession *session = reinterpret_cast<CallSession *>(replaced->get_user_pointer());
537 538 539 540 541 542 543 544 545
		if (session) {
			lInfo() << "CallSession " << q << " replaces CallSession " << session << ". This last one is going to be terminated automatically";
			session->terminate();
		}
	}
	return 0;
}

void CallSessionPrivate::handleIncomingReceivedStateInIncomingNotification () {
546
	L_Q();
547 548
	/* Try to be best-effort in giving real local or routable contact address for 100Rel case */
	setContactOp();
549
	op->notify_ringing(false);
550
	if (op->get_replaces() && lp_config_get_int(linphone_core_get_config(q->getCore()->getCCore()), "sip", "auto_answer_replacing_calls", 1))
551 552 553 554 555 556 557 558 559 560 561 562 563
		q->accept();
}

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

564
bool CallSessionPrivate::isUpdateAllowed (CallSession::State &nextState) const {
565
	switch (state) {
566 567 568 569 570
		case CallSession::State::IncomingReceived:
		case CallSession::State::IncomingEarlyMedia:
		case CallSession::State::OutgoingRinging:
		case CallSession::State::OutgoingEarlyMedia:
			nextState = CallSession::State::EarlyUpdating;
571
			break;
572 573 574 575 576
		case CallSession::State::Connected:
		case CallSession::State::StreamsRunning:
		case CallSession::State::PausedByRemote:
		case CallSession::State::UpdatedByRemote:
			nextState = CallSession::State::Updating;
577
			break;
578 579
		case CallSession::State::Paused:
			nextState = CallSession::State::Pausing;
580
			break;
581 582 583 584
		case CallSession::State::OutgoingProgress:
		case CallSession::State::Pausing:
		case CallSession::State::Resuming:
		case CallSession::State::Updating:
585 586 587
			nextState = state;
			break;
		default:
588
			lError() << "Update is not allowed in [" << Utils::toString(state) << "] state";
589 590 591 592 593
			return false;
	}
	return true;
}

594 595 596 597 598 599
int CallSessionPrivate::restartInvite () {
	L_Q();
	createOp();
	return q->startInvite(nullptr, subject);
}

600 601 602 603
/*
 * Called internally when reaching the Released state, to perform cleanups to break circular references.
**/
void CallSessionPrivate::setReleased () {
604
	L_Q();
605 606 607 608 609
	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 */
610
		op->release();
611 612
		op = nullptr;
	}
613 614
	referer = nullptr;
	transferTarget = nullptr;
615

616
	if (listener)
617
		listener->onCallSessionSetReleased(q->getSharedFromThis());
618 619 620 621 622 623 624 625
}

/* 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() {
626
	L_Q();
627 628
	completeLog();
	if (listener)
629
		listener->onCallSessionSetTerminated(q->getSharedFromThis());
630 631
}

632
LinphoneStatus CallSessionPrivate::startAcceptUpdate (CallSession::State nextState, const std::string &stateInfo) {
633
	op->accept();
634 635 636 637
	setState(nextState, stateInfo);
	return 0;
}

638
LinphoneStatus CallSessionPrivate::startUpdate (const string &subject) {
639
	L_Q();
640 641 642 643 644 645 646 647 648 649 650
	string newSubject(subject);
	if (newSubject.empty()) {
		if (q->getParams()->getPrivate()->getInConference())
			newSubject = "Conference";
		else if (q->getParams()->getPrivate()->getInternalCallUpdate())
			newSubject = "ICE processing concluded";
		else if (q->getParams()->getPrivate()->getNoUserConsent())
			newSubject = "Refreshing";
		else
			newSubject = "Media change";
	}
651 652
	if (destProxy && destProxy->op) {
		/* Give a chance to update the contact address if connectivity has changed */
653
		op->set_contact_address(destProxy->op->get_contact_address());
654
	} else
655
		op->set_contact_address(nullptr);
656
	return op->update(newSubject.c_str(), q->getParams()->getPrivate()->getNoUserConsent());
657 658 659
}

void CallSessionPrivate::terminate () {
660
	if ((state == CallSession::State::IncomingReceived) && (linphone_error_info_get_reason(ei) != LinphoneReasonNotAnswered)) {
661 662 663
		linphone_error_info_set_reason(ei, LinphoneReasonDeclined);
		nonOpError = true;
	}
664
	setState(CallSession::State::End, "Call terminated");
665 666
}

667
void CallSessionPrivate::updateCurrentParams () const {}
668 669 670

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

Ghislain MARY's avatar
Ghislain MARY committed
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
void CallSessionPrivate::setBroken () {
	switch (state) {
		// For all the early states, we prefer to drop the call
		case CallSession::State::OutgoingInit:
		case CallSession::State::OutgoingProgress:
		case CallSession::State::OutgoingRinging:
		case CallSession::State::OutgoingEarlyMedia:
		case CallSession::State::IncomingReceived:
		case CallSession::State::IncomingEarlyMedia:
			// During the early states, the SAL layer reports the failure from the dialog or transaction layer,
			// hence, there is nothing special to do
		case CallSession::State::StreamsRunning:
		case CallSession::State::Updating:
		case CallSession::State::Pausing:
		case CallSession::State::Resuming:
		case CallSession::State::Paused:
		case CallSession::State::PausedByRemote:
		case CallSession::State::UpdatedByRemote:
			// During these states, the dialog is established. A failure of a transaction is not expected to close it.
			// Instead we have to repair the dialog by sending a reINVITE
			broken = true;
			needLocalIpRefresh = true;
			break;
		default:
			lError() << "CallSessionPrivate::setBroken(): unimplemented case";
			break;
	}
}

700
void CallSessionPrivate::setContactOp () {
701
	L_Q();
702 703 704
	SalAddress *salAddress = nullptr;
	LinphoneAddress *contact = getFixedContact();
	if (contact) {
705 706 707
		auto contactParams = q->getParams()->getPrivate()->getCustomContactParameters();
		for (auto it = contactParams.begin(); it != contactParams.end(); it++)
			linphone_address_set_param(contact, it->first.c_str(), it->second.empty() ? nullptr : it->second.c_str());
708
		salAddress = const_cast<SalAddress *>(L_GET_PRIVATE_FROM_C_OBJECT(contact)->getInternalAddress());
709
		op->set_contact_address(salAddress);
Ghislain MARY's avatar
Ghislain MARY committed
710
		linphone_address_unref(contact);
711 712 713 714 715
	}
}

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

Ghislain MARY's avatar
Ghislain MARY committed
716 717
void CallSessionPrivate::onNetworkReachable (bool sipNetworkReachable, bool mediaNetworkReachable) {
	if (sipNetworkReachable)
718
		repairIfBroken();
Ghislain MARY's avatar
Ghislain MARY committed
719 720
	else
		setBroken();
721 722 723 724 725 726 727 728
}

void CallSessionPrivate::onRegistrationStateChanged (LinphoneProxyConfig *cfg, LinphoneRegistrationState cstate, const std::string &message) {
	repairIfBroken();
}

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

729
void CallSessionPrivate::completeLog () {
730
	L_Q();
731 732
	log->duration = computeDuration(); /* Store duration since connected */
	log->error_info = linphone_error_info_ref(ei);
733
	if (log->status == LinphoneCallMissed)
734 735
		q->getCore()->getCCore()->missed_calls++;
	linphone_core_report_call_log(q->getCore()->getCCore(), log);
736 737
}

738 739 740 741
void CallSessionPrivate::createOp () {
	createOpTo(log->to);
}

742
void CallSessionPrivate::createOpTo (const LinphoneAddress *to) {
743
	L_Q();
744
	if (op)
745
		op->release();
746
	op = new SalCallOp(q->getCore()->getCCore()->sal);
747
	op->set_user_pointer(q);
748 749
	if (params->getPrivate()->getReferer())
		op->set_referer(params->getPrivate()->getReferer()->getPrivate()->getOp());
750
	linphone_configure_op(q->getCore()->getCCore(), op, to, q->getParams()->getPrivate()->getCustomHeaders(), false);
751
	if (q->getParams()->getPrivacy() != LinphonePrivacyDefault)
752
		op->set_privacy((SalPrivacyMask)q->getParams()->getPrivacy());
753 754 755 756 757 758
	/* else privacy might be set by proxy */
}

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

LinphoneAddress * CallSessionPrivate::getFixedContact () const {
759
	L_Q();
760
	LinphoneAddress *result = nullptr;
761
	if (op && op->get_contact_address()) {
762 763
		/* If already choosed, don't change it */
		return nullptr;
764
	} else if (pingOp && pingOp->get_contact_address()) {
765 766
		/* If the ping OPTIONS request succeeded use the contact guessed from the received, rport */
		lInfo() << "Contact has been fixed using OPTIONS";
767
		char *addr = sal_address_as_string(pingOp->get_contact_address());
768 769
		result = linphone_address_new(addr);
		ms_free(addr);
770
	} else if (destProxy && destProxy->op && linphone_proxy_config_get_contact(destProxy)) {
771 772
		/* If using a proxy, use the contact address as guessed with the REGISTERs */
		lInfo() << "Contact has been fixed using proxy";
773
		result = linphone_address_clone(linphone_proxy_config_get_contact(destProxy));
774
	} else {
775
		result = linphone_core_get_primary_contact_parsed(q->getCore()->getCCore());
776 777 778 779 780 781 782 783 784 785
		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;
}

786 787 788 789 790 791 792 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 820 821 822 823 824 825 826
// -----------------------------------------------------------------------------

void CallSessionPrivate::reinviteToRecoverFromConnectionLoss () {
	L_Q();
	lInfo() << "CallSession [" << q << "] is going to be updated (reINVITE) in order to recover from lost connectivity";
	q->update(params);
}

void CallSessionPrivate::repairByInviteWithReplaces () {
	L_Q();
	const char *callId = op->get_call_id();
	const char *fromTag = op->get_local_tag();
	const char *toTag = op->get_remote_tag();
	op->kill_dialog();
	createOp();
	op->set_replaces(callId, fromTag, toTag);
	q->startInvite(nullptr);
}

void CallSessionPrivate::repairIfBroken () {
	L_Q();
	LinphoneCore *lc = q->getCore()->getCCore();
	LinphoneConfig *config = linphone_core_get_config(lc);
	if (!lp_config_get_int(config, "sip", "repair_broken_calls", 1) || !lc->media_network_reachable || !broken)
		return;

	// If we are registered and this session has been broken due to a past network disconnection,
	// attempt to repair it

	// Make sure that the proxy from which we received this call, or to which we routed this call is registered first
	if (destProxy) {
		// In all other cases, ie no proxy config, or a proxy config for which no registration was requested,
		// we can start the call session repair immediately.
		if (linphone_proxy_config_register_enabled(destProxy)
			&& (linphone_proxy_config_get_state(destProxy) != LinphoneRegistrationOk))
			return;
	}

	SalErrorInfo sei;
	memset(&sei, 0, sizeof(sei));
	switch (state) {
827 828
		case CallSession::State::Updating:
		case CallSession::State::Pausing:
829 830 831 832 833 834
			if (op->dialog_request_pending()) {
				// Need to cancel first re-INVITE as described in section 5.5 of RFC 6141
				op->cancel_invite();
				reinviteOnCancelResponseRequested = true;
			}
			break;
835 836 837
		case CallSession::State::StreamsRunning:
		case CallSession::State::Paused:
		case CallSession::State::PausedByRemote:
838 839 840
			if (!op->dialog_request_pending())
				reinviteToRecoverFromConnectionLoss();
			break;
841
		case CallSession::State::UpdatedByRemote:
842 843 844 845 846 847
			if (op->dialog_request_pending()) {
				sal_error_info_set(&sei, SalReasonServiceUnavailable, "SIP", 0, nullptr, nullptr);
				op->decline_with_error_info(&sei, nullptr);
			}
			reinviteToRecoverFromConnectionLoss();
			break;
848 849
		case CallSession::State::OutgoingInit:
		case CallSession::State::OutgoingProgress:
850 851 852
			op->cancel_invite();
			reinviteOnCancelResponseRequested = true;
			break;
853 854
		case CallSession::State::OutgoingEarlyMedia:
		case CallSession::State::OutgoingRinging:
855 856
			repairByInviteWithReplaces();
			break;
857 858
		case CallSession::State::IncomingEarlyMedia:
		case CallSession::State::IncomingReceived:
859 860 861
			// Keep the call broken until a forked INVITE is received from the server
			break;
		default:
862
			lWarning() << "CallSessionPrivate::repairIfBroken: don't know what to do in state [" << Utils::toString(state);
863 864 865 866 867 868
			broken = false;
			break;
	}
	sal_error_info_reset(&sei);
}

869 870
// =============================================================================

871 872 873
CallSession::CallSession (const shared_ptr<Core> &core, const CallSessionParams *params, CallSessionListener *listener)
	: Object(*new CallSessionPrivate), CoreAccessor(core) {
	L_D();
874
	getCore()->getPrivate()->registerListener(d);
875 876 877 878
	d->listener = listener;
	if (params)
		d->setParams(new CallSessionParams(*params));
	d->init();
879 880 881
	lInfo() << "New CallSession [" << this << "] initialized (LinphoneCore version: " << linphone_core_get_version() << ")";
}

882 883
CallSession::CallSession (CallSessionPrivate &p, const shared_ptr<Core> &core) : Object(p), CoreAccessor(core) {
	L_D();
884
	getCore()->getPrivate()->registerListener(d);
885 886 887 888 889
	d->init();
}

CallSession::~CallSession () {
	L_D();
890
	getCore()->getPrivate()->unregisterListener(d);
891 892 893 894 895 896 897 898 899 900 901 902 903
	if (d->currentParams)
		delete d->currentParams;
	if (d->params)
		delete d->params;
	if (d->remoteParams)
		delete d->remoteParams;
	if (d->ei)
		linphone_error_info_unref(d->ei);
	if (d->log)
		linphone_call_log_unref(d->log);
	if (d->op)
		d->op->release();
}
904

905 906
// -----------------------------------------------------------------------------

907
LinphoneStatus CallSession::accept (const CallSessionParams *csp) {
908
	L_D();
909 910 911 912 913 914
	LinphoneStatus result = d->checkForAcceptation();
	if (result < 0) return result;
	d->accept(csp);
	return 0;
}

915
LinphoneStatus CallSession::acceptUpdate (const CallSessionParams *csp) {
916
	L_D();
917 918
	if (d->state != CallSession::State::UpdatedByRemote) {
		lError() << "CallSession::acceptUpdate(): invalid state " << Utils::toString(d->state) << " to call this method";
919 920
		return -1;
	}
921
	return d->acceptUpdate(csp, d->prevState, Utils::toString(d->prevState));
922 923
}

924
void CallSession::configure (LinphoneCallDir direction, LinphoneProxyConfig *cfg, SalCallOp *op, const Address &from, const Address &to) {
925
	L_D();