callbacks.c 29.3 KB
Newer Older
Simon Morlat's avatar
Simon Morlat committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
linphone
Copyright (C) 2010  Simon MORLAT (simon.morlat@free.fr)

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
17
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
Simon Morlat's avatar
Simon Morlat committed
18 19 20
*/


21 22 23
#include "c-wrapper/internal/c-sal.h"
#include "sal/call-op.h"
#include "sal/message-op.h"
24
#include "sal/refer-op.h"
Simon Morlat's avatar
Simon Morlat committed
25

26
#include "linphone/core.h"
27
#include "linphone/utils/utils.h"
Simon Morlat's avatar
Simon Morlat committed
28
#include "private.h"
29
#include "mediastreamer2/mediastream.h"
30
#include "linphone/lpconfig.h"
31
#include <bctoolbox/defs.h>
32

33
// stat
34
#ifndef _WIN32
35 36 37 38 39
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#endif

40
#include "c-wrapper/c-wrapper.h"
41
#include "call/call-p.h"
Ronan's avatar
Ronan committed
42
#include "chat/chat-room/chat-room.h"
43
#include "chat/chat-room/server-group-chat-room-p.h"
44
#include "conference/participant.h"
45
#include "conference/session/call-session-p.h"
46
#include "conference/session/call-session.h"
47
#include "conference/session/media-session-p.h"
48
#include "conference/session/media-session.h"
49
#include "core/core-p.h"
50

51 52
using namespace std;

53
using namespace LinphonePrivate;
54

55
static void register_failure(SalOp *op);
56

