File: LinuxSessionFunctions.cpp

package info (click to toggle)
veyon 4.9.7%2Brepack1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 14,028 kB
  • sloc: cpp: 52,043; ansic: 7,307; python: 228; makefile: 222; sh: 48
file content (492 lines) | stat: -rw-r--r-- 11,885 bytes parent folder | download | duplicates (2)
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
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
482
483
484
485
486
487
488
489
490
491
492
/*
 * LinuxSessionFunctions.cpp - implementation of LinuxSessionFunctions class
 *
 * Copyright (c) 2020-2025 Tobias Junghans <tobydox@veyon.io>
 *
 * This file is part of Veyon - https://veyon.io
 *
 * 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 (see COPYING); if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 */

#include <QCoreApplication>
#include <QDateTime>
#include <QDBusReply>
#include <QHostInfo>
#include <QProcessEnvironment>
#include <QSettings>

#ifdef HAVE_LIBPROCPS
#include <proc/readproc.h>
#endif

#include "LinuxCoreFunctions.h"
#include "LinuxSessionFunctions.h"
#include "PlatformSessionManager.h"


LinuxSessionFunctions::SessionId LinuxSessionFunctions::currentSessionId()
{
	return PlatformSessionManager::resolveSessionId( currentSessionPath() );
}



LinuxSessionFunctions::SessionUptime LinuxSessionFunctions::currentSessionUptime() const
{
	return getSessionUptimeSeconds(currentSessionPath());
}



QString LinuxSessionFunctions::currentSessionClientAddress() const
{
	return getSessionProperty(currentSessionPath(), QStringLiteral("RemoteHost")).toString();
}



QString LinuxSessionFunctions::currentSessionClientName() const
{
	return currentSessionClientAddress();
}



QString LinuxSessionFunctions::currentSessionHostName() const
{
	return QHostInfo::localHostName();
}



QString LinuxSessionFunctions::currentSessionType() const
{
	const auto env = QProcessEnvironment::systemEnvironment();

	if( env.contains( QStringLiteral("WAYLAND_DISPLAY") ) )
	{
		return QStringLiteral("wayland");
	}
	else if( env.contains( QStringLiteral("DISPLAY") ) )
	{
		return QStringLiteral("x11");
	}

	return getSessionProperty( currentSessionPath(), QStringLiteral("Type") ).toString();
}



bool LinuxSessionFunctions::currentSessionHasUser() const
{
	return getSessionClass( currentSessionPath() ) == Class::User;
}



LinuxSessionFunctions::EnvironmentVariables LinuxSessionFunctions::currentSessionEnvironmentVariables() const
{
	const auto sessionLeader = getSessionLeaderPid(currentSessionPath());
	auto sessionEnv = getSessionEnvironment(sessionLeader);
	if (sessionEnv.isEmpty())
	{
		sessionEnv = QProcessEnvironment::systemEnvironment();
	}
	const auto sessionEnvVars = sessionEnv.keys();

	EnvironmentVariables envVars;
	for (const auto& sessionEnvVar : sessionEnvVars)
	{
		envVars[sessionEnvVar] = sessionEnv.value(sessionEnvVar);
	}

	return envVars;
}



QVariant LinuxSessionFunctions::querySettingsValueInCurrentSession(const QString& key) const
{
	return QSettings(QSettings::UserScope, QCoreApplication::organizationName(), QCoreApplication::applicationName()).value(key);
}



QStringList LinuxSessionFunctions::listSessions()
{
	QStringList sessions;

	const QDBusReply<QDBusArgument> reply = LinuxCoreFunctions::systemdLoginManager()->call( QStringLiteral("ListSessions") );

	if( reply.isValid() )
	{
		const auto data = reply.value();

		data.beginArray();
		while( data.atEnd() == false )
		{
			LoginDBusSession session;

			data.beginStructure();
			data >> session.id >> session.uid >> session.name >> session.seatId >> session.path;
			data.endStructure();

			sessions.append( session.path.path() );
		}
		return sessions;
	}

	vCritical() << "Could not query sessions:" << reply.error().message();

	return sessions;
}



