__main__.py 8.7 KB

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