57
static void call_received(SalCallOp *h) {
58
	/* Look if this INVITE is for a call that has already been notified but broken because of network failure */
59
	LinphoneCore *lc = reinterpret_cast<LinphoneCore *>(h->get_sal()->get_user_pointer());
60
	if (L_GET_PRIVATE_FROM_C_OBJECT(lc)->inviteReplacesABrokenCall(h))
61
		return;
62

63
	LinphoneAddress *fromAddr = nullptr;
64
	const char *pAssertedId = sal_custom_header_find(h->get_recv_custom_header(), "P-Asserted-Identity");
65 66 67 68 69
	/* In some situation, better to trust the network rather than the UAC */
	if (lp_config_get_int(linphone_core_get_config(lc), "sip", "call_logs_use_asserted_id_instead_of_from", 0)) {
		if (pAssertedId) {
			LinphoneAddress *pAssertedIdAddr = linphone_address_new(pAssertedId);
			if (pAssertedIdAddr) {
70
				ms_message("Using P-Asserted-Identity [%s] instead of from [%s] for op [%p]", pAssertedId, h->get_from(), h);
71 72 73 74 75 76 77 78
				fromAddr = pAssertedIdAddr;
			} else
				ms_warning("Unsupported P-Asserted-Identity header for op [%p] ", h);
		} else
			ms_warning("No P-Asserted-Identity header found so cannot use it for op [%p] instead of from", h);
	}

	if (!fromAddr)
79 80
		fromAddr = linphone_address_new(h->get_from());
	LinphoneAddress *toAddr = linphone_address_new(h->get_to());
81

82 83 84
	if (_linphone_core_is_conference_creation(lc, toAddr)) {
		linphone_address_unref(toAddr);
		linphone_address_unref(fromAddr);
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
		if (sal_address_has_param(h->get_remote_contact_address(), "text")) {
			bool oneToOneChatRoom = false;
			const char *oneToOneChatRoomStr = sal_custom_header_find(h->get_recv_custom_header(), "One-To-One-Chat-Room");
			if (oneToOneChatRoomStr && (strcmp(oneToOneChatRoomStr, "true") == 0))
				oneToOneChatRoom = true;
			if (oneToOneChatRoom) {
				IdentityAddress from(h->get_from());
				list<IdentityAddress> identAddresses = ServerGroupChatRoom::parseResourceLists(h->get_remote_body());
				if (identAddresses.size() != 1) {
					h->decline(SalReasonNotAcceptable, nullptr);
					return;
				}
				IdentityAddress confAddr = L_GET_PRIVATE_FROM_C_OBJECT(lc)->mainDb->findOneToOneConferenceChatRoomAddress(from, identAddresses.front());
				if (confAddr.isValid()) {
					shared_ptr<AbstractChatRoom> chatRoom = L_GET_CPP_PTR_FROM_C_OBJECT(lc)->findChatRoom(ChatRoomId(confAddr, confAddr));
					L_GET_PRIVATE(static_pointer_cast<ServerGroupChatRoom>(chatRoom))->confirmRecreation(h);
					return;
				}
			}
			_linphone_core_create_server_group_chat_room(lc, h);
		}
		// TODO: handle media conference creation if the "text" feature tag is not present
107 108
		return;
	} else if (sal_address_has_param(h->get_remote_contact_address(), "text")) {
109
		shared_ptr<AbstractChatRoom> chatRoom = L_GET_CPP_PTR_FROM_C_OBJECT(lc)->findChatRoom(
110
			ChatRoomId(IdentityAddress(h->get_to()), IdentityAddress(h->get_to()))
111 112 113
		);
		if (chatRoom) {
			L_GET_PRIVATE(static_pointer_cast<ServerGroupChatRoom>(chatRoom))->confirmJoining(h);
114 115
			linphone_address_unref(toAddr);
			linphone_address_unref(fromAddr);
116
			return;
117 118 119 120 121
		}
	} else {
		// TODO: handle media conference joining if the "text" feature tag is not present
	}

122 123 124
	/* First check if we can answer successfully to this invite */
	LinphonePresenceActivity *activity = nullptr;
	if ((linphone_presence_model_get_basic_status(lc->presence_model) == LinphonePresenceBasicStatusClosed)
125
		&& (activity = linphone_presence_model_get_activity(lc->presence_model))) {
126
		char *altContact = nullptr;
127 128
		switch (linphone_presence_activity_get_type(activity)) {
			case LinphonePresenceActivityPermanentAbsence:
129 130
				altContact = linphone_presence_model_get_contact(lc->presence_model);
				if (altContact) {
Ghislain MARY's avatar
Ghislain MARY committed
131 132
					SalErrorInfo sei;
					memset(&sei, 0, sizeof(sei));
133
					sal_error_info_set(&sei, SalReasonRedirect, "SIP", 0, nullptr, nullptr);
134 135
					SalAddress *altAddr = sal_address_new(altContact);
					h->decline_with_error_info(&sei, altAddr);
136
					ms_free(altContact);
137
					sal_address_unref(altAddr);
138 139 140
					LinphoneErrorInfo *ei = linphone_error_info_new();
					linphone_error_info_set(ei, nullptr, LinphoneReasonMovedPermanently, 302, "Moved permanently", nullptr);
					linphone_core_report_early_failed_call(lc, LinphoneCallIncoming, fromAddr, toAddr, ei);
141
					h->release();
142
					sal_error_info_reset(&sei);
143
					return;
144
				}
145 146
				break;
			default:
147
				/* Nothing special to be done */
148
				break;
149
		}
Simon Morlat's avatar
Simon Morlat committed
150
	}
151

152
	if (!L_GET_PRIVATE_FROM_C_OBJECT(lc)->canWeAddCall()) { /* Busy */
153
		h->decline(SalReasonBusy, nullptr);
154 155 156
		LinphoneErrorInfo *ei = linphone_error_info_new();
		linphone_error_info_set(ei, nullptr, LinphoneReasonBusy, 486, "Busy - too many calls", nullptr);
		linphone_core_report_early_failed_call(lc, LinphoneCallIncoming, fromAddr, toAddr, ei);
157
		h->release();
Simon Morlat's avatar
Simon Morlat committed
158 159
		return;
	}
160

161 162
	/* Check if I'm the caller */
	LinphoneAddress *fromAddressToSearchIfMe = nullptr;
163
	if (h->get_privacy() == SalPrivacyNone)
164 165 166 167 168
		fromAddressToSearchIfMe = linphone_address_clone(fromAddr);
	else if (pAssertedId)
		fromAddressToSearchIfMe = linphone_address_new(pAssertedId);
	else
		ms_warning("Hidden from identity, don't know if it's me");
169
	if (fromAddressToSearchIfMe && L_GET_PRIVATE_FROM_C_OBJECT(lc)->isAlreadyInCallWithAddress(*L_GET_CPP_PTR_FROM_C_OBJECT(fromAddressToSearchIfMe))) {
170 171
		char *addr = linphone_address_as_string(fromAddr);
		ms_warning("Receiving a call while one with same address [%s] is initiated, refusing this one with busy message", addr);
172
		h->decline(SalReasonBusy, nullptr);
173 174 175
		LinphoneErrorInfo *ei = linphone_error_info_new();
		linphone_error_info_set(ei, nullptr, LinphoneReasonBusy, 486, "Busy - duplicated call", nullptr);
		linphone_core_report_early_failed_call(lc, LinphoneCallIncoming, fromAddr, toAddr, ei);
176
		h->release();
177
		linphone_address_unref(fromAddressToSearchIfMe);
178
		ms_free(addr);
Simon Morlat's avatar
Simon Morlat committed
179 180
		return;
	}
181 182
	if (fromAddressToSearchIfMe)
		linphone_address_unref(fromAddressToSearchIfMe);
183

184 185 186
	LinphoneCall *call = linphone_call_new_incoming(lc, fromAddr, toAddr, h);
	linphone_address_unref(fromAddr);
	linphone_address_unref(toAddr);
187
	L_GET_PRIVATE_FROM_C_OBJECT(call)->startIncomingNotification();
188 189
}

190 191
static void call_rejected(SalCallOp *h){
	LinphoneCore *lc=(LinphoneCore *)h->get_sal()->get_user_pointer();
192 193
	LinphoneErrorInfo *ei = linphone_error_info_new();
	linphone_error_info_from_sal_op(ei, h);
194
	linphone_core_report_early_failed_call(lc, LinphoneCallIncoming, linphone_address_new(h->get_from()), linphone_address_new(h->get_to()), ei);
195 196
}

