__main__.py 11 KB

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