QVariant LinuxSessionFunctions::getSessionProperty(const QString& session, const QString& property, bool logErrors)
{
	QDBusInterface loginManager( QStringLiteral("org.freedesktop.login1"),
								 session,
								 QStringLiteral("org.freedesktop.DBus.Properties"),
								 QDBusConnection::systemBus() );

	if (loginManager.connection().isConnected() == false)
	{
		vDebug() << "system bus not connected";
		return {};
	}

	const QDBusReply<QDBusVariant> reply = loginManager.call( QStringLiteral("Get"),
															  QStringLiteral("org.freedesktop.login1.Session"),
															  property );

	if( reply.isValid() == false )
	{
		if (logErrors)
		{
			vCritical() << "Could not query property" << property
						<< "of session" << session
						<< "error:" << reply.error().message();
		}
		return {};
	}

	return reply.value().variant();
}



int LinuxSessionFunctions::getSessionLeaderPid( const QString& session )
{
	const auto leader = getSessionProperty( session, QStringLiteral("Leader") );

	if( leader.isNull() )
	{
		return -1;
	}

	return leader.toInt();
}



LinuxSessionFunctions::SessionUptime LinuxSessionFunctions::getSessionUptimeSeconds( const QString& session )
{
	const auto sessionUptimeUsec = getSessionProperty( session, QStringLiteral("Timestamp") );

	if( sessionUptimeUsec.isNull() )
	{
		return -1;
	}

#if QT_VERSION < QT_VERSION_CHECK(5, 8, 0)
	const auto currentTimestamp = QDateTime::currentMSecsSinceEpoch() / 1000;
#else
	const auto currentTimestamp = QDateTime::currentSecsSinceEpoch();
#endif

	return SessionUptime(currentTimestamp - sessionUptimeUsec.toLongLong() / (1000 * 1000));
}



LinuxSessionFunctions::Class LinuxSessionFunctions::getSessionClass( const QString& session )
{
	auto sessionClass = getSessionProperty(session, QStringLiteral("Class")).toString();
	if (sessionClass.isEmpty() && session == currentSessionPath())
	{
		sessionClass = QProcessEnvironment::systemEnvironment().value(LinuxSessionFunctions::xdgSessionClassEnvVarName());
	}

	if( sessionClass == QLatin1String("user") )
	{
		return Class::User;
	}
	else if( sessionClass == QLatin1String("greeter") )
	{
		return Class::Greeter;
	}
	else if( sessionClass == QLatin1String("lock-screen") )
	{
		return Class::LockScreen;
	}

	return Class::Unknown;
}



LinuxSessionFunctions::Type LinuxSessionFunctions::getSessionType( const QString& session )
{
	const auto type = getSessionProperty( session, QStringLiteral("Type") ).toString();
	if( type == QLatin1String("tty") )
	{
		return Type::TTY;
	}
	else if( type == QLatin1String("x11") )
	{
		return Type::X11;
	}
	else if( type == QLatin1String("mir") )
	{
		return Type::Mir;
	}
	else if( type == QLatin1String("wayland") )
	{
		return Type::Wayland;
	}
	else if (type == QLatin1String("unspecified"))
	{
		return Type::Unspecified;
	}

	if( type.isEmpty() == false )
	{
		vWarning() << "unknown session type" << type;
	}

	return Type::Unspecified;
}



QString LinuxSessionFunctions::getSessionId(const QString& session, bool logErrors)
{
	return getSessionProperty(session, QStringLiteral("Id"), logErrors).toString();
}



QString LinuxSessionFunctions::getSessionUser(const QString& session)
{
	quint32 uid{0};
	QString userObjectPath;

	const auto reply = getSessionProperty(session, QStringLiteral("User"));
	if (reply.isValid())
	{
		const auto replyData = reply.value<QDBusArgument>();
		replyData.beginStructure();
		replyData >> uid >> userObjectPath;
		replyData.endStructure();

		return userObjectPath;
	}

	return {};
}



LinuxSessionFunctions::State LinuxSessionFunctions::getSessionState( const QString& session )
{
	static const QMap<QString, State> stateMap{
		{ QStringLiteral("offline"), State::Offline },
		{ QStringLiteral("lingering"), State::Lingering },
		{ QStringLiteral("online"), State::Online },
		{ QStringLiteral("active"), State::Active },
		{ QStringLiteral("opening"), State::Opening },
		{ QStringLiteral("closing"), State::Closing }
	};

	const auto stateString = getSessionProperty( session, QStringLiteral("State") ).toString();
	const auto state = stateMap.value( stateString, State::Unknown );
	if( state == State::Unknown && stateString.isEmpty() == false )
	{
		vDebug() << stateString;
	}

	return state;
}