197
static void call_ringing(SalOp *h) {
198
	LinphonePrivate::CallSession *session = reinterpret_cast<LinphonePrivate::CallSession *>(h->get_user_pointer());
199 200
	if (!session) return;
	L_GET_PRIVATE(session)->remoteRinging();
201 202
}

203 204 205 206 207
/*
 * could be reach :
 *  - when the call is accepted
 *  - when a request is accepted (pause, resume)
 */
208
static void call_accepted(SalOp *op) {
209
	LinphonePrivate::CallSession *session = reinterpret_cast<LinphonePrivate::CallSession *>(op->get_user_pointer());
210 211 212
	if (!session) {
		ms_warning("call_accepted: CallSession no longer exists");
		return;
Simon Morlat's avatar
Simon Morlat committed
213
	}
214
	L_GET_PRIVATE(session)->accepted();
215 216
}

217
/* this callback is called when an incoming re-INVITE/ SIP UPDATE modifies the session*/
218
static void call_updating(SalOp *op, bool_t is_update) {
219
	LinphonePrivate::CallSession *session = reinterpret_cast<LinphonePrivate::CallSession *>(op->get_user_pointer());
220 221 222
	if (!session) {
		ms_warning("call_updating: CallSession no longer exists");
		return;
223
	}
224
	L_GET_PRIVATE(session)->updating(!!is_update);
225 226 227
}


228
static void call_ack_received(SalOp *op, SalCustomHeader *ack) {
229
	LinphonePrivate::CallSession *session = reinterpret_cast<LinphonePrivate::CallSession *>(op->get_user_pointer());
230 231
	if (!session) {
		ms_warning("call_ack_received(): no CallSession for which an ack is expected");
232 233
		return;
	}
234
	L_GET_PRIVATE(session)->ackReceived(reinterpret_cast<LinphoneHeaders *>(ack));
235 236
}

237

238
static void call_ack_being_sent(SalOp *op, SalCustomHeader *ack) {
239
	LinphonePrivate::CallSession *session = reinterpret_cast<LinphonePrivate::CallSession *>(op->get_user_pointer());
240 241
	if (!session) {
		ms_warning("call_ack_being_sent(): no CallSession for which an ack is supposed to be sent");
242 243
		return;
	}
244
	L_GET_PRIVATE(session)->ackBeingSent(reinterpret_cast<LinphoneHeaders *>(ack));
245 246
}

247
static void call_terminated(SalOp *op, const char *from) {
248
	LinphonePrivate::CallSession *session = reinterpret_cast<LinphonePrivate::CallSession *>(op->get_user_pointer());
249 250 251
	if (!session)
		return;
	L_GET_PRIVATE(session)->terminated();
252 253
}

254
static void call_failure(SalOp *op) {
255
	LinphonePrivate::CallSession *session = reinterpret_cast<LinphonePrivate::CallSession *>(op->get_user_pointer());
256 257 258
	if (!session) {
		ms_warning("Failure reported on already terminated CallSession");
		return;
259
	}
260
	L_GET_PRIVATE(session)->failure();
261 262
}

263
static void call_released(SalOp *op) {
264
	LinphonePrivate::CallSession *session = reinterpret_cast<LinphonePrivate::CallSession *>(op->get_user_pointer());
265 266 267 268
	if (!session) {
		/* We can get here when the core manages call at Sal level without creating a Call object. Typicially,
		 * when declining an incoming call with busy because maximum number of calls is reached. */
		return;
Simon Morlat's avatar
Simon Morlat committed
269
	}
270
	L_GET_PRIVATE(session)->setState(LinphonePrivate::CallSession::State::Released, "Call released");
271 272
}

273
static void call_cancel_done(SalOp *op) {
274 275 276 277
	LinphonePrivate::CallSession *session = reinterpret_cast<LinphonePrivate::CallSession *>(op->get_user_pointer());
	if (!session) {
		ms_warning("Cancel done reported on already terminated CallSession");
		return;
278
	}
279
	L_GET_PRIVATE(session)->cancelDone();
280 281
}

jehan's avatar
jehan committed
282
static void auth_failure(SalOp *op, SalAuthInfo* info) {
283
	LinphoneCore *lc = reinterpret_cast<LinphoneCore *>(op->get_sal()->get_user_pointer());
284
	LinphoneAuthInfo *ai = NULL;
285

286 287
	if (info != NULL) {
		ai = (LinphoneAuthInfo*)_linphone_core_find_auth_info(lc, info->realm, info->username, info->domain, TRUE);
288
		if (ai){
289
			LinphoneAuthMethod method = info->mode == SalAuthModeHttpDigest ? LinphoneAuthHttpDigest : LinphoneAuthTls;
290
			LinphoneAuthInfo *auth_info = linphone_core_create_auth_info(lc, info->username, NULL, NULL, NULL, info->realm, info->domain);
291
			ms_message("%s/%s/%s/%s authentication fails.", info->realm, info->username, info->domain, info->mode == SalAuthModeHttpDigest ? "HttpDigest" : "Tls");
292
			/*ask again for password if auth info was already supplied but apparently not working*/
293
			linphone_core_notify_authentication_requested(lc, auth_info, method);
Ghislain MARY's avatar
Ghislain MARY committed
294
			linphone_auth_info_unref(auth_info);
295 296
			// Deprecated
			linphone_core_notify_auth_info_requested(lc, info->realm, info->username, info->domain);
297
		}
jehan's avatar
jehan committed
298
	}
299
}
300

