call-session.cpp 37 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 83 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 177 178 179 180 181 182 183 184 185 186 187 188 189
	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) {
	L_Q(CallSession);
	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;
			case LinphoneCallStreamsRunning:
				if ((prevState == LinphoneCallUpdating) || (prevState == LinphoneCallUpdatedByRemote)) {
					LinphoneReason reason = linphone_error_info_get_reason(ei);
					char *msg;
					if (reason != LinphoneReasonNone) {
						msg = ms_strdup_printf(_("Call parameters could not be modified: %s."), linphone_reason_to_string(reason));
					} else {
						msg = ms_strdup(_("Call parameters were successfully modified."));
					}
					linphone_core_notify_display_status(core, msg);
					ms_free(msg);
				}
				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)
190
			listener->onCallSessionStateChanged(*q, state, message);
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
		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;
}

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

224 225 226 227 228 229
void CallSessionPrivate::abort (const string &errorMsg) {
	sal_call_terminate(op);
	linphone_core_notify_display_status(core, "Call aborted");
	setState(LinphoneCallError, errorMsg);
}

230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
void CallSessionPrivate::accepted () {
	L_Q(CallSession);
	char *msg = nullptr;
	/* 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");
			msg = ms_strdup_printf(_("Call answered by %s"), q->getRemoteAddressAsString().c_str());
			linphone_core_notify_display_status(core, msg);
			ms_free(msg);
			break;
		default:
			break;
	}
	currentParams->setPrivacy((LinphonePrivacyMask)sal_op_get_privacy(op));
}

void CallSessionPrivate::ackBeingSent (LinphoneHeaders *headers) {
	L_Q(CallSession);
	if (listener)
253
		listener->onAckBeingSent(*q, headers);
254 255 256 257 258
}

void CallSessionPrivate::ackReceived (LinphoneHeaders *headers) {
	L_Q(CallSession);
	if (listener)
259
		listener->onAckReceived(*q, headers);
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 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 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 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
}

bool CallSessionPrivate::failure () {
	L_Q(CallSession);
	linphone_core_notify_show_interface(core);
	const char *msg = ei->full_string;
	const char *msg486 = "User is busy.";
	const char *msg480 = "User is temporarily unavailable.";
	const char *msg600 = "User does not want to be disturbed.";
	const char *msg603 = "Call declined.";
	const SalErrorInfo *ei = sal_op_get_error_info(op);
	switch (ei->reason) {
		case SalReasonNone:
			break;
		case SalReasonRequestTimeout:
			msg = "Request timeout.";
			linphone_core_notify_display_status(core, msg);
			break;
		case SalReasonDeclined:
			linphone_core_notify_display_status(core, msg603);
			break;
		case SalReasonBusy:
			linphone_core_notify_display_status(core, msg486);
			break;
		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;
				}
				msg = "Redirected";
				linphone_core_notify_display_status(core, msg);
			}
			break;
		case SalReasonTemporarilyUnavailable:
			linphone_core_notify_display_status(core, msg480);
			break;
		case SalReasonNotFound:
			linphone_core_notify_display_status(core, msg);
			break;
		case SalReasonDoNotDisturb:
			linphone_core_notify_display_status(core, msg600);
			break;
		case SalReasonUnsupportedContent: /* This is for compatibility: linphone sent 415 because of SDP offer answer failure */
		case SalReasonNotAcceptable:
			break;
		default:
			linphone_core_notify_display_status(core, "Call failed.");
			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 () {
	L_Q(CallSession);
	if (state == LinphoneCallOutgoingInit) {
		pingReplied = true;
		if (isReadyForInvite())
			q->startInvite(nullptr);
	}
}

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

void CallSessionPrivate::updated (bool isUpdate) {
	deferUpdate = lp_config_get_int(linphone_core_get_config(core), "sip", "defer_update_default", FALSE);
	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 () {
	L_Q(CallSession);
	linphone_core_notify_display_status(core, "Call is updated by remote");
	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);
}

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

482
void CallSessionPrivate::accept (const CallSessionParams *params) {
483 484 485 486
	L_Q(CallSession);
	/* Try to be best-effort in giving real local or routable contact address */
	setContactOp();
	if (params) {
487 488
		this->params = new CallSessionParams(*params);
		sal_op_set_sent_custom_header(op, this->params->getPrivate()->getCustomHeaders());
489 490 491 492 493
	}

	sal_call_accept(op);
	linphone_core_notify_display_status(core, _("Connected."));
	if (listener)
494
		listener->onSetCurrentSession(*q);
495 496 497
	setState(LinphoneCallConnected, "Connected");
}

498
LinphoneStatus CallSessionPrivate::acceptUpdate (const CallSessionParams *csp, LinphoneCallState nextState, const string &stateInfo) {
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 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 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
	return startAcceptUpdate(nextState, stateInfo);
}

LinphoneStatus CallSessionPrivate::checkForAcceptation () const {
	L_Q(const CallSession);
	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;
	}
	bctbx_list_t *copy = bctbx_list_copy(linphone_core_get_calls(core));
	for (bctbx_list_t *it = copy; it != nullptr; it = bctbx_list_next(it)) {
		LinphoneCall *call = reinterpret_cast<LinphoneCall *>(bctbx_list_get_data(it));
		shared_ptr<CallSession> session = linphone_call_get_cpp_obj(call)->getPrivate()->getActiveSession();
		if (session.get() == q) continue;
		switch (session->getState()) {
			case LinphoneCallOutgoingInit:
			case LinphoneCallOutgoingProgress:
			case LinphoneCallOutgoingRinging:
			case LinphoneCallOutgoingEarlyMedia:
				lInfo() << "Already existing CallSession [" << session << "] in state [" << linphone_call_state_to_string(session->getState())
					<< "], canceling it before accepting new CallSession [" << q << "]";
				session->terminate();
				break;
			default:
				break; /* Nothing to do */
		}
	}
	bctbx_list_free(copy);

	/* 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 () {
	L_Q(CallSession);
	/* 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 () {
	L_Q(CallSession);
	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)
621
		listener->onCallSessionSetReleased(*q);
622 623 624 625 626 627 628 629 630 631 632
}

/* 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() {
	L_Q(CallSession);
	completeLog();
	if (listener)
633
		listener->onCallSessionSetTerminated(*q);
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
}

LinphoneStatus CallSessionPrivate::startAcceptUpdate (LinphoneCallState nextState, const std::string &stateInfo) {
	sal_call_accept(op);
	setState(nextState, stateInfo);
	return 0;
}

LinphoneStatus CallSessionPrivate::startUpdate () {
	L_Q(CallSession);
	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";
	linphone_core_notify_display_status(core, "Modifying call parameters...");
	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;
	}
	linphone_core_notify_display_status(core, _("Call ended"));
	setState(LinphoneCallEnd, "Call terminated");
}

void CallSessionPrivate::updateCurrentParams () {}

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

void CallSessionPrivate::setContactOp () {
	SalAddress *salAddress = nullptr;
	LinphoneAddress *contact = getFixedContact();
	if (contact) {
679
		salAddress = const_cast<SalAddress *>(L_GET_PRIVATE_FROM_C_STRUCT(contact, Address)->getInternalAddress());
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
		sal_address_ref(salAddress);
		linphone_address_unref(contact);
	}
	sal_op_set_and_clean_contact_address(op, salAddress);
}

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

void CallSessionPrivate::completeLog () {
	log->duration = computeDuration(); /* Store duration since connected */
	log->error_info = linphone_error_info_ref(ei);
	if (log->status == LinphoneCallMissed) {
		core->missed_calls++;
		char *info = bctbx_strdup_printf(ngettext("You have missed %i call.", "You have missed %i calls.", core->missed_calls), core->missed_calls);
		linphone_core_notify_display_status(core, info);
		bctbx_free(info);
	}
	linphone_core_report_call_log(core, log);
}

