root/lib/services/services_linux.c

/* [previous][next][first][last][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. sigchld_setup
  2. sigchld_open
  3. sigchld_close
  4. sigchld_received
  5. sigchld_cleanup
  6. sigchld_handler
  7. sigchld_setup
  8. sigchld_open
  9. sigchld_close
  10. sigchld_received
  11. sigchld_cleanup
  12. close_pipe
  13. svc_read_output
  14. dispatch_stdout
  15. dispatch_stderr
  16. pipe_out_done
  17. pipe_err_done
  18. set_ocf_env
  19. set_ocf_env_with_prefix
  20. set_alert_env
  21. add_action_env_vars
  22. pipe_in_single_parameter
  23. pipe_in_action_stdin_parameters
  24. recurring_action_timer
  25. services__finalize_async_op
  26. close_op_input
  27. finish_op_output
  28. log_op_output
  29. parse_exit_reason_from_stderr
  30. async_action_complete
  31. services__generic_error
  32. services__not_installed_error
  33. services__authorization_error
  34. services__configuration_error
  35. services__handle_exec_error
  36. exit_child
  37. action_launch_child
  38. wait_for_sync_result
  39. services__execute_file
  40. services_os_get_single_directory_list
  41. services_os_get_directory_list

   1 /*
   2  * Copyright 2010-2024 the Pacemaker project contributors
   3  *
   4  * The version control history for this file may have further details.
   5  *
   6  * This source code is licensed under the GNU Lesser General Public License
   7  * version 2.1 or later (LGPLv2.1+) WITHOUT ANY WARRANTY.
   8  */
   9 
  10 #include <crm_internal.h>
  11 
  12 #include <sys/types.h>
  13 #include <sys/stat.h>
  14 #include <sys/wait.h>
  15 #include <errno.h>
  16 #include <unistd.h>
  17 #include <dirent.h>
  18 #include <grp.h>
  19 #include <string.h>
  20 #include <sys/time.h>
  21 #include <sys/resource.h>
  22 
  23 #include "crm/crm.h"
  24 #include "crm/common/mainloop.h"
  25 #include "crm/services.h"
  26 #include "crm/services_internal.h"
  27 
  28 #include "services_private.h"
  29 
  30 static void close_pipe(int fildes[]);
  31 
  32 /* We have two alternative ways of handling SIGCHLD when synchronously waiting
  33  * for spawned processes to complete. Both rely on polling a file descriptor to
  34  * discover SIGCHLD events.
  35  *
  36  * If sys/signalfd.h is available (e.g. on Linux), we call signalfd() to
  37  * generate the file descriptor. Otherwise, we use the "self-pipe trick"
  38  * (opening a pipe and writing a byte to it when SIGCHLD is received).
  39  */
  40 #ifdef HAVE_SYS_SIGNALFD_H
  41 
  42 // signalfd() implementation
  43 
  44 #include <sys/signalfd.h>
  45 
  46 // Everything needed to manage SIGCHLD handling
  47 struct sigchld_data_s {
  48     sigset_t mask;      // Signals to block now (including SIGCHLD)
  49     sigset_t old_mask;  // Previous set of blocked signals
  50     bool ignored;       // If SIGCHLD for another child has been ignored
  51 };
  52 
  53 // Initialize SIGCHLD data and prepare for use
  54 static bool
  55 sigchld_setup(struct sigchld_data_s *data)
     /* [previous][next][first][last][top][bottom][index][help] */
  56 {
  57     sigemptyset(&(data->mask));
  58     sigaddset(&(data->mask), SIGCHLD);
  59 
  60     sigemptyset(&(data->old_mask));
  61 
  62     // Block SIGCHLD (saving previous set of blocked signals to restore later)
  63     if (sigprocmask(SIG_BLOCK, &(data->mask), &(data->old_mask)) < 0) {
  64         crm_info("Wait for child process completion failed: %s "
  65                  QB_XS " source=sigprocmask", pcmk_rc_str(errno));
  66         return false;
  67     }
  68 
  69     data->ignored = false;
  70 
  71     return true;
  72 }
  73 
  74 // Get a file descriptor suitable for polling for SIGCHLD events
  75 static int
  76 sigchld_open(struct sigchld_data_s *data)
     /* [previous][next][first][last][top][bottom][index][help] */
  77 {
  78     int fd;
  79 
  80     CRM_CHECK(data != NULL, return -1);
  81 
  82     fd = signalfd(-1, &(data->mask), SFD_NONBLOCK);
  83     if (fd < 0) {
  84         crm_info("Wait for child process completion failed: %s "
  85                  QB_XS " source=signalfd", pcmk_rc_str(errno));
  86     }
  87     return fd;
  88 }
  89 
  90 // Close a file descriptor returned by sigchld_open()
  91 static void
  92 sigchld_close(int fd)
     /* [previous][next][first][last][top][bottom][index][help] */
  93 {
  94     if (fd > 0) {
  95         close(fd);
  96     }
  97 }
  98 
  99 // Return true if SIGCHLD was received from polled fd
 100 static bool
 101 sigchld_received(int fd, int pid, struct sigchld_data_s *data)
     /* [previous][next][first][last][top][bottom][index][help] */
 102 {
 103     struct signalfd_siginfo fdsi;
 104     ssize_t s;
 105 
 106     if (fd < 0) {
 107         return false;
 108     }
 109     s = read(fd, &fdsi, sizeof(struct signalfd_siginfo));
 110     if (s != sizeof(struct signalfd_siginfo)) {
 111         crm_info("Wait for child process completion failed: %s "
 112                  QB_XS " source=read", pcmk_rc_str(errno));
 113 
 114     } else if (fdsi.ssi_signo == SIGCHLD) {
 115         if (fdsi.ssi_pid == pid) {
 116             return true;
 117 
 118         } else {
 119             /* This SIGCHLD is for another child. We have to ignore it here but
 120              * will still need to resend it after this synchronous action has
 121              * completed and SIGCHLD has been restored to be handled by the
 122              * previous SIGCHLD handler, so that it will be handled.
 123              */
 124             data->ignored = true;
 125             return false;
 126         }
 127     }
 128     return false;
 129 }
 130 
 131 // Do anything needed after done waiting for SIGCHLD
 132 static void
 133 sigchld_cleanup(struct sigchld_data_s *data)
     /* [previous][next][first][last][top][bottom][index][help] */
 134 {
 135     // Restore the original set of blocked signals
 136     if ((sigismember(&(data->old_mask), SIGCHLD) == 0)
 137         && (sigprocmask(SIG_UNBLOCK, &(data->mask), NULL) < 0)) {
 138         crm_warn("Could not clean up after child process completion: %s",
 139                  pcmk_rc_str(errno));
 140     }
 141 
 142     // Resend any ignored SIGCHLD for other children so that they'll be handled.
 143     if (data->ignored && kill(getpid(), SIGCHLD) != 0) {
 144         crm_warn("Could not resend ignored SIGCHLD to ourselves: %s",
 145                  pcmk_rc_str(errno));
 146     }
 147 }
 148 
 149 #else // HAVE_SYS_SIGNALFD_H not defined
 150 
 151 // Self-pipe implementation (see above for function descriptions)
 152 
 153 struct sigchld_data_s {
 154     int pipe_fd[2];             // Pipe file descriptors
 155     struct sigaction sa;        // Signal handling info (with SIGCHLD)
 156     struct sigaction old_sa;    // Previous signal handling info
 157     bool ignored;               // If SIGCHLD for another child has been ignored
 158 };
 159 
 160 // We need a global to use in the signal handler
 161 volatile struct sigchld_data_s *last_sigchld_data = NULL;
 162 
 163 static void
 164 sigchld_handler(void)
     /* [previous][next][first][last][top][bottom][index][help] */
 165 {
 166     // We received a SIGCHLD, so trigger pipe polling
 167     if ((last_sigchld_data != NULL)
 168         && (last_sigchld_data->pipe_fd[1] >= 0)
 169         && (write(last_sigchld_data->pipe_fd[1], "", 1) == -1)) {
 170         crm_info("Wait for child process completion failed: %s "
 171                  QB_XS " source=write", pcmk_rc_str(errno));
 172     }
 173 }
 174 
 175 static bool
 176 sigchld_setup(struct sigchld_data_s *data)
     /* [previous][next][first][last][top][bottom][index][help] */
 177 {
 178     int rc;
 179 
 180     data->pipe_fd[0] = data->pipe_fd[1] = -1;
 181 
 182     if (pipe(data->pipe_fd) == -1) {
 183         crm_info("Wait for child process completion failed: %s "
 184                  QB_XS " source=pipe", pcmk_rc_str(errno));
 185         return false;
 186     }
 187 
 188     rc = pcmk__set_nonblocking(data->pipe_fd[0]);
 189     if (rc != pcmk_rc_ok) {
 190         crm_info("Could not set pipe input non-blocking: %s " QB_XS " rc=%d",
 191                  pcmk_rc_str(rc), rc);
 192     }
 193     rc = pcmk__set_nonblocking(data->pipe_fd[1]);
 194     if (rc != pcmk_rc_ok) {
 195         crm_info("Could not set pipe output non-blocking: %s " QB_XS " rc=%d",
 196                  pcmk_rc_str(rc), rc);
 197     }
 198 
 199     // Set SIGCHLD handler
 200     data->sa.sa_handler = (sighandler_t) sigchld_handler;
 201     data->sa.sa_flags = 0;
 202     sigemptyset(&(data->sa.sa_mask));
 203     if (sigaction(SIGCHLD, &(data->sa), &(data->old_sa)) < 0) {
 204         crm_info("Wait for child process completion failed: %s "
 205                  QB_XS " source=sigaction", pcmk_rc_str(errno));
 206     }
 207 
 208     data->ignored = false;
 209 
 210     // Remember data for use in signal handler
 211     last_sigchld_data = data;
 212     return true;
 213 }
 214 
 215 static int
 216 sigchld_open(struct sigchld_data_s *data)
     /* [previous][next][first][last][top][bottom][index][help] */
 217 {
 218     CRM_CHECK(data != NULL, return -1);
 219     return data->pipe_fd[0];
 220 }
 221 
 222 static void
 223 sigchld_close(int fd)
     /* [previous][next][first][last][top][bottom][index][help] */
 224 {
 225     // Pipe will be closed in sigchld_cleanup()
 226     return;
 227 }
 228 
 229 static bool
 230 sigchld_received(int fd, int pid, struct sigchld_data_s *data)
     /* [previous][next][first][last][top][bottom][index][help] */
 231 {
 232     char ch;
 233 
 234     if (fd < 0) {
 235         return false;
 236     }
 237 
 238     // Clear out the self-pipe
 239     while (read(fd, &ch, 1) == 1) /*omit*/;
 240     return true;
 241 }
 242 
 243 static void
 244 sigchld_cleanup(struct sigchld_data_s *data)
     /* [previous][next][first][last][top][bottom][index][help] */
 245 {
 246     // Restore the previous SIGCHLD handler
 247     if (sigaction(SIGCHLD, &(data->old_sa), NULL) < 0) {
 248         crm_warn("Could not clean up after child process completion: %s",
 249                  pcmk_rc_str(errno));
 250     }
 251 
 252     close_pipe(data->pipe_fd);
 253 
 254     // Resend any ignored SIGCHLD for other children so that they'll be handled.
 255     if (data->ignored && kill(getpid(), SIGCHLD) != 0) {
 256         crm_warn("Could not resend ignored SIGCHLD to ourselves: %s",
 257                  pcmk_rc_str(errno));
 258     }
 259 }
 260 
 261 #endif
 262 
 263 /*!
 264  * \internal
 265  * \brief Close the two file descriptors of a pipe
 266  *
 267  * \param[in,out] fildes  Array of file descriptors opened by pipe()
 268  */
 269 static void
 270 close_pipe(int fildes[])
     /* [previous][next][first][last][top][bottom][index][help] */
 271 {
 272     if (fildes[0] >= 0) {
 273         close(fildes[0]);
 274         fildes[0] = -1;
 275     }
 276     if (fildes[1] >= 0) {
 277         close(fildes[1]);
 278         fildes[1] = -1;
 279     }
 280 }
 281 
 282 #define out_type(is_stderr) ((is_stderr)? "stderr" : "stdout")
 283 
 284 // Maximum number of bytes of stdout or stderr we'll accept
 285 #define MAX_OUTPUT (10 * 1024 * 1024)
 286 
 287 static gboolean
 288 svc_read_output(int fd, svc_action_t * op, bool is_stderr)
     /* [previous][next][first][last][top][bottom][index][help] */
 289 {
 290     char *data = NULL;
 291     ssize_t rc = 0;
 292     size_t len = 0;
 293     size_t discarded = 0;
 294     char buf[500];
 295     static const size_t buf_read_len = sizeof(buf) - 1;
 296 
 297     if (fd < 0) {
 298         crm_trace("No fd for %s", op->id);
 299         return FALSE;
 300     }
 301 
 302     if (is_stderr && op->stderr_data) {
 303         len = strlen(op->stderr_data);
 304         data = op->stderr_data;
 305         crm_trace("Reading %s stderr into offset %lld",
 306                   op->id, (long long) len);
 307 
 308     } else if (is_stderr == FALSE && op->stdout_data) {
 309         len = strlen(op->stdout_data);
 310         data = op->stdout_data;
 311         crm_trace("Reading %s stdout into offset %lld",
 312                   op->id, (long long) len);
 313 
 314     } else {
 315         crm_trace("Reading %s %s", op->id, out_type(is_stderr));
 316     }
 317 
 318     do {
 319         errno = 0;
 320         rc = read(fd, buf, buf_read_len);
 321         if (rc > 0) {
 322             if (len < MAX_OUTPUT) {
 323                 buf[rc] = 0;
 324                 crm_trace("Received %lld bytes of %s %s: %.80s",
 325                           (long long) rc, op->id, out_type(is_stderr), buf);
 326                 data = pcmk__realloc(data, len + rc + 1);
 327                 strcpy(data + len, buf);
 328                 len += rc;
 329             } else {
 330                 discarded += rc;
 331             }
 332 
 333         } else if (errno != EINTR) { // Fatal error or EOF
 334             rc = 0;
 335             break;
 336         }
 337     } while ((rc == buf_read_len) || (rc < 0));
 338 
 339     if (discarded > 0) {
 340         crm_warn("Truncated %s %s to %lld bytes (discarded %lld)",
 341                  op->id, out_type(is_stderr), (long long) len,
 342                  (long long) discarded);
 343     }
 344 
 345     if (is_stderr) {
 346         op->stderr_data = data;
 347     } else {
 348         op->stdout_data = data;
 349     }
 350 
 351     return rc != 0;
 352 }
 353 
 354 static int
 355 dispatch_stdout(gpointer userdata)
     /* [previous][next][first][last][top][bottom][index][help] */
 356 {
 357     svc_action_t *op = (svc_action_t *) userdata;
 358 
 359     return svc_read_output(op->opaque->stdout_fd, op, FALSE);
 360 }
 361 
 362 static int
 363 dispatch_stderr(gpointer userdata)
     /* [previous][next][first][last][top][bottom][index][help] */
 364 {
 365     svc_action_t *op = (svc_action_t *) userdata;
 366 
 367     return svc_read_output(op->opaque->stderr_fd, op, TRUE);
 368 }
 369 
 370 static void
 371 pipe_out_done(gpointer user_data)
     /* [previous][next][first][last][top][bottom][index][help] */
 372 {
 373     svc_action_t *op = (svc_action_t *) user_data;
 374 
 375     crm_trace("%p", op);
 376 
 377     op->opaque->stdout_gsource = NULL;
 378     if (op->opaque->stdout_fd > STDOUT_FILENO) {
 379         close(op->opaque->stdout_fd);
 380     }
 381     op->opaque->stdout_fd = -1;
 382 }
 383 
 384 static void
 385 pipe_err_done(gpointer user_data)
     /* [previous][next][first][last][top][bottom][index][help] */
 386 {
 387     svc_action_t *op = (svc_action_t *) user_data;
 388 
 389     op->opaque->stderr_gsource = NULL;
 390     if (op->opaque->stderr_fd > STDERR_FILENO) {
 391         close(op->opaque->stderr_fd);
 392     }
 393     op->opaque->stderr_fd = -1;
 394 }
 395 
 396 static struct mainloop_fd_callbacks stdout_callbacks = {
 397     .dispatch = dispatch_stdout,
 398     .destroy = pipe_out_done,
 399 };
 400 
 401 static struct mainloop_fd_callbacks stderr_callbacks = {
 402     .dispatch = dispatch_stderr,
 403     .destroy = pipe_err_done,
 404 };
 405 
 406 static void
 407 set_ocf_env(const char *key, const char *value, gpointer user_data)
     /* [previous][next][first][last][top][bottom][index][help] */
 408 {
 409     if (setenv(key, value, 1) != 0) {
 410         crm_perror(LOG_ERR, "setenv failed for key:%s and value:%s", key, value);
 411     }
 412 }
 413 
 414 static void
 415 set_ocf_env_with_prefix(gpointer key, gpointer value, gpointer user_data)
     /* [previous][next][first][last][top][bottom][index][help] */
 416 {
 417     char buffer[500];
 418 
 419     snprintf(buffer, sizeof(buffer), strcmp(key, "OCF_CHECK_LEVEL") != 0 ? "OCF_RESKEY_%s" : "%s", (char *)key);
 420     set_ocf_env(buffer, value, user_data);
 421 }
 422 
 423 static void
 424 set_alert_env(gpointer key, gpointer value, gpointer user_data)
     /* [previous][next][first][last][top][bottom][index][help] */
 425 {
 426     int rc;
 427 
 428     if (value != NULL) {
 429         rc = setenv(key, value, 1);
 430     } else {
 431         rc = unsetenv(key);
 432     }
 433 
 434     if (rc < 0) {
 435         crm_perror(LOG_ERR, "setenv %s=%s",
 436                   (char*)key, (value? (char*)value : ""));
 437     } else {
 438         crm_trace("setenv %s=%s", (char*)key, (value? (char*)value : ""));
 439     }
 440 }
 441 
 442 /*!
 443  * \internal
 444  * \brief Add environment variables suitable for an action
 445  *
 446  * \param[in] op  Action to use
 447  */
 448 static void
 449 add_action_env_vars(const svc_action_t *op)
     /* [previous][next][first][last][top][bottom][index][help] */
 450 {
 451     void (*env_setter)(gpointer, gpointer, gpointer) = NULL;
 452     if (op->agent == NULL) {
 453         env_setter = set_alert_env;  /* we deal with alert handler */
 454 
 455     } else if (pcmk__str_eq(op->standard, PCMK_RESOURCE_CLASS_OCF, pcmk__str_casei)) {
 456         env_setter = set_ocf_env_with_prefix;
 457     }
 458 
 459     if (env_setter != NULL && op->params != NULL) {
 460         g_hash_table_foreach(op->params, env_setter, NULL);
 461     }
 462 
 463     if (env_setter == NULL || env_setter == set_alert_env) {
 464         return;
 465     }
 466 
 467     set_ocf_env("OCF_RA_VERSION_MAJOR", PCMK_OCF_MAJOR_VERSION, NULL);
 468     set_ocf_env("OCF_RA_VERSION_MINOR", PCMK_OCF_MINOR_VERSION, NULL);
 469     set_ocf_env("OCF_ROOT", PCMK_OCF_ROOT, NULL);
 470     set_ocf_env("OCF_EXIT_REASON_PREFIX", PCMK_OCF_REASON_PREFIX, NULL);
 471 
 472     if (op->rsc) {
 473         set_ocf_env("OCF_RESOURCE_INSTANCE", op->rsc, NULL);
 474     }
 475 
 476     if (op->agent != NULL) {
 477         set_ocf_env("OCF_RESOURCE_TYPE", op->agent, NULL);
 478     }
 479 
 480     /* Notes: this is not added to specification yet. Sept 10,2004 */
 481     if (op->provider != NULL) {
 482         set_ocf_env("OCF_RESOURCE_PROVIDER", op->provider, NULL);
 483     }
 484 }
 485 
 486 static void
 487 pipe_in_single_parameter(gpointer key, gpointer value, gpointer user_data)
     /* [previous][next][first][last][top][bottom][index][help] */
 488 {
 489     svc_action_t *op = user_data;
 490     char *buffer = crm_strdup_printf("%s=%s\n", (char *)key, (char *) value);
 491     size_t len = strlen(buffer);
 492     size_t total = 0;
 493     ssize_t ret = 0;
 494 
 495     do {
 496         errno = 0;
 497         ret = write(op->opaque->stdin_fd, buffer + total, len - total);
 498         if (ret > 0) {
 499             total += ret;
 500         }
 501     } while ((errno == EINTR) && (total < len));
 502     free(buffer);
 503 }
 504 
 505 /*!
 506  * \internal
 507  * \brief Pipe parameters in via stdin for action
 508  *
 509  * \param[in] op  Action to use
 510  */
 511 static void
 512 pipe_in_action_stdin_parameters(const svc_action_t *op)
     /* [previous][next][first][last][top][bottom][index][help] */
 513 {
 514     if (op->params) {
 515         g_hash_table_foreach(op->params, pipe_in_single_parameter, (gpointer) op);
 516     }
 517 }
 518 
 519 gboolean
 520 recurring_action_timer(gpointer data)
     /* [previous][next][first][last][top][bottom][index][help] */
 521 {
 522     svc_action_t *op = data;
 523 
 524     crm_debug("Scheduling another invocation of %s", op->id);
 525 
 526     /* Clean out the old result */
 527     free(op->stdout_data);
 528     op->stdout_data = NULL;
 529     free(op->stderr_data);
 530     op->stderr_data = NULL;
 531     op->opaque->repeat_timer = 0;
 532 
 533     services_action_async(op, NULL);
 534     return FALSE;
 535 }
 536 
 537 /*!
 538  * \internal
 539  * \brief Finalize handling of an asynchronous operation
 540  *
 541  * Given a completed asynchronous operation, cancel or reschedule it as
 542  * appropriate if recurring, call its callback if registered, stop tracking it,
 543  * and clean it up.
 544  *
 545  * \param[in,out] op  Operation to finalize
 546  *
 547  * \return Standard Pacemaker return code
 548  * \retval EINVAL      Caller supplied NULL or invalid \p op
 549  * \retval EBUSY       Uncanceled recurring action has only been cleaned up
 550  * \retval pcmk_rc_ok  Action has been freed
 551  *
 552  * \note If the return value is not pcmk_rc_ok, the caller is responsible for
 553  *       freeing the action.
 554  */
 555 int
 556 services__finalize_async_op(svc_action_t *op)
     /* [previous][next][first][last][top][bottom][index][help] */
 557 {
 558     CRM_CHECK((op != NULL) && !(op->synchronous), return EINVAL);
 559 
 560     if (op->interval_ms != 0) {
 561         // Recurring operations must be either cancelled or rescheduled
 562         if (op->cancel) {
 563             services__set_cancelled(op);
 564             cancel_recurring_action(op);
 565         } else {
 566             op->opaque->repeat_timer = pcmk__create_timer(op->interval_ms,
 567                                                           recurring_action_timer,
 568                                                           op);
 569         }
 570     }
 571 
 572     if (op->opaque->callback != NULL) {
 573         op->opaque->callback(op);
 574     }
 575 
 576     // Stop tracking the operation (as in-flight or blocked)
 577     op->pid = 0;
 578     services_untrack_op(op);
 579 
 580     if ((op->interval_ms != 0) && !(op->cancel)) {
 581         // Do not free recurring actions (they will get freed when cancelled)
 582         services_action_cleanup(op);
 583         return EBUSY;
 584     }
 585 
 586     services_action_free(op);
 587     return pcmk_rc_ok;
 588 }
 589 
 590 static void
 591 close_op_input(svc_action_t *op)
     /* [previous][next][first][last][top][bottom][index][help] */
 592 {
 593     if (op->opaque->stdin_fd >= 0) {
 594         close(op->opaque->stdin_fd);
 595     }
 596 }
 597 
 598 static void
 599 finish_op_output(svc_action_t *op, bool is_stderr)
     /* [previous][next][first][last][top][bottom][index][help] */
 600 {
 601     mainloop_io_t **source;
 602     int fd;
 603 
 604     if (is_stderr) {
 605         source = &(op->opaque->stderr_gsource);
 606         fd = op->opaque->stderr_fd;
 607     } else {
 608         source = &(op->opaque->stdout_gsource);
 609         fd = op->opaque->stdout_fd;
 610     }
 611 
 612     if (op->synchronous || *source) {
 613         crm_trace("Finish reading %s[%d] %s",
 614                   op->id, op->pid, (is_stderr? "stderr" : "stdout"));
 615         svc_read_output(fd, op, is_stderr);
 616         if (op->synchronous) {
 617             close(fd);
 618         } else {
 619             mainloop_del_fd(*source);
 620             *source = NULL;
 621         }
 622     }
 623 }
 624 
 625 // Log an operation's stdout and stderr
 626 static void
 627 log_op_output(svc_action_t *op)
     /* [previous][next][first][last][top][bottom][index][help] */
 628 {
 629     char *prefix = crm_strdup_printf("%s[%d] error output", op->id, op->pid);
 630 
 631     /* The library caller has better context to know how important the output
 632      * is, so log it at info and debug severity here. They can log it again at
 633      * higher severity if appropriate.
 634      */
 635     crm_log_output(LOG_INFO, prefix, op->stderr_data);
 636     strcpy(prefix + strlen(prefix) - strlen("error output"), "output");
 637     crm_log_output(LOG_DEBUG, prefix, op->stdout_data);
 638     free(prefix);
 639 }
 640 
 641 // Truncate exit reasons at this many characters
 642 #define EXIT_REASON_MAX_LEN 128
 643 
 644 static void
 645 parse_exit_reason_from_stderr(svc_action_t *op)
     /* [previous][next][first][last][top][bottom][index][help] */
 646 {
 647     const char *reason_start = NULL;
 648     const char *reason_end = NULL;
 649     const int prefix_len = strlen(PCMK_OCF_REASON_PREFIX);
 650 
 651     if ((op->stderr_data == NULL) ||
 652         // Only OCF agents have exit reasons in stderr
 653         !pcmk__str_eq(op->standard, PCMK_RESOURCE_CLASS_OCF, pcmk__str_none)) {
 654         return;
 655     }
 656 
 657     // Find the last occurrence of the magic string indicating an exit reason
 658     for (const char *cur = strstr(op->stderr_data, PCMK_OCF_REASON_PREFIX);
 659          cur != NULL; cur = strstr(cur, PCMK_OCF_REASON_PREFIX)) {
 660 
 661         cur += prefix_len; // Skip over magic string
 662         reason_start = cur;
 663     }
 664 
 665     if ((reason_start == NULL) || (reason_start[0] == '\n')
 666         || (reason_start[0] == '\0')) {
 667         return; // No or empty exit reason
 668     }
 669 
 670     // Exit reason goes to end of line (or end of output)
 671     reason_end = strchr(reason_start, '\n');
 672     if (reason_end == NULL) {
 673         reason_end = reason_start + strlen(reason_start);
 674     }
 675 
 676     // Limit size of exit reason to something reasonable
 677     if (reason_end > (reason_start + EXIT_REASON_MAX_LEN)) {
 678         reason_end = reason_start + EXIT_REASON_MAX_LEN;
 679     }
 680 
 681     free(op->opaque->exit_reason);
 682     op->opaque->exit_reason = strndup(reason_start, reason_end - reason_start);
 683 }
 684 
 685 /*!
 686  * \internal
 687  * \brief Process the completion of an asynchronous child process
 688  *
 689  * \param[in,out] p         Child process that completed
 690  * \param[in]     pid       Process ID of child
 691  * \param[in]     core      (Unused)
 692  * \param[in]     signo     Signal that interrupted child, if any
 693  * \param[in]     exitcode  Exit status of child process
 694  */
 695 static void
 696 async_action_complete(mainloop_child_t *p, pid_t pid, int core, int signo,
     /* [previous][next][first][last][top][bottom][index][help] */
 697                       int exitcode)
 698 {
 699     svc_action_t *op = mainloop_child_userdata(p);
 700 
 701     mainloop_clear_child_userdata(p);
 702     CRM_CHECK(op->pid == pid,
 703               services__set_result(op, services__generic_error(op),
 704                                    PCMK_EXEC_ERROR, "Bug in mainloop handling");
 705               return);
 706 
 707     /* Depending on the priority the mainloop gives the stdout and stderr
 708      * file descriptors, this function could be called before everything has
 709      * been read from them, so force a final read now.
 710      */
 711     finish_op_output(op, true);
 712     finish_op_output(op, false);
 713 
 714     close_op_input(op);
 715 
 716     if (signo == 0) {
 717         crm_debug("%s[%d] exited with status %d", op->id, op->pid, exitcode);
 718         services__set_result(op, exitcode, PCMK_EXEC_DONE, NULL);
 719         log_op_output(op);
 720         parse_exit_reason_from_stderr(op);
 721 
 722     } else if (mainloop_child_timeout(p)) {
 723         const char *kind = services__action_kind(op);
 724 
 725         crm_info("%s %s[%d] timed out after %s",
 726                  kind, op->id, op->pid, pcmk__readable_interval(op->timeout));
 727         services__format_result(op, services__generic_error(op),
 728                                 PCMK_EXEC_TIMEOUT,
 729                                 "%s did not complete within %s",
 730                                 kind, pcmk__readable_interval(op->timeout));
 731 
 732     } else if (op->cancel) {
 733         /* If an in-flight recurring operation was killed because it was
 734          * cancelled, don't treat that as a failure.
 735          */
 736         crm_info("%s[%d] terminated with signal %d (%s)",
 737                  op->id, op->pid, signo, strsignal(signo));
 738         services__set_result(op, PCMK_OCF_OK, PCMK_EXEC_CANCELLED, NULL);
 739 
 740     } else {
 741         crm_info("%s[%d] terminated with signal %d (%s)",
 742                  op->id, op->pid, signo, strsignal(signo));
 743         services__format_result(op, PCMK_OCF_UNKNOWN_ERROR, PCMK_EXEC_ERROR,
 744                                 "%s interrupted by %s signal",
 745                                 services__action_kind(op), strsignal(signo));
 746     }
 747 
 748     services__finalize_async_op(op);
 749 }
 750 
 751 /*!
 752  * \internal
 753  * \brief Return agent standard's exit status for "generic error"
 754  *
 755  * When returning an internal error for an action, a value that is appropriate
 756  * to the action's agent standard must be used. This function returns a value
 757  * appropriate for errors in general.
 758  *
 759  * \param[in] op  Action that error is for
 760  *
 761  * \return Exit status appropriate to agent standard
 762  * \note Actions without a standard will get PCMK_OCF_UNKNOWN_ERROR.
 763  */
 764 int
 765 services__generic_error(const svc_action_t *op)
     /* [previous][next][first][last][top][bottom][index][help] */
 766 {
 767     if ((op == NULL) || (op->standard == NULL)) {
 768         return PCMK_OCF_UNKNOWN_ERROR;
 769     }
 770 
 771 #if PCMK__ENABLE_LSB
 772     if (pcmk__str_eq(op->standard, PCMK_RESOURCE_CLASS_LSB, pcmk__str_casei)
 773         && pcmk__str_eq(op->action, PCMK_ACTION_STATUS, pcmk__str_casei)) {
 774 
 775         return PCMK_LSB_STATUS_UNKNOWN;
 776     }
 777 #endif
 778 
 779     return PCMK_OCF_UNKNOWN_ERROR;
 780 }
 781 
 782 /*!
 783  * \internal
 784  * \brief Return agent standard's exit status for "not installed"
 785  *
 786  * When returning an internal error for an action, a value that is appropriate
 787  * to the action's agent standard must be used. This function returns a value
 788  * appropriate for "not installed" errors.
 789  *
 790  * \param[in] op  Action that error is for
 791  *
 792  * \return Exit status appropriate to agent standard
 793  * \note Actions without a standard will get PCMK_OCF_UNKNOWN_ERROR.
 794  */
 795 int
 796 services__not_installed_error(const svc_action_t *op)
     /* [previous][next][first][last][top][bottom][index][help] */
 797 {
 798     if ((op == NULL) || (op->standard == NULL)) {
 799         return PCMK_OCF_UNKNOWN_ERROR;
 800     }
 801 
 802 #if PCMK__ENABLE_LSB
 803     if (pcmk__str_eq(op->standard, PCMK_RESOURCE_CLASS_LSB, pcmk__str_casei)
 804         && pcmk__str_eq(op->action, PCMK_ACTION_STATUS, pcmk__str_casei)) {
 805 
 806         return PCMK_LSB_STATUS_NOT_INSTALLED;
 807     }
 808 #endif
 809 
 810     return PCMK_OCF_NOT_INSTALLED;
 811 }
 812 
 813 /*!
 814  * \internal
 815  * \brief Return agent standard's exit status for "insufficient privileges"
 816  *
 817  * When returning an internal error for an action, a value that is appropriate
 818  * to the action's agent standard must be used. This function returns a value
 819  * appropriate for "insufficient privileges" errors.
 820  *
 821  * \param[in] op  Action that error is for
 822  *
 823  * \return Exit status appropriate to agent standard
 824  * \note Actions without a standard will get PCMK_OCF_UNKNOWN_ERROR.
 825  */
 826 int
 827 services__authorization_error(const svc_action_t *op)
     /* [previous][next][first][last][top][bottom][index][help] */
 828 {
 829     if ((op == NULL) || (op->standard == NULL)) {
 830         return PCMK_OCF_UNKNOWN_ERROR;
 831     }
 832 
 833 #if PCMK__ENABLE_LSB
 834     if (pcmk__str_eq(op->standard, PCMK_RESOURCE_CLASS_LSB, pcmk__str_casei)
 835         && pcmk__str_eq(op->action, PCMK_ACTION_STATUS, pcmk__str_casei)) {
 836 
 837         return PCMK_LSB_STATUS_INSUFFICIENT_PRIV;
 838     }
 839 #endif
 840 
 841     return PCMK_OCF_INSUFFICIENT_PRIV;
 842 }
 843 
 844 /*!
 845  * \internal
 846  * \brief Return agent standard's exit status for "not configured"
 847  *
 848  * When returning an internal error for an action, a value that is appropriate
 849  * to the action's agent standard must be used. This function returns a value
 850  * appropriate for "not configured" errors.
 851  *
 852  * \param[in] op        Action that error is for
 853  * \param[in] is_fatal  Whether problem is cluster-wide instead of only local
 854  *
 855  * \return Exit status appropriate to agent standard
 856  * \note Actions without a standard will get PCMK_OCF_UNKNOWN_ERROR.
 857  */
 858 int
 859 services__configuration_error(const svc_action_t *op, bool is_fatal)
     /* [previous][next][first][last][top][bottom][index][help] */
 860 {
 861     if ((op == NULL) || (op->standard == NULL)) {
 862         return PCMK_OCF_UNKNOWN_ERROR;
 863     }
 864 
 865 #if PCMK__ENABLE_LSB
 866     if (pcmk__str_eq(op->standard, PCMK_RESOURCE_CLASS_LSB, pcmk__str_casei)
 867         && pcmk__str_eq(op->action, PCMK_ACTION_STATUS, pcmk__str_casei)) {
 868 
 869         return PCMK_LSB_NOT_CONFIGURED;
 870     }
 871 #endif
 872 
 873     return is_fatal? PCMK_OCF_NOT_CONFIGURED : PCMK_OCF_INVALID_PARAM;
 874 }
 875 
 876 
 877 /*!
 878  * \internal
 879  * \brief Set operation rc and status per errno from stat(), fork() or execvp()
 880  *
 881  * \param[in,out] op     Operation to set rc and status for
 882  * \param[in]     error  Value of errno after system call
 883  *
 884  * \return void
 885  */
 886 void
 887 services__handle_exec_error(svc_action_t * op, int error)
     /* [previous][next][first][last][top][bottom][index][help] */
 888 {
 889     const char *name = op->opaque->exec;
 890 
 891     if (name == NULL) {
 892         name = op->agent;
 893         if (name == NULL) {
 894             name = op->id;
 895         }
 896     }
 897 
 898     switch (error) {   /* see execve(2), stat(2) and fork(2) */
 899         case ENOENT:   /* No such file or directory */
 900         case EISDIR:   /* Is a directory */
 901         case ENOTDIR:  /* Path component is not a directory */
 902         case EINVAL:   /* Invalid executable format */
 903         case ENOEXEC:  /* Invalid executable format */
 904             services__format_result(op, services__not_installed_error(op),
 905                                     PCMK_EXEC_NOT_INSTALLED, "%s: %s",
 906                                     name, pcmk_rc_str(error));
 907             break;
 908         case EACCES:   /* permission denied (various errors) */
 909         case EPERM:    /* permission denied (various errors) */
 910             services__format_result(op, services__authorization_error(op),
 911                                     PCMK_EXEC_ERROR, "%s: %s",
 912                                     name, pcmk_rc_str(error));
 913             break;
 914         default:
 915             services__set_result(op, services__generic_error(op),
 916                                  PCMK_EXEC_ERROR, pcmk_rc_str(error));
 917     }
 918 }
 919 
 920 /*!
 921  * \internal
 922  * \brief Exit a child process that failed before executing agent
 923  *
 924  * \param[in] op           Action that failed
 925  * \param[in] exit_status  Exit status code to use
 926  * \param[in] exit_reason  Exit reason to output if for OCF agent
 927  */
 928 static void
 929 exit_child(const svc_action_t *op, int exit_status, const char *exit_reason)
     /* [previous][next][first][last][top][bottom][index][help] */
 930 {
 931     if ((op != NULL) && (exit_reason != NULL)
 932         && pcmk__str_eq(op->standard, PCMK_RESOURCE_CLASS_OCF,
 933                         pcmk__str_none)) {
 934         fprintf(stderr, PCMK_OCF_REASON_PREFIX "%s\n", exit_reason);
 935     }
 936     pcmk_common_cleanup();
 937     _exit(exit_status);
 938 }
 939 
 940 static void
 941 action_launch_child(svc_action_t *op)
     /* [previous][next][first][last][top][bottom][index][help] */
 942 {
 943     int rc;
 944 
 945     /* SIGPIPE is ignored (which is different from signal blocking) by the gnutls library.
 946      * Depending on the libqb version in use, libqb may set SIGPIPE to be ignored as well. 
 947      * We do not want this to be inherited by the child process. By resetting this the signal
 948      * to the default behavior, we avoid some potential odd problems that occur during OCF
 949      * scripts when SIGPIPE is ignored by the environment. */
 950     signal(SIGPIPE, SIG_DFL);
 951 
 952     if (sched_getscheduler(0) != SCHED_OTHER) {
 953         struct sched_param sp;
 954 
 955         memset(&sp, 0, sizeof(sp));
 956         sp.sched_priority = 0;
 957 
 958         if (sched_setscheduler(0, SCHED_OTHER, &sp) == -1) {
 959             crm_info("Could not reset scheduling policy for %s", op->id);
 960         }
 961     }
 962 
 963     if (setpriority(PRIO_PROCESS, 0, 0) == -1) {
 964         crm_info("Could not reset process priority for %s", op->id);
 965     }
 966 
 967     /* Man: The call setpgrp() is equivalent to setpgid(0,0)
 968      * _and_ compiles on BSD variants too
 969      * need to investigate if it works the same too.
 970      */
 971     setpgid(0, 0);
 972 
 973     pcmk__close_fds_in_child(false);
 974 
 975     /* It would be nice if errors in this function could be reported as
 976      * execution status (for example, PCMK_EXEC_NO_SECRETS for the secrets error
 977      * below) instead of exit status. However, we've already forked, so
 978      * exit status is all we have. At least for OCF actions, we can output an
 979      * exit reason for the parent to parse.
 980      */
 981 
 982 #if PCMK__ENABLE_CIBSECRETS
 983     rc = pcmk__substitute_secrets(op->rsc, op->params);
 984     if (rc != pcmk_rc_ok) {
 985         if (pcmk__str_eq(op->action, PCMK_ACTION_STOP, pcmk__str_casei)) {
 986             crm_info("Proceeding with stop operation for %s "
 987                      "despite being unable to load CIB secrets (%s)",
 988                      op->rsc, pcmk_rc_str(rc));
 989         } else {
 990             crm_err("Considering %s unconfigured "
 991                     "because unable to load CIB secrets: %s",
 992                     op->rsc, pcmk_rc_str(rc));
 993             exit_child(op, services__configuration_error(op, false),
 994                        "Unable to load CIB secrets");
 995         }
 996     }
 997 #endif
 998 
 999     add_action_env_vars(op);
1000 
1001     /* Become the desired user */
1002     if (op->opaque->uid && (geteuid() == 0)) {
1003 
1004         // If requested, set effective group
1005         if (op->opaque->gid && (setgid(op->opaque->gid) < 0)) {
1006             crm_err("Considering %s unauthorized because could not set "
1007                     "child group to %d: %s",
1008                     op->id, op->opaque->gid, strerror(errno));
1009             exit_child(op, services__authorization_error(op),
1010                        "Could not set group for child process");
1011         }
1012 
1013         // Erase supplementary group list
1014         // (We could do initgroups() if we kept a copy of the username)
1015         if (setgroups(0, NULL) < 0) {
1016             crm_err("Considering %s unauthorized because could not "
1017                     "clear supplementary groups: %s", op->id, strerror(errno));
1018             exit_child(op, services__authorization_error(op),
1019                        "Could not clear supplementary groups for child process");
1020         }
1021 
1022         // Set effective user
1023         if (setuid(op->opaque->uid) < 0) {
1024             crm_err("Considering %s unauthorized because could not set user "
1025                     "to %d: %s", op->id, op->opaque->uid, strerror(errno));
1026             exit_child(op, services__authorization_error(op),
1027                        "Could not set user for child process");
1028         }
1029     }
1030 
1031     // Execute the agent (doesn't return if successful)
1032     execvp(op->opaque->exec, op->opaque->args);
1033 
1034     // An earlier stat() should have avoided most possible errors
1035     rc = errno;
1036     services__handle_exec_error(op, rc);
1037     crm_err("Unable to execute %s: %s", op->id, strerror(rc));
1038     exit_child(op, op->rc, "Child process was unable to execute file");
1039 }
1040 
1041 /*!
1042  * \internal
1043  * \brief Wait for synchronous action to complete, and set its result
1044  *
1045  * \param[in,out] op    Action to wait for
1046  * \param[in,out] data  Child signal data
1047  */
1048 static void
1049 wait_for_sync_result(svc_action_t *op, struct sigchld_data_s *data)
     /* [previous][next][first][last][top][bottom][index][help] */