301
static void register_success(SalOp *op, bool_t registered){
302
	LinphoneProxyConfig *cfg=(LinphoneProxyConfig *)op->get_user_pointer();
303 304
	if (!cfg){
		ms_message("Registration success for deleted proxy config, ignored");
305 306
		return;
	}
307
	linphone_proxy_config_set_state(cfg, registered ? LinphoneRegistrationOk : LinphoneRegistrationCleared ,
308
									registered ? "Registration successful" : "Unregistration done");
309 310
}

311
static void register_failure(SalOp *op){
312 313
	LinphoneProxyConfig *cfg=(LinphoneProxyConfig*)op->get_user_pointer();
	const SalErrorInfo *ei=op->get_error_info();
314
	const char *details=ei->full_string;
315 316 317 318 319 320

	if (cfg==NULL){
		ms_warning("Registration failed for unknown proxy config.");
		return ;
	}
	if (details==NULL)
321
		details="no response timeout";
322

323
	if ((ei->reason == SalReasonServiceUnavailable || ei->reason == SalReasonIOError)
324
			&& linphone_proxy_config_get_state(cfg) == LinphoneRegistrationOk) {
325
		linphone_proxy_config_set_state(cfg,LinphoneRegistrationProgress,"Service unavailable, retrying");
326 327 328
	} else {
		linphone_proxy_config_set_state(cfg,LinphoneRegistrationFailed,details);
	}
329
	if (cfg->presence_publish_event){
330
		/*prevent publish to be sent now until registration gets successful*/
331 332
		linphone_event_terminate(cfg->presence_publish_event);
		cfg->presence_publish_event=NULL;
333 334
		cfg->send_publish=cfg->publish;
	}
335 336
}

337
static void vfu_request(SalOp *op) {
338
	LinphonePrivate::CallSession *session = reinterpret_cast<LinphonePrivate::CallSession *>(op->get_user_pointer());
339 340 341 342 343 344
	if (!session)
		return;
	LinphonePrivate::MediaSession *mediaSession = dynamic_cast<LinphonePrivate::MediaSession *>(session);
	if (!mediaSession) {
		ms_warning("VFU request but no MediaSession!");
		return;
345
	}
346
	L_GET_PRIVATE(mediaSession)->sendVfu();
347 348
}

Ghislain MARY's avatar
Ghislain MARY committed
349 350 351 352 353 354 355 356 357 358
static void dtmf_received(SalOp *op, char dtmf) {
	LinphonePrivate::CallSession *session = reinterpret_cast<LinphonePrivate::CallSession *>(op->get_user_pointer());
	if (!session)
		return;
	LinphonePrivate::MediaSession *mediaSession = dynamic_cast<LinphonePrivate::MediaSession *>(session);
	if (!mediaSession) {
		ms_warning("DTMF received but no MediaSession!");
		return;
	}
	L_GET_PRIVATE(mediaSession)->dtmfReceived(dtmf);
359 360
}

361 362 363 364 365 366 367 368 369 370 371 372
static void call_refer_received(SalOp *op, const SalAddress *referTo) {
	LinphonePrivate::CallSession *session = reinterpret_cast<LinphonePrivate::CallSession *>(op->get_user_pointer());
	char *addrStr = sal_address_as_string_uri_only(referTo);
	Address referToAddr(addrStr);
	string method;
	if (referToAddr.isValid())
		method = referToAddr.getMethodParam();
	if (session && (method.empty() || (method == "INVITE"))) {
		L_GET_PRIVATE(session)->referred(referToAddr);
	} else {
		LinphoneCore *lc = reinterpret_cast<LinphoneCore *>(op->get_sal()->get_user_pointer());
		linphone_core_notify_refer_received(lc, addrStr);
373
	}
374
	bctbx_free(addrStr);
375 376
}

Ghislain MARY's avatar
Ghislain MARY committed
377
static void message_received(SalOp *op, const SalMessage *msg){
378 379
	LinphoneCore *lc=(LinphoneCore *)op->get_sal()->get_user_pointer();
	LinphoneCall *call=(LinphoneCall*)op->get_user_pointer();
380
	LinphoneReason reason = lc->chat_deny_code;
381 382
	if (reason == LinphoneReasonNone) {
		linphone_core_message_received(lc, op, msg);
383
	}
Sylvain Berfini's avatar
Sylvain Berfini committed
384
	auto messageOp = dynamic_cast<SalMessageOpInterface *>(op);
385 386
	messageOp->reply(linphone_reason_to_sal(reason));
	if (!call) op->release();
387 388
}

