__main__.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2011-2017 Guillaume Ayoub
  3. #
  4. # This library is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This library is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  16. """
  17. Radicale executable module.
  18. This module can be executed from a command line with ``$python -m radicale`` or
  19. from a python programme with ``radicale.__main__.run()``.
  20. """
  21. import argparse
  22. import atexit
  23. import os
  24. import select
  25. import signal
  26. import socket
  27. import ssl
  28. import sys
  29. from wsgiref.simple_server import make_server
  30. from . import (
  31. VERSION, Application, RequestHandler, ThreadedHTTPServer,
  32. ThreadedHTTPSServer, config, log)
  33. def run():
  34. """Run Radicale as a standalone server."""
  35. # Get command-line arguments
  36. parser = argparse.ArgumentParser(usage="radicale [OPTIONS]")
  37. parser.add_argument("--version", action="version", version=VERSION)
  38. parser.add_argument(
  39. "-C", "--config", help="use a specific configuration file")
  40. groups = {}
  41. for section, values in config.INITIAL_CONFIG.items():
  42. group = parser.add_argument_group(section)
  43. groups[group] = []
  44. for option, data in values.items():
  45. kwargs = data.copy()
  46. long_name = "--{0}-{1}".format(
  47. section, option.replace("_", "-"))
  48. args = kwargs.pop("aliases", [])
  49. args.append(long_name)
  50. kwargs["dest"] = "{0}_{1}".format(section, option)
  51. groups[group].append(kwargs["dest"])
  52. if kwargs.pop("value") in ("True", "False"):
  53. kwargs["action"] = "store_const"
  54. kwargs["const"] = "True"
  55. opposite_args = kwargs.pop("opposite", [])
  56. opposite_args.append("--no{0}".format(long_name[1:]))
  57. group.add_argument(*args, **kwargs)
  58. kwargs["const"] = "False"
  59. kwargs["help"] = "do not {0} (opposite of {1})".format(
  60. kwargs["help"], long_name)
  61. group.add_argument(*opposite_args, **kwargs)
  62. else:
  63. group.add_argument(*args, **kwargs)
  64. args = parser.parse_args()
  65. if args.config is not None:
  66. configuration = config.load()
  67. if args.config:
  68. configuration_found = configuration.read(args.config)
  69. else:
  70. configuration_found = True
  71. else:
  72. configuration_paths = [
  73. "/etc/radicale/config",
  74. os.path.expanduser("~/.config/radicale/config")]
  75. if "RADICALE_CONFIG" in os.environ:
  76. configuration_paths.append(os.environ["RADICALE_CONFIG"])
  77. configuration = config.load(configuration_paths)
  78. configuration_found = True
  79. # Update Radicale configuration according to arguments
  80. for group, actions in groups.items():
  81. section = group.title
  82. for action in actions:
  83. value = getattr(args, action)
  84. if value is not None:
  85. configuration.set(section, action.split('_', 1)[1], value)
  86. # Start logging
  87. filename = os.path.expanduser(configuration.get("logging", "config"))
  88. debug = configuration.getboolean("logging", "debug")
  89. logger = log.start("radicale", filename, debug)
  90. # Log a warning if the configuration file of the command line is not found
  91. if not configuration_found:
  92. logger.error("Configuration file '%s' not found" % args.config)
  93. exit(1)
  94. try:
  95. serve(configuration, logger)
  96. except Exception:
  97. logger.exception("An exception occurred during server startup:")
  98. exit(1)
  99. def daemonize(configuration, logger):
  100. """Fork and decouple if Radicale is configured as daemon."""
  101. # Check and create PID file in a race-free manner
  102. if configuration.get("server", "pid"):
  103. try:
  104. pid_path = os.path.abspath(os.path.expanduser(
  105. configuration.get("server", "pid")))
  106. pid_fd = os.open(
  107. pid_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
  108. except OSError as e:
  109. raise OSError("PID file exists: %s" %
  110. configuration.get("server", "pid")) from e
  111. pid = os.fork()
  112. if pid:
  113. # Write PID
  114. if configuration.get("server", "pid"):
  115. with os.fdopen(pid_fd, "w") as pid_file:
  116. pid_file.write(str(pid))
  117. sys.exit()
  118. if configuration.get("server", "pid"):
  119. os.close(pid_fd)
  120. # Register exit function
  121. def cleanup():
  122. """Remove the PID files."""
  123. logger.debug("Cleaning up")
  124. # Remove PID file
  125. os.unlink(pid_path)
  126. atexit.register(cleanup)
  127. # Decouple environment
  128. os.chdir("/")
  129. os.setsid()
  130. with open(os.devnull, "r") as null_in:
  131. os.dup2(null_in.fileno(), sys.stdin.fileno())
  132. with open(os.devnull, "w") as null_out:
  133. os.dup2(null_out.fileno(), sys.stdout.fileno())
  134. os.dup2(null_out.fileno(), sys.stderr.fileno())
  135. def serve(configuration, logger):
  136. """Serve radicale from configuration."""
  137. logger.info("Starting Radicale")
  138. # Create collection servers
  139. servers = {}
  140. if configuration.getboolean("server", "ssl"):
  141. server_class = ThreadedHTTPSServer
  142. server_class.certificate = configuration.get("server", "certificate")
  143. server_class.key = configuration.get("server", "key")
  144. server_class.ciphers = configuration.get("server", "ciphers")
  145. server_class.protocol = getattr(
  146. ssl, configuration.get("server", "protocol"), ssl.PROTOCOL_SSLv23)
  147. # Test if the SSL files can be read
  148. for name in ("certificate", "key"):
  149. filename = getattr(server_class, name)
  150. try:
  151. open(filename, "r").close()
  152. except IOError as exception:
  153. logger.warning("Error while reading SSL %s %r: %s" % (
  154. name, filename, exception))
  155. else:
  156. server_class = ThreadedHTTPServer
  157. server_class.client_timeout = configuration.getint("server", "timeout")
  158. server_class.max_connections = configuration.getint(
  159. "server", "max_connections")
  160. server_class.logger = logger
  161. RequestHandler.logger = logger
  162. if not configuration.getboolean("server", "dns_lookup"):
  163. RequestHandler.address_string = lambda self: self.client_address[0]
  164. shutdown_program = False
  165. for host in configuration.get("server", "hosts").split(","):
  166. address, port = host.strip().rsplit(":", 1)
  167. address, port = address.strip("[] "), int(port)
  168. application = Application(configuration, logger)
  169. server = make_server(
  170. address, port, application, server_class, RequestHandler)
  171. servers[server.socket] = server
  172. logger.debug("Listening to %s port %s",
  173. server.server_name, server.server_port)
  174. if configuration.getboolean("server", "ssl"):
  175. logger.debug("Using SSL")
  176. # Create a socket pair to notify the select syscall of program shutdown
  177. # This is not available in python < 3.5 on Windows
  178. if hasattr(socket, "socketpair"):
  179. shutdown_program_socket_in, shutdown_program_socket_out = (
  180. socket.socketpair())
  181. else:
  182. shutdown_program_socket_in, shutdown_program_socket_out = None, None
  183. # SIGTERM and SIGINT (aka KeyboardInterrupt) should just mark this for
  184. # shutdown
  185. def shutdown(*args):
  186. nonlocal shutdown_program
  187. if shutdown_program:
  188. # Ignore following signals
  189. return
  190. logger.info("Stopping Radicale")
  191. shutdown_program = True
  192. if shutdown_program_socket_in:
  193. shutdown_program_socket_in.sendall(b"goodbye")
  194. signal.signal(signal.SIGTERM, shutdown)
  195. signal.signal(signal.SIGINT, shutdown)
  196. # Main loop: wait for requests on any of the servers or program shutdown
  197. sockets = list(servers.keys())
  198. if shutdown_program_socket_out:
  199. # Use socket pair to get notified of program shutdown
  200. sockets.append(shutdown_program_socket_out)
  201. select_timeout = None
  202. else:
  203. # Fallback to busy waiting
  204. select_timeout = 1.0
  205. if configuration.getboolean("server", "daemon"):
  206. daemonize(configuration, logger)
  207. logger.debug("Radicale server ready")
  208. while not shutdown_program:
  209. try:
  210. rlist, _, xlist = select.select(
  211. sockets, [], sockets, select_timeout)
  212. except (KeyboardInterrupt, select.error):
  213. # SIGINT is handled by signal handler above
  214. rlist, xlist = [], []
  215. if xlist:
  216. raise RuntimeError("Unhandled socket error")
  217. if rlist:
  218. server = servers.get(rlist[0])
  219. if server:
  220. server.handle_request()
  221. if __name__ == "__main__":
  222. run()