1050 {
1051     int status = 0;
1052     int timeout = op->timeout;
1053     time_t start = time(NULL);
1054     struct pollfd fds[3];
1055     int wait_rc = 0;
1056     const char *wait_reason = NULL;
1057 
1058     fds[0].fd = op->opaque->stdout_fd;
1059     fds[0].events = POLLIN;
1060     fds[0].revents = 0;
1061 
1062     fds[1].fd = op->opaque->stderr_fd;
1063     fds[1].events = POLLIN;
1064     fds[1].revents = 0;
1065 
1066     fds[2].fd = sigchld_open(data);
1067     fds[2].events = POLLIN;
1068     fds[2].revents = 0;
1069 
1070     crm_trace("Waiting for %s[%d]", op->id, op->pid);
1071     do {
1072         int poll_rc = poll(fds, 3, timeout);
1073 
1074         wait_reason = NULL;
1075 
1076         if (poll_rc > 0) {
1077             if (fds[0].revents & POLLIN) {
1078                 svc_read_output(op->opaque->stdout_fd, op, FALSE);
1079             }
1080 
1081             if (fds[1].revents & POLLIN) {
1082                 svc_read_output(op->opaque->stderr_fd, op, TRUE);
1083             }
1084 
1085             if ((fds[2].revents & POLLIN)
1086                 && sigchld_received(fds[2].fd, op->pid, data)) {
1087                 wait_rc = waitpid(op->pid, &status, WNOHANG);
1088 
1089                 if ((wait_rc > 0) || ((wait_rc < 0) && (errno == ECHILD))) {
1090                     // Child process exited or doesn't exist
1091                     break;
1092 
1093                 } else if (wait_rc < 0) {
1094                     wait_reason = pcmk_rc_str(errno);
1095                     crm_info("Wait for completion of %s[%d] failed: %s "
1096                              QB_XS " source=waitpid",
1097                              op->id, op->pid, wait_reason);
1098                     wait_rc = 0; // Act as if process is still running
1099 
1100 #ifndef HAVE_SYS_SIGNALFD_H
1101                 } else {
1102                    /* The child hasn't exited, so this SIGCHLD could be for
1103                     * another child. We have to ignore it here but will still
1104                     * need to resend it after this synchronous action has
1105                     * completed and SIGCHLD has been restored to be handled by
1106                     * the previous handler, so that it will be handled.
1107                     */
1108                     data->ignored = true;
1109 #endif
1110                 }
1111             }
1112 
1113         } else if (poll_rc == 0) {
1114             // Poll timed out with no descriptors ready
1115             timeout = 0;
1116             break;
1117 
1118         } else if ((poll_rc < 0) && (errno != EINTR)) {
1119             wait_reason = pcmk_rc_str(errno);
1120             crm_info("Wait for completion of %s[%d] failed: %s "
1121                      QB_XS " source=poll", op->id, op->pid, wait_reason);
1122             break;
1123         }
1124 
1125         timeout = op->timeout - (time(NULL) - start) * 1000;
1126 
1127     } while ((op->timeout < 0 || timeout > 0));
1128 
1129     crm_trace("Stopped waiting for %s[%d]", op->id, op->pid);
1130     finish_op_output(op, true);
1131     finish_op_output(op, false);
1132     close_op_input(op);
1133     sigchld_close(fds[2].fd);
1134 
1135     if (wait_rc <= 0) {
1136 
1137         if ((op->timeout > 0) && (timeout <= 0)) {
1138             services__format_result(op, services__generic_error(op),
1139                                     PCMK_EXEC_TIMEOUT,
1140                                     "%s did not exit within specified timeout",
1141                                     services__action_kind(op));
1142             crm_info("%s[%d] timed out after %dms",
1143                      op->id, op->pid, op->timeout);
1144 
1145         } else {
1146             services__set_result(op, services__generic_error(op),
1147                                  PCMK_EXEC_ERROR, wait_reason);
1148         }
1149 
1150         /* If only child hasn't been successfully waited for, yet.
1151            This is to limit killing wrong target a bit more. */
1152         if ((wait_rc == 0) && (waitpid(op->pid, &status, WNOHANG) == 0)) {
1153             if (kill(op->pid, SIGKILL)) {
1154                 crm_warn("Could not kill rogue child %s[%d]: %s",
1155                          op->id, op->pid, pcmk_rc_str(errno));
1156             }
1157             /* Safe to skip WNOHANG here as we sent non-ignorable signal. */
1158             while ((waitpid(op->pid, &status, 0) == (pid_t) -1)
1159                    && (errno == EINTR)) {
1160                 /* keep waiting */;
1161             }
1162         }
1163 
1164     } else if (WIFEXITED(status)) {
1165         services__set_result(op, WEXITSTATUS(status), PCMK_EXEC_DONE, NULL);
1166         parse_exit_reason_from_stderr(op);
1167         crm_info("%s[%d] exited with status %d", op->id, op->pid, op->rc);
1168 
1169     } else if (WIFSIGNALED(status)) {
1170         int signo = WTERMSIG(status);
1171 
1172         services__format_result(op, services__generic_error(op),
1173                                 PCMK_EXEC_ERROR, "%s interrupted by %s signal",
1174                                 services__action_kind(op), strsignal(signo));
1175         crm_info("%s[%d] terminated with signal %d (%s)",
1176                  op->id, op->pid, signo, strsignal(signo));
1177 
1178 #ifdef WCOREDUMP
1179         if (WCOREDUMP(status)) {
1180             crm_warn("%s[%d] dumped core", op->id, op->pid);
1181         }
1182 #endif
1183 
1184     } else {
1185         // Shouldn't be possible to get here
1186         services__set_result(op, services__generic_error(op), PCMK_EXEC_ERROR,
1187                              "Unable to wait for child to complete");
1188     }
1189 }
1190 
1191 /*!
1192  * \internal
1193  * \brief Execute an action whose standard uses executable files
1194  *
1195  * \param[in,out] op  Action to execute
1196  *
1197  * \return Standard Pacemaker return value
1198  * \retval EBUSY          Recurring operation could not be initiated
1199  * \retval pcmk_rc_error  Synchronous action failed
1200  * \retval pcmk_rc_ok     Synchronous action succeeded, or asynchronous action
1201  *                        should not be freed (because it's pending or because
1202  *                        it failed to execute and was already freed)
1203  *
1204  * \note If the return value for an asynchronous action is not pcmk_rc_ok, the
1205  *       caller is responsible for freeing the action.
1206  */
1207 int
1208 services__execute_file(svc_action_t *op)
     /* [previous][next][first][last][top][bottom][index][help] */