389
static void parse_presence_requested(SalOp *op, const char *content_type, const char *content_subtype, const char *body, SalPresenceModel **result) {
390
	linphone_notify_parse_presence(content_type, content_subtype, body, result);
391 392
}

393
static void convert_presence_to_xml_requested(SalOp *op, SalPresenceModel *presence, const char *contact, char **content) {
394
	/*for backward compatibility because still used by notify. No loguer used for publish*/
395

396 397 398
	if(linphone_presence_model_get_presentity((LinphonePresenceModel*)presence) == NULL) {
		LinphoneAddress * presentity = linphone_address_new(contact);
		linphone_presence_model_set_presentity((LinphonePresenceModel*)presence, presentity);
jehan's avatar
jehan committed
399
		linphone_address_unref(presentity);
400 401
	}
	*content = linphone_presence_model_to_xml((LinphonePresenceModel*)presence);
402 403
}

404
static void notify_presence(SalOp *op, SalSubscribeStatus ss, SalPresenceModel *model, const char *msg){
405
	LinphoneCore *lc=(LinphoneCore *)op->get_sal()->get_user_pointer();
406
	linphone_notify_recv(lc,op,ss,model);
407 408
}

409 410
static void subscribe_presence_received(SalPresenceOp *op, const char *from){
	LinphoneCore *lc=(LinphoneCore *)op->get_sal()->get_user_pointer();
411
	linphone_subscription_new(lc,op,from);
412 413
}

414 415
static void subscribe_presence_closed(SalPresenceOp *op, const char *from){
	LinphoneCore *lc=(LinphoneCore *)op->get_sal()->get_user_pointer();
416
	linphone_subscription_closed(lc,op);
417 418
}

419
static void ping_reply(SalOp *op) {
420
	LinphonePrivate::CallSession *session = reinterpret_cast<LinphonePrivate::CallSession *>(op->get_user_pointer());
421 422 423
	if (!session) {
		ms_warning("Ping reply without CallSession attached...");
		return;
Simon Morlat's avatar
Simon Morlat committed
424
	}
425
	L_GET_PRIVATE(session)->pingReply();
426
}
jehan's avatar
jehan committed
427

428
static bool_t fill_auth_info_with_client_certificate(LinphoneCore *lc, SalAuthInfo* sai) {
429 430
	const char *chain_file = linphone_core_get_tls_cert_path(lc);
	const char *key_file = linphone_core_get_tls_key_path(lc);
431

432
	if (key_file && chain_file) {
433
#ifndef _WIN32
434 435 436 437 438 439 440 441 442 443
		// optinal check for files
		struct stat st;
		if (stat(key_file, &st)) {
			ms_warning("No client certificate key found in %s", key_file);
			return FALSE;
		}
		if (stat(chain_file, &st)) {
			ms_warning("No client certificate chain found in %s", chain_file);
			return FALSE;
		}
444
#endif
445 446 447 448 449 450
		sal_certificates_chain_parse_file(sai, chain_file, SAL_CERTIFICATE_RAW_FORMAT_PEM);
		sal_signing_key_parse_file(sai, key_file, "");
	} else if (lc->tls_cert && lc->tls_key) {
		sal_certificates_chain_parse(sai, lc->tls_cert, SAL_CERTIFICATE_RAW_FORMAT_PEM);
		sal_signing_key_parse(sai, lc->tls_key, "");
	}
Simon Morlat's avatar
Simon Morlat committed
451
	return sai->certificates && sai->key;
452 453
}

