__main__.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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 (VERSION, Application, RequestHandler, ThreadedHTTPServer,
  31. ThreadedHTTPSServer, config, log)
  32. def run():
  33. """Run Radicale as a standalone server."""
  34. # Get command-line arguments
  35. parser = argparse.ArgumentParser(usage="radicale [OPTIONS]")
  36. parser.add_argument("--version", action="version", version=VERSION)
  37. parser.add_argument(
  38. "-C", "--config", help="use a specific configuration file")
  39. groups = {}
  40. for section, values in config.INITIAL_CONFIG.items():
  41. group = parser.add_argument_group(section)
  42. groups[group] = []
  43. for option, data in values.items():
  44. kwargs = data.copy()
  45. long_name = "--{0}-{1}".format(
  46. section, option.replace("_", "-"))
  47. args = kwargs.pop("aliases", [])
  48. args.append(long_name)
  49. kwargs["dest"] = "{0}_{1}".format(section, option)
  50. groups[group].append(kwargs["dest"])
  51. del kwargs["value"]
  52. if "internal" in kwargs:
  53. del kwargs["internal"]
  54. if kwargs["type"] == bool:
  55. del kwargs["type"]
  56. kwargs["action"] = "store_const"
  57. kwargs["const"] = "True"
  58. opposite_args = kwargs.pop("opposite", [])
  59. opposite_args.append("--no{0}".format(long_name[1:]))
  60. group.add_argument(*args, **kwargs)
  61. kwargs["const"] = "False"
  62. kwargs["help"] = "do not {0} (opposite of {1})".format(
  63. kwargs["help"], long_name)
  64. group.add_argument(*opposite_args, **kwargs)
  65. else:
  66. group.add_argument(*args, **kwargs)
  67. args = parser.parse_args()
  68. if args.config is not None:
  69. config_paths = [args.config] if args.config else []
  70. ignore_missing_paths = False
  71. else:
  72. config_paths = ["/etc/radicale/config",
  73. os.path.expanduser("~/.config/radicale/config")]
  74. if "RADICALE_CONFIG" in os.environ:
  75. config_paths.append(os.environ["RADICALE_CONFIG"])
  76. ignore_missing_paths = True
  77. try:
  78. configuration = config.load(config_paths,
  79. ignore_missing_paths=ignore_missing_paths)
  80. except Exception as e:
  81. print("ERROR: Invalid configuration: %s" % e, file=sys.stderr)
  82. if args.logging_debug:
  83. raise
  84. exit(1)
  85. # Update Radicale configuration according to arguments
  86. for group, actions in groups.items():
  87. section = group.title
  88. for action in actions:
  89. value = getattr(args, action)
  90. if value is not None:
  91. configuration.set(section, action.split('_', 1)[1], value)
  92. # Start logging
  93. filename = os.path.expanduser(configuration.get("logging", "config"))
  94. debug = configuration.getboolean("logging", "debug")
  95. try:
  96. logger = log.start("radicale", filename, debug)
  97. except Exception as e:
  98. print("ERROR: Failed to start logger: %s" % e, file=sys.stderr)
  99. if debug:
  100. raise
  101. exit(1)
  102. try:
  103. serve(configuration, logger)
  104. except Exception as e:
  105. logger.error("An exception occurred during server startup: %s", e,
  106. exc_info=True)
  107. exit(1)
  108. def daemonize(configuration, logger):
  109. """Fork and decouple if Radicale is configured as daemon."""
  110. # Check and create PID file in a race-free manner
  111. if configuration.get("server", "pid"):
  112. try:
  113. pid_path = os.path.abspath(os.path.expanduser(
  114. configuration.get("server", "pid")))
  115. pid_fd = os.open(
  116. pid_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
  117. except OSError as e:
  118. raise OSError("PID file exists: %r" %
  119. configuration.get("server", "pid")) from e
  120. pid = os.fork()
  121. if pid:
  122. # Write PID
  123. if configuration.get("server", "pid"):
  124. with os.fdopen(pid_fd, "w") as pid_file:
  125. pid_file.write(str(pid))
  126. sys.exit()
  127. if configuration.get("server", "pid"):
  128. os.close(pid_fd)
  129. # Register exit function
  130. def cleanup():
  131. """Remove the PID files."""
  132. logger.debug("Cleaning up")
  133. # Remove PID file
  134. os.unlink(pid_path)
  135. atexit.register(cleanup)
  136. # Decouple environment
  137. os.chdir("/")
  138. os.setsid()
  139. with open(os.devnull, "r") as null_in:
  140. os.dup2(null_in.fileno(), sys.stdin.fileno())
  141. with open(os.devnull, "w") as null_out:
  142. os.dup2(null_out.fileno(), sys.stdout.fileno())
  143. os.dup2(null_out.fileno(), sys.stderr.fileno())
  144. def serve(configuration, logger):
  145. """Serve radicale from configuration."""
  146. logger.info("Starting Radicale")
  147. # Create collection servers
  148. servers = {}
  149. if configuration.getboolean("server", "ssl"):
  150. server_class = ThreadedHTTPSServer
  151. server_class.certificate = configuration.get("server", "certificate")
  152. server_class.key = configuration.get("server", "key")
  153. server_class.certificate_authority = configuration.get(
  154. "server", "certificate_authority")
  155. server_class.ciphers = configuration.get("server", "ciphers")
  156. server_class.protocol = getattr(
  157. ssl, configuration.get("server", "protocol"), ssl.PROTOCOL_SSLv23)
  158. # Test if the SSL files can be read
  159. for name in ["certificate", "key"] + (
  160. ["certificate_authority"]
  161. if server_class.certificate_authority else []):
  162. filename = getattr(server_class, name)
  163. try:
  164. open(filename, "r").close()
  165. except OSError as e:
  166. raise RuntimeError("Failed to read SSL %s %r: %s" %
  167. (name, filename, e)) from e
  168. else:
  169. server_class = ThreadedHTTPServer
  170. server_class.client_timeout = configuration.getint("server", "timeout")
  171. server_class.max_connections = configuration.getint(
  172. "server", "max_connections")
  173. server_class.logger = logger
  174. RequestHandler.logger = logger
  175. if not configuration.getboolean("server", "dns_lookup"):
  176. RequestHandler.address_string = lambda self: self.client_address[0]
  177. shutdown_program = False
  178. for host in configuration.get("server", "hosts").split(","):
  179. try:
  180. address, port = host.strip().rsplit(":", 1)
  181. address, port = address.strip("[] "), int(port)
  182. except ValueError as e:
  183. raise RuntimeError(
  184. "Failed to parse address %r: %s" % (host, e)) from e
  185. application = Application(configuration, logger)
  186. try:
  187. server = make_server(
  188. address, port, application, server_class, RequestHandler)
  189. except OSError as e:
  190. raise RuntimeError(
  191. "Failed to start server %r: %s" % (host, e)) from e
  192. servers[server.socket] = server
  193. logger.info("Listening to %r on port %d%s",
  194. server.server_name, server.server_port, " using SSL"
  195. if configuration.getboolean("server", "ssl") else "")
  196. # Create a socket pair to notify the select syscall of program shutdown
  197. # This is not available in python < 3.5 on Windows
  198. if hasattr(socket, "socketpair"):
  199. shutdown_program_socket_in, shutdown_program_socket_out = (
  200. socket.socketpair())
  201. else:
  202. shutdown_program_socket_in, shutdown_program_socket_out = None, None
  203. # SIGTERM and SIGINT (aka KeyboardInterrupt) should just mark this for
  204. # shutdown
  205. def shutdown(*args):
  206. nonlocal shutdown_program
  207. if shutdown_program:
  208. # Ignore following signals
  209. return
  210. logger.info("Stopping Radicale")
  211. shutdown_program = True
  212. if shutdown_program_socket_in:
  213. shutdown_program_socket_in.sendall(b"goodbye")
  214. signal.signal(signal.SIGTERM, shutdown)
  215. signal.signal(signal.SIGINT, shutdown)
  216. # Main loop: wait for requests on any of the servers or program shutdown
  217. sockets = list(servers.keys())
  218. if shutdown_program_socket_out:
  219. # Use socket pair to get notified of program shutdown
  220. sockets.append(shutdown_program_socket_out)
  221. select_timeout = None
  222. else:
  223. # Fallback to busy waiting
  224. select_timeout = 1.0
  225. if configuration.getboolean("server", "daemon"):
  226. daemonize(configuration, logger)
  227. logger.info("Radicale server ready")
  228. while not shutdown_program:
  229. try:
  230. rlist, _, xlist = select.select(
  231. sockets, [], sockets, select_timeout)
  232. except (KeyboardInterrupt, select.error):
  233. # SIGINT is handled by signal handler above
  234. rlist, xlist = [], []
  235. if xlist:
  236. raise RuntimeError("unhandled socket error")
  237. if rlist:
  238. server = servers.get(rlist[0])
  239. if server:
  240. server.handle_request()
  241. if __name__ == "__main__":
  242. run()