diff --git a/src/libcalamares/CMakeLists.txt b/src/libcalamares/CMakeLists.txt index 0516b5613..56bacb32a 100644 --- a/src/libcalamares/CMakeLists.txt +++ b/src/libcalamares/CMakeLists.txt @@ -76,6 +76,7 @@ set( libSources utils/Dirs.cpp utils/Entropy.cpp utils/Logger.cpp + utils/Permissions.cpp utils/PluginFactory.cpp utils/Retranslator.cpp utils/String.cpp diff --git a/src/libcalamares/utils/Permissions.cpp b/src/libcalamares/utils/Permissions.cpp new file mode 100644 index 000000000..a7afbc5fc --- /dev/null +++ b/src/libcalamares/utils/Permissions.cpp @@ -0,0 +1,124 @@ +/* === This file is part of Calamares - === + * + * SPDX-FileCopyrightText: 2018 Scott Harvey + * SPDX-License-Identifier: GPL-3.0-or-later + * License-Filename: LICENSE + * + */ + +#include "Permissions.h" + +#include "Logger.h" + +#include +#include +#include + +#include + +namespace CalamaresUtils +{ + +Permissions::Permissions() + : m_username() + , m_group() + , m_value( 0 ) + , m_valid( false ) +{ +} + + +Permissions::Permissions( QString const& p ) + : Permissions() +{ + parsePermissions( p ); +} + +void +Permissions::parsePermissions( QString const& p ) +{ + + QStringList segments = p.split( ":" ); + + if ( segments.length() != 3 ) + { + m_valid = false; + return; + } + + if ( segments[ 0 ].isEmpty() || segments[ 1 ].isEmpty() ) + { + m_valid = false; + return; + } + + bool ok; + int octal = segments[ 2 ].toInt( &ok, 8 ); + if ( !ok || octal == 0 ) + { + m_valid = false; + return; + } + else + { + m_value = octal; + } + + // We have exactly three segments and the third is valid octal, + // so we can declare the string valid and set the user and group names + m_valid = true; + m_username = segments[ 0 ]; + m_group = segments[ 1 ]; + + return; +} + +bool +Permissions::apply( const QString& path, int mode ) +{ + // We **don't** use QFile::setPermissions() here because it takes + // a Qt flags object that subtlely does not align with POSIX bits. + // The Qt flags are **hex** based, so 0x755 for rwxr-xr-x, while + // our integer (mode_t) stores **octal** based flags. + // + // Call chmod(2) directly, that's what Qt would be doing underneath + // anyway. + int r = chmod( path.toUtf8().constData(), mode_t( mode ) ); + if ( r ) + { + cDebug() << Logger::SubEntry << "Could not set permissions of" << path << "to" << QString::number( mode, 8 ); + } + return r == 0; +} + +bool +Permissions::apply( const QString& path, const CalamaresUtils::Permissions& p ) +{ + if ( !p.isValid() ) + { + return false; + } + bool r = apply( path, p.value() ); + if ( r ) + { + // We don't use chgrp(2) or chown(2) here because then we need to + // go through the users list (which one, target or source?) to get + // uid_t and gid_t values to pass to that system call. + // + // Do a lame cop-out and let the chown(8) utility do the heavy lifting. + if ( QProcess::execute( "chown", { p.username() + ':' + p.group(), path } ) ) + { + r = false; + cDebug() << Logger::SubEntry << "Could not set owner of" << path << "to" + << ( p.username() + ':' + p.group() ); + } + } + if ( r ) + { + /* NOTUSED */ apply( path, p.value() ); + } + return r; +} + + +} // namespace CalamaresUtils diff --git a/src/libcalamares/utils/Permissions.h b/src/libcalamares/utils/Permissions.h new file mode 100644 index 000000000..1f0dd38da --- /dev/null +++ b/src/libcalamares/utils/Permissions.h @@ -0,0 +1,92 @@ +/* === This file is part of Calamares - === + * + * SPDX-FileCopyrightText: 2018 Scott Harvey + * SPDX-License-Identifier: GPL-3.0-or-later + * License-Filename: LICENSE + * + */ + +#ifndef LIBCALAMARES_PERMISSIONS_H +#define LIBCALAMARES_PERMISSIONS_H + +#include "DllMacro.h" + +#include + +namespace CalamaresUtils +{ + +/** + * @brief The Permissions class takes a QString @p in the form of + * ::, checks it for validity, and makes the three + * components available indivdually. + */ +class DLLEXPORT Permissions +{ + +public: + /** @brief Constructor + * + * Splits the string @p at the colon (":") into separate elements for + * , , and (permissions), where is interpreted + * as an **octal** integer. That is, "root:wheel:755" will give + * you an integer value of four-hundred-ninety-three (493), + * corresponding to the UNIX file permissions rwxr-xr-x, + * as one would expect from chmod and other command-line utilities. + */ + Permissions( QString const& p ); + + /// @brief Default constructor of an invalid Permissions. + Permissions(); + + /// @brief Was the Permissions object constructed from valid data? + bool isValid() const { return m_valid; } + /// @brief The user (first component, e.g. "root" in "root:wheel:755") + QString username() const { return m_username; } + /// @brief The group (second component, e.g. "wheel" in "root:wheel:755") + QString group() const { return m_group; } + /** @brief The value (file permission) as an integer. + * + * Bear in mind that input is in octal, but integers are just integers; + * naively printing them will get decimal results (e.g. 493 from the + * input of "root:wheel:755"). This is suitable to pass to apply(). + */ + int value() const { return m_value; } + /** @brief The value (file permission) as octal string + * + * This is suitable for passing to chmod-the-program, or for + * recreating the original Permissions string. + */ + QString octal() const { return QString::number( value(), 8 ); } + + /** @brief Sets the file-access @p mode of @p path + * + * Pass a path that is relative (or absolute) in the **host** system. + */ + static bool apply( const QString& path, int mode ); + /** @brief Do both chmod and chown on @p path + * + * Note that interpreting user- and group- names for applying the + * permissions can be different between the host system and the target + * system; the target might not have a "live" user, for instance, and + * the host won't have the user-entered username for the installation. + * + * For this call, the names are interpreted in the **host** system. + * Pass a path that is relative (or absolute) in the **host** system. + */ + static bool apply( const QString& path, const Permissions& p ); + /// Convenience method for apply(const QString&, const Permissions& ) + bool apply( const QString& path ) const { return apply( path, *this ); } + +private: + void parsePermissions( QString const& p ); + + QString m_username; + QString m_group; + int m_value; + bool m_valid; +}; + +} // namespace CalamaresUtils + +#endif // LIBCALAMARES_PERMISSIONS_H diff --git a/src/modules/preservefiles/CMakeLists.txt b/src/modules/preservefiles/CMakeLists.txt index f6cd98008..571de31ca 100644 --- a/src/modules/preservefiles/CMakeLists.txt +++ b/src/modules/preservefiles/CMakeLists.txt @@ -4,7 +4,6 @@ calamares_add_plugin( preservefiles TYPE job EXPORT_MACRO PLUGINDLLEXPORT_PRO SOURCES - permissions.cpp PreserveFiles.cpp LINK_PRIVATE_LIBRARIES calamares diff --git a/src/modules/preservefiles/PreserveFiles.cpp b/src/modules/preservefiles/PreserveFiles.cpp index 175f8e4f8..8352e861d 100644 --- a/src/modules/preservefiles/PreserveFiles.cpp +++ b/src/modules/preservefiles/PreserveFiles.cpp @@ -1,39 +1,28 @@ /* === This file is part of Calamares - === * - * Copyright 2018, Adriaan de Groot + * SPDX-FileCopyrightText: 2018 Adriaan de Groot + * SPDX-License-Identifier: GPL-3.0-or-later + * License-Filename: LICENSE * - * Calamares is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Calamares 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 Calamares. If not, see . */ #include "PreserveFiles.h" -#include "permissions.h" - #include "CalamaresVersion.h" -#include "JobQueue.h" #include "GlobalStorage.h" - +#include "JobQueue.h" #include "utils/CalamaresUtilsSystem.h" #include "utils/CommandList.h" #include "utils/Logger.h" +#include "utils/Permissions.h" #include "utils/Units.h" #include using CalamaresUtils::operator""_MiB; -QString targetPrefix() +QString +targetPrefix() { if ( CalamaresUtils::System::instance()->doChroot() ) { @@ -42,9 +31,13 @@ QString targetPrefix() { QString r = gs->value( "rootMountPoint" ).toString(); if ( !r.isEmpty() ) + { return r; + } else + { cDebug() << "RootMountPoint is empty"; + } } else { @@ -55,16 +48,21 @@ QString targetPrefix() return QLatin1String( "/" ); } -QString atReplacements( QString s ) +QString +atReplacements( QString s ) { Calamares::GlobalStorage* gs = Calamares::JobQueue::instance()->globalStorage(); QString root( "/" ); QString user; if ( gs && gs->contains( "rootMountPoint" ) ) + { root = gs->value( "rootMountPoint" ).toString(); + } if ( gs && gs->contains( "username" ) ) + { user = gs->value( "username" ).toString(); + } return s.replace( "@@ROOT@@", root ).replace( "@@USER@@", user ); } @@ -74,9 +72,7 @@ PreserveFiles::PreserveFiles( QObject* parent ) { } -PreserveFiles::~PreserveFiles() -{ -} +PreserveFiles::~PreserveFiles() {} QString PreserveFiles::prettyName() const @@ -107,8 +103,7 @@ copy_file( const QString& source, const QString& dest ) { b = sourcef.read( 1_MiB ); destf.write( b ); - } - while ( b.count() > 0 ); + } while ( b.count() > 0 ); sourcef.close(); destf.close(); @@ -116,14 +111,19 @@ copy_file( const QString& source, const QString& dest ) return true; } -Calamares::JobResult PreserveFiles::exec() +Calamares::JobResult +PreserveFiles::exec() { if ( m_items.isEmpty() ) + { return Calamares::JobResult::error( tr( "No files configured to save for later." ) ); + } QString prefix = targetPrefix(); if ( !prefix.endsWith( '/' ) ) + { prefix.append( '/' ); + } int count = 0; for ( const auto& it : m_items ) @@ -133,37 +133,34 @@ Calamares::JobResult PreserveFiles::exec() QString dest = prefix + bare_dest; if ( it.type == ItemType::Log ) + { source = Logger::logFile(); + } if ( it.type == ItemType::Config ) { if ( Calamares::JobQueue::instance()->globalStorage()->save( dest ) ) + { cWarning() << "Could not write config for" << dest; + } else + { ++count; + } } else if ( source.isEmpty() ) + { cWarning() << "Skipping unnamed source file for" << dest; + } else { if ( copy_file( source, dest ) ) { if ( it.perm.isValid() ) { - auto s_p = CalamaresUtils::System::instance(); - - int r; - - r = s_p->targetEnvCall( QStringList{ "chown", it.perm.username(), bare_dest } ); - if ( r ) - cWarning() << "Could not chown target" << bare_dest; - - r = s_p->targetEnvCall( QStringList{ "chgrp", it.perm.group(), bare_dest } ); - if ( r ) - cWarning() << "Could not chgrp target" << bare_dest; - - r = s_p->targetEnvCall( QStringList{ "chmod", it.perm.octal(), bare_dest } ); - if ( r ) - cWarning() << "Could not chmod target" << bare_dest; + if ( !it.perm.apply( CalamaresUtils::System::instance()->targetPath( bare_dest ) ) ) + { + cWarning() << "Could not set attributes of" << bare_dest; + } } ++count; @@ -171,12 +168,13 @@ Calamares::JobResult PreserveFiles::exec() } } - return count == m_items.count() ? - Calamares::JobResult::ok() : - Calamares::JobResult::error( tr( "Not all of the configured files could be preserved." ) ); + return count == m_items.count() + ? Calamares::JobResult::ok() + : Calamares::JobResult::error( tr( "Not all of the configured files could be preserved." ) ); } -void PreserveFiles::setConfigurationMap(const QVariantMap& configurationMap) +void +PreserveFiles::setConfigurationMap( const QVariantMap& configurationMap ) { auto files = configurationMap[ "files" ]; if ( !files.isValid() ) @@ -193,7 +191,9 @@ void PreserveFiles::setConfigurationMap(const QVariantMap& configurationMap) QString defaultPermissions = configurationMap[ "perm" ].toString(); if ( defaultPermissions.isEmpty() ) + { defaultPermissions = QStringLiteral( "root:root:0400" ); + } QVariantList l = files.toList(); unsigned int c = 0; @@ -203,22 +203,23 @@ void PreserveFiles::setConfigurationMap(const QVariantMap& configurationMap) { QString filename = li.toString(); if ( !filename.isEmpty() ) - m_items.append( Item{ filename, filename, Permissions( defaultPermissions ), ItemType::Path } ); + m_items.append( Item { filename, filename, CalamaresUtils::Permissions( defaultPermissions ), ItemType::Path } ); else + { cDebug() << "Empty filename for preservefiles, item" << c; + } } else if ( li.type() == QVariant::Map ) { const auto map = li.toMap(); QString dest = map[ "dest" ].toString(); QString from = map[ "from" ].toString(); - ItemType t = - ( from == "log" ) ? ItemType::Log : - ( from == "config" ) ? ItemType::Config : - ItemType::None; + ItemType t = ( from == "log" ) ? ItemType::Log : ( from == "config" ) ? ItemType::Config : ItemType::None; QString perm = map[ "perm" ].toString(); if ( perm.isEmpty() ) + { perm = defaultPermissions; + } if ( dest.isEmpty() ) { @@ -230,15 +231,16 @@ void PreserveFiles::setConfigurationMap(const QVariantMap& configurationMap) } else { - m_items.append( Item{ QString(), dest, Permissions( perm ), t } ); + m_items.append( Item { QString(), dest, CalamaresUtils::Permissions( perm ), t } ); } } else + { cDebug() << "Invalid type for preservefiles, item" << c; + } ++c; } } -CALAMARES_PLUGIN_FACTORY_DEFINITION( PreserveFilesFactory, registerPlugin(); ) - +CALAMARES_PLUGIN_FACTORY_DEFINITION( PreserveFilesFactory, registerPlugin< PreserveFiles >(); ) diff --git a/src/modules/preservefiles/PreserveFiles.h b/src/modules/preservefiles/PreserveFiles.h index 587ac9bab..fdba933fa 100644 --- a/src/modules/preservefiles/PreserveFiles.h +++ b/src/modules/preservefiles/PreserveFiles.h @@ -1,34 +1,22 @@ /* === This file is part of Calamares - === * - * Copyright 2018, Adriaan de Groot + * SPDX-FileCopyrightText: 2018 Adriaan de Groot + * SPDX-License-Identifier: GPL-3.0-or-later + * License-Filename: LICENSE * - * Calamares is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Calamares 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 Calamares. If not, see . */ #ifndef PRESERVEFILES_H #define PRESERVEFILES_H -#include -#include -#include - #include "CppJob.h" #include "DllMacro.h" - +#include "utils/Permissions.h" #include "utils/PluginFactory.h" -#include "permissions.h" +#include +#include +#include class PLUGINDLLEXPORT PreserveFiles : public Calamares::CppJob { @@ -40,15 +28,15 @@ class PLUGINDLLEXPORT PreserveFiles : public Calamares::CppJob Path, Log, Config - } ; + }; struct Item { QString source; QString dest; - Permissions perm; + CalamaresUtils::Permissions perm; ItemType type; - } ; + }; using ItemList = QList< Item >; @@ -68,4 +56,4 @@ private: CALAMARES_PLUGIN_FACTORY_DECLARATION( PreserveFilesFactory ) -#endif // PRESERVEFILES_H +#endif // PRESERVEFILES_H diff --git a/src/modules/preservefiles/permissions.cpp b/src/modules/preservefiles/permissions.cpp deleted file mode 100644 index a3f8ac136..000000000 --- a/src/modules/preservefiles/permissions.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/* === This file is part of Calamares - === - * - * Copyright (C) 2018 Scott Harvey - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -#include -#include -#include "permissions.h" - -Permissions::Permissions() : - m_username(), - m_group(), - m_valid(false), - m_value(0) -{ -} - - -Permissions::Permissions(QString p) : Permissions() -{ - parsePermissions(p); -} - -void Permissions::parsePermissions(const QString& p) { - - QStringList segments = p.split(":"); - - if (segments.length() != 3) { - m_valid = false; - return; - } - - if (segments[0].isEmpty() || segments[1].isEmpty()) { - m_valid = false; - return; - } - - bool ok; - int octal = segments[2].toInt(&ok, 8); - if (!ok || octal == 0) { - m_valid = false; - return; - } else { - m_value = octal; - } - - // We have exactly three segments and the third is valid octal, - // so we can declare the string valid and set the user and group names - m_valid = true; - m_username = segments[0]; - m_group = segments[1]; - - return; - -} - - - - - - diff --git a/src/modules/preservefiles/permissions.h b/src/modules/preservefiles/permissions.h deleted file mode 100644 index 4cb70a2c2..000000000 --- a/src/modules/preservefiles/permissions.h +++ /dev/null @@ -1,62 +0,0 @@ -/* === This file is part of Calamares - === - * - * Copyright (C) 2018 Scott Harvey - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -#ifndef PERMISSIONS_H -#define PERMISSIONS_H - -#include - -/** - * @brief The Permissions class takes a QString @p in the form of - * ::, checks it for validity, and makes the three - * components available indivdually. - */ -class Permissions -{ - -public: - - /** @brief Constructor - * - * Splits the string @p at the colon (":") into separate elements for - * , , and (permissions), where is returned as - * an **octal** integer. - */ - Permissions(QString p); - - /** @brief Default constructor of an invalid Permissions. */ - Permissions(); - - bool isValid() const { return m_valid; } - QString username() const { return m_username; } - QString group() const { return m_group; } - int value() const { return m_value; } - QString octal() const { return QString::number( m_value, 8 ); } - -private: - void parsePermissions(QString const &p); - - QString m_username; - QString m_group; - bool m_valid; - int m_value; - -}; - -#endif // PERMISSIONS_H diff --git a/src/modules/users/CMakeLists.txt b/src/modules/users/CMakeLists.txt index 1d969a93b..a449d39ac 100644 --- a/src/modules/users/CMakeLists.txt +++ b/src/modules/users/CMakeLists.txt @@ -49,6 +49,13 @@ calamares_add_test( ${CRYPT_LIBRARIES} ) +calamares_add_test( + userscreatetest + SOURCES + CreateUserTests.cpp + CreateUserJob.cpp +) + calamares_add_test( userstest SOURCES diff --git a/src/modules/users/CreateUserJob.cpp b/src/modules/users/CreateUserJob.cpp index 776b45ce9..beb454ac0 100644 --- a/src/modules/users/CreateUserJob.cpp +++ b/src/modules/users/CreateUserJob.cpp @@ -12,6 +12,7 @@ #include "JobQueue.h" #include "utils/CalamaresUtilsSystem.h" #include "utils/Logger.h" +#include "utils/Permissions.h" #include #include @@ -54,6 +55,109 @@ CreateUserJob::prettyStatusMessage() const return tr( "Creating user %1." ).arg( m_userName ); } +STATICTEST QStringList +groupsInTargetSystem( const QDir& targetRoot ) +{ + QFileInfo groupsFi( targetRoot.absoluteFilePath( "etc/group" ) ); + QFile groupsFile( groupsFi.absoluteFilePath() ); + if ( !groupsFile.open( QIODevice::ReadOnly | QIODevice::Text ) ) + { + return QStringList(); + } + QString groupsData = QString::fromLocal8Bit( groupsFile.readAll() ); + QStringList groupsLines = groupsData.split( '\n' ); + QStringList::iterator it = groupsLines.begin(); + while ( it != groupsLines.end() ) + { + if ( it->startsWith( '#' ) ) + { + it = groupsLines.erase( it ); + continue; + } + int indexOfFirstToDrop = it->indexOf( ':' ); + if ( indexOfFirstToDrop < 1 ) + { + it = groupsLines.erase( it ); + continue; + } + it->truncate( indexOfFirstToDrop ); + ++it; + } + return groupsLines; +} + +static void +ensureGroupsExistInTarget( const QStringList& wantedGroups, const QStringList& availableGroups ) +{ + for ( const QString& group : wantedGroups ) + { + if ( !availableGroups.contains( group ) ) + { +#ifdef __FreeBSD__ + CalamaresUtils::System::instance()->targetEnvCall( { "pw", "groupadd", "-n", group } ); +#else + CalamaresUtils::System::instance()->targetEnvCall( { "groupadd", group } ); +#endif + } + } +} + +static Calamares::JobResult +createUser( const QString& loginName, const QString& fullName, const QString& shell ) +{ + QStringList useraddCommand; +#ifdef __FreeBSD__ + useraddCommand << "pw" + << "useradd" + << "-n" << loginName << "-m" + << "-c" << fullName; + if ( !shell.isEmpty() ) + { + useraddCommand << "-s" << shell; + } +#else + useraddCommand << "useradd" + << "-m" + << "-U"; + if ( !shell.isEmpty() ) + { + useradd << "-s" << shell; + } + useradd << "-c" << fullName; + useradd << loginName; +#endif + + auto commandResult = CalamaresUtils::System::instance()->targetEnvCommand( useraddCommand ); + if ( commandResult.getExitCode() ) + { + cError() << "useradd failed" << commandResult.getExitCode(); + return commandResult.explainProcess( useraddCommand, std::chrono::seconds( 10 ) /* bogus timeout */ ); + } + return Calamares::JobResult::ok(); +} + +static Calamares::JobResult +setUserGroups( const QString& loginName, const QStringList& groups ) +{ + QStringList setgroupsCommand; +#ifdef __FreeBSD__ + setgroupsCommand << "pw" + << "usermod" + << "-n" << loginName << "-G" << groups.join( ',' ); +#else + setgroupsCommand << "usermod" + << "-aG" << groups.join( ',' ) << loginName; +#endif + + auto commandResult = CalamaresUtils::System::instance()->targetEnvCommand( setgroupsCommand ); + if ( commandResult.getExitCode() ) + { + cError() << "usermod failed" << commandResult.getExitCode(); + return commandResult.explainProcess( setgroupsCommand, std::chrono::seconds( 10 ) /* bogus timeout */ ); + } + return Calamares::JobResult::ok(); +} + Calamares::JobResult CreateUserJob::exec() @@ -65,65 +169,37 @@ CreateUserJob::exec() { cDebug() << "[CREATEUSER]: preparing sudoers"; - QFileInfo sudoersFi( destDir.absoluteFilePath( "etc/sudoers.d/10-installer" ) ); + QString sudoersLine = QString( "%%1 ALL=(ALL) ALL\n" ).arg( gs->value( "sudoersGroup" ).toString() ); + auto fileResult + = CalamaresUtils::System::instance()->createTargetFile( QStringLiteral( "/etc/sudoers.d/10-installer" ), + sudoersLine.toUtf8().constData(), + CalamaresUtils::System::WriteMode::Overwrite ); - if ( !sudoersFi.absoluteDir().exists() ) + if ( fileResult ) { - return Calamares::JobResult::error( tr( "Sudoers dir is not writable." ) ); + if ( CalamaresUtils::Permissions::apply( fileResult.path(), 0440 ) ) + { + return Calamares::JobResult::error( tr( "Cannot chmod sudoers file." ) ); + } } - - QFile sudoersFile( sudoersFi.absoluteFilePath() ); - if ( !sudoersFile.open( QIODevice::WriteOnly | QIODevice::Text ) ) + else { return Calamares::JobResult::error( tr( "Cannot create sudoers file for writing." ) ); } - - QString sudoersGroup = gs->value( "sudoersGroup" ).toString(); - - QTextStream sudoersOut( &sudoersFile ); - sudoersOut << QString( "%%1 ALL=(ALL) ALL\n" ).arg( sudoersGroup ); - - if ( QProcess::execute( "chmod", { "440", sudoersFi.absoluteFilePath() } ) ) - return Calamares::JobResult::error( tr( "Cannot chmod sudoers file." ) ); } cDebug() << "[CREATEUSER]: preparing groups"; - QFileInfo groupsFi( destDir.absoluteFilePath( "etc/group" ) ); - QFile groupsFile( groupsFi.absoluteFilePath() ); - if ( !groupsFile.open( QIODevice::ReadOnly | QIODevice::Text ) ) - { - return Calamares::JobResult::error( tr( "Cannot open groups file for reading." ) ); - } - QString groupsData = QString::fromLocal8Bit( groupsFile.readAll() ); - QStringList groupsLines = groupsData.split( '\n' ); - for ( QStringList::iterator it = groupsLines.begin(); it != groupsLines.end(); ++it ) - { - int indexOfFirstToDrop = it->indexOf( ':' ); - it->truncate( indexOfFirstToDrop ); - } - - for ( const QString& group : m_defaultGroups ) - { - if ( !groupsLines.contains( group ) ) - { - CalamaresUtils::System::instance()->targetEnvCall( { "groupadd", group } ); - } - } - - QString defaultGroups = m_defaultGroups.join( ',' ); - if ( m_autologin ) + QStringList availableGroups = groupsInTargetSystem( destDir ); + QStringList groupsForThisUser = m_defaultGroups; + if ( m_autologin && gs->contains( "autologinGroup" ) && !gs->value( "autologinGroup" ).toString().isEmpty() ) { - QString autologinGroup; - if ( gs->contains( "autologinGroup" ) && !gs->value( "autologinGroup" ).toString().isEmpty() ) - { - autologinGroup = gs->value( "autologinGroup" ).toString(); - CalamaresUtils::System::instance()->targetEnvCall( { "groupadd", autologinGroup } ); - defaultGroups.append( QString( ",%1" ).arg( autologinGroup ) ); - } + groupsForThisUser << gs->value( "autologinGroup" ).toString(); } + ensureGroupsExistInTarget( m_defaultGroups, availableGroups ); - // If we're looking to reuse the contents of an existing /home + // If we're looking to reuse the contents of an existing /home. + // This GS setting comes from the **partitioning** module. if ( gs->value( "reuseHome" ).toBool() ) { QString shellFriendlyHome = "/home/" + m_userName; @@ -133,6 +209,7 @@ CreateUserJob::exec() QString backupDirName = "dotfiles_backup_" + QDateTime::currentDateTime().toString( "yyyy-MM-dd_HH-mm-ss" ); existingHome.mkdir( backupDirName ); + // We need the extra `sh -c` here to ensure that we can expand the shell globs CalamaresUtils::System::instance()->targetEnvCall( { "sh", "-c", "mv -f " + shellFriendlyHome + "/.* " + shellFriendlyHome + "/" + backupDirName } ); } @@ -140,33 +217,21 @@ CreateUserJob::exec() cDebug() << "[CREATEUSER]: creating user"; - QStringList useradd { "useradd", "-m", "-U" }; - QString shell = gs->value( "userShell" ).toString(); - if ( !shell.isEmpty() ) - { - useradd << "-s" << shell; - } - useradd << "-c" << m_fullName; - useradd << m_userName; - - auto commandResult = CalamaresUtils::System::instance()->targetEnvCommand( useradd ); - if ( commandResult.getExitCode() ) + auto useraddResult = createUser( m_userName, m_fullName, gs->value( "userShell" ).toString() ); + if ( !useraddResult ) { - cError() << "useradd failed" << commandResult.getExitCode(); - return commandResult.explainProcess( useradd, std::chrono::seconds( 10 ) /* bogus timeout */ ); + return useraddResult; } - commandResult - = CalamaresUtils::System::instance()->targetEnvCommand( { "usermod", "-aG", defaultGroups, m_userName } ); - if ( commandResult.getExitCode() ) + auto usergroupsResult = setUserGroups( m_userName, groupsForThisUser ); + if ( !usergroupsResult ) { - cError() << "usermod failed" << commandResult.getExitCode(); - return commandResult.explainProcess( "usermod", std::chrono::seconds( 10 ) /* bogus timeout */ ); + return usergroupsResult; } QString userGroup = QString( "%1:%2" ).arg( m_userName ).arg( m_userName ); QString homeDir = QString( "/home/%1" ).arg( m_userName ); - commandResult = CalamaresUtils::System::instance()->targetEnvCommand( { "chown", "-R", userGroup, homeDir } ); + auto commandResult = CalamaresUtils::System::instance()->targetEnvCommand( { "chown", "-R", userGroup, homeDir } ); if ( commandResult.getExitCode() ) { cError() << "chown failed" << commandResult.getExitCode();