jehan's avatar
jehan committed
454
static bool_t fill_auth_info(LinphoneCore *lc, SalAuthInfo* sai) {
455 456 457 458 459 460
	LinphoneAuthInfo *ai = NULL;
	if (sai->mode == SalAuthModeTls) {
		ai = (LinphoneAuthInfo*)_linphone_core_find_tls_auth_info(lc);
	} else {
		ai = (LinphoneAuthInfo*)_linphone_core_find_auth_info(lc,sai->realm,sai->username,sai->domain, FALSE);
	}
jehan's avatar
jehan committed
461
	if (ai) {
462
		if (sai->mode == SalAuthModeHttpDigest) {
463 464 465 466 467 468 469 470 471 472 473 474
			/*
			 * Compare algorithm of server(sai) with algorithm of client(ai), if they are not correspondant,
			 * exit. The default algorithm is MD5 if it's NULL.
			 */
			if (sai->algorithm && ai->algorithm) {
				if (strcmp(ai->algorithm, sai->algorithm))
					return TRUE;
			} else if (
				(ai->algorithm && strcmp(ai->algorithm, "MD5")) ||
				(sai->algorithm && strcmp(sai->algorithm, "MD5"))
			)
				return TRUE;
475

476 477 478
			sai->userid = ms_strdup(ai->userid ? ai->userid : ai->username);
			sai->password = ai->passwd?ms_strdup(ai->passwd) : NULL;
			sai->ha1 = ai->ha1 ? ms_strdup(ai->ha1) : NULL;
479 480 481 482 483 484 485 486 487 488 489
		} else if (sai->mode == SalAuthModeTls) {
			if (ai->tls_cert && ai->tls_key) {
				sal_certificates_chain_parse(sai, ai->tls_cert, SAL_CERTIFICATE_RAW_FORMAT_PEM);
				sal_signing_key_parse(sai, ai->tls_key, "");
			} else if (ai->tls_cert_path && ai->tls_key_path) {
				sal_certificates_chain_parse_file(sai, ai->tls_cert_path, SAL_CERTIFICATE_RAW_FORMAT_PEM);
				sal_signing_key_parse_file(sai, ai->tls_key_path, "");
			} else {
				fill_auth_info_with_client_certificate(lc, sai);
			}
		}
490

491 492 493 494 495
		if (sai->realm && !ai->realm){
			/*if realm was not known, then set it so that ha1 may eventually be calculated and clear text password dropped*/
			linphone_auth_info_set_realm(ai, sai->realm);
			linphone_core_write_auth_info(lc, ai);
		}
jehan's avatar
jehan committed
496 497
		return TRUE;
	} else {
498 499 500
		if (sai->mode == SalAuthModeTls) {
			return fill_auth_info_with_client_certificate(lc, sai);
		}
jehan's avatar
jehan committed
501 502 503
		return FALSE;
	}
}
jehan's avatar
jehan committed
504
static bool_t auth_requested(Sal* sal, SalAuthInfo* sai) {
505
	LinphoneCore *lc = (LinphoneCore *)sal->get_user_pointer();
506 507 508 509
	if (fill_auth_info(lc,sai)) {
		return TRUE;
	} else {
		LinphoneAuthMethod method = sai->mode == SalAuthModeHttpDigest ? LinphoneAuthHttpDigest : LinphoneAuthTls;
510 511
		LinphoneAuthInfo *ai = linphone_core_create_auth_info(lc, sai->username, NULL, NULL, NULL, sai->realm, sai->domain);
		linphone_core_notify_authentication_requested(lc, ai, method);
Ghislain MARY's avatar
Ghislain MARY committed
512
		linphone_auth_info_unref(ai);
513 514
		// Deprecated
		linphone_core_notify_auth_info_requested(lc, sai->realm, sai->username, sai->domain);
515
		if (fill_auth_info(lc, sai)) {
516
			return TRUE;
jehan's avatar
jehan committed
517 518 519 520
		}
		return FALSE;
	}
}
521

522 523 524 525 526
static void notify_refer(SalOp *op, SalReferStatus status) {
	LinphonePrivate::CallSession *session = reinterpret_cast<LinphonePrivate::CallSession *>(op->get_user_pointer());
	if (!session) {
		ms_warning("Receiving notify_refer for unknown CallSession");
		return;
527
	}
528
	LinphonePrivate::CallSession::State cstate;
529
	switch (status) {
530
		case SalReferTrying:
531
			cstate = LinphonePrivate::CallSession::State::OutgoingProgress;
532
			break;
533
		case SalReferSuccess:
534
			cstate = LinphonePrivate::CallSession::State::Connected;
535
			break;
536 537
		case SalReferFailed:
		default:
538
			cstate = LinphonePrivate::CallSession::State::Error;
539
			break;
540
	}
541
	L_GET_PRIVATE(session)->setTransferState(cstate);
542
	if (cstate == LinphonePrivate::CallSession::State::Connected)
543
		session->terminate(); // Automatically terminate the call as the transfer is complete
544 545
}

Ghislain MARY's avatar
Ghislain MARY committed
546
static LinphoneChatMessageState chatStatusSal2Linphone(SalMessageDeliveryStatus status){
547
	switch(status){
Ghislain MARY's avatar
Ghislain MARY committed
548
		case SalMessageDeliveryInProgress:
549
			return LinphoneChatMessageStateInProgress;
Ghislain MARY's avatar
Ghislain MARY committed
550
		case SalMessageDeliveryDone:
551
			return LinphoneChatMessageStateDelivered;
Ghislain MARY's avatar
Ghislain MARY committed
552
		case SalMessageDeliveryFailed:
553 554 555 556 557
			return LinphoneChatMessageStateNotDelivered;
	}
	return LinphoneChatMessageStateIdle;
}

Ghislain MARY's avatar
Ghislain MARY committed
558
static void message_delivery_update(SalOp *op, SalMessageDeliveryStatus status){
559
	LinphoneChatMessage *chat_msg=(LinphoneChatMessage* )op->get_user_pointer();
560 561 562 563 564

	if (chat_msg == NULL) {
		// Do not handle delivery status for isComposing messages.
		return;
	}
565
	// check that the message does not belong to an already destroyed chat room - if so, do not invoke callbacks
566
	if (linphone_chat_message_get_chat_room(chat_msg) != NULL) {
567
		linphone_chat_message_update_state(chat_msg, chatStatusSal2Linphone(status));
568 569 570
	}
}

