File indexing completed on 2024-04-28 05:25:54

0001 // SPDX-FileCopyrightText: 2022 Jonah BrĂ¼chert <jbb@kaidan.im>
0002 // SPDX-FileCopyrightText: 2022 Harald Sitter <sitter@kde.org>
0003 // SPDX-License-Identifier: GPL-2.0-or-later
0004 
0005 #include "shellcommand.h"
0006 
0007 #include <KSandbox>
0008 #include <KShell>
0009 
0010 #include <pwd.h>
0011 #include <sys/types.h>
0012 #include <unistd.h>
0013 
0014 ShellCommand::ShellCommand(QObject *parent)
0015     : QObject(parent)
0016     , m_cmd(KShell::splitArgs(command()))
0017 {
0018 }
0019 
0020 QString ShellCommand::executable() const
0021 {
0022     return m_cmd.front();
0023 }
0024 
0025 QStringList ShellCommand::args() const
0026 {
0027     return m_cmd.mid(1);
0028 }
0029 
0030 QString ShellCommand::command() const
0031 {
0032     // Signal to running processes that we can handle colors
0033     qputenv("TERM", "xterm-256color");
0034 
0035     if (KSandbox::isFlatpak()) {
0036         auto shell = []() {
0037             // From Konsole: https://github.com/KDE/konsole/blob/c450e754c789915b6dd27514a18f311ba9249981/src/profile/Profile.cpp#L177
0038             auto pw = getpwuid(getuid());
0039             // pw: Do not pass the returned pointer to free.
0040             if (pw != nullptr) {
0041                 QProcess proc;
0042                 proc.setProgram(QStringLiteral("getent"));
0043                 proc.setArguments({QStringLiteral("passwd"), QString::number(pw->pw_uid)});
0044                 KSandbox::startHostProcess(proc);
0045                 proc.waitForFinished();
0046                 return QString::fromUtf8(proc.readAllStandardOutput().simplified().split(':').at(6));
0047             } else {
0048                 return QStringLiteral("bash");
0049             }
0050         }();
0051 
0052         return QStringLiteral("host-spawn %1").arg(shell);
0053     } else {
0054         return qEnvironmentVariable("SHELL");
0055     }
0056 }