LinuxSessionFunctions::LoginDBusSessionSeat LinuxSessionFunctions::getSessionSeat( const QString& session )
{
	const auto seatArgument = getSessionProperty( session, QStringLiteral("Seat") ).value<QDBusArgument>();

	LoginDBusSessionSeat seat;
	seatArgument.beginStructure();
	seatArgument >> seat.id;
	seatArgument >> seat.path;
	seatArgument.endStructure();

	return seat;
}



QProcessEnvironment LinuxSessionFunctions::getSessionEnvironment( int sessionLeaderPid )
{
	QProcessEnvironment sessionEnv;

#ifdef HAVE_LIBPROCPS
	LinuxCoreFunctions::forEachChildProcess(
		[&sessionEnv]( proc_t* procInfo ) {
			if( procInfo->environ != nullptr )
			{
				for( int i = 0; procInfo->environ[i]; ++i )
				{
					const auto env = QString::fromUtf8( procInfo->environ[i] );
					const auto separatorPos = env.indexOf( QLatin1Char('=') );
					if( separatorPos > 0 )
					{
						sessionEnv.insert( env.left( separatorPos ), env.mid( separatorPos+1 ) );
					}
				}

				return true;
			}

			return false;
		},
		sessionLeaderPid, PROC_FILLENV, true );
#elif defined(HAVE_LIBPROC2)
	LinuxCoreFunctions::forEachChildProcess([&sessionEnv](const pids_stack* stack)
	{
		static constexpr auto EnvironItemIndex = 2;
		const auto environ = PIDS_VAL(EnvironItemIndex, strv, stack);

		if (environ != nullptr)
		{
			for (int i = 0; environ[i]; ++i)
			{
				const auto env = QString::fromUtf8(environ[i]);
				const auto separatorPos = env.indexOf(QLatin1Char('='));
				if (separatorPos > 0)
				{
					sessionEnv.insert(env.left(separatorPos), env.mid(separatorPos+1));
				}
			}

			return true;
		}

		return false;
	},
	sessionLeaderPid, {PIDS_ENVIRON_V}, true);
#endif

	return sessionEnv;
}



QString LinuxSessionFunctions::currentSessionPath(bool ignoreErrors)
{
	const auto xdgSessionPath = QProcessEnvironment::systemEnvironment().value( sessionPathEnvVarName() );
	if (xdgSessionPath.isEmpty() == false)
	{
		return xdgSessionPath;
	}

	const auto sessionAuto = QStringLiteral("/org/freedesktop/login1/session/auto");
	const auto sessionSelf = QStringLiteral("/org/freedesktop/login1/session/self"); // systemd < 243
	static QString sessionPathFromXdgSessionId;

	static bool hasSessionAuto = false;
	static bool hasSessionSelf = false;

	if (hasSessionAuto)
	{
		return sessionAuto;
	}

	if (hasSessionSelf)
	{
		return sessionSelf;
	}

	if (sessionPathFromXdgSessionId.isEmpty() == false)
	{
		return sessionPathFromXdgSessionId;
	}

	if (getSessionId(sessionAuto, false).isNull() == false)
	{
		hasSessionAuto = true;
		return sessionAuto;
	}

	if (getSessionId(sessionSelf, false).isNull() == false)
	{
		hasSessionSelf = true;
		return sessionSelf;
	}

	const auto xdgSessionId = QProcessEnvironment::systemEnvironment().value(xdgSessionIdEnvVarName());
	if (xdgSessionId.isEmpty() == false)
	{
		const QDBusReply<QDBusObjectPath> reply = LinuxCoreFunctions::systemdLoginManager()->call(
			QDBus::Block, QStringLiteral("GetSession"), xdgSessionId);

		if (reply.isValid())
		{
			sessionPathFromXdgSessionId = reply.value().path();
			return sessionPathFromXdgSessionId;
		}
	}

	if (ignoreErrors == false)
	{
		vWarning() << "could not determine dbus object path of current session – please make sure systemd is "
					  "up to date and/or the environment variable" << xdgSessionIdEnvVarName() << "is set";
	}

	return {};
}



bool LinuxSessionFunctions::isOpen( const QString& session )
{
	const auto state = getSessionState( session );

	return state == State::Active ||
		   state == State::Online ||
		   state == State::Opening;
}


bool LinuxSessionFunctions::isGraphical( const QString& session )
{
	const auto type = getSessionType( session );

	return type == Type::X11 ||
		   type == Type::Wayland ||
		   type == Type::Mir;
}