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
|
/** @file runfilter.cc
* @brief Run an external filter and capture its output in a std::string.
*/
/* Copyright (C) 2003,2006,2007,2009,2010,2011,2013,2015,2017,2018 Olly Betts
*
* 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; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <config.h>
#include "runfilter.h"
#include <iostream>
#include <string>
#include <vector>
#include <sys/types.h>
#include "safefcntl.h"
#include <cerrno>
#include <cstdio>
#include <cstring>
#ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
#endif
#ifdef HAVE_SYS_RESOURCE_H
# include <sys/resource.h>
#endif
#include "safesysselect.h"
#ifdef HAVE_SYS_SOCKET_H
# include <sys/socket.h>
#endif
#include "safesyswait.h"
#include "safeunistd.h"
#if defined HAVE_FORK && defined HAVE_SOCKETPAIR
# include <signal.h>
#endif
#include "freemem.h"
#include "stringutils.h"
#ifdef _MSC_VER
# define popen _popen
# define pclose _pclose
#endif
using namespace std;
static int devnull = -1;
#if defined HAVE_FORK && defined HAVE_SOCKETPAIR
bool
command_needs_shell(const char * p)
{
for ( ; *p; ++p) {
// Probably overly conservative, but suitable for
// real-world cases.
if (strchr("!\"#$&()*;<>?[\\]^`{|}~", *p) != NULL) {
return true;
}
}
return false;
}
static bool
unquote(string & s, size_t & j)
{
bool quoted = false;
if (s[j] == '\'') {
single_quoted:
quoted = true;
s.erase(j, 1);
while (true) {
j = s.find('\'', j + 1);
if (j == s.npos) {
// Unmatched ' in command string.
// dash exits 2 in this case, bash exits 1.
_exit(2);
}
// Replace four character sequence '\'' with ' - this is
// how a single quote inside single quotes gets escaped.
if (s[j + 1] != '\\' ||
s[j + 2] != '\'' ||
s[j + 3] != '\'') {
break;
}
s.erase(j + 1, 3);
}
if (j + 1 != s.size()) {
char ch = s[j + 1];
if (ch != ' ' && ch != '\t' && ch != '\n') {
// Handle the expansion of e.g.: --input=%f,html
s.erase(j, 1);
goto out_of_quotes;
}
}
} else {
out_of_quotes:
j = s.find_first_of(" \t\n'", j + 1);
// Handle the expansion of e.g.: --input=%f
if (j != s.npos && s[j] == '\'') goto single_quoted;
}
if (j != s.npos) {
s[j++] = '\0';
}
return quoted;
}
static pid_t pid_to_kill_on_signal;
#ifdef HAVE_SIGACTION
static struct sigaction old_hup_handler;
static struct sigaction old_int_handler;
static struct sigaction old_quit_handler;
static struct sigaction old_term_handler;
extern "C" {
static void
handle_signal(int signum)
{
if (pid_to_kill_on_signal) {
kill(pid_to_kill_on_signal, SIGKILL);
pid_to_kill_on_signal = 0;
}
switch (signum) {
case SIGHUP:
sigaction(signum, &old_hup_handler, NULL);
break;
case SIGINT:
sigaction(signum, &old_int_handler, NULL);
break;
case SIGQUIT:
sigaction(signum, &old_quit_handler, NULL);
break;
case SIGTERM:
sigaction(signum, &old_term_handler, NULL);
break;
default:
return;
}
raise(signum);
}
}
static inline void
runfilter_init_signal_handlers_()
{
struct sigaction sa;
sa.sa_handler = handle_signal;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGHUP, &sa, &old_hup_handler);
sigaction(SIGINT, &sa, &old_int_handler);
sigaction(SIGQUIT, &sa, &old_quit_handler);
sigaction(SIGTERM, &sa, &old_term_handler);
}
#else
static sighandler_t old_hup_handler;
static sighandler_t old_int_handler;
static sighandler_t old_quit_handler;
static sighandler_t old_term_handler;
extern "C" {
static void
handle_signal(int signum)
{
if (pid_to_kill_on_signal) {
kill(pid_to_kill_on_signal, SIGKILL);
pid_to_kill_on_signal = 0;
}
switch (signum) {
case SIGHUP:
signal(signum, old_hup_handler);
break;
case SIGINT:
signal(signum, old_int_handler);
break;
case SIGQUIT:
signal(signum, old_quit_handler);
break;
case SIGTERM:
signal(signum, old_term_handler);
break;
default:
return;
}
raise(signum);
}
}
static inline void
runfilter_init_signal_handlers_()
{
old_hup_handler = signal(SIGHUP, handle_signal);
old_int_handler = signal(SIGINT, handle_signal);
old_quit_handler = signal(SIGQUIT, handle_signal);
old_term_handler = signal(SIGTERM, handle_signal);
}
#endif
#else
bool
command_needs_shell(const char *)
{
// We don't try to avoid the shell on this platform, so don't waste time
// analysing commands to see if they could.
return true;
}
static inline void
runfilter_init_signal_handlers_()
{
}
#endif
void
runfilter_init()
{
runfilter_init_signal_handlers_();
devnull = open("/dev/null", O_WRONLY);
if (devnull < 0) {
cerr << "Failed to open /dev/null: " << strerror(errno) << endl;
exit(1);
}
// Ensure that devnull isn't fd 0, 1 or 2 (stdin, stdout or stderr) and
// that we have open fds for stdin, stdout and stderr. This simplifies the
// code after fork() because it doesn't need to worry about such corner
// cases.
while (devnull <= 2) {
devnull = dup(devnull);
}
}
void
run_filter(int fd_in, const string& cmd, bool use_shell, string* out,
int alt_status)
{
#if defined HAVE_FORK && defined HAVE_SOCKETPAIR
// We want to be able to get the exit status of the child process.
signal(SIGCHLD, SIG_DFL);
int fds[2];
if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, fds) < 0)
throw ReadError("socketpair failed");
pid_t child = fork();
if (child == 0) {
// We're the child process.
#ifdef HAVE_SETPGID
// Put the child process into its own process group, so that we can
// easily kill it and any children it in turn forks if we need to.
setpgid(0, 0);
pid_to_kill_on_signal = -child;
#else
pid_to_kill_on_signal = child;
#endif
// Close the parent's side of the socket pair.
close(fds[0]);
if (fd_in != -1) {
// Connect piped input to stdin.
dup2(fd_in, 0);
close(fd_in);
}
// Connect stdout to our side of the socket pair.
dup2(fds[1], 1);
#ifdef HAVE_SETRLIMIT
// Impose some pretty generous resource limits to prevent run-away
// filter programs from causing problems.
// Limit CPU time to 300 seconds (5 minutes).
struct rlimit cpu_limit = { 300, RLIM_INFINITY };
setrlimit(RLIMIT_CPU, &cpu_limit);
#if defined RLIMIT_AS || defined RLIMIT_VMEM || defined RLIMIT_DATA
// Limit process data to free physical memory.
long mem = get_free_physical_memory();
if (mem > 0) {
struct rlimit ram_limit = {
static_cast<rlim_t>(mem),
RLIM_INFINITY
};
#ifdef RLIMIT_AS
setrlimit(RLIMIT_AS, &ram_limit);
#elif defined RLIMIT_VMEM
setrlimit(RLIMIT_VMEM, &ram_limit);
#else
// Only limits the data segment rather than the total address
// space, but that's better than nothing.
setrlimit(RLIMIT_DATA, &ram_limit);
#endif
}
#endif
#endif
if (use_shell) {
#if !defined HAVE_SETENV && !defined HAVE_PUTENV
use_shell_after_all:
#endif
execl("/bin/sh", "/bin/sh", "-c", cmd.c_str(), (void*)NULL);
_exit(-1);
}
string s(cmd);
// Handle any environment variable assignments.
// Name must start with alpha or '_', contain only alphanumerics and
// '_', and there must be no quoting of either the name or the '='.
size_t j = 0;
while (true) {
j = s.find_first_not_of(" \t\n", j);
if (!(C_isalnum(s[j]) || s[j] == '_')) break;
size_t i = j;
do ++j; while (C_isalnum(s[j]) || s[j] == '_');
if (s[j] != '=') {
j = i;
break;
}
#ifdef HAVE_SETENV
size_t eq = j;
unquote(s, j);
s[eq] = '\0';
setenv(&s[i], &s[eq + 1], 1);
j = s.find_first_not_of(" \t\n", j);
#elif defined HAVE_PUTENV
unquote(s, j);
putenv(&s[i]);
#else
goto use_shell_after_all;
#endif
}
vector<const char *> argv;
while (true) {
size_t i = s.find_first_not_of(" \t\n", j);
if (i == string::npos) break;
bool quoted = unquote(s, j);
const char * word = s.c_str() + i;
if (!quoted) {
// Handle simple cases of redirection.
if (strcmp(word, ">/dev/null") == 0) {
dup2(devnull, 1);
continue;
}
if (strcmp(word, "2>/dev/null") == 0) {
dup2(devnull, 2);
continue;
}
if (strcmp(word, "2>&1") == 0) {
dup2(1, 2);
continue;
}
if (strcmp(word, "1>&2") == 0) {
dup2(2, 1);
continue;
}
}
argv.push_back(word);
}
if (argv.empty()) _exit(0);
argv.push_back(NULL);
execvp(argv[0], const_cast<char **>(&argv[0]));
// Emulate shell behaviour and exit with status 127 if the command
// isn't found, and status 126 for other problems. In particular, we
// rely on 127 below to throw NoSuchFilter.
_exit(errno == ENOENT ? 127 : 126);
}
// We're the parent process.
// Close the child's side of the socket pair.
close(fds[1]);
if (child == -1) {
// fork() failed.
close(fds[0]);
throw ReadError("fork failed");
}
int fd = fds[0];
fd_set readfds;
FD_ZERO(&readfds);
while (true) {
// If we wait 300 seconds (5 minutes) without getting data from the
// filter, then give up to avoid waiting forever for a filter which
// has ended up blocked waiting for something which will never happen.
struct timeval tv;
tv.tv_sec = 300;
tv.tv_usec = 0;
FD_SET(fd, &readfds);
int r = select(fd + 1, &readfds, NULL, NULL, &tv);
if (r <= 0) {
if (r < 0) {
if (errno == EINTR || errno == EAGAIN) {
// select() interrupted by a signal, so retry.
continue;
}
cerr << "Reading from filter failed (" << strerror(errno) << ")"
<< endl;
} else {
cerr << "Filter inactive for too long" << endl;
}
#ifdef HAVE_SETPGID
kill(-child, SIGKILL);
#else
kill(child, SIGKILL);
#endif
close(fd);
int status = 0;
while (waitpid(child, &status, 0) < 0 && errno == EINTR) { }
pid_to_kill_on_signal = 0;
throw ReadError(status);
}
char buf[4096];
ssize_t res = read(fd, buf, sizeof(buf));
if (res == 0) break;
if (res == -1) {
if (errno == EINTR) {
// read() interrupted by a signal, so retry.
continue;
}
close(fd);
#ifdef HAVE_SETPGID
kill(-child, SIGKILL);
#endif
int status = 0;
while (waitpid(child, &status, 0) < 0 && errno == EINTR) { }
pid_to_kill_on_signal = 0;
throw ReadError(status);
}
if (out) out->append(buf, res);
}
close(fd);
#ifdef HAVE_SETPGID
kill(-child, SIGKILL);
#endif
int status = 0;
while (waitpid(child, &status, 0) < 0) {
if (errno != EINTR)
throw ReadError("wait pid failed");
}
pid_to_kill_on_signal = 0;
#else
(void)use_shell;
FILE * fh = popen(cmd.c_str(), "r");
if (fh == NULL) throw ReadError("popen failed");
while (!feof(fh)) {
char buf[4096];
size_t len = fread(buf, 1, 4096, fh);
if (ferror(fh)) {
(void)pclose(fh);
throw ReadError("fread failed");
}
if (out) out->append(buf, len);
}
int status = pclose(fh);
#endif
if (WIFEXITED(status)) {
int exit_status = WEXITSTATUS(status);
if (exit_status == 0 || exit_status == alt_status)
return;
if (exit_status == 127)
throw NoSuchFilter();
}
#ifdef SIGXCPU
if (WIFSIGNALED(status) && WTERMSIG(status) == SIGXCPU) {
cerr << "Filter process consumed too much CPU time" << endl;
}
#endif
throw ReadError(status);
}
|