daemon.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. # This file is part of jwmud, written by Helmut Pozimski in 2014.
  2. #
  3. # jwmud is free software: you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License as published by
  5. # the Free Software Foundation, version 2 of the License.
  6. #
  7. # jwmud is distributed in the hope that it will be useful,
  8. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. # GNU General Public License for more details.
  11. #
  12. # You should have received a copy of the GNU General Public License
  13. # along with jwmud. If not, see <http://www.gnu.org/licenses/>.
  14. # -*- coding: utf8 -*-
  15. import os
  16. import sys
  17. from jwmudlib import jwmu_exceptions
  18. class Daemon(object):
  19. """ Tries to implement a well behaving unix daemon in a generic way,
  20. so the code could be used in different projects.
  21. """
  22. def __init__(self, pfile_path, pfile_name):
  23. """ Initializes the object. """
  24. self.__pfile_path = pfile_path
  25. self.__pfile_name = pfile_name
  26. self.__daemon = False
  27. self.__pid = 0
  28. def Daemonize(self):
  29. """ Turns the calling process into a daemon running on it's own """
  30. try:
  31. # Fork for the first time
  32. self.__pid = os.fork()
  33. except OSError:
  34. sys.exit(os.EX_OSERR)
  35. else:
  36. if self.__pid > 0:
  37. sys.exit(os.EX_OK)
  38. # Become session and group leader
  39. # noinspection PyArgumentList
  40. os.setsid()
  41. try:
  42. #Fork for the second time
  43. self.__pid = os.fork()
  44. except OSError:
  45. sys.exit(os.EX_OSERR)
  46. else:
  47. if self.__pid > 0:
  48. sys.exit(os.EX_OK)
  49. # Change cwd to / to avoid interfering with other mounted file systems
  50. os.chdir("/")
  51. # Reset the umask
  52. os.umask(0)
  53. # Close possibly open file descriptors
  54. os.close(0)
  55. os.close(1)
  56. os.close(2)
  57. # And redirect them to /dev/null
  58. os.open("/dev/null", 0)
  59. os.open("/dev/null", 1)
  60. os.open("/dev/null", 2)
  61. self.__daemon = True
  62. def DropPrivileges(self, user, group):
  63. """ If the daemon is running as root user, drop privileges and continue
  64. running as the defined unprivileged user.
  65. """
  66. pid_file_path = os.path.join(self.__pfile_path, self.__pfile_name)
  67. try:
  68. passwd_file = open("/etc/passwd", "r")
  69. group_file = open("/etc/group", "r")
  70. except PermissionError:
  71. raise jwmu_exceptions.PasswdOrGroupAccessFailed()
  72. else:
  73. uid = ""
  74. gid = ""
  75. for line in passwd_file:
  76. if user in line:
  77. uid = line.split(":")[2]
  78. break
  79. for line in group_file:
  80. if group in line.split(":")[0]:
  81. gid = line.split(":")[2]
  82. break
  83. passwd_file.close()
  84. group_file.close()
  85. if os.getuid() == 0:
  86. os.chown(pid_file_path, int(uid), int(gid))
  87. os.setgid(int(gid))
  88. os.setuid(int(uid))
  89. def Start(self):
  90. """ Performs the operations needed to "start" the daemon """
  91. pid_file_path = os.path.join(self.__pfile_path, self.__pfile_name)
  92. if os.access(pid_file_path, os.F_OK):
  93. old_pid_file = open(pid_file_path, "r")
  94. old_pid = old_pid_file.read().strip()
  95. old_pid_file.close()
  96. if os.access(os.path.join("/proc/", old_pid), os.F_OK):
  97. raise jwmu_exceptions.DaemonAlreadyRunning()
  98. if self.__daemon is True:
  99. try:
  100. pid_file = open(pid_file_path, "w")
  101. except IOError:
  102. raise jwmu_exceptions.WritingPIDFileFailed()
  103. else:
  104. pid_file.write(str(os.getpid()) + "\n")
  105. pid_file.close()
  106. def Stop(self):
  107. """ Performs the operations needed to stop the daemon """
  108. if self.__daemon is True:
  109. try:
  110. os.remove(os.path.join(self.__pfile_path, self.__pfile_name))
  111. except OSError:
  112. return False
  113. else:
  114. return True
  115. else:
  116. return True