__main__.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2011-2016 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 atexit
  22. import optparse
  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 (
  31. VERSION, Application, RequestHandler, ThreadedHTTPServer,
  32. ThreadedHTTPSServer, config, log)
  33. opt_dict = {
  34. '--server-daemon': {
  35. 'help': 'launch as daemon',
  36. 'aliases': ['-d', '--daemon']},
  37. '--server-pid': {
  38. 'help': 'set PID filename for daemon mode',
  39. 'aliases': ['-p', '--pid']},
  40. '--server-hosts': {
  41. 'help': 'set server hostnames and ports',
  42. 'aliases': ['-H', '--hosts'],
  43. },
  44. '--server-ssl': {
  45. 'help': 'use SSL connection',
  46. 'aliases': ['-s', '--ssl'],
  47. },
  48. '--server-key': {
  49. 'help': 'set private key file',
  50. 'aliases': ['-k', '--key']
  51. },
  52. '--server-certificate': {
  53. 'help': 'set certificate file',
  54. 'aliases': ['-c', '--certificate']
  55. },
  56. '--logging-debug': {
  57. 'help': 'print debug informations',
  58. 'aliases': ['-D', '--debug']
  59. }
  60. }
  61. def run():
  62. """Run Radicale as a standalone server."""
  63. # Get command-line options
  64. parser = optparse.OptionParser(version=VERSION)
  65. for section, values in config.INITIAL_CONFIG.items():
  66. group = optparse.OptionGroup(parser, section)
  67. for option, default_value in values.items():
  68. long_name = '--{0}-{1}'.format(section, option)
  69. kwargs = {}
  70. args = [long_name]
  71. if default_value.lower() in ('true', 'false'):
  72. kwargs['action'] = 'store_true'
  73. if long_name in opt_dict:
  74. args.extend(opt_dict[long_name].get('aliases'))
  75. opt_dict[long_name].pop('aliases')
  76. kwargs.update(opt_dict[long_name])
  77. group.add_option(*args, **kwargs)
  78. if section == 'server':
  79. group.add_option(
  80. "-f", "--foreground", action="store_false",
  81. dest="server_daemon",
  82. help="launch in foreground (opposite of --daemon)")
  83. group.add_option(
  84. "-S", "--no-ssl", action="store_false", dest="server_ssl",
  85. help="do not use SSL connection (opposite of --ssl)")
  86. parser.add_option_group(group)
  87. parser.add_option(
  88. "-C", "--config",
  89. help="use a specific configuration file")
  90. options = parser.parse_args()[0]
  91. if options.config:
  92. configuration = config.load()
  93. configuration_found = configuration.read(options.config)
  94. else:
  95. configuration_paths = [
  96. "/etc/radicale/config",
  97. os.path.expanduser("~/.config/radicale/config")]
  98. if "RADICALE_CONFIG" in os.environ:
  99. configuration_paths.append(os.environ["RADICALE_CONFIG"])
  100. configuration = config.load(configuration_paths)
  101. configuration_found = True
  102. # Update Radicale configuration according to options
  103. for group in parser.option_groups:
  104. section = group.title
  105. for option in group.option_list:
  106. key = option.dest
  107. print(key)
  108. config_key = key.split('_', 1)[1]
  109. if key:
  110. value = getattr(options, key)
  111. if value is not None:
  112. configuration.set(section, config_key, str(value))
  113. # Start logging
  114. filename = os.path.expanduser(configuration.get("logging", "config"))
  115. debug = configuration.getboolean("logging", "debug")
  116. logger = log.start("radicale", filename, debug)
  117. # Log a warning if the configuration file of the command line is not found
  118. if not configuration_found:
  119. logger.warning("Configuration file '%s' not found" % options.config)
  120. try:
  121. serve(configuration, logger)
  122. except Exception:
  123. logger.exception("An exception occurred during server startup:")
  124. exit(1)
  125. def serve(configuration, logger):
  126. """Serve radicale from configuration."""
  127. # Fork if Radicale is launched as daemon
  128. if configuration.getboolean("server", "daemon"):
  129. # Check and create PID file in a race-free manner
  130. if configuration.get("server", "pid"):
  131. try:
  132. pid_fd = os.open(
  133. configuration.get("server", "pid"),
  134. os.O_CREAT | os.O_EXCL | os.O_WRONLY)
  135. except:
  136. raise OSError(
  137. "PID file exists: %s" % configuration.get("server", "pid"))
  138. pid = os.fork()
  139. if pid:
  140. sys.exit()
  141. # Write PID
  142. if configuration.get("server", "pid"):
  143. with os.fdopen(pid_fd, "w") as pid_file:
  144. pid_file.write(str(os.getpid()))
  145. # Decouple environment
  146. os.umask(0)
  147. os.chdir("/")
  148. os.setsid()
  149. with open(os.devnull, "r") as null_in:
  150. os.dup2(null_in.fileno(), sys.stdin.fileno())
  151. with open(os.devnull, "w") as null_out:
  152. os.dup2(null_out.fileno(), sys.stdout.fileno())
  153. os.dup2(null_out.fileno(), sys.stderr.fileno())
  154. # Register exit function
  155. def cleanup():
  156. """Remove the PID files."""
  157. logger.debug("Cleaning up")
  158. # Remove PID file
  159. if (configuration.get("server", "pid") and
  160. configuration.getboolean("server", "daemon")):
  161. os.unlink(configuration.get("server", "pid"))
  162. atexit.register(cleanup)
  163. logger.info("Starting Radicale")
  164. logger.debug(
  165. "Base URL prefix: %s", configuration.get("server", "base_prefix"))
  166. # Create collection servers
  167. servers = {}
  168. if configuration.getboolean("server", "ssl"):
  169. server_class = ThreadedHTTPSServer
  170. server_class.certificate = configuration.get("server", "certificate")
  171. server_class.key = configuration.get("server", "key")
  172. server_class.ciphers = configuration.get("server", "ciphers")
  173. server_class.protocol = getattr(
  174. ssl, configuration.get("server", "protocol"), ssl.PROTOCOL_SSLv23)
  175. # Test if the SSL files can be read
  176. for name in ("certificate", "key"):
  177. filename = getattr(server_class, name)
  178. try:
  179. open(filename, "r").close()
  180. except IOError as exception:
  181. logger.warning("Error while reading SSL %s %r: %s" % (
  182. name, filename, exception))
  183. else:
  184. server_class = ThreadedHTTPServer
  185. server_class.client_timeout = configuration.getint("server", "timeout")
  186. server_class.max_connections = configuration.getint(
  187. "server", "max_connections")
  188. RequestHandler.logger = logger
  189. if not configuration.getboolean("server", "dns_lookup"):
  190. RequestHandler.address_string = lambda self: self.client_address[0]
  191. shutdown_program = False
  192. for host in configuration.get("server", "hosts").split(","):
  193. address, port = host.strip().rsplit(":", 1)
  194. address, port = address.strip("[] "), int(port)
  195. application = Application(configuration, logger)
  196. server = make_server(
  197. address, port, application, server_class, RequestHandler)
  198. servers[server.socket] = server
  199. logger.debug("Listening to %s port %s",
  200. server.server_name, server.server_port)
  201. if configuration.getboolean("server", "ssl"):
  202. logger.debug("Using SSL")
  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. else:
  230. # Fallback to busy waiting
  231. select_timeout = 1.0
  232. logger.debug("Radicale server ready")
  233. while not shutdown_program:
  234. try:
  235. rlist, _, xlist = select.select(
  236. sockets, [], sockets, select_timeout)
  237. except (KeyboardInterrupt, select.error):
  238. # SIGINT is handled by signal handler above
  239. rlist, xlist = [], []
  240. if xlist:
  241. raise RuntimeError("Unhandled socket error")
  242. if rlist:
  243. server = servers.get(rlist[0])
  244. if server:
  245. server.handle_request()
  246. if __name__ == "__main__":
  247. run()