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
|
/*
This file is part of the Maude 3 interpreter.
Copyright 2020-2023 SRI International, Menlo Park, CA 94025, USA.
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
//
// Main process manipulation code.
//
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
bool
ProcessManagerSymbol::getChildProcess(DagNode* processArg, int& processId, ChildProcess*& cpp)
{
if (processArg->symbol() == processOidSymbol)
{
DagNode* idArg = safeCast(FreeDagNode*, processArg)->getArgument(0);
if (succSymbol->getSignedInt(idArg, processId))
{
ProcessMap::iterator i = childProcesses.find(processId);
if (i != childProcesses.end())
{
cpp = &(i->second);
return true;
}
}
}
return false;
}
bool
ProcessManagerSymbol::makeNonblockingSocketPair(int pair[2],
FreeDagNode* message,
ObjectSystemRewritingContext& context,
bool readOnly)
{
//
// pair[0] will be the parent side of the socket and it needs to
// be nonblocking because SocketManagerSymbol assumes nonblocking
// reads and writes.
//
// We also set the close-on-execute flag so that the file descriptors
// aren't leaked into future children.
//
// If the readOnly flag is set we shutdown() the write half of
// pair[0] for cleanliness.
//
const char* errText;
if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) != -1)
{
//
// Nonblocking is done by modifying the file status flags.
//
int flags = fcntl(pair[0], F_GETFL);
if (flags != -1 && fcntl(pair[0], F_SETFL, flags | O_NONBLOCK) != -1)
{
//
// Close on execute is done by modifying the file descriptor flags.
//
int flags2 = fcntl(pair[0], F_GETFD);
if (flags2 != -1 && fcntl(pair[0], F_SETFD, flags2 | FD_CLOEXEC) != -1)
{
if (!readOnly || shutdown(pair[0], SHUT_WR) != -1)
return true;
}
}
errText = strerror(errno); // close() is allowed to change errno
//
// Must not leak file descriptors.
//
close(pair[0]);
close(pair[1]);
}
else
errText = strerror(errno);
//
// One of the system calls failed. Return error message.
//
errorReply(errText, message, context);
return false;
}
bool
ProcessManagerSymbol::makeCloseOnExitPipe(int pair[2],
FreeDagNode* message,
ObjectSystemRewritingContext& context)
{
//
// We create a pipe where the writing end will be closed on execve()
// to allow detection of successful execve().
//
const char* errText;
if (pipe(pair) != -1)
{
//
// Close on execute is done by modifying the file descriptor flags.
//
int flags = fcntl(pair[WRITE_END], F_GETFD);
if (flags != -1 && fcntl(pair[WRITE_END], F_SETFD, flags | FD_CLOEXEC) != -1)
return true;
errText = strerror(errno); // close() is allowed to change errno
//
// Must not leak file descriptors.
//
close(pair[READ_END]);
close(pair[WRITE_END]);
}
else
errText = strerror(errno);
errorReply(errText, message, context);
return false;
}
bool
ProcessManagerSymbol::createProcess(FreeDagNode* message,
ObjectSystemRewritingContext& context)
{
Assert(message->getArgument(0)->symbol() == this, "misdirected message");
//
// We will allow (but not insist on) a full path to the executable file.
//
DagNode* executableArg = message->getArgument(2);
if (executableArg->symbol() != stringSymbol)
{
IssueAdvisory("process manager declined malformed message " << QUOTE(message) << '.');
return false;
}
//
// Check we have a list of strings and count the length.
//
DagNode* argumentsArg = message->getArgument(3);
int nrArgs = checkStringList(argumentsArg);
if (nrArgs == -1)
{
IssueAdvisory("process manager declined malformed message " << QUOTE(message) << '.');
return false;
}
//
// Currently we don't support any options but eventually we
// will stuff enviroment variable changes in here.
//
DagNode* optionsArg = message->getArgument(4);
if (optionsArg->symbol() != emptyProcessOptionSetSymbol)
{
IssueAdvisory("process manager declined malformed message " << QUOTE(message) << '.');
return false;
}
//
// Request looks well formed. Now see if we're allowed to
// created processes.
//
if (!allowProcesses)
{
IssueAdvisory("execution of arbitrary binaries disabled.");
errorReply("process creation disabled", message, context);
return true;
}
//
// Socket pair to communicate with stdin/stdout of created process.
//
int ioSockets[2];
if (!makeNonblockingSocketPair(ioSockets, message, context, false))
return true;
//
// Socket pair to communicate with stderr of created process.
//
int errSockets[2];
if (!makeNonblockingSocketPair(errSockets, message, context, true))
{
//
// Must not leak file descriptors.
//
close(ioSockets[0]);
close(ioSockets[1]);
return true;
}
//
// Now we need to deal with the issue that the child may
// fail to execute a new image and we need to recognize this
// in the parent. We do this with a close on execute pipe.
//
int failureReturnPipe[2];
if(!makeCloseOnExitPipe(failureReturnPipe, message, context))
{
//
// Must not leak file descriptors.
//
close(errSockets[0]);
close(errSockets[1]);
close(ioSockets[0]);
close(ioSockets[1]);
return true;
}
//
// Now we spawn a child process.
//
pid_t pid = fork();
if (pid == -1)
{
const char* errText = strerror(errno);
//
// Must not leak file descriptors.
//
close(failureReturnPipe[READ_END]);
close(failureReturnPipe[WRITE_END]);
close(errSockets[0]);
close(errSockets[1]);
close(ioSockets[0]);
close(ioSockets[1]);
errorReply(errText, message, context);
return true;
}
if (pid == 0)
{
//
// We are the child.
//
close(ioSockets[0]); // close parent end
close(failureReturnPipe[READ_END]); // close read end
dup2(ioSockets[1], STDIN_FILENO); // replace stdin with ioSockets[1]
dup2(ioSockets[1], STDOUT_FILENO); // replace stdout with ioSockets[1]
close(errSockets[0]); // close parent end
dup2(errSockets[1], STDERR_FILENO); // replace stderr with errSockets[1]
//
// Make the argument vector.
//
// We never free the strings we allocate via makeZeroTerminatedString()
// because we will either execvp() or exit().
//
const Rope& rope = safeCast(StringDagNode*, executableArg)->getValue();
const char* file = rope.makeZeroTerminatedString();
char* const* argv = makeStringArray(executableArg, argumentsArg, nrArgs);
//
// Replace Maude binary with file; on success failureReturnPipe[WRITE_END]
// will be closed, enabling the parent to see our success.
//
(void) execvp(file, argv);
//
// We can only reach here if the execvp() call failed.
// We pass an error message back though failureReturnPipe.
//
const char* errText = strerror(errno);
size_t length = strlen(errText);
while (length > 0)
{
ssize_t nrChars = write(failureReturnPipe[WRITE_END], errText, length);
if (nrChars < 0)
break;
length -= nrChars;
errText += nrChars;
}
close(failureReturnPipe[WRITE_END]); // just to be sure characters are in pipe
exit(1);
}
//
// We are the parent.
//
close(failureReturnPipe[WRITE_END]); // close write end
close(errSockets[1]); // close child end
close(ioSockets[1]); // close child end
//
// Now did the child succeed in executing a new image?
// We read the failureReturnPipe up to EOF to find out.
//
Rope errorMessage;
char buffer[ERROR_BUFFER_SIZE];
for (;;)
{
int nrChar = read(failureReturnPipe[READ_END], buffer, ERROR_BUFFER_SIZE);
if (nrChar <= 0)
break;
errorMessage += Rope(buffer, nrChar);
}
if (!(errorMessage.empty()))
{
//
// Non-empty error message means execvp() failed in the child.
// Close file descriptors and inject a processError() reply.
//
close(failureReturnPipe[READ_END]);
close(errSockets[0]);
close(ioSockets[0]);
errorReply(errorMessage, message, context);
return true;
}
//
// No characters before EOF indicates execvp() succeeded.
// We pass control of the sockets over to SocketManagerSymbol.
//
DagNode* ioSocketName = socketManagerSymbol->manageSocket(ioSockets[0],
false,
false,
context);
DagNode* errSocketName = socketManagerSymbol->manageSocket(errSockets[0],
false,
true,
context);
//
// Make new ChildProcess record.
//
childProcesses[pid].ioSocket = ioSockets[0];
childProcesses[pid].errSocket = errSockets[0];
Vector<DagNode*> reply(5);
reply.resize(1);
reply[0] = succSymbol->makeNatDag(pid);
DagNode* processName = processOidSymbol->makeDagNode(reply);
context.addExternalObject(processName, this);
reply.resize(5);
reply[2] = processName;
reply[3] = ioSocketName;
reply[4] = errSocketName;
reply[1] = message->getArgument(0);
DagNode* target = message->getArgument(1);
reply[0] = target;
DagNode* replyMsg = createdProcessMsg->makeDagNode(reply);
DebugAdvisory("placing " << replyMsg << " in the buffer");
context.bufferMessage(target, replyMsg);
return true;
}
int
ProcessManagerSymbol::checkStringList(DagNode* stringList)
{
//
// Returns length of list or -1 if bad.
//
Symbol* s = stringList->symbol();
if (s == stringListSymbol)
{
//
// List of >=2 strings.
//
int count = 0;
for (DagArgumentIterator i(stringList); i.valid(); i.next())
{
if (i.argument()->symbol() != stringSymbol)
return -1;
++count;
}
return count;
}
else if (s == stringSymbol)
return 1; // singleton case
else if (s == nilStringListSymbol)
return 0; // empty case
return -1;
}
char* const*
ProcessManagerSymbol::makeStringArray(DagNode* zeroArgument,
DagNode* remainingArguments,
int nrRemainingArguments)
{
char** array = new char*[1 + nrRemainingArguments + 1];
const Rope& rope = safeCast(StringDagNode*, zeroArgument)->getValue();
array[0] = rope.makeZeroTerminatedString();
int index = 1;
Symbol* s = remainingArguments->symbol();
if (s == stringListSymbol)
{
//
// List of >=2 strings.
//
for (DagArgumentIterator i(remainingArguments); i.valid(); i.next(), ++index)
{
const Rope& rope = safeCast(StringDagNode*, i.argument())->getValue();
array[index] = rope.makeZeroTerminatedString();
}
}
else if (s == stringSymbol)
{
//
// Singleton case.
//
const Rope& rope = safeCast(StringDagNode*, remainingArguments)->getValue();
array[index] = rope.makeZeroTerminatedString();
++index;
}
array[index] = 0;
return array;
}
bool
ProcessManagerSymbol::waitForExit(FreeDagNode* message, ObjectSystemRewritingContext& context)
{
DebugEnter("message = " << message);
//
// If we already saw a waitForExit() for this process, either
// it completed and removed the child from ProcessMap OR we
// have a pending waitForExit() in which case we fill out
// the waitContext to allow for an async reply. Either
// way we don't accept a second waitForExit() message.
//
DagNode* processName = message->getArgument(0);
int processId;
ChildProcess* cpp;
if (getChildProcess(processName, processId, cpp))
{
//
// If we already have an incomplete waitForExit() we don't
// accept a second one.
//
if (cpp->waitContext != 0)
{
IssueAdvisory(processName << " declined extra waitForExit() message.");
return false;
}
//
// We need to request a callback before we call waitpid() because
// callbacks rely on SIGCHLD and the signal could arrive between
// the waitpid() call and the callback request and be lost.
//
requestChildExitCallback(processId);
//
// If child already exited, there won't be a signal and hence
// no callback.
//
int wstatus;
pid_t exitPid = waitpid(processId, &wstatus, WNOHANG);
Assert(exitPid != -1, "unexpect error from waitpid() for process " << processId);
if (exitPid != 0)
{
Assert(exitPid == processId, "waitpid() for " << processId << " got " << exitPid);
//
// Child status changes; make sure it is an exit.
//
if (WIFEXITED(wstatus))
{
//
// Normal exit with exit code.
//
cancelChildExitCallback(processId);
int exitCode = WEXITSTATUS(wstatus);
exitedReply(processId, exitCode, message, context);
return true;
}
else if (WIFSIGNALED(wstatus))
{
//
// Terminated by signal.
//
cancelChildExitCallback(processId);
int terminatingSignal = WTERMSIG(wstatus);
exitedReply(processId, ~terminatingSignal, message, context);
return true;
}
else
{
//
// Some other status change. This means child was alive when
// waitpid() was called so we can rely on the callback.
//
}
}
else
{
//
// No status change. This means child was alive when
// waitpid() was called so we can rely on the callback.
//
}
//
// We will rely on the callback we just requested so we need to
// save the context and message for later.
//
cpp->waitContext = &context;
cpp->waitMessage.setNode(message);
return true;
}
IssueAdvisory("no process to receive message " << QUOTE(message) << '.');
return false;
}
int
ProcessManagerSymbol::getSignalNumber(const char* signalString)
{
#define MACRO(signalName) \
if (strcmp(signalString, #signalName) == 0) \
return signalName;
#include "supportedSignals.cc"
#undef MACRO
return NONE;
}
bool
ProcessManagerSymbol::signalProcess(FreeDagNode* message, ObjectSystemRewritingContext& context)
{
DagNode* signalName = message->getArgument(2);
if (signalName->symbol() == stringSymbol)
{
const Rope& rope = safeCast(StringDagNode*, signalName)->getValue();
char* signalString = rope.makeZeroTerminatedString();
int signalNumber = getSignalNumber(signalString);
delete [] signalString;
if (signalNumber != NONE)
{
DagNode* processName = message->getArgument(0);
int processId;
ChildProcess* cpp;
if (getChildProcess(processName, processId, cpp))
{
kill(processId, signalNumber);
//
// Make signaledProcess() message.
//
DagNode* target = message->getArgument(1);
Vector<DagNode*> reply(2);
reply[0] = target;
reply[1] = processName;
context.bufferMessage(target, signaledProcessMsg->makeDagNode(reply));
return true;
}
IssueAdvisory("no process to receive message " << QUOTE(message) << '.');
}
}
else
IssueAdvisory("malformed message " << QUOTE(message) << '.');
return false;
}
|