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

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