571 572 573 574 575
static void info_received(SalOp *op, SalBodyHandler *body_handler) {
	LinphonePrivate::CallSession *session = reinterpret_cast<LinphonePrivate::CallSession *>(op->get_user_pointer());
	if (!session)
		return;
	L_GET_PRIVATE(session)->infoReceived(body_handler);
Simon Morlat's avatar
Simon Morlat committed
576 577
}

578
static void subscribe_response(SalOp *op, SalSubscribeStatus status, int will_retry){
579
	LinphoneEvent *lev=(LinphoneEvent*)op->get_user_pointer();
580

581
	if (lev==NULL) return;
582

583 584 585 586 587
	if (status==SalSubscribeActive){
		linphone_event_set_state(lev,LinphoneSubscriptionActive);
	}else if (status==SalSubscribePending){
		linphone_event_set_state(lev,LinphoneSubscriptionPending);
	}else{
588
		if (will_retry){
Simon Morlat's avatar
Simon Morlat committed
589 590 591
			linphone_event_set_state(lev,LinphoneSubscriptionOutgoingProgress);
		}
		else linphone_event_set_state(lev,LinphoneSubscriptionError);
592 593 594
	}
}

595 596 597
static void notify(SalSubscribeOp *op, SalSubscribeStatus st, const char *eventname, SalBodyHandler *body_handler){
	LinphoneEvent *lev=(LinphoneEvent*)op->get_user_pointer();
	LinphoneCore *lc=(LinphoneCore *)op->get_sal()->get_user_pointer();
598 599
	bool_t out_of_dialog = (lev==NULL);
	if (out_of_dialog) {
600 601
		/*out of dialog notify */
		lev = linphone_event_new_with_out_of_dialog_op(lc,op,LinphoneSubscriptionOutgoing,eventname);
602
	}
603
	{
604
		LinphoneContent *ct=linphone_content_from_sal_body_handler(body_handler);
Ghislain MARY's avatar
Ghislain MARY committed
605 606 607 608
		if (ct) {
			linphone_core_notify_notify_received(lc,lev,eventname,ct);
			linphone_content_unref(ct);
		}
609
	}
610 611 612
	if (out_of_dialog){
		/*out of dialog NOTIFY do not create an implicit subscription*/
		linphone_event_set_state(lev, LinphoneSubscriptionTerminated);
613
	}else if (st!=SalSubscribeNone){
614 615 616 617
		linphone_event_set_state(lev,linphone_subscription_state_from_sal(st));
	}
}

618 619 620
static void subscribe_received(SalSubscribeOp *op, const char *eventname, const SalBodyHandler *body_handler){
	LinphoneEvent *lev=(LinphoneEvent*)op->get_user_pointer();
	LinphoneCore *lc=(LinphoneCore *)op->get_sal()->get_user_pointer();
621

622
	if (lev==NULL) {
Simon Morlat's avatar
Simon Morlat committed
623
		lev=linphone_event_new_with_op(lc,op,LinphoneSubscriptionIncoming,eventname);
624 625 626 627
		linphone_event_set_state(lev,LinphoneSubscriptionIncomingReceived);
	}else{
		/*subscribe refresh, unhandled*/
	}
628

629 630
}

631
static void incoming_subscribe_closed(SalOp *op){
632
	LinphoneEvent *lev=(LinphoneEvent*)op->get_user_pointer();
633

634 635 636
	linphone_event_set_state(lev,LinphoneSubscriptionTerminated);
}

637
static void on_publish_response(SalOp* op){
638 639
	LinphoneEvent *lev=(LinphoneEvent*)op->get_user_pointer();
	const SalErrorInfo *ei=op->get_error_info();
640

641
	if (lev==NULL) return;
642
	if (ei->reason==SalReasonNone){
643 644
		if (!lev->terminating)
			linphone_event_set_publish_state(lev,LinphonePublishOk);
645
		else
646 647
			linphone_event_set_publish_state(lev,LinphonePublishCleared);
	}else{
Simon Morlat's avatar
Simon Morlat committed
648 649 650 651 652
		if (lev->publish_state==LinphonePublishOk){
			linphone_event_set_publish_state(lev,LinphonePublishProgress);
		}else{
			linphone_event_set_publish_state(lev,LinphonePublishError);
		}
653 654 655
	}
}

656

657
static void on_expire(SalOp *op){
658
	LinphoneEvent *lev=(LinphoneEvent*)op->get_user_pointer();
659

660
	if (lev==NULL) return;
661

662 663
	if (linphone_event_get_publish_state(lev)==LinphonePublishOk){
		linphone_event_set_publish_state(lev,LinphonePublishExpiring);
664 665
	}else if (linphone_event_get_subscription_state(lev)==LinphoneSubscriptionActive){
		linphone_event_set_state(lev,LinphoneSubscriptionExpiring);
666 667 668
	}
}