1209 {
1210     int stdout_fd[2];
1211     int stderr_fd[2];
1212     int stdin_fd[2] = {-1, -1};
1213     int rc;
1214     struct stat st;
1215     struct sigchld_data_s data = { .ignored = false };
1216 
1217     // Catch common failure conditions early
1218     if (stat(op->opaque->exec, &st) != 0) {
1219         rc = errno;
1220         crm_info("Cannot execute '%s': %s " QB_XS " stat rc=%d",
1221                  op->opaque->exec, pcmk_rc_str(rc), rc);
1222         services__handle_exec_error(op, rc);
1223         goto done;
1224     }
1225 
1226     if (pipe(stdout_fd) < 0) {
1227         rc = errno;
1228         crm_info("Cannot execute '%s': %s " QB_XS " pipe(stdout) rc=%d",
1229                  op->opaque->exec, pcmk_rc_str(rc), rc);
1230         services__handle_exec_error(op, rc);
1231         goto done;
1232     }
1233 
1234     if (pipe(stderr_fd) < 0) {
1235         rc = errno;
1236 
1237         close_pipe(stdout_fd);
1238 
1239         crm_info("Cannot execute '%s': %s " QB_XS " pipe(stderr) rc=%d",
1240                  op->opaque->exec, pcmk_rc_str(rc), rc);
1241         services__handle_exec_error(op, rc);
1242         goto done;
1243     }
1244 
1245     if (pcmk_is_set(pcmk_get_ra_caps(op->standard), pcmk_ra_cap_stdin)) {
1246         if (pipe(stdin_fd) < 0) {
1247             rc = errno;
1248 
1249             close_pipe(stdout_fd);
1250             close_pipe(stderr_fd);
1251 
1252             crm_info("Cannot execute '%s': %s " QB_XS " pipe(stdin) rc=%d",
1253                      op->opaque->exec, pcmk_rc_str(rc), rc);
1254             services__handle_exec_error(op, rc);
1255             goto done;
1256         }
1257     }
1258 
1259     if (op->synchronous && !sigchld_setup(&data)) {
1260         close_pipe(stdin_fd);
1261         close_pipe(stdout_fd);
1262         close_pipe(stderr_fd);
1263         sigchld_cleanup(&data);
1264         services__set_result(op, services__generic_error(op), PCMK_EXEC_ERROR,
1265                              "Could not manage signals for child process");
1266         goto done;
1267     }
1268 
1269     op->pid = fork();
1270     switch (op->pid) {
1271         case -1:
1272             rc = errno;
1273             close_pipe(stdin_fd);
1274             close_pipe(stdout_fd);
1275             close_pipe(stderr_fd);
1276 
1277             crm_info("Cannot execute '%s': %s " QB_XS " fork rc=%d",
1278                      op->opaque->exec, pcmk_rc_str(rc), rc);
1279             services__handle_exec_error(op, rc);
1280             if (op->synchronous) {
1281                 sigchld_cleanup(&data);
1282             }
1283             goto done;
1284             break;
1285 
1286         case 0:                /* Child */
1287             close(stdout_fd[0]);
1288             close(stderr_fd[0]);
1289             if (stdin_fd[1] >= 0) {
1290                 close(stdin_fd[1]);
1291             }
1292             if (STDOUT_FILENO != stdout_fd[1]) {
1293                 if (dup2(stdout_fd[1], STDOUT_FILENO) != STDOUT_FILENO) {
1294                     crm_warn("Can't redirect output from '%s': %s "
1295                              QB_XS " errno=%d",
1296                              op->opaque->exec, pcmk_rc_str(errno), errno);
1297                 }
1298                 close(stdout_fd[1]);
1299             }
1300             if (STDERR_FILENO != stderr_fd[1]) {
1301                 if (dup2(stderr_fd[1], STDERR_FILENO) != STDERR_FILENO) {
1302                     crm_warn("Can't redirect error output from '%s': %s "
1303                              QB_XS " errno=%d",
1304                              op->opaque->exec, pcmk_rc_str(errno), errno);
1305                 }
1306                 close(stderr_fd[1]);
1307             }
1308             if ((stdin_fd[0] >= 0) &&
1309                 (STDIN_FILENO != stdin_fd[0])) {
1310                 if (dup2(stdin_fd[0], STDIN_FILENO) != STDIN_FILENO) {
1311                     crm_warn("Can't redirect input to '%s': %s "
1312                              QB_XS " errno=%d",
1313                              op->opaque->exec, pcmk_rc_str(errno), errno);
1314                 }
1315                 close(stdin_fd[0]);
1316             }
1317 
1318             if (op->synchronous) {
1319                 sigchld_cleanup(&data);
1320             }
1321 
1322             action_launch_child(op);
1323             pcmk__assert(false); // action_launch_child() should not return
1324     }
1325 
1326     /* Only the parent reaches here */
1327     close(stdout_fd[1]);
1328     close(stderr_fd[1]);
1329     if (stdin_fd[0] >= 0) {
1330         close(stdin_fd[0]);
1331     }
1332 
1333     op->opaque->stdout_fd = stdout_fd[0];
1334     rc = pcmk__set_nonblocking(op->opaque->stdout_fd);
1335     if (rc != pcmk_rc_ok) {
1336         crm_info("Could not set '%s' output non-blocking: %s "
1337                  QB_XS " rc=%d",
1338                  op->opaque->exec, pcmk_rc_str(rc), rc);
1339     }
1340 
1341     op->opaque->stderr_fd = stderr_fd[0];
1342     rc = pcmk__set_nonblocking(op->opaque->stderr_fd);
1343     if (rc != pcmk_rc_ok) {
1344         crm_info("Could not set '%s' error output non-blocking: %s "
1345                  QB_XS " rc=%d",
1346                  op->opaque->exec, pcmk_rc_str(rc), rc);
1347     }
1348 
1349     op->opaque->stdin_fd = stdin_fd[1];
1350     if (op->opaque->stdin_fd >= 0) {
1351         // using buffer behind non-blocking-fd here - that could be improved
1352         // as long as no other standard uses stdin_fd assume stonith
1353         rc = pcmk__set_nonblocking(op->opaque->stdin_fd);
1354         if (rc != pcmk_rc_ok) {
1355             crm_info("Could not set '%s' input non-blocking: %s "
1356                     QB_XS " fd=%d,rc=%d", op->opaque->exec,
1357                     pcmk_rc_str(rc), op->opaque->stdin_fd, rc);
1358         }
1359         pipe_in_action_stdin_parameters(op);
1360         // as long as we are handling parameters directly in here just close
1361         close(op->opaque->stdin_fd);
1362         op->opaque->stdin_fd = -1;
1363     }
1364 
1365     // after fds are setup properly and before we plug anything into mainloop
1366     if (op->opaque->fork_callback) {
1367         op->opaque->fork_callback(op);
1368     }
1369 
1370     if (op->synchronous) {
1371         wait_for_sync_result(op, &data);
1372         sigchld_cleanup(&data);
1373         goto done;
1374     }
1375 
1376     crm_trace("Waiting async for '%s'[%d]", op->opaque->exec, op->pid);
1377     mainloop_child_add_with_flags(op->pid, op->timeout, op->id, op,
1378                                   pcmk_is_set(op->flags, SVC_ACTION_LEAVE_GROUP)? mainloop_leave_pid_group : 0,
1379                                   async_action_complete);
1380 
1381     op->opaque->stdout_gsource = mainloop_add_fd(op->id,
1382                                                  G_PRIORITY_LOW,
1383                                                  op->opaque->stdout_fd, op,
1384                                                  &stdout_callbacks);
1385     op->opaque->stderr_gsource = mainloop_add_fd(op->id,
1386                                                  G_PRIORITY_LOW,
1387                                                  op->opaque->stderr_fd, op,
1388                                                  &stderr_callbacks);
1389     services_add_inflight_op(op);
1390     return pcmk_rc_ok;
1391 
1392 done:
1393     if (op->synchronous) {
1394         return (op->rc == PCMK_OCF_OK)? pcmk_rc_ok : pcmk_rc_error;
1395     } else {
1396         return services__finalize_async_op(op);
1397     }
1398 }
1399 
1400 GList *
1401 services_os_get_single_directory_list(const char *root, gboolean files, gboolean executable)
     /* [previous][next][first][last][top][bottom][index][help] */
