__main__.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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.ciphers = configuration.get("server", "ciphers")
  152. server_class.protocol = getattr(
  153. ssl, configuration.get("server", "protocol"), ssl.PROTOCOL_SSLv23)
  154. # Test if the SSL files can be read
  155. for name in ("certificate", "key"):
  156. filename = getattr(server_class, name)
  157. try:
  158. open(filename, "r").close()
  159. except OSError as e:
  160. raise RuntimeError("Failed to read SSL %s %r: %s" %
  161. (name, filename, e)) from e
  162. else:
  163. server_class = ThreadedHTTPServer
  164. server_class.client_timeout = configuration.getint("server", "timeout")
  165. server_class.max_connections = configuration.getint(
  166. "server", "max_connections")
  167. server_class.logger = logger
  168. RequestHandler.logger = logger
  169. if not configuration.getboolean("server", "dns_lookup"):
  170. RequestHandler.address_string = lambda self: self.client_address[0]
  171. shutdown_program = False
  172. for host in configuration.get("server", "hosts").split(","):
  173. try:
  174. address, port = host.strip().rsplit(":", 1)
  175. address, port = address.strip("[] "), int(port)
  176. except ValueError as e:
  177. raise RuntimeError(
  178. "Failed to parse address %r: %s" % (host, e)) from e
  179. application = Application(configuration, logger)
  180. try:
  181. server = make_server(
  182. address, port, application, server_class, RequestHandler)
  183. except OSError as e:
  184. raise RuntimeError(
  185. "Failed to start server %r: %s" % (host, e)) from e
  186. servers[server.socket] = server
  187. logger.info("Listening to %r on port %d%s",
  188. server.server_name, server.server_port, " using SSL"
  189. if configuration.getboolean("server", "ssl") else "")
  190. # Create a socket pair to notify the select syscall of program shutdown
  191. # This is not available in python < 3.5 on Windows
  192. if hasattr(socket, "socketpair"):
  193. shutdown_program_socket_in, shutdown_program_socket_out = (
  194. socket.socketpair())
  195. else:
  196. shutdown_program_socket_in, shutdown_program_socket_out = None, None
  197. # SIGTERM and SIGINT (aka KeyboardInterrupt) should just mark this for
  198. # shutdown
  199. def shutdown(*args):
  200. nonlocal shutdown_program
  201. if shutdown_program:
  202. # Ignore following signals
  203. return
  204. logger.info("Stopping Radicale")
  205. shutdown_program = True
  206. if shutdown_program_socket_in:
  207. shutdown_program_socket_in.sendall(b"goodbye")
  208. signal.signal(signal.SIGTERM, shutdown)
  209. signal.signal(signal.SIGINT, shutdown)
  210. # Main loop: wait for requests on any of the servers or program shutdown
  211. sockets = list(servers.keys())
  212. if shutdown_program_socket_out:
  213. # Use socket pair to get notified of program shutdown
  214. sockets.append(shutdown_program_socket_out)
  215. select_timeout = None
  216. else:
  217. # Fallback to busy waiting
  218. select_timeout = 1.0
  219. if configuration.getboolean("server", "daemon"):
  220. daemonize(configuration, logger)
  221. logger.info("Radicale server ready")
  222. while not shutdown_program:
  223. try:
  224. rlist, _, xlist = select.select(
  225. sockets, [], sockets, select_timeout)
  226. except (KeyboardInterrupt, select.error):
  227. # SIGINT is handled by signal handler above
  228. rlist, xlist = [], []
  229. if xlist:
  230. raise RuntimeError("unhandled socket error")
  231. if rlist:
  232. server = servers.get(rlist[0])
  233. if server:
  234. server.handle_request()
  235. if __name__ == "__main__":
  236. run()