forked from linuxdeepin/ddm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDisplay.cpp
More file actions
429 lines (364 loc) · 15.4 KB
/
Display.cpp
File metadata and controls
429 lines (364 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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
190
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
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
/***************************************************************************
* Copyright (c) 2014-2015 Pier Luigi Fiorini <pierluigi.fiorini@gmail.com>
* Copyright (c) 2014 Martin Bříza <mbriza@redhat.com>
* Copyright (c) 2013 Abdurrahman AVCI <abdurrahmanavci@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
***************************************************************************/
#include "Display.h"
#include "Auth.h"
#include "Configuration.h"
#include "DaemonApp.h"
#include "DisplayManager.h"
#include "Messages.h"
#include "SeatManager.h"
#include "SocketServer.h"
#include "SocketWriter.h"
#include "TreelandConnector.h"
#include "TreelandDisplayServer.h"
#include "XorgDisplayServer.h"
#include "config.h"
#include "Login1Manager.h"
#include "VirtualTerminal.h"
#include <QDBusConnection>
#include <QDebug>
#include <QFile>
#include <QLocalSocket>
#include <QScopeGuard>
#include <QTimer>
#include <fcntl.h>
#include <linux/vt.h>
#include <pwd.h>
#include <qstringliteral.h>
#include <systemd/sd-login.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <unistd.h>
#define STRINGIFY(x) #x
namespace DDM {
static bool isTtyInUse(const QString &desiredTty) {
char **sessions = nullptr;
auto guard = qScopeGuard([&sessions] {
if (sessions) {
for (char **s = sessions; s && *s; ++s)
free(*s);
free(sessions);
}
});
sd_get_sessions(&sessions);
for (char **s = sessions; s && *s; ++s) {
char *tty = nullptr;
char *state = nullptr;
auto guard2 = qScopeGuard([&tty, &state] {
if (tty)
free(tty);
if (state)
free(state);
});
if (sd_session_get_tty(*s, &tty) < 0 || sd_session_get_state(*s, &state) < 0)
continue;
if (desiredTty == tty && strcmp(state, "closing") != 0) {
qDebug() << "tty" << desiredTty << "already in use by session" << *s;
return true;
}
}
return false;
}
static int fetchAvailableVt() {
if (!isTtyInUse(QStringLiteral("tty" STRINGIFY(DDM_INITIAL_VT)))) {
return DDM_INITIAL_VT;
}
const auto vt = VirtualTerminal::currentVt();
if (vt > 0 && !isTtyInUse(QStringLiteral("tty%1").arg(vt))) {
return vt;
}
return VirtualTerminal::setUpNewVt();
}
Display::Display(SeatManager *parent, QString name)
: QObject(parent)
, name(name)
, m_socketServer(new SocketServer(this)) {
// Create display server
terminalId = fetchAvailableVt();
qDebug("Using VT %d", terminalId);
m_treeland = new TreelandDisplayServer(m_socketServer, this);
// Record current VT as ddm user session
DaemonApp::instance()->displayManager()->AddSession(
{},
name,
"dde",
static_cast<uint>(VirtualTerminal::currentVt()));
// connect connected signal
connect(m_socketServer, &SocketServer::connected, this, &Display::connected);
// connect login signal
connect(m_socketServer, &SocketServer::login, this, &Display::login);
// connect logout signal
connect(m_socketServer, &SocketServer::logout, this, &Display::logout);
// connect lock signal
connect(m_socketServer, &SocketServer::lock, this, &Display::lock);
// connect unlock signal
connect(m_socketServer, &SocketServer::unlock,this, &Display::unlock);
// connect login result signals
connect(this, &Display::loginFailed, m_socketServer, &SocketServer::loginFailed);
}
Display::~Display() {
stop();
}
void Display::activateSession(const QString &user, int xdgSessionId) {
if (xdgSessionId <= 0 && user != QStringLiteral("dde")) {
qCritical() << "Invalid xdg session id" << xdgSessionId << "for user" << user;
return;
}
m_treeland->activateUser(user, xdgSessionId);
if (xdgSessionId > 0 && Logind::isAvailable()) {
OrgFreedesktopLogin1ManagerInterface manager(Logind::serviceName(), Logind::managerPath(), QDBusConnection::systemBus());
manager.ActivateSession(QString::number(xdgSessionId));
}
}
bool Display::start() {
if (m_started)
return true;
VirtualTerminal::jumpToVt(terminalId, false);
if (!m_treeland->start())
return false;
// start socket server
m_socketServer->start("treeland");
// Update dbus info
DaemonApp::instance()->displayManager()->setAuthInfo(m_socketServer->socketAddress());
// change the owner and group of the socket to avoid permission denied errors
struct passwd *pw = getpwnam("dde");
if (pw && chown(qPrintable(m_socketServer->socketAddress()), pw->pw_uid, pw->pw_gid) == -1)
qWarning() << "Failed to change owner of the socket";
// set flags
m_started = true;
return true;
}
void Display::stop() {
// check flag
if (!m_started)
return;
for (auto *auth : std::as_const(auths)) {
disconnect(auth, &Auth::sessionFinished, nullptr, nullptr);
delete auth;
}
auths.clear();
// stop socket server
m_socketServer->stop();
if (m_x11Server)
m_x11Server->stop();
// stop display server
m_treeland->stop();
// reset flag
m_started = false;
// emit signal
emit stopped();
}
void Display::connected(QLocalSocket *socket) {
// send logged in users (for possible crash recovery)
SocketWriter writer(socket);
for (Auth *auth : std::as_const(auths)) {
if (auth->sessionOpened)
writer << quint32(DaemonMessages::UserLoggedIn) << auth->user << auth->xdgSessionId;
}
}
void Display::login(QLocalSocket *socket,
const QString &user, const QString &password,
const Session &session) {
if (user == QLatin1String("dde")) {
qWarning() << "Login attempt for user dde";
emit loginFailed(socket, user);
return;
}
qInfo() << "Start login for user" << user;
// Get Auth object
Auth *auth = nullptr;
for (auto *item : std::as_const(auths)) {
if (item->user == user) {
auth = item;
break;
}
}
if (!auth)
auth = new Auth(this, user);
if (auth->authenticated) {
qWarning() << "Existing authentication ongoing, aborting";
return;
}
// sanity check
if (!session.isValid()) {
qCritical() << "Invalid session" << session.fileName();
return;
}
if (session.xdgSessionType().isEmpty()) {
qCritical() << "Failed to find XDG session type for session" << session.fileName();
return;
}
if (session.exec().isEmpty()) {
qCritical() << "Failed to find command for session" << session.fileName();
return;
}
// Run password check
if (session.isSingleMode())
auth->tty = VirtualTerminal::setUpNewVt();
else
auth->tty = terminalId;
if (!auth->authenticate(password.toLocal8Bit())) {
Q_EMIT loginFailed(socket, user);
return;
}
// some information
qInfo() << "Authentication succeeded for user" << user << ", opening session"
<< session.fileName() << ", command:" << session.exec() << ", VT:" << auth->tty;
// save last user and last session
DaemonApp::instance()->displayManager()->setLastActivatedUser(user);
if (mainConfig.Users.RememberLastUser.get())
stateConfig.Last.User.set(auth->user);
else
stateConfig.Last.User.setDefault();
if (mainConfig.Users.RememberLastSession.get())
stateConfig.Last.Session.set(session.fileName());
else
stateConfig.Last.Session.setDefault();
stateConfig.save();
// Prepare session environment
QProcessEnvironment env;
env.insert(session.additionalEnv());
// session id
const QString sessionId = QStringLiteral("Session%1").arg(daemonApp->newSessionId());
env.insert(QStringLiteral("XDG_SESSION_PATH"), daemonApp->displayManager()->sessionPath(sessionId));
auth->sessionId = sessionId;
env.insert(QStringLiteral("PATH"), mainConfig.Users.DefaultPath.get());
env.insert(QStringLiteral("DESKTOP_SESSION"), session.desktopSession());
if (!session.desktopNames().isEmpty())
env.insert(QStringLiteral("XDG_CURRENT_DESKTOP"), session.desktopNames());
env.insert(QStringLiteral("XDG_SESSION_CLASS"), QStringLiteral("user"));
env.insert(QStringLiteral("XDG_SESSION_TYPE"), session.xdgSessionType());
env.insert(QStringLiteral("XDG_VTNR"), QString::number(auth->tty));
env.insert(QStringLiteral("XDG_SEAT"), name);
env.insert(QStringLiteral("XDG_SEAT_PATH"), daemonApp->displayManager()->seatPath(name));
env.insert(QStringLiteral("XDG_SESSION_DESKTOP"), session.desktopNames());
// Special preparation for each display server type
//
// TODO: Let Treeland drop DRM master when inactive, so that X
// server and other Wayland compositor can co-exist with
// greeter (the Treeland)
QByteArray cookie;
if (session.isSingleMode()) {
auth->type = Treeland;
env.insert("DDE_CURRENT_COMPOSITOR", "TreeLand");
} else if (session.xdgSessionType() == QLatin1String("x11")) {
auth->type = X11;
qInfo() << "Stopping Treeland";
daemonApp->treelandConnector()->disconnect();
m_treeland->stop();
QThread::msleep(500); // give some time to treeland to stop properly
// Start X server
qInfo() << "Starting X11 display server";
m_x11Server = new XorgDisplayServer(this);
connect(m_x11Server, &XorgDisplayServer::stopped, this, &Display::stop);
if (!m_x11Server->start(auth->tty)) {
qCritical() << "Failed to start X11 display server";
return;
}
m_x11Server->setupDisplay();
auth->display = m_x11Server->display;
env.insert(QStringLiteral("DISPLAY"), m_x11Server->display);
cookie = m_x11Server->cookie();
} else {
auth->type = Wayland;
qInfo() << "Stopping Treeland";
daemonApp->treelandConnector()->disconnect();
m_treeland->stop();
QThread::msleep(500); // give some time to treeland to stop properly
}
// Open Logind session & Exec the desktop process
int xdgSessionId = auth->openSession(session.exec(), env, cookie);
if (xdgSessionId <= 0) {
qCritical() << "Failed to open logind session for user" << user;
delete auth;
return;
}
connect(auth, &Auth::sessionFinished, this, [this, auth]() {
qWarning() << "Session for user" << auth->user << "finished";
auths.removeAll(auth);
daemonApp->displayManager()->RemoveSession(auth->sessionId);
delete auth;
});
daemonApp->displayManager()->AddSession(sessionId, name, user, auth->tty);
daemonApp->displayManager()->setLastSession(sessionId);
// The user process is ongoing, append to active auths
// The auth will be delete later in userProcessFinished()
auths << auth;
qInfo() << "Successfully logged in user" << user;
}
void Display::logout([[maybe_unused]] QLocalSocket *socket, int id) {
qDebug() << "Logout requested for session id" << id;
// Do not kill the session leader process before
// TerminateSession! Logind will only kill the session's
// cgroup (session_stop_scope) when the session is not in
// "stopping" state, killing the session leader beforehand
// will put the session in "stopping" early.
// https://github.com/systemd/systemd/blob/main/src/login/logind-session.c#L938
OrgFreedesktopLogin1ManagerInterface manager(Logind::serviceName(),
Logind::managerPath(),
QDBusConnection::systemBus());
manager.TerminateSession(QString::number(id));
}
void Display::lock([[maybe_unused]] QLocalSocket *socket, int id) {
qDebug() << "Lock requested for session id" << id;
OrgFreedesktopLogin1ManagerInterface manager(Logind::serviceName(),
Logind::managerPath(),
QDBusConnection::systemBus());
manager.LockSession(QString::number(id));
}
void Display::unlock(QLocalSocket *socket, const QString &user, const QString &password) {
if (user == QLatin1String("dde")) {
emit loginFailed(socket, user);
return;
}
qInfo() << "Start identify user" << user;
// Only run password check
//
// No user process execution, so the auth can be thrown away
// immediately after use
Auth auth(this, user);
if (!auth.authenticate(password.toLocal8Bit())) {
Q_EMIT loginFailed(socket, user);
return;
}
// Save last user
DaemonApp::instance()->displayManager()->setLastActivatedUser(user);
if (mainConfig.Users.RememberLastUser.get())
stateConfig.Last.User.set(user);
else
stateConfig.Last.User.setDefault();
stateConfig.save();
// Find the auth that started the session, which contains full informations
for (auto *auth : std::as_const(auths)) {
if (auth->user == user && auth->xdgSessionId > 0) {
OrgFreedesktopLogin1ManagerInterface manager(Logind::serviceName(),
Logind::managerPath(),
QDBusConnection::systemBus());
manager.UnlockSession(QString::number(auth->xdgSessionId));
VirtualTerminal::jumpToVt(auth->tty, false);
qInfo() << "Successfully identified user" << user;
return;
}
}
qWarning() << "No active session found for user" << user;
Q_EMIT loginFailed(socket, user);
}
}