1402 {
1403     GList *list = NULL;
1404     struct dirent **namelist;
1405     int entries = 0, lpc = 0;
1406     char buffer[PATH_MAX];
1407 
1408     entries = scandir(root, &namelist, NULL, alphasort);
1409     if (entries <= 0) {
1410         return list;
1411     }
1412 
1413     for (lpc = 0; lpc < entries; lpc++) {
1414         struct stat sb;
1415 
1416         if ('.' == namelist[lpc]->d_name[0]) {
1417             free(namelist[lpc]);
1418             continue;
1419         }
1420 
1421         snprintf(buffer, sizeof(buffer), "%s/%s", root, namelist[lpc]->d_name);
1422 
1423         if (stat(buffer, &sb)) {
1424             continue;
1425         }
1426 
1427         if (S_ISDIR(sb.st_mode)) {
1428             if (files) {
1429                 free(namelist[lpc]);
1430                 continue;
1431             }
1432 
1433         } else if (S_ISREG(sb.st_mode)) {
1434             if (files == FALSE) {
1435                 free(namelist[lpc]);
1436                 continue;
1437 
1438             } else if (executable
1439                        && (sb.st_mode & S_IXUSR) == 0
1440                        && (sb.st_mode & S_IXGRP) == 0 && (sb.st_mode & S_IXOTH) == 0) {
1441                 free(namelist[lpc]);
1442                 continue;
1443             }
1444         }
1445 
1446         list = g_list_append(list, strdup(namelist[lpc]->d_name));
1447 
1448         free(namelist[lpc]);
1449     }
1450 
1451     free(namelist);
1452     return list;
1453 }
1454 
1455 GList *
1456 services_os_get_directory_list(const char *root, gboolean files, gboolean executable)
     /* [previous][next][first][last][top][bottom][index][help] */
1457 {
1458     GList *result = NULL;
1459     char *dirs = strdup(root);
1460     char *dir = NULL;
1461 
1462     if (pcmk__str_empty(dirs)) {
1463         free(dirs);
1464         return result;
1465     }
1466 
1467     for (dir = strtok(dirs, ":"); dir != NULL; dir = strtok(NULL, ":")) {
1468         GList *tmp = services_os_get_single_directory_list(dir, files, executable);
1469 
1470         if (tmp) {
1471             result = g_list_concat(result, tmp);
1472         }
1473     }
1474 
1475     free(dirs);
1476 
1477     return result;
1478 }

/* [previous][next][first][last][top][bottom][index][help] */