669
static void on_notify_response(SalOp *op){
670
	LinphoneEvent *lev=(LinphoneEvent*)op->get_user_pointer();
671 672 673 674 675 676

	if (lev==NULL) return;
	/*this is actually handling out of dialogs notify - for the moment*/
	if (!lev->is_out_of_dialog_op) return;
	switch (linphone_event_get_subscription_state(lev)){
		case LinphoneSubscriptionIncomingReceived:
677
			if (op->get_error_info()->reason == SalReasonNone){
678 679 680 681 682 683 684 685 686 687
				linphone_event_set_state(lev, LinphoneSubscriptionTerminated);
			}else{
				linphone_event_set_state(lev, LinphoneSubscriptionError);
			}
		break;
		default:
			ms_warning("Unhandled on_notify_response() case %s", linphone_subscription_state_to_string(linphone_event_get_subscription_state(lev)));
	}
}

688
static void refer_received(SalOp *op, const SalAddress *refer_to){
689
	if (sal_address_has_param(refer_to, "text")) {
690 691 692
		char *refer_uri = sal_address_as_string(refer_to);
		LinphonePrivate::Address addr(refer_uri);
		bctbx_free(refer_uri);
693 694
		if (addr.isValid()) {
			LinphoneCore *lc = reinterpret_cast<LinphoneCore *>(op->get_sal()->get_user_pointer());
695
			if (addr.hasUriParam("method") && (addr.getUriParamValue("method") == "BYE")) {
696 697
				if (linphone_core_conference_server_enabled(lc)) {
					// Removal of a participant at the server side
698
					shared_ptr<AbstractChatRoom> chatRoom = L_GET_CPP_PTR_FROM_C_OBJECT(lc)->findChatRoom(
699
						ChatRoomId(IdentityAddress(op->get_to()), IdentityAddress(op->get_to()))
700
					);
701
					if (chatRoom) {
702
						std::shared_ptr<Participant> participant = chatRoom->findParticipant(IdentityAddress(op->get_from()));
703 704 705 706
						if (!participant || !participant->isAdmin()) {
							static_cast<SalReferOp *>(op)->reply(SalReasonDeclined);
							return;
						}
707
						participant = chatRoom->findParticipant(addr);
708
						if (participant)
709
							chatRoom->removeParticipant(participant);
710 711 712 713 714
						static_cast<SalReferOp *>(op)->reply(SalReasonNone);
						return;
					}
				} else {
					// The server asks a participant to leave a chat room
715
					LinphoneChatRoom *cr = L_GET_C_BACK_PTR(
716
						L_GET_CPP_PTR_FROM_C_OBJECT(lc)->findChatRoom(ChatRoomId(addr, IdentityAddress(op->get_to())))
717
					);
718 719 720 721 722 723
					if (cr) {
						L_GET_CPP_PTR_FROM_C_OBJECT(cr)->leave();
						static_cast<SalReferOp *>(op)->reply(SalReasonNone);
						return;
					}
					static_cast<SalReferOp *>(op)->reply(SalReasonDeclined);
724 725
				}
			} else if (addr.hasParam("admin")) {
726
				LinphoneChatRoom *cr = L_GET_C_BACK_PTR(L_GET_CPP_PTR_FROM_C_OBJECT(lc)->findChatRoom(
727
					ChatRoomId(IdentityAddress(op->get_to()), IdentityAddress(op->get_to()))
728
				));
729
				if (cr) {
730 731 732 733 734 735 736
					Address fromAddr(op->get_from());
					std::shared_ptr<Participant> participant = L_GET_CPP_PTR_FROM_C_OBJECT(cr)->findParticipant(fromAddr);
					if (!participant || !participant->isAdmin()) {
						static_cast<SalReferOp *>(op)->reply(SalReasonDeclined);
						return;
					}
					participant = L_GET_CPP_PTR_FROM_C_OBJECT(cr)->findParticipant(addr);
737 738 739 740 741 742 743 744
					if (participant) {
						bool value = Utils::stob(addr.getParamValue("admin"));
						L_GET_CPP_PTR_FROM_C_OBJECT(cr)->setParticipantAdminStatus(participant, value);
					}
					static_cast<SalReferOp *>(op)->reply(SalReasonNone);
					return;
				}
			} else {
745
				LinphoneChatRoom *cr = L_GET_C_BACK_PTR(L_GET_CPP_PTR_FROM_C_OBJECT(lc)->findChatRoom(ChatRoomId(addr, IdentityAddress(op->get_to()))));
746
				if (!cr)
747
					cr = _linphone_client_group_chat_room_new(lc, addr.asString().c_str(), nullptr, FALSE);
748 749 750
				L_GET_CPP_PTR_FROM_C_OBJECT(cr)->join();
				static_cast<SalReferOp *>(op)->reply(SalReasonNone);
				return;
751 752 753 754
			}
		}
	}
	static_cast<SalReferOp *>(op)->reply(SalReasonDeclined);
755