__main__.py 10 KB

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