Skip to content

Commit fb30135

Browse files
reddevillgdengbo11
authored andcommitted
fix: Correctly quote arguments in container entrypoint script
This change introduces a quoting mechanism (`quoteArg`) that: 1. Encloses each argument in single quotes. 2. Escapes embedded single quotes within an argument (e.g., `it's` becomes `'it'\''s'`). This ensures that arguments are passed to the `exec` command in the entrypoint script as single, intact units, even if they contain spaces or single quotes. Signed-off-by: reddevillg <reddevillg@gmail.com>
1 parent 9450698 commit fb30135

1 file changed

Lines changed: 21 additions & 8 deletions

File tree

libs/linglong/src/linglong/runtime/container.cpp

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -190,13 +190,7 @@ utils::error::Result<void> Container::run(const ocppi::runtime::config::types::P
190190
});
191191

192192
auto originalArgs =
193-
this->cfg.process->args.value_or(std::vector<std::string>{ "echo", "'noting to run'" });
194-
QStringList appArgs;
195-
std::transform(originalArgs.begin(),
196-
originalArgs.end(),
197-
std::back_inserter(appArgs),
198-
QString::fromStdString);
199-
appArgs.prepend("exec");
193+
this->cfg.process->args.value_or(std::vector<std::string>{ "echo", "noting to run" });
200194

201195
auto entrypoint = bundle / "entrypoint.sh";
202196
{
@@ -211,7 +205,26 @@ utils::error::Result<void> Container::run(const ocppi::runtime::config::types::P
211205
ofs << "#!/run/linglong/container-init /bin/bash\n";
212206
ofs << "source /etc/profile\n"; // we need use /etc/profile to generate all needed
213207
// environment variables
214-
ofs << appArgs.join(' ').toStdString();
208+
ofs << "exec ";
209+
210+
// quote the argument to avoid the space in the argument and use single quote to avoid the
211+
// shell to expand the argument
212+
// example:
213+
// arg: "let's go"
214+
// quoteArg: "'let'\''s go'"
215+
auto quoteArg = [](std::string arg) {
216+
const std::string quotePrefix = "'\\";
217+
for (auto it = arg.begin(); it != arg.end(); it++) {
218+
if (*it == '\'') {
219+
it = arg.insert(it, quotePrefix.cbegin(), quotePrefix.cend());
220+
it = arg.insert(it + quotePrefix.size() + 1, 1, '\'');
221+
}
222+
}
223+
return "'" + arg + "'";
224+
};
225+
for (auto arg : originalArgs) {
226+
ofs << quoteArg(arg) << " ";
227+
}
215228
}
216229

217230
std::filesystem::permissions(entrypoint, std::filesystem::perms::owner_all, ec);

0 commit comments

Comments
 (0)