Repository navigation
Expand file tree
/
Copy pathmainwindow.cpp
More file actions
1677 lines (1560 loc) · 65.3 KB
/
Copy pathmainwindow.cpp
File metadata and controls
1677 lines (1560 loc) · 65.3 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
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
493
494
495
496
497
498
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
621
622
623
624
625
626
627
628
629
630
631
632
633
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
679
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
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
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
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
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
940
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
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (C) 2003-2010 by Warren Woodford
Copyright (C) 2014 by Timothy E. Harris
for modifications applicable to the MX Linux project.
Heavily modified by Adrian adrian@mxlinux.org
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "mainwindow.h"
#include "about.h"
#include "passedit.h"
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QFileDialog>
#include <QFileInfo>
#include <QProcess>
#include <QRegularExpression>
#include <QScreen>
#include <QSet>
#include <QSignalBlocker>
#include <QStandardPaths>
#include <QTextEdit>
#include <optional>
#include <grp.h>
#include <pwd.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cerrno>
#include <vector>
#ifndef VERSION
#define VERSION "?.?.?.?"
#endif
MainWindow::MainWindow(QWidget *parent)
: QDialog(parent)
{
qDebug().noquote() << QCoreApplication::applicationName() << "version:" << VERSION;
setupUi(this);
setWindowFlags(Qt::Window); // For the close, min and max buttons
setWindowIcon(QApplication::windowIcon());
passUser = new PassEdit(userPasswordEdit, userPassword2Edit, 1, this);
passChange = new PassEdit(lineEditChangePass, lineEditChangePassConf, 1, this);
shell = new Cmd(this);
displayManager = detectDisplayManager();
tabWidget->blockSignals(true);
tabWidget->setCurrentIndex(Tab::Administration);
tabWidget->blockSignals(false);
QSize savedSize = QDialog::size();
restoreGeometry(settings.value("geometry").toByteArray());
if (isMaximized()) { // If started maximized give option to resize to normal window size
resize(savedSize);
QRect screenGeometry = QApplication::primaryScreen()->geometry();
int x = (screenGeometry.width() - width()) / 2;
int y = (screenGeometry.height() - height()) / 2;
move(x, y);
}
refresh();
setConnections();
}
MainWindow::~MainWindow()
{
settings.setValue("geometry", saveGeometry());
}
namespace
{
// The conventional uid of the "nobody" pseudo-account. lslogins -u only hides
// it because it lies above the default UID_MAX; exclude it explicitly so it
// stays hidden even if /etc/login.defs raises UID_MAX past it.
constexpr uid_t kNobodyUid = 65534;
struct UidRange
{
uid_t min = 1000;
uid_t max = 60000;
};
// Bounds for a "real" (non-system) account, matching the defaults that
// `lslogins -u`/adduser/useradd use unless /etc/login.defs overrides them.
// The file is read once and cached: it doesn't change over the process's
// lifetime.
const UidRange &uidRange()
{
static const UidRange range = [] {
UidRange result;
QFile loginDefs(QStringLiteral("/etc/login.defs"));
if (loginDefs.open(QIODevice::ReadOnly | QIODevice::Text)) {
while (!loginDefs.atEnd()) {
const QString line = QString::fromUtf8(loginDefs.readLine()).trimmed();
const QStringList parts = line.split(QRegularExpression("\\s+"), Qt::SkipEmptyParts);
if (parts.size() < 2) {
continue;
}
bool ok = false;
const qlonglong value = parts.at(1).toLongLong(&ok);
if (!ok || value < 0) {
continue;
}
if (parts.at(0) == QLatin1String("UID_MIN")) {
result.min = static_cast<uid_t>(value);
} else if (parts.at(0) == QLatin1String("UID_MAX")) {
result.max = static_cast<uid_t>(value);
}
}
}
return result;
}();
return range;
}
// The autologin user SDDM will actually use. SDDM reads its configuration in
// this order, later values overriding earlier ones: the system drop-ins in
// /usr/lib/sddm/sddm.conf.d, the local drop-ins in /etc/sddm.conf.d (each
// directory's *.conf files in alphabetical order), then /etc/sddm.conf. The
// helper may write either /etc/sddm.conf.d/kde_settings.conf or /etc/sddm.conf,
// so reading a single file can disagree with what was just configured.
QString sddmAutologinUser()
{
QStringList files;
for (const QString &dirPath : {QStringLiteral("/usr/lib/sddm/sddm.conf.d"), QStringLiteral("/etc/sddm.conf.d")}) {
const QDir dir(dirPath);
const QStringList names = dir.entryList({QStringLiteral("*.conf")}, QDir::Files | QDir::Readable, QDir::Name);
for (const QString &name : names) {
files << dir.filePath(name);
}
}
files << QStringLiteral("/etc/sddm.conf");
QString user;
for (const QString &file : std::as_const(files)) {
if (!QFileInfo::exists(file)) {
continue;
}
const QSettings conf(file, QSettings::IniFormat);
if (conf.contains(QStringLiteral("Autologin/User"))) {
user = conf.value(QStringLiteral("Autologin/User")).toString();
}
}
return user;
}
// The comm (executable) name of every running process, collected in a single
// /proc scan so callers checking several candidate names don't each pay for
// their own scan. Note this is an exact match on comm, unlike pgrep's
// unanchored substring/regex match — fine for the fixed daemon names we look
// for (lightdm/sddm/plasmalogin), which are never a strict substring match away
// from something else.
QSet<QByteArray> runningProcessNames()
{
QSet<QByteArray> names;
QDir proc(QStringLiteral("/proc"));
const QStringList pids = proc.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
for (const QString &pid : pids) {
bool isPid = false;
pid.toInt(&isPid);
if (!isPid) {
continue;
}
QFile commFile(QStringLiteral("/proc/%1/comm").arg(pid));
if (commFile.open(QIODevice::ReadOnly)) {
names.insert(commFile.readAll().trimmed());
}
}
return names;
}
// Whether `user` is listed as a supplementary member of `group`; empty when the
// group cannot be looked up, so the answer is unknown rather than "no".
std::optional<bool> isSupplementaryMember(const QString &user, const QString &group)
{
const struct group *gr = getgrnam(group.toLocal8Bit().constData());
if (!gr) {
return std::nullopt;
}
const QByteArray name = user.toLocal8Bit();
for (char **member = gr->gr_mem; member && *member; ++member) {
if (name == *member) {
return true;
}
}
return false;
}
} // namespace
void MainWindow::refresh()
{
setCursor(QCursor(Qt::ArrowCursor));
syncProgressBar->setValue(0);
switch (tabWidget->currentIndex()) {
case Tab::Options:
refreshOptions();
buttonApply->setEnabled(false);
break;
case Tab::Copy:
refreshCopy();
buttonApply->setEnabled(true);
break;
case Tab::AddRemoveGroup:
refreshGroups();
buttonApply->setEnabled(false);
break;
case Tab::GroupMembership:
refreshMembership();
buttonApply->setEnabled(false);
break;
default:
refreshAdd();
refreshDelete();
refreshChangePass();
refreshRename();
users.clear();
{
const UidRange &range = uidRange();
setpwent();
while (const passwd *pw = getpwent()) {
if (pw->pw_uid >= range.min && pw->pw_uid <= range.max && pw->pw_uid != kNobodyUid) {
users << QString::fromLocal8Bit(pw->pw_name);
}
}
endpwent();
}
users.sort();
comboRenameUser->addItems(users);
comboChangePass->addItems(users);
comboDeleteUser->addItems(users);
buttonApply->setEnabled(false);
break;
}
}
DisplayManager MainWindow::detectDisplayManager() const
{
const QSet<QByteArray> running = runningProcessNames();
if (running.contains("lightdm")) {
return DisplayManager::Lightdm;
}
if (running.contains("sddm")) {
return DisplayManager::Sddm;
}
if (running.contains("plasmalogin")) {
return DisplayManager::Plasmalogin;
}
return DisplayManager::None;
}
void MainWindow::refreshOptions()
{
userComboBox->clear();
userComboBox->addItems(users);
checkGroups->setChecked(false);
checkMozilla->setChecked(false);
// Load the autologin state of the preselected user (also resets the radios).
userComboBox_activated(userComboBox->currentText());
// Autologin options only make sense when a supported login manager is running.
groupBox->setVisible(displayManager != DisplayManager::None);
}
void MainWindow::refreshCopy()
{
fromUserComboBox->clear();
fromUserComboBox->addItems(users);
const QString logname = currentLogname();
fromUserComboBox->setCurrentIndex(fromUserComboBox->findText(logname));
copyRadioButton->setChecked(true);
entireRadioButton->setChecked(true);
QStringList items = users;
items.removeAll(logname);
items.removeAll(fromUserComboBox->currentText());
items.sort();
toUserComboBox->clear();
toUserComboBox->addItems(items);
if (items.isEmpty()) {
toUserComboBox->addItem(QString());
}
toUserComboBox->addItem(tr("browse..."));
}
void MainWindow::refreshAdd()
{
userNameEdit->clear();
userPasswordEdit->clear();
userPassword2Edit->clear();
addUserBox->setEnabled(true);
const QString adminGroup = adminGroupName();
const QStringList extraGroups = defaultExtraGroups();
const bool adminInDefaults = !adminGroup.isEmpty() && extraGroups.contains(adminGroup);
checkSudoGroup->setVisible(!adminGroup.isEmpty());
checkSudoGroup->setChecked(adminInDefaults);
if (!adminGroup.isEmpty()) {
checkSudoGroup->setText(tr("Add user to %1 group").arg(adminGroup));
}
}
void MainWindow::refreshDelete()
{
comboDeleteUser->clear();
comboDeleteUser->addItem(tr("none"));
deleteHomeCheckBox->setChecked(false);
deleteUserBox->setEnabled(true);
}
void MainWindow::refreshChangePass()
{
comboChangePass->clear();
comboChangePass->addItem(tr("none"));
changePasswordBox->setEnabled(true);
comboChangePass->addItem(QStringLiteral("root"));
lineEditChangePass->clear();
lineEditChangePassConf->clear();
}
void MainWindow::refreshGroups()
{
groupNameEdit->clear();
addBox->setEnabled(true);
deleteBox->setEnabled(true);
buildListGroupsToRemove();
}
void MainWindow::refreshMembership()
{
userComboMembership->clear();
listGroups->clear();
userComboMembership->addItems(users);
buildListGroups();
}
void MainWindow::refreshRename()
{
renameUserNameEdit->clear();
comboRenameUser->clear();
comboRenameUser->addItem(tr("none"));
renameUserBox->setEnabled(true);
}
// Apply but do not close
void MainWindow::applyOptions()
{
const QString user = userComboBox->currentText();
QString home = user;
if (user != QStringLiteral("root")) {
home = QStringLiteral("/home/%1").arg(user);
}
if (checkGroups->isChecked() || checkMozilla->isChecked()) {
QString msg = tr("The user configuration will be repaired. Please close all other applications now. When "
"finished, please logout or reboot. Are you sure you want to repair now?");
if (checkMozilla->isChecked()) {
msg.prepend(tr("The folder %1 will be deleted, with the Firefox profiles it contains (bookmarks, saved "
"passwords, history and extensions). No backup is made, and this cannot be undone.")
.arg(home + "/.mozilla")
+ "\n\n");
}
int ans = QMessageBox::warning(this, windowTitle(), msg, QMessageBox::Yes, QMessageBox::No);
if (ans != QMessageBox::Yes) {
return;
}
}
setCursor(QCursor(Qt::WaitCursor));
// A refused elevation is already reported by Cmd (and the tab refreshed by
// buttonApply_clicked); any other failure is shown with the helper's output.
QString output;
const auto reportFailure = [this, &output](const QString &title, const QString &message) {
if (shell->elevationError()) {
return;
}
QMessageBox::critical(this, title, output.isEmpty() ? message : message + "\n\n" + output);
};
// Restore groups
if (checkGroups->isChecked() && user != QStringLiteral("root")) {
// Only the list of existing group names is used here (listGroups'
// memberships are for the Group Membership tab's user).
buildListGroups();
QStringList extra_groups_list = defaultExtraGroups();
if (!groupNamesLoaded) {
reportFailure(windowTitle(), tr("Could not read the system groups. Group membership was not restored."));
} else if (extra_groups_list.isEmpty()) {
QMessageBox::information(this, windowTitle(),
tr("No default extra groups are configured on this system."));
} else {
QStringList new_group_list;
for (const QString &group : extra_groups_list) {
if (!listGroups->findItems(group, Qt::MatchExactly).isEmpty()) {
new_group_list << group;
}
}
// The admin group is a separate choice (see applyAdd) and is usually
// not in EXTRA_GROUPS; restoring defaults must not take away admin
// rights the user already has. If that membership cannot be read,
// nothing is restored rather than risk removing it.
const QString adminGroup = adminGroupName();
std::optional<bool> keepAdmin = false;
if (!adminGroup.isEmpty() && !new_group_list.contains(adminGroup)) {
keepAdmin = isSupplementaryMember(user, adminGroup);
}
if (!keepAdmin) {
reportFailure(windowTitle(), tr("Could not read the members of the %1 group. Group membership was "
"not restored.")
.arg(adminGroup));
} else {
if (*keepAdmin) {
new_group_list << adminGroup;
}
if (shell->runHelper({"set-groups", user, new_group_list.join(',')}, &output)) {
QMessageBox::information(this, windowTitle(), tr("User group membership was restored."));
} else {
reportFailure(windowTitle(), tr("Could not restore the user's group membership."));
}
}
}
}
// Reset Mozilla configs
if (checkMozilla->isChecked()) {
if (shell->runHelper({"remove-home-path", user, home + "/.mozilla"}, &output)) {
QMessageBox::information(this, windowTitle(), tr("Mozilla settings were reset."));
} else {
reportFailure(windowTitle(), tr("Could not reset the Mozilla settings."));
}
}
// Only touch the display-manager config when the choice differs from the state
// loaded for this user; applying an unrelated reset must not change autologin.
if (radioAutologinNo->isChecked() && autologinLoaded) {
if (shell->runHelper({"autologin-disable", user}, &output)) {
autologinLoaded = false;
QMessageBox::information(this, tr("Autologin options"),
(tr("Autologin has been disabled for the '%1' account.").arg(user)));
} else {
reportFailure(tr("Autologin options"),
tr("Autologin could not be disabled for the '%1' account.").arg(user));
userComboBox_activated(user); // show the actual autologin state again
}
} else if (radioAutologinYes->isChecked() && !autologinLoaded) {
// The helper configures only the running display manager; supply the
// desired session names so it can set them on the sddm config it chooses.
QString manager;
switch (displayManager) {
case DisplayManager::Lightdm:
manager = QStringLiteral("lightdm");
break;
case DisplayManager::Sddm:
manager = QStringLiteral("sddm");
break;
case DisplayManager::Plasmalogin:
manager = QStringLiteral("plasmalogin");
break;
case DisplayManager::None:
break; // the autologin options are hidden
}
QString kdeSession;
QString defaultSession;
if (qEnvironmentVariable("XDG_CURRENT_DESKTOP") == QLatin1String("KDE")) {
const QString sessionType = qEnvironmentVariable("XDG_SESSION_TYPE");
if (sessionType == QLatin1String("wayland")) {
kdeSession = QStringLiteral("plasma");
} else if (sessionType == QLatin1String("x11")) {
kdeSession = QStringLiteral("plasmax11");
}
defaultSession = QStringLiteral("plasma.desktop");
}
if (shell->runHelper({"autologin-enable", user, kdeSession, defaultSession, manager}, &output)) {
autologinLoaded = true;
QMessageBox::information(this, tr("Autologin options"),
(tr("Autologin has been enabled for the '%1' account.").arg(user)));
} else {
reportFailure(tr("Autologin options"),
tr("Autologin could not be enabled for the '%1' account.").arg(user));
userComboBox_activated(user); // show the actual autologin state again
}
}
setCursor(QCursor(Qt::ArrowCursor));
buttonApply->setEnabled(false);
}
void MainWindow::applyDesktop()
{
if (toUserComboBox->currentText().isEmpty()) {
QMessageBox::information(
this, windowTitle(),
tr("You must specify a 'copy to' destination. You cannot copy to the desktop you are logged in to."));
return;
}
if (toUserComboBox->currentText().contains('/') && isExcludedCopyDestination(toUserComboBox->currentText())) {
QMessageBox::information(
this, windowTitle(),
tr("You cannot copy to the source desktop or the desktop you are logged in to."));
return;
}
if (QMessageBox::Yes
!= QMessageBox::critical(
this, windowTitle(),
tr("Before copying, close all other applications. Be sure the copy to destination is large enough to "
"contain the files you are copying. Copying between desktops may overwrite or delete your files or "
"preferences on the destination desktop. Are you sure you want to proceed?"),
QMessageBox::Yes, QMessageBox::No)) {
return;
}
QString fromDir = QStringLiteral("/home/%1").arg(fromUserComboBox->currentText());
QString toDir = QStringLiteral("/home/%1").arg(toUserComboBox->currentText());
if (toUserComboBox->currentText().contains('/')) { // If a directory rather than a user name
toDir = toUserComboBox->currentText();
}
if (docsRadioButton->isChecked()) {
fromDir.append("/Documents");
toDir.append("/Documents");
} else if (mozillaRadioButton->isChecked()) {
fromDir.append("/.mozilla");
toDir.append("/.mozilla");
} else if (sharedRadioButton->isChecked()) {
fromDir.append("/Shared");
toDir.append("/Shared");
}
fromDir.append('/');
// Snapshot the operation now so the post-copy follow-ups in syncDone act on
// exactly what was copied, independent of any later change to the controls.
CopyJob job;
job.fromUser = fromUserComboBox->currentText();
job.toUser = toUserComboBox->currentText();
job.fromDir = fromDir;
job.toDir = toDir;
job.toIsDir = toUserComboBox->currentText().contains('/');
job.entire = entireRadioButton->isChecked();
job.rewritePaths = entireRadioButton->isChecked() || mozillaRadioButton->isChecked();
job.sync = syncRadioButton->isChecked();
setCursor(QCursor(Qt::WaitCursor));
if (syncRadioButton->isChecked()) {
syncStatusEdit->setText(tr("Synchronizing desktop..."));
} else {
syncStatusEdit->setText(tr("Copying desktop..."));
}
for (int tab = 0; tab < Tab::MAX; ++tab) {
if (tab == Tab::Copy) {
continue;
}
tabWidget->setTabEnabled(tab, false);
}
const auto conn = connect(shell, &Cmd::outputAvailable, this, [this](const QString &out) {
QRegularExpression regex("\\b(\\d+)%");
QRegularExpressionMatch match = regex.match(out);
if (match.hasMatch()) {
bool ok = false;
int percent = match.captured(1).toInt(&ok);
if (ok && percent > syncProgressBar->value()) {
syncProgressBar->setValue(percent);
}
}
});
// For a copy into an account, the helper confines the destination to that
// account's home and gives it ownership of everything it writes.
QStringList rsyncArgs {"rsync-copy", job.fromUser, fromDir, toDir, job.sync ? "sync" : "copy"};
if (!job.toIsDir) {
rsyncArgs << job.toUser;
}
syncDone(shell->runHelper(rsyncArgs), job);
disconnect(conn);
for (int tab = 0; tab < Tab::MAX; ++tab) {
tabWidget->setTabEnabled(tab, true);
}
}
void MainWindow::applyAdd()
{
// Validate data before proceeding, see if username is reasonable length
if (userNameEdit->text().length() < 2) {
QMessageBox::critical(this, windowTitle(),
tr("The user name needs to be at least 2 characters long. Please select a longer "
"name before proceeding."));
return;
} else if (!userNameEdit->text().contains(QRegularExpression("^[A-Za-z_][A-Za-z0-9_-]*[$]?$"))) {
QMessageBox::critical(this, windowTitle(),
tr("The user name cannot contain special characters or spaces.\n"
"Please choose another name before proceeding."));
return;
}
// Check that user name is not already used
if (getpwnam(userNameEdit->text().toLocal8Bit().constData()) != nullptr) {
QMessageBox::critical(this, windowTitle(), tr("Sorry, this name is in use. Please enter a different name."));
return;
}
if (!passUser->confirmed()) {
QMessageBox::critical(this, windowTitle(), tr("Password entries do not match. Please try again."));
return;
}
if (!passUser->lengthOK()) {
QMessageBox::critical(this, windowTitle(),
tr("The password cannot be empty. Please enter a password before proceeding."));
return;
}
const QString adminGroup = adminGroupName();
QStringList extraGroups = defaultExtraGroups();
if (!adminGroup.isEmpty()) {
if (checkSudoGroup->isChecked() && !extraGroups.contains(adminGroup)) {
extraGroups << adminGroup;
} else if (!checkSudoGroup->isChecked()) {
extraGroups.removeAll(adminGroup);
}
}
const QString dshell = defaultShellPath();
const bool hasAdduser = commandExists("adduser");
const bool hasUseradd = commandExists("useradd");
if (!hasAdduser && !hasUseradd) {
QMessageBox::critical(this, windowTitle(),
tr("No suitable user management tools found (adduser or useradd)."));
return;
}
// adduser/useradd reuse a home directory that already exists (e.g. left
// behind when a user was deleted without removing it); a rollback below
// must never delete such a directory. Only a definite "not found" counts as
// absent; any other lookup error (e.g. no access to /home) keeps the home.
const QString expectedHome = QStringLiteral("/home/%1").arg(userNameEdit->text());
struct stat homeStat {};
const bool homeAbsent = ::lstat(QFile::encodeName(expectedHome).constData(), &homeStat) != 0 && errno == ENOENT;
// The helper picks adduser/useradd, detects its option spelling, and applies
// the groups; extra groups are only used by the useradd path, matching the
// adduser path's reliance on the system EXTRA_GROUPS configuration.
const bool success = shell->runHelper({"add-user", userNameEdit->text(), dshell, extraGroups.join(',')});
if (!success) {
if (!shell->elevationError()) {
QMessageBox::critical(this, windowTitle(), tr("Failed to add the user."));
}
return;
}
QString userNameArg = userNameEdit->text();
const QByteArray passwordInput = userPasswordEdit->text().toUtf8() + '\n' + userPasswordEdit->text().toUtf8() + '\n';
if (shell->runHelper({"set-password", userNameArg}, nullptr, &passwordInput, QuietMode::Yes)) {
// Make the admin group match the checkbox, then confirm it does: the
// system defaults may already have granted it, and when they have not,
// this call is what grants it. An unknown membership (group lookup
// failed) is treated as needing the change, and then reported as
// unverified.
const bool wantAdmin = checkSudoGroup->isChecked();
std::optional<bool> isAdmin = wantAdmin;
if (!adminGroup.isEmpty()) {
if (isSupplementaryMember(userNameArg, adminGroup) != wantAdmin) {
shell->runHelper({wantAdmin ? "group-add-member" : "group-remove-member", userNameArg, adminGroup},
nullptr, nullptr, QuietMode::Yes);
}
isAdmin = isSupplementaryMember(userNameArg, adminGroup);
}
if (!isAdmin) {
QMessageBox::warning(this, windowTitle(),
tr("The user was added, but its membership in the %1 group could not be verified.")
.arg(adminGroup));
} else if (*isAdmin != wantAdmin) {
QMessageBox::warning(this, windowTitle(),
wantAdmin ? tr("The user was added, but could not be added to the %1 group.")
.arg(adminGroup)
: tr("The user was added, but could not be removed from the %1 group.")
.arg(adminGroup));
} else {
QMessageBox::information(this, windowTitle(), tr("The user was added ok."));
}
refresh();
} else {
// The account already exists, but without a usable password. Remove the
// account this call just created so the user can simply try again; if
// that is not possible (e.g. elevation was refused), say what was left.
// Its home is removed only if this call created it.
QStringList delUserArgs {"del-user", userNameArg};
const passwd *pw = getpwnam(userNameArg.toLocal8Bit().constData());
if (homeAbsent && pw && QString::fromLocal8Bit(pw->pw_dir) == expectedHome) {
delUserArgs << "--remove-home";
}
const bool removed
= !shell->elevationError() && shell->runHelper(delUserArgs, nullptr, nullptr, QuietMode::Yes);
if (removed) {
QMessageBox::critical(this, windowTitle(), tr("Failed to add the user."));
} else {
QMessageBox::critical(this, windowTitle(),
tr("The user %1 was created, but its password could not be set. "
"Set a password for it or delete it on the Administration tab.")
.arg(userNameArg));
}
refresh();
}
}
// Change user password
void MainWindow::applyChangePass()
{
if (!passChange->confirmed()) {
QMessageBox::critical(this, windowTitle(), tr("Password entries do not match. Please try again."));
return;
}
if (!passChange->lengthOK()) {
QMessageBox::critical(this, windowTitle(),
tr("The password cannot be empty. Please enter a password before proceeding."));
return;
}
const QByteArray passwordInput
= lineEditChangePass->text().toUtf8() + '\n' + lineEditChangePass->text().toUtf8() + '\n';
if (shell->runHelper({"set-password", comboChangePass->currentText()}, nullptr, &passwordInput, QuietMode::Yes)) {
QMessageBox::information(this, windowTitle(), tr("Password successfully changed."));
refresh();
} else if (!shell->elevationError()) {
QMessageBox::critical(this, windowTitle(), tr("Failed to change password."));
}
}
void MainWindow::applyDelete()
{
const QString logname = currentLogname();
if (logname.isEmpty()) {
QMessageBox::critical(this, windowTitle(),
tr("Could not determine which account is logged in, so users cannot be deleted."));
return;
}
if (logname == comboDeleteUser->currentText()) {
QMessageBox::critical(
this, windowTitle(),
tr("The selected user name is currently in use.") + "\n\n"
+ tr("To delete this user, please log out and log back in using another user account."));
refresh();
return;
}
QString msg = tr("This action cannot be undone. Are you sure you want to delete user %1?")
.arg(comboDeleteUser->currentText());
if (QMessageBox::Yes == QMessageBox::warning(this, windowTitle(), msg, QMessageBox::Yes, QMessageBox::No)) {
const QString username = comboDeleteUser->currentText();
const bool hasDeluser = commandExists("deluser");
const bool hasUserdel = commandExists("userdel");
if (!hasDeluser && !hasUserdel) {
QMessageBox::critical(this, windowTitle(),
tr("No suitable user removal tools found (deluser or userdel)."));
return;
}
if (deleteHomeCheckBox->isChecked()) {
shell->runHelper({"kill-user", username}, nullptr, nullptr, QuietMode::Yes);
}
QStringList delUserArgs {"del-user", username};
if (deleteHomeCheckBox->isChecked()) {
delUserArgs << "--remove-home";
}
const bool deleted = shell->runHelper(delUserArgs);
if (deleted) {
QString cleanupOutput;
if (shell->runHelper({"autologin-remove-user", username}, &cleanupOutput)) {
QMessageBox::information(this, windowTitle(), tr("The user has been deleted."));
} else {
// The account is gone either way; say what was left behind.
const QString msg
= tr("The user has been deleted, but automatic login for %1 could not be removed from the "
"display manager configuration.")
.arg(username);
QMessageBox::warning(this, windowTitle(),
cleanupOutput.isEmpty() ? msg : msg + "\n\n" + cleanupOutput);
}
} else if (!shell->elevationError()) {
QMessageBox::critical(this, windowTitle(), tr("Failed to delete the user."));
}
refresh();
}
}
void MainWindow::applyGroup()
{
// Checks if adding or removing groups
if (addBox->isEnabled()) {
// validate data before proceeding
// see if groupname is reasonable length
if (groupNameEdit->text().length() < 2) {
QMessageBox::critical(this, windowTitle(),
tr("The group name needs to be at least 2 characters long. Please select a longer "
"name before proceeding."));
return;
} else if (!groupNameEdit->text().contains(QRegularExpression("^[a-z_][a-z0-9_-]*[$]?$"))) {
QMessageBox::critical(this, windowTitle(),
tr("The group name needs to be lower case and it \n"
"cannot contain special characters or spaces.\n"
"Please choose another name before proceeding."));
return;
}
// Check that group name is not already used
if (getgrnam(groupNameEdit->text().toLocal8Bit().constData()) != nullptr) {
QMessageBox::critical(this, windowTitle(),
tr("Sorry, that group name already exists. Please enter a different name."));
return;
}
const bool hasAddgroup = commandExists("addgroup");
const bool hasGroupadd = commandExists("groupadd");
if (!hasAddgroup && !hasGroupadd) {
QMessageBox::critical(this, windowTitle(),
tr("No suitable group creation tools found (addgroup or groupadd)."));
return;
}
// Run the group-creation command via the helper
const QString scope = checkGroupUserLevel->checkState() == Qt::Checked ? QStringLiteral("user")
: QStringLiteral("system");
if (shell->runHelper({"add-group", groupNameEdit->text(), scope})) {
QMessageBox::information(this, windowTitle(), tr("The system group was added ok."));
} else if (!shell->elevationError()) {
QMessageBox::critical(this, windowTitle(), tr("Failed to add the system group."));
}
} else { // Deleting group if addBox disabled
QStringList groups;
for (int i = 0; i < listGroupsToRemove->count(); ++i) {
auto *item = listGroupsToRemove->item(i);
if (item && item->checkState() == Qt::Checked) {
groups << item->text();
}
}
if (groups.isEmpty()) {
refresh();
return;
}
QString msg
= groups.count() == 1
? tr("This action cannot be undone. Are you sure you want to delete group %1?").arg(groups.at(0))
: tr("This action cannot be undone. Are you sure you want to delete the following groups: %1?")
.arg(groups.join(' '));
int ans = QMessageBox::warning(this, windowTitle(), msg, QMessageBox::Yes, QMessageBox::No);
if (ans == QMessageBox::Yes) {
const bool hasDelgroup = commandExists("delgroup");
const bool hasGroupdel = commandExists("groupdel");
if (!hasDelgroup && !hasGroupdel) {
QMessageBox::critical(this, windowTitle(),
tr("No suitable group removal tools found (delgroup or groupdel)."));
return;
}
auto it = std::find_if(groups.cbegin(), groups.cend(),
[&](const auto &group) { return !shell->runHelper({"del-group", group}); });
if (it != groups.cend()) {
const auto &group = *it;
if (!shell->elevationError()) {
QMessageBox::critical(this, windowTitle(),
tr("Failed to delete the group.") + '\n' + tr("Group: %1").arg(group));
}
refresh();
return;
}
msg = groups.count() == 1 ? tr("The group has been deleted.") : tr("The groups have been deleted.");
QMessageBox::information(this, windowTitle(), msg);
}
}
refresh();
}
void MainWindow::applyMembership()
{
if (!membershipLoaded) {
return; // never replace the memberships with a list that was not fully read
}
QStringList groups;
for (int i = 0; i < listGroups->count(); ++i) {
auto *item = listGroups->item(i);
if (item && item->checkState() == Qt::Checked) {
groups << item->text();
}
}
if (shell->runHelper({"set-groups", userComboMembership->currentText(), groups.join(',')})) {
QMessageBox::information(this, windowTitle(), tr("The changes have been applied."));
} else if (!shell->elevationError()) {
QMessageBox::critical(this, windowTitle(), tr("Failed to apply group changes"));
}
}
void MainWindow::applyRename()
{
const QString old_name = comboRenameUser->currentText();
const QString new_name = renameUserNameEdit->text();
// Validate data before proceeding
// Check if selected user is in use
const QString logname = currentLogname();
if (logname.isEmpty()) {
QMessageBox::critical(this, windowTitle(),
tr("Could not determine which account is logged in, so users cannot be renamed."));
return;
}
if (logname == old_name) {
QMessageBox::critical(
this, windowTitle(),
tr("The selected user name is currently in use.") + "\n\n"
+ tr("To rename this user, please log out and log back in using another user account."));
refresh();
return;
}
// See if username is reasonable length
if (new_name.length() < 2) {
QMessageBox::critical(this, windowTitle(),
tr("The user name needs to be at least 2 characters long. Please select a longer "
"name before proceeding."));
return;
} else if (!new_name.contains(QRegularExpression("^[A-Za-z_][A-Za-z0-9_-]*[$]?$"))) {
QMessageBox::critical(this, windowTitle(),
tr("The user name cannot contain special characters or spaces.\n"
"Please choose another name before proceeding."));
return;
}
if (getpwnam(new_name.toLocal8Bit().constData()) != nullptr) {
QMessageBox::critical(this, windowTitle(),
tr("Sorry, this name already exists on your system. Please enter a different name."));
return;
}
shell->runHelper({"kill-user", old_name}, nullptr, nullptr, QuietMode::Yes);
// Rename the user. The helper relocates the home directory, updates the
// GECOS/full-name field, renames the personal group, and rewrites "home/<old>"
// references inside the (new) home directory.
bool success = shell->runHelper({"rename-user", old_name, new_name});
if (!success) {
if (!shell->elevationError()) {
QMessageBox::critical(this, windowTitle(),
tr("Failed to rename the user. Please make sure that the user is not logged in, you "
"might need to restart"));
}
return;
}
// Change autologin name (Xfce and KDE)
QString cleanupOutput;
if (shell->runHelper({"autologin-rename", old_name, new_name}, &cleanupOutput)) {
QMessageBox::information(this, windowTitle(), tr("The user was renamed."));
} else {
// The account is renamed either way; say what was left behind.
const QString msg = tr("The user was renamed, but automatic login could not be updated from %1 to %2 in the "
"display manager configuration.")
.arg(old_name, new_name);
QMessageBox::warning(this, windowTitle(), cleanupOutput.isEmpty() ? msg : msg + "\n\n" + cleanupOutput);
}
refresh();
}
void MainWindow::syncDone(bool success, const CopyJob &job)
{
// Captured before any follow-up helper call replaces the output buffer.
const QString failureOutput = success ? QString() : shell->readAllOutput();
// A browsed directory is not a managed home: there is nothing to fix up.
// Ownership of a copy into an account was already set by rsync.
if (success && !job.toIsDir) {
// Fix "home/<from>" references for entire-home or .mozilla copies, only in
// the files that came from the source.
if (job.rewritePaths) {
QString rewriteOutput;
if (!shell->runHelper({"rewrite-home-paths", job.toUser, job.toDir, job.fromUser, job.toUser, job.fromDir},
&rewriteOutput)
&& !shell->elevationError()) {
// The copy itself succeeded; only the path fix-up did not.
const QString msg = tr("The files were copied, but references to /home/%1 in them could not be "
"changed to /home/%2.")
.arg(job.fromUser, job.toUser);
QMessageBox::warning(this, windowTitle(),
rewriteOutput.isEmpty() ? msg : msg + "\n\n" + rewriteOutput);
}
}
if (job.entire) {
shell->runHelper({"remove-home-path", job.toUser, job.toDir + "/.recently-used"});
shell->runHelper({"clean-openoffice-locks", job.toUser, job.toDir}, nullptr, nullptr, QuietMode::Yes);
}
}
if (success) {
syncStatusEdit->setText(job.sync ? tr("Synchronizing desktop...ok") : tr("Copying desktop...ok"));
} else {
syncStatusEdit->setText(job.sync ? tr("Synchronizing desktop...failed") : tr("Copying desktop...failed"));
}
syncProgressBar->setValue(syncProgressBar->maximum());
setCursor(QCursor(Qt::ArrowCursor));
if (!success && !shell->elevationError()) {