__main__.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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 os
  23. import sys
  24. import optparse
  25. import select
  26. import signal
  27. import socket
  28. import ssl
  29. from wsgiref.simple_server import make_server
  30. from . import (
  31. Application, config, HTTPServer, HTTPSServer, log, RequestHandler, VERSION)
  32. # This is a script, many branches and variables
  33. # pylint: disable=R0912,R0914
  34. def run():
  35. """Run Radicale as a standalone server."""
  36. # Get command-line options
  37. parser = optparse.OptionParser(version=VERSION)
  38. parser.add_option(
  39. "-d", "--daemon", action="store_true",
  40. help="launch as daemon")
  41. parser.add_option(
  42. "-p", "--pid",
  43. help="set PID filename for daemon mode")
  44. parser.add_option(
  45. "-f", "--foreground", action="store_false", dest="daemon",
  46. help="launch in foreground (opposite of --daemon)")
  47. parser.add_option(
  48. "-H", "--hosts",
  49. help="set server hostnames and ports")
  50. parser.add_option(
  51. "-s", "--ssl", action="store_true",
  52. help="use SSL connection")
  53. parser.add_option(
  54. "-S", "--no-ssl", action="store_false", dest="ssl",
  55. help="do not use SSL connection (opposite of --ssl)")
  56. parser.add_option(
  57. "-k", "--key",
  58. help="set private key file")
  59. parser.add_option(
  60. "-c", "--certificate",
  61. help="set certificate file")
  62. parser.add_option(
  63. "-D", "--debug", action="store_true",
  64. help="print debug information")
  65. parser.add_option(
  66. "-C", "--config",
  67. help="use a specific configuration file")
  68. options = parser.parse_args()[0]
  69. if options.config:
  70. configuration = config.load()
  71. configuration_found = configuration.read(options.config)
  72. else:
  73. configuration_paths = [
  74. "/etc/radicale/config",
  75. os.path.expanduser("~/.config/radicale/config")]
  76. if "RADICALE_CONFIG" in os.environ:
  77. configuration_paths.append(os.environ["RADICALE_CONFIG"])
  78. configuration = config.load(configuration_paths)
  79. configuration_found = True
  80. # Update Radicale configuration according to options
  81. for option in parser.option_list:
  82. key = option.dest
  83. if key:
  84. section = "logging" if key == "debug" else "server"
  85. value = getattr(options, key)
  86. if value is not None:
  87. configuration.set(section, key, str(value))
  88. # Start logging
  89. filename = os.path.expanduser(configuration.get("logging", "config"))
  90. debug = configuration.getboolean("logging", "debug")
  91. logger = log.start("radicale", filename, debug)
  92. # Log a warning if the configuration file of the command line is not found
  93. if not configuration_found:
  94. logger.warning("Configuration file '%s' not found" % options.config)
  95. # Fork if Radicale is launched as daemon
  96. if configuration.getboolean("server", "daemon"):
  97. # Check and create PID file in a race-free manner
  98. if configuration.get("server", "pid"):
  99. try:
  100. pid_fd = os.open(
  101. configuration.get("server", "pid"),
  102. os.O_CREAT | os.O_EXCL | os.O_WRONLY)
  103. except:
  104. raise OSError(
  105. "PID file exists: %s" % configuration.get("server", "pid"))
  106. pid = os.fork()
  107. if pid:
  108. sys.exit()
  109. # Write PID
  110. if configuration.get("server", "pid"):
  111. with os.fdopen(pid_fd, "w") as pid_file:
  112. pid_file.write(str(os.getpid()))
  113. # Decouple environment
  114. os.umask(0)
  115. os.chdir("/")
  116. os.setsid()
  117. with open(os.devnull, "r") as null_in:
  118. os.dup2(null_in.fileno(), sys.stdin.fileno())
  119. with open(os.devnull, "w") as null_out:
  120. os.dup2(null_out.fileno(), sys.stdout.fileno())
  121. os.dup2(null_out.fileno(), sys.stderr.fileno())
  122. # Register exit function
  123. def cleanup():
  124. """Remove the PID files."""
  125. logger.debug("Cleaning up")
  126. # Remove PID file
  127. if (configuration.get("server", "pid") and
  128. configuration.getboolean("server", "daemon")):
  129. os.unlink(configuration.get("server", "pid"))
  130. atexit.register(cleanup)
  131. logger.info("Starting Radicale")
  132. logger.debug(
  133. "Base URL prefix: %s" % configuration.get("server", "base_prefix"))
  134. # Create collection servers
  135. servers = {}
  136. if configuration.getboolean("server", "ssl"):
  137. server_class = HTTPSServer
  138. server_class.certificate = configuration.get("server", "certificate")
  139. server_class.key = configuration.get("server", "key")
  140. server_class.cyphers = configuration.get("server", "cyphers")
  141. server_class.certificate = getattr(
  142. ssl, configuration.get("server", "protocol"), ssl.PROTOCOL_SSLv23)
  143. # Test if the SSL files can be read
  144. for name in ("certificate", "key"):
  145. filename = getattr(server_class, name)
  146. try:
  147. open(filename, "r").close()
  148. except IOError as exception:
  149. logger.warning(
  150. "Error while reading SSL %s %r: %s" % (
  151. name, filename, exception))
  152. else:
  153. server_class = HTTPServer
  154. if not configuration.getboolean("server", "dns_lookup"):
  155. RequestHandler.address_string = lambda self: self.client_address[0]
  156. shutdown_program = [False]
  157. for host in configuration.get("server", "hosts").split(","):
  158. address, port = host.strip().rsplit(":", 1)
  159. address, port = address.strip("[] "), int(port)
  160. application = Application(configuration, logger)
  161. server = make_server(
  162. address, port, application, server_class, RequestHandler)
  163. servers[server.socket] = server
  164. logger.debug("Listening to %s port %s" % (
  165. server.server_name, server.server_port))
  166. if configuration.getboolean("server", "ssl"):
  167. logger.debug("Using SSL")
  168. # Create a socket pair to notify the select syscall of program shutdown
  169. # This is not available in python < 3.5 on Windows
  170. if hasattr(socket, "socketpair"):
  171. shutdown_program_socket_in, shutdown_program_socket_out = (
  172. socket.socketpair())
  173. else:
  174. shutdown_program_socket_in, shutdown_program_socket_out = None, None
  175. # SIGTERM and SIGINT (aka KeyboardInterrupt) should just mark this for
  176. # shutdown
  177. def shutdown(*args):
  178. if shutdown_program[0]:
  179. # Ignore following signals
  180. return
  181. logger.info("Stopping Radicale")
  182. shutdown_program[0] = True
  183. if shutdown_program_socket_in:
  184. shutdown_program_socket_in.sendall(b"goodbye")
  185. signal.signal(signal.SIGTERM, shutdown)
  186. signal.signal(signal.SIGINT, shutdown)
  187. # Main loop: wait for requests on any of the servers or program shutdown
  188. sockets = list(servers.keys())
  189. if shutdown_program_socket_out:
  190. # Use socket pair to get notified of program shutdown
  191. sockets.append(shutdown_program_socket_out)
  192. select_timeout = None
  193. else:
  194. # Fallback to busy waiting
  195. select_timeout = 1.0
  196. logger.debug("Radicale server ready")
  197. while not shutdown_program[0]:
  198. try:
  199. rlist, _, xlist = select.select(
  200. sockets, [], sockets, select_timeout)
  201. except (KeyboardInterrupt, select.error):
  202. # SIGINT is handled by signal handler above
  203. rlist, xlist = [], []
  204. if xlist:
  205. raise RuntimeError("Unhandled socket error")
  206. if rlist:
  207. server = servers.get(rlist[0])
  208. if server:
  209. server.handle_request()
  210. # pylint: enable=R0912,R0914
  211. if __name__ == "__main__":
  212. run()