2
0

systemd.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * systemd socket activation support
  3. *
  4. * Copyright 2017 Red Hat, Inc. and/or its affiliates
  5. *
  6. * Authors:
  7. * Richard W.M. Jones <rjones@redhat.com>
  8. *
  9. * This work is licensed under the terms of the GNU GPL, version 2 or later.
  10. * See the COPYING file in the top-level directory.
  11. */
  12. #include "qemu/osdep.h"
  13. #include "qemu/systemd.h"
  14. #include "qemu/cutils.h"
  15. #include "qemu/error-report.h"
  16. #ifndef _WIN32
  17. unsigned int check_socket_activation(void)
  18. {
  19. const char *s;
  20. unsigned long pid;
  21. unsigned long nr_fds;
  22. unsigned int i;
  23. int fd;
  24. int err;
  25. s = getenv("LISTEN_PID");
  26. if (s == NULL) {
  27. return 0;
  28. }
  29. err = qemu_strtoul(s, NULL, 10, &pid);
  30. if (err) {
  31. return 0;
  32. }
  33. if (pid != getpid()) {
  34. return 0;
  35. }
  36. s = getenv("LISTEN_FDS");
  37. if (s == NULL) {
  38. return 0;
  39. }
  40. err = qemu_strtoul(s, NULL, 10, &nr_fds);
  41. if (err) {
  42. return 0;
  43. }
  44. assert(nr_fds <= UINT_MAX);
  45. /* So these are not passed to any child processes we might start. */
  46. unsetenv("LISTEN_FDS");
  47. unsetenv("LISTEN_PID");
  48. /* So the file descriptors don't leak into child processes. */
  49. for (i = 0; i < nr_fds; ++i) {
  50. fd = FIRST_SOCKET_ACTIVATION_FD + i;
  51. if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
  52. /* If we cannot set FD_CLOEXEC then it probably means the file
  53. * descriptor is invalid, so socket activation has gone wrong
  54. * and we should exit.
  55. */
  56. error_report("Socket activation failed: "
  57. "invalid file descriptor fd = %d: %s",
  58. fd, g_strerror(errno));
  59. exit(EXIT_FAILURE);
  60. }
  61. }
  62. return (unsigned int) nr_fds;
  63. }
  64. #else /* !_WIN32 */
  65. unsigned int check_socket_activation(void)
  66. {
  67. return 0;
  68. }
  69. #endif