__main__.py 9.9 KB

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