2018-07-09 16:47:36 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
2019-01-20 18:37:45 +00:00
|
|
|
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
|
|
|
# Copyright (C) 2012-2019 janeczku, OzzieIsaacs, andrerfcsantos, idalin
|
|
|
|
#
|
|
|
|
# This program is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
2018-07-09 16:47:36 +00:00
|
|
|
import sys
|
|
|
|
import os
|
2019-06-10 17:19:27 +00:00
|
|
|
import errno
|
2018-09-23 17:15:50 +00:00
|
|
|
import signal
|
2019-06-06 15:10:22 +00:00
|
|
|
import socket
|
2021-03-15 12:48:05 +00:00
|
|
|
import subprocess # nosec
|
2023-01-29 08:54:07 +00:00
|
|
|
from .services.background_scheduler import BackgroundScheduler
|
2018-09-23 17:15:50 +00:00
|
|
|
|
2018-07-09 16:47:36 +00:00
|
|
|
try:
|
2020-04-25 12:56:51 +00:00
|
|
|
from gevent.pywsgi import WSGIServer
|
2022-03-28 11:58:41 +00:00
|
|
|
from .gevent_wsgi import MyWSGIHandler
|
2018-07-09 16:47:36 +00:00
|
|
|
from gevent.pool import Pool
|
2019-06-10 17:19:27 +00:00
|
|
|
from gevent import __version__ as _version
|
2020-09-27 11:00:07 +00:00
|
|
|
from greenlet import GreenletExit
|
|
|
|
import ssl
|
2019-07-14 17:38:07 +00:00
|
|
|
VERSION = 'Gevent ' + _version
|
2019-06-10 17:19:27 +00:00
|
|
|
_GEVENT = True
|
2018-07-09 16:47:36 +00:00
|
|
|
except ImportError:
|
2022-03-28 11:58:41 +00:00
|
|
|
from .tornado_wsgi import MyWSGIContainer
|
2018-07-09 16:47:36 +00:00
|
|
|
from tornado.httpserver import HTTPServer
|
|
|
|
from tornado.ioloop import IOLoop
|
2019-06-10 17:19:27 +00:00
|
|
|
from tornado import version as _version
|
2019-07-14 17:38:07 +00:00
|
|
|
VERSION = 'Tornado ' + _version
|
2019-06-10 17:19:27 +00:00
|
|
|
_GEVENT = False
|
2018-07-09 16:47:36 +00:00
|
|
|
|
2019-07-14 17:28:32 +00:00
|
|
|
from . import logger
|
2019-06-06 15:10:22 +00:00
|
|
|
|
|
|
|
|
2019-06-11 16:35:20 +00:00
|
|
|
log = logger.create()
|
|
|
|
|
|
|
|
|
2019-07-14 19:06:40 +00:00
|
|
|
def _readable_listen_address(address, port):
|
|
|
|
if ':' in address:
|
|
|
|
address = "[" + address + "]"
|
|
|
|
return '%s:%s' % (address, port)
|
|
|
|
|
|
|
|
|
|
|
|
class WebServer(object):
|
2018-07-09 16:47:36 +00:00
|
|
|
|
|
|
|
def __init__(self):
|
2019-06-10 17:19:27 +00:00
|
|
|
signal.signal(signal.SIGINT, self._killServer)
|
|
|
|
signal.signal(signal.SIGTERM, self._killServer)
|
2018-07-09 16:47:36 +00:00
|
|
|
|
2019-06-10 17:19:27 +00:00
|
|
|
self.wsgiserver = None
|
2019-06-11 16:35:20 +00:00
|
|
|
self.access_logger = None
|
2019-06-10 17:19:27 +00:00
|
|
|
self.restart = False
|
|
|
|
self.app = None
|
|
|
|
self.listen_address = None
|
|
|
|
self.listen_port = None
|
|
|
|
self.unix_socket_file = None
|
|
|
|
self.ssl_args = None
|
|
|
|
|
|
|
|
def init_app(self, application, config):
|
|
|
|
self.app = application
|
|
|
|
self.listen_address = config.get_config_ipaddress()
|
|
|
|
self.listen_port = config.config_port
|
|
|
|
|
2019-06-10 10:18:11 +00:00
|
|
|
if config.config_access_log:
|
2019-06-10 17:19:27 +00:00
|
|
|
log_name = "gevent.access" if _GEVENT else "tornado.access"
|
|
|
|
formatter = logger.ACCESS_FORMATTER_GEVENT if _GEVENT else logger.ACCESS_FORMATTER_TORNADO
|
2020-05-24 07:59:45 +00:00
|
|
|
self.access_logger, logfile = logger.create_access_log(config.config_access_logfile, log_name, formatter)
|
|
|
|
if logfile != config.config_access_logfile:
|
|
|
|
log.warning("Accesslog path %s not valid, falling back to default", config.config_access_logfile)
|
|
|
|
config.config_access_logfile = logfile
|
|
|
|
config.save()
|
2019-06-22 08:55:09 +00:00
|
|
|
else:
|
|
|
|
if not _GEVENT:
|
|
|
|
logger.get('tornado.access').disabled = True
|
2019-06-06 15:10:22 +00:00
|
|
|
|
|
|
|
certfile_path = config.get_config_certfile()
|
|
|
|
keyfile_path = config.get_config_keyfile()
|
|
|
|
if certfile_path and keyfile_path:
|
|
|
|
if os.path.isfile(certfile_path) and os.path.isfile(keyfile_path):
|
2019-07-14 19:06:40 +00:00
|
|
|
self.ssl_args = dict(certfile=certfile_path, keyfile=keyfile_path)
|
2019-06-06 15:10:22 +00:00
|
|
|
else:
|
2020-04-19 17:08:58 +00:00
|
|
|
log.warning('The specified paths for the ssl certificate file and/or key file seem to be broken. '
|
|
|
|
'Ignoring ssl.')
|
2019-06-11 16:35:20 +00:00
|
|
|
log.warning('Cert path: %s', certfile_path)
|
|
|
|
log.warning('Key path: %s', keyfile_path)
|
2019-06-06 15:10:22 +00:00
|
|
|
|
2019-06-10 17:19:27 +00:00
|
|
|
def _make_gevent_unix_socket(self, socket_file):
|
|
|
|
# the socket file must not exist prior to bind()
|
|
|
|
if os.path.exists(socket_file):
|
|
|
|
# avoid nuking regular files and symbolic links (could be a mistype or security issue)
|
|
|
|
if os.path.isfile(socket_file) or os.path.islink(socket_file):
|
|
|
|
raise OSError(errno.EEXIST, os.strerror(errno.EEXIST), socket_file)
|
|
|
|
os.remove(socket_file)
|
|
|
|
|
|
|
|
unix_sock = WSGIServer.get_listener(socket_file, family=socket.AF_UNIX)
|
|
|
|
self.unix_socket_file = socket_file
|
|
|
|
|
|
|
|
# ensure current user and group have r/w permissions, no permissions for other users
|
|
|
|
# this way the socket can be shared in a semi-secure manner
|
|
|
|
# between the user running calibre-web and the user running the fronting webserver
|
2019-06-21 07:46:03 +00:00
|
|
|
os.chmod(socket_file, 0o660)
|
2019-06-10 17:19:27 +00:00
|
|
|
|
|
|
|
return unix_sock
|
|
|
|
|
2019-06-06 15:10:22 +00:00
|
|
|
def _make_gevent_socket(self):
|
2019-06-10 17:19:27 +00:00
|
|
|
if os.name != 'nt':
|
|
|
|
unix_socket_file = os.environ.get("CALIBRE_UNIX_SOCKET")
|
|
|
|
if unix_socket_file:
|
2019-07-14 19:06:40 +00:00
|
|
|
return self._make_gevent_unix_socket(unix_socket_file), "unix:" + unix_socket_file
|
2019-06-10 17:19:27 +00:00
|
|
|
|
|
|
|
if self.listen_address:
|
2019-07-14 19:06:40 +00:00
|
|
|
return (self.listen_address, self.listen_port), None
|
2019-06-10 17:19:27 +00:00
|
|
|
|
2019-06-06 15:10:22 +00:00
|
|
|
if os.name == 'nt':
|
2019-06-21 07:46:03 +00:00
|
|
|
self.listen_address = '0.0.0.0'
|
2019-07-14 19:06:40 +00:00
|
|
|
return (self.listen_address, self.listen_port), None
|
2019-06-06 15:10:22 +00:00
|
|
|
|
|
|
|
try:
|
2019-07-14 19:06:40 +00:00
|
|
|
address = ('::', self.listen_port)
|
2019-06-10 17:19:27 +00:00
|
|
|
sock = WSGIServer.get_listener(address, family=socket.AF_INET6)
|
2019-06-06 15:10:22 +00:00
|
|
|
except socket.error as ex:
|
2019-06-11 16:35:20 +00:00
|
|
|
log.error('%s', ex)
|
2019-06-21 07:46:03 +00:00
|
|
|
log.warning('Unable to listen on "", trying on IPv4 only...')
|
2019-07-14 19:06:40 +00:00
|
|
|
address = ('', self.listen_port)
|
2019-06-10 17:19:27 +00:00
|
|
|
sock = WSGIServer.get_listener(address, family=socket.AF_INET)
|
2019-07-14 19:06:40 +00:00
|
|
|
|
|
|
|
return sock, _readable_listen_address(*address)
|
2019-02-06 20:52:24 +00:00
|
|
|
|
2021-03-14 12:28:52 +00:00
|
|
|
@staticmethod
|
2021-03-14 13:29:40 +00:00
|
|
|
def _get_args_for_reloading():
|
2021-02-06 08:42:27 +00:00
|
|
|
"""Determine how the script was executed, and return the args needed
|
|
|
|
to execute it again in a new process.
|
|
|
|
Code from https://github.com/pyload/pyload. Author GammaC0de, voulter
|
|
|
|
"""
|
|
|
|
rv = [sys.executable]
|
|
|
|
py_script = sys.argv[0]
|
|
|
|
args = sys.argv[1:]
|
|
|
|
# Need to look at main module to determine how it was executed.
|
|
|
|
__main__ = sys.modules["__main__"]
|
|
|
|
|
|
|
|
# The value of __package__ indicates how Python was called. It may
|
|
|
|
# not exist if a setuptools script is installed as an egg. It may be
|
|
|
|
# set incorrectly for entry points created with pip on Windows.
|
2023-02-18 12:59:10 +00:00
|
|
|
if getattr(__main__, "__package__", "") == "" or (
|
2021-02-15 12:33:42 +00:00
|
|
|
os.name == "nt"
|
|
|
|
and __main__.__package__ == ""
|
|
|
|
and not os.path.exists(py_script)
|
2021-02-15 13:17:05 +00:00
|
|
|
and os.path.exists("{}.exe".format(py_script))
|
2021-02-06 08:42:27 +00:00
|
|
|
):
|
|
|
|
# Executed a file, like "python app.py".
|
|
|
|
py_script = os.path.abspath(py_script)
|
|
|
|
|
|
|
|
if os.name == "nt":
|
|
|
|
# Windows entry points have ".exe" extension and should be
|
|
|
|
# called directly.
|
2021-02-15 13:17:05 +00:00
|
|
|
if not os.path.exists(py_script) and os.path.exists("{}.exe".format(py_script)):
|
2021-02-06 08:42:27 +00:00
|
|
|
py_script += ".exe"
|
|
|
|
|
|
|
|
if (
|
|
|
|
os.path.splitext(sys.executable)[1] == ".exe"
|
|
|
|
and os.path.splitext(py_script)[1] == ".exe"
|
|
|
|
):
|
|
|
|
rv.pop(0)
|
|
|
|
|
|
|
|
rv.append(py_script)
|
|
|
|
else:
|
|
|
|
# Executed a module, like "python -m module".
|
|
|
|
if sys.argv[0] == "-m":
|
|
|
|
args = sys.argv
|
|
|
|
else:
|
|
|
|
if os.path.isfile(py_script):
|
|
|
|
# Rewritten by Python from "-m script" to "/path/to/script.py".
|
|
|
|
py_module = __main__.__package__
|
|
|
|
name = os.path.splitext(os.path.basename(py_script))[0]
|
|
|
|
|
|
|
|
if name != "__main__":
|
2021-02-15 13:17:05 +00:00
|
|
|
py_module += ".{}".format(name)
|
2021-02-06 08:42:27 +00:00
|
|
|
else:
|
|
|
|
# Incorrectly rewritten by pydevd debugger from "-m script" to "script".
|
|
|
|
py_module = py_script
|
|
|
|
|
|
|
|
rv.extend(("-m", py_module.lstrip(".")))
|
|
|
|
|
|
|
|
rv.extend(args)
|
|
|
|
return rv
|
|
|
|
|
2019-06-10 17:19:27 +00:00
|
|
|
def _start_gevent(self):
|
2019-06-06 15:10:22 +00:00
|
|
|
ssl_args = self.ssl_args or {}
|
|
|
|
|
2018-07-09 16:47:36 +00:00
|
|
|
try:
|
2019-06-21 07:46:03 +00:00
|
|
|
sock, output = self._make_gevent_socket()
|
2019-07-14 19:06:40 +00:00
|
|
|
if output is None:
|
|
|
|
output = _readable_listen_address(self.listen_address, self.listen_port)
|
2019-06-21 07:46:03 +00:00
|
|
|
log.info('Starting Gevent server on %s', output)
|
2022-03-28 11:58:41 +00:00
|
|
|
self.wsgiserver = WSGIServer(sock, self.app, log=self.access_logger, handler_class=MyWSGIHandler,
|
2022-05-09 17:47:43 +00:00
|
|
|
error_log=log,
|
2022-03-28 11:58:41 +00:00
|
|
|
spawn=Pool(), **ssl_args)
|
2020-09-27 11:00:07 +00:00
|
|
|
if ssl_args:
|
|
|
|
wrap_socket = self.wsgiserver.wrap_socket
|
|
|
|
def my_wrap_socket(*args, **kwargs):
|
|
|
|
try:
|
|
|
|
return wrap_socket(*args, **kwargs)
|
2020-10-20 15:38:37 +00:00
|
|
|
except (ssl.SSLError, OSError) as ex:
|
2020-09-27 11:00:07 +00:00
|
|
|
log.warning('Gevent SSL Error: %s', ex)
|
|
|
|
raise GreenletExit
|
|
|
|
|
|
|
|
self.wsgiserver.wrap_socket = my_wrap_socket
|
2018-07-09 16:47:36 +00:00
|
|
|
self.wsgiserver.serve_forever()
|
2019-06-10 17:19:27 +00:00
|
|
|
finally:
|
|
|
|
if self.unix_socket_file:
|
|
|
|
os.remove(self.unix_socket_file)
|
|
|
|
self.unix_socket_file = None
|
|
|
|
|
|
|
|
def _start_tornado(self):
|
2020-02-08 12:24:01 +00:00
|
|
|
if os.name == 'nt' and sys.version_info > (3, 7):
|
2019-10-31 14:46:38 +00:00
|
|
|
import asyncio
|
|
|
|
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
|
2019-07-14 19:06:40 +00:00
|
|
|
log.info('Starting Tornado server on %s', _readable_listen_address(self.listen_address, self.listen_port))
|
2019-06-10 17:19:27 +00:00
|
|
|
|
2022-03-28 11:58:41 +00:00
|
|
|
# Max Buffersize set to 200MB
|
|
|
|
http_server = HTTPServer(MyWSGIContainer(self.app),
|
2019-07-14 19:06:40 +00:00
|
|
|
max_buffer_size=209700000,
|
|
|
|
ssl_options=self.ssl_args)
|
2019-06-10 17:19:27 +00:00
|
|
|
http_server.listen(self.listen_port, self.listen_address)
|
2020-02-15 08:08:39 +00:00
|
|
|
self.wsgiserver = IOLoop.current()
|
2019-06-10 17:19:27 +00:00
|
|
|
self.wsgiserver.start()
|
|
|
|
# wait for stop signal
|
|
|
|
self.wsgiserver.close(True)
|
|
|
|
|
|
|
|
def start(self):
|
2019-06-06 15:10:22 +00:00
|
|
|
try:
|
2019-06-10 17:19:27 +00:00
|
|
|
if _GEVENT:
|
|
|
|
# leave subprocess out to allow forking for fetchers and processors
|
|
|
|
self._start_gevent()
|
|
|
|
else:
|
|
|
|
self._start_tornado()
|
|
|
|
except Exception as ex:
|
|
|
|
log.error("Error starting server: %s", ex)
|
|
|
|
print("Error starting server: %s" % ex)
|
2020-04-02 16:23:24 +00:00
|
|
|
self.stop()
|
2019-06-10 17:19:27 +00:00
|
|
|
return False
|
|
|
|
finally:
|
|
|
|
self.wsgiserver = None
|
2018-07-09 16:47:36 +00:00
|
|
|
|
2021-03-19 14:26:41 +00:00
|
|
|
# prevent irritating log of pending tasks message from asyncio
|
|
|
|
logger.get('asyncio').setLevel(logger.logging.CRITICAL)
|
|
|
|
|
2019-06-10 17:19:27 +00:00
|
|
|
if not self.restart:
|
2019-06-11 16:35:20 +00:00
|
|
|
log.info("Performing shutdown of Calibre-Web")
|
2019-06-10 17:19:27 +00:00
|
|
|
return True
|
2018-07-09 16:47:36 +00:00
|
|
|
|
2019-06-10 17:19:27 +00:00
|
|
|
log.info("Performing restart of Calibre-Web")
|
2021-02-06 08:42:27 +00:00
|
|
|
args = self._get_args_for_reloading()
|
2023-02-18 12:59:10 +00:00
|
|
|
if os.environ.get('FLASK_DEBUG'):
|
|
|
|
subprocess.run(args, close_fds=True) # nosec
|
|
|
|
else:
|
|
|
|
subprocess.Popen(args, close_fds=True) # nosec
|
2019-06-10 17:19:27 +00:00
|
|
|
return True
|
2018-07-09 16:47:36 +00:00
|
|
|
|
2023-01-29 08:54:07 +00:00
|
|
|
@staticmethod
|
|
|
|
def shutdown_scheduler():
|
|
|
|
scheduler = BackgroundScheduler()
|
|
|
|
if scheduler:
|
|
|
|
scheduler.scheduler.shutdown()
|
|
|
|
|
2020-08-30 11:43:08 +00:00
|
|
|
def _killServer(self, __, ___):
|
2019-06-10 17:19:27 +00:00
|
|
|
self.stop()
|
2018-09-23 17:15:50 +00:00
|
|
|
|
2019-06-10 17:19:27 +00:00
|
|
|
def stop(self, restart=False):
|
2020-03-29 14:22:11 +00:00
|
|
|
from . import updater_thread
|
|
|
|
updater_thread.stop()
|
|
|
|
|
2019-07-07 12:53:38 +00:00
|
|
|
log.info("webserver stop (restart=%s)", restart)
|
2023-01-29 08:54:07 +00:00
|
|
|
self.shutdown_scheduler()
|
2019-06-10 17:19:27 +00:00
|
|
|
self.restart = restart
|
2018-11-24 19:47:11 +00:00
|
|
|
if self.wsgiserver:
|
2019-06-10 17:19:27 +00:00
|
|
|
if _GEVENT:
|
2018-11-24 19:47:11 +00:00
|
|
|
self.wsgiserver.close()
|
|
|
|
else:
|
2020-02-15 08:08:39 +00:00
|
|
|
self.wsgiserver.add_callback_from_signal(self.wsgiserver.stop)
|