void CallSessionPrivate::createOpTo (const LinphoneAddress *to) {
	L_Q(CallSession);
	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);
	} else if (destProxy && destProxy->op && sal_op_get_contact_address(destProxy->op)) {
		/* If using a proxy, use the contact address as guessed with the REGISTERs */
		lInfo() << "Contact has been fixed using proxy";
		char *addr = sal_address_as_string(sal_op_get_contact_address(destProxy->op));
		result = linphone_address_new(addr);
		ms_free(addr);
	} 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;
}

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

749
CallSession::CallSession (const Conference &conference, const CallSessionParams *params, CallSessionListener *listener)
750 751 752 753
	: Object(*new CallSessionPrivate(conference, params, listener)) {
	lInfo() << "New CallSession [" << this << "] initialized (LinphoneCore version: " << linphone_core_get_version() << ")";
}

754 755
CallSession::CallSession (CallSessionPrivate &p) : Object(p) {}

756 757
// -----------------------------------------------------------------------------

758
LinphoneStatus CallSession::accept (const CallSessionParams *csp) {
759 760 761 762 763 764 765
	L_D(CallSession);
	LinphoneStatus result = d->checkForAcceptation();
	if (result < 0) return result;
	d->accept(csp);
	return 0;
}

766
LinphoneStatus CallSession::acceptUpdate (const CallSessionParams *csp) {
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
	L_D(CallSession);
	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) {
	L_D(CallSession);
	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
791
		sal_op_cnx_ip_to_0000_if_sendonly_enable(op, !!lp_config_get_default_int(linphone_core_get_config(d->core),
792 793 794 795 796 797 798
			"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) {
799
		d->params = new CallSessionParams();
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 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
		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) {
	L_D(CallSession);
	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 () {
	L_D(CallSession);
	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) {
	L_D(CallSession);
	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 */
		startInvite(nullptr);
	}
	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 () {
	L_D(CallSession);
	if (d->listener)
882
		d->listener->onCallSessionAccepted(*this);
883
	/* Prevent the CallSession from being destroyed while we are notifying, if the user declines within the state callback */
884
	shared_ptr<CallSession> ref = static_pointer_cast<CallSession>(shared_from_this());
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
#if 0
	call->bg_task_id=sal_begin_background_task("liblinphone call notification", NULL, NULL);
#endif
	if (d->deferIncomingNotification) {
		lInfo() << "Defer ringing";
		return;
	}

	LinphoneAddress *fromParsed = linphone_address_new(sal_op_get_from(d->op));
	linphone_address_clean(fromParsed);
	char *tmp = linphone_address_as_string(fromParsed);
	linphone_address_unref(fromParsed);
	char *msg = ms_strdup_printf("%s %s%s", tmp, _("is contacting you"), (sal_call_autoanswer_asked(d->op)) ? _(" and asked autoanswer") : "");
	ms_free(tmp);
	linphone_core_notify_show_interface(d->core);
	linphone_core_notify_display_status(d->core, msg);
	ms_free(msg);

	if (d->listener)
904
		d->listener->onIncomingCallSessionStarted(*this);
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939

	d->setState(LinphoneCallIncomingReceived, "Incoming call");

	/* 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();
	}
}

int CallSession::startInvite (const Address *destination) {
	L_D(CallSession);
	/* 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);
	}
	ostringstream os;
	os << "Contacting " << destinationStr;
	linphone_core_notify_display_status(d->core, os.str().c_str());
	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 */
940
	shared_ptr<CallSession> ref = static_pointer_cast<CallSession>(shared_from_this());
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989
	int result = sal_call(d->op, from, destinationStr.c_str());
	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. */
			linphone_core_notify_display_status(d->core, _("Could not call"));
			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) {
	L_D(CallSession);
	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;
}

990
LinphoneStatus CallSession::update (const CallSessionParams *csp) {
991 992 993 994 995
	L_D(CallSession);
	LinphoneCallState nextState;
	LinphoneCallState initialState = d->state;
	if (!d->isUpdateAllowed(nextState))
		return -1;
996
	if (d->currentParams == csp)
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
		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 {
	L_D(const CallSession);
	return d->direction;
}

int CallSession::getDuration () const {
	L_D(const CallSession);
	switch (d->state) {
		case LinphoneCallEnd:
		case LinphoneCallError:
		case LinphoneCallReleased:
			return d->log->duration;
		default:
			return d->computeDuration();
	}
}

const LinphoneErrorInfo * CallSession::getErrorInfo () const {
	L_D(const CallSession);
	if (!d->nonOpError)
		linphone_error_info_from_sal_op(d->ei, d->op);
	return d->ei;
}

LinphoneCallLog * CallSession::getLog () const {
	L_D(const CallSession);
	return d->log;
}

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

const Address& CallSession::getRemoteAddress () const {
	L_D(const CallSession);
	return *L_GET_CPP_PTR_FROM_C_STRUCT((d->direction == LinphoneCallIncoming)
		? linphone_call_log_get_from(d->log) : linphone_call_log_get_to(d->log),
1045
		Address);
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
}

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

string CallSession::getRemoteContact () const {
	L_D(const CallSession);
	if (d->op) {
		/* sal_op_get_remote_contact preserves header params */
		return sal_op_get_remote_contact(d->op);
	}
	return string();
}

1061
const CallSessionParams * CallSession::getRemoteParams () {
1062 1063 1064 1065 1066 1067
	L_D(CallSession);
	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)
1068
				d->remoteParams = new CallSessionParams();
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
			d->remoteParams->getPrivate()->setCustomHeaders(ch);
		}
		return d->remoteParams;
	}
	return nullptr;
}

LinphoneCallState CallSession::getState () const {
	L_D(const CallSession);
	return d->state;
}

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

string CallSession::getRemoteUserAgent () const {
	L_D(const CallSession);
	if (d->op)
		return sal_op_get_remote_ua(d->op);
	return string();
}

1090
CallSessionParams * CallSession::getCurrentParams () {
1091 1092 1093 1094 1095 1096 1097
	L_D(CallSession);
	d->updateCurrentParams();
	return d->currentParams;
}

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

1098
const CallSessionParams * CallSession::getParams () const {
1099 1100 1101 1102
	L_D(const CallSession);
	return d->params;
}

1103
LINPHONE_END_NAMESPACE