✨ Add ipv4- and ipv6-only command line flags

-4 or --ipv4 will behave as if "--host 0.0.0.0" (or any other specific
v4 address) was supplied and only bind the server socket to v4. It will
be ignored if a v6 address is set to bind to.

-6 or --ipv6 will only bind the server socket to v6 instead of dual
stack on both v4 and v6. It will be ignored if a v4 address is set to
bind to.

Implements #2904
This commit is contained in:
Gina Häußge committed 2019-03-11 17:21:28 +01:00
1 parent a1e8694073
commit f020fc1bc6
2 files changed
+76 -24

No files matched your search

+29 -13
View File
@@ -11,7 +11,7 @@ import sys
from octoprint.cli import bulk_options, standard_options, set_ctx_obj_option, get_ctx_obj_option
def run_server(basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode,
def run_server(basedir, configfile, host, port, v6_only, debug, allow_root, logging_config, verbosity, safe_mode,
ignore_blacklist, octoprint_daemon=None):
"""Initializes the environment and starts up the server."""
@@ -110,6 +110,7 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
environment_detector=environment_detector,
host=host,
port=port,
v6_only=v6_only,
debug=debug,
safe_mode=safe_mode,
allow_root=allow_root,
@@ -120,9 +121,13 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
server_options = bulk_options([
click.option("--host", type=click.STRING, callback=set_ctx_obj_option,
help="Specify the host on which to bind the server."),
help="Specify the host address on which to bind the server."),
click.option("--port", type=click.INT, callback=set_ctx_obj_option,
help="Specify the port on which to bind the server."),
click.option("-4", "--ipv4", "v4", is_flag=True, callback=set_ctx_obj_option,
help="Bind to IPv4 addresses only. Implies '--host 0.0.0.0'. Silently ignored if -6 is present."),
click.option("-6", "--ipv6", "v6", is_flag=True, callback=set_ctx_obj_option,
help="Bind to IPv6 addresses only. Disables dual stack when binding to any v6 addresses. Silently ignored if -4 is present."),
click.option("--logging", type=click.Path(), callback=set_ctx_obj_option,
help="Specify the config file to use for configuring logging."),
click.option("--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option,
@@ -132,7 +137,7 @@ server_options = bulk_options([
click.option("--ignore-blacklist", "ignore_blacklist", is_flag=True, callback=set_ctx_obj_option,
help="Disable processing of the plugin blacklist.")
])
"""Decorator to add the options shared among the server commands: ``--host``, ``--port``,
"""Decorator to add the options shared among the server commands: ``--host``, ``--port``, ``-4``, ``-6``
``--logging``, ``--iknowwhatimdoing`` and ``--debug``."""
daemon_options = bulk_options([
@@ -162,11 +167,11 @@ def enable_safemode(ctx, **kwargs):
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the settings manager.", err=True)
ctx.exit(-1)
else:
settings.setBoolean(["server", "startOnceInSafeMode"], True)
settings.save()
settings.setBoolean(["server", "startOnceInSafeMode"], True)
settings.save()
click.echo("Safe mode flag set, OctoPrint will start in safe mode on next restart.")
click.echo("Safe mode flag set, OctoPrint will start in safe mode on next restart.")
@server_commands.command(name="serve")
@@ -181,6 +186,8 @@ def serve_command(ctx, **kwargs):
host = get_value("host")
port = get_value("port")
v4 = get_value("v4")
v6 = get_value("v6")
logging = get_value("logging")
allow_root = get_value("allow_root")
debug = get_value("debug")
@@ -191,7 +198,10 @@ def serve_command(ctx, **kwargs):
safe_mode = "flag" if get_value("safe_mode") else None
ignore_blacklist = get_value("ignore_blacklist")
run_server(basedir, configfile, host, port, debug,
if v4 and not host:
host = "0.0.0.0"
run_server(basedir, configfile, host, port, v6, debug,
allow_root, logging, verbosity, safe_mode,
ignore_blacklist)
@@ -218,6 +228,8 @@ if sys.platform != "win32" and sys.platform != "darwin":
host = get_value("host")
port = get_value("port")
v4 = get_value("v4")
v6 = get_value("v6")
logging = get_value("logging")
allow_root = get_value("allow_root")
debug = get_value("debug")
@@ -229,6 +241,9 @@ if sys.platform != "win32" and sys.platform != "darwin":
safe_mode = "flag" if get_value("safe_mode") else None
ignore_blacklist = get_value("ignore_blacklist")
if v4 and not host:
host = "0.0.0.0"
if pid is None:
click.echo("No path to a pidfile set",
file=sys.stderr)
@@ -236,14 +251,15 @@ if sys.platform != "win32" and sys.platform != "darwin":
from octoprint.daemon import Daemon
class OctoPrintDaemon(Daemon):
def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity,
safe_mode, ignore_blacklist):
def __init__(self, pidfile, basedir, configfile, host, port, v6_only, debug, allow_root, logging_config,
verbosity, safe_mode, ignore_blacklist):
Daemon.__init__(self, pidfile)
self._basedir = basedir
self._configfile = configfile
self._host = host
self._port = port
self._v6_only = v6_only
self._debug = debug
self._allow_root = allow_root
self._logging_config = logging_config
@@ -252,12 +268,12 @@ if sys.platform != "win32" and sys.platform != "darwin":
self._ignore_blacklist = ignore_blacklist
def run(self):
run_server(self._basedir, self._configfile, self._host, self._port, self._debug,
run_server(self._basedir, self._configfile, self._host, self._port, self._v6_only, self._debug,
self._allow_root, self._logging_config, self._verbosity, self._safe_mode,
self._ignore_blacklist, octoprint_daemon=self)
octoprint_daemon = OctoPrintDaemon(pid, basedir, configfile, host, port, debug, allow_root, logging, verbosity,
safe_mode, ignore_blacklist)
octoprint_daemon = OctoPrintDaemon(pid, basedir, configfile, host, port, v6, debug, allow_root, logging,
verbosity, safe_mode, ignore_blacklist)
if command == "start":
octoprint_daemon.start()
+47 -11
View File
@@ -162,7 +162,7 @@ def unauthorized_user():
class Server(object):
def __init__(self, settings=None, plugin_manager=None, connectivity_checker=None, environment_detector=None,
event_manager=None, host=None, port=None, debug=False, safe_mode=False, allow_root=False,
event_manager=None, host=None, port=None, v6_only=False, debug=False, safe_mode=False, allow_root=False,
octoprint_daemon=None):
self._settings = settings
self._plugin_manager = plugin_manager
@@ -171,6 +171,7 @@ class Server(object):
self._event_manager = event_manager
self._host = host
self._port = port
self._v6_only = v6_only
self._debug = debug
self._safe_mode = safe_mode
self._allow_root = allow_root
@@ -223,6 +224,9 @@ class Server(object):
debug = self._debug
safe_mode = self._safe_mode
if self._v6_only and not octoprint.util.net.HAS_V6:
raise RuntimeError("IPv6 only mode configured but system doesn't support IPv6")
if self._host is None:
host = self._settings.get(["server", "host"])
if host is None:
@@ -681,9 +685,13 @@ class Server(object):
server_kwargs.update(dict(idle_connection_timeout=600))
self._server = util.tornado.CustomHTTPServer(self._tornado_app, **server_kwargs)
self._server.listen(self._port, address=self._host if self._host != "::" else None) # special case - tornado
# only listens on v4 & v6
# if we use None as address
listening_address = self._host
if self._host == "::" and not self._v6_only:
# special case - tornado only listens on v4 _and_ v6 if we use None as address
listening_address = None
self._server.listen(self._port, address=listening_address)
### From now on it's ok to launch subprocesses again
@@ -728,8 +736,16 @@ class Server(object):
# prepare our after startup function
def on_after_startup():
self._logger.info("Listening on http://{}:{}".format(self._host if not ":" in self._host else "[" + self._host + "]",
self._port))
if self._host == "::":
if self._v6_only:
# only v6
self._logger.info("Listening on http://[::]:{port}".format(port=self._port))
else:
# all v4 and v6
self._logger.info("Listening on http://0.0.0.0:{port} and http://[::]:{port}".format(port=self._port))
else:
self._logger.info("Listening on http://{}:{}".format(self._host if not ":" in self._host else "[" + self._host + "]",
self._port))
if safe_mode and self._settings.getBoolean(["server", "startOnceInSafeMode"]):
self._logger.info("Server started successfully in safe mode as requested from config, removing flag")
@@ -1590,6 +1606,7 @@ class Server(object):
host = self._host
port = self._port
v6_only = self._v6_only
class IntermediaryServerHandler(BaseHTTPRequestHandler):
def __init__(self, rules=None, *args, **kwargs):
@@ -1646,23 +1663,42 @@ class Server(object):
rules = map(process, filter(lambda rule: len(rule) == 2 or len(rule) == 3, rules))
HTTPServerV4 = HTTPServer
class HTTPServerV6(HTTPServer):
address_family = socket.AF_INET6
class HTTPServerV6SingleStack(HTTPServerV6):
def __init__(self, *args, **kwargs):
HTTPServer.__init__(self, *args, **kwargs)
HTTPServerV6.__init__(self, *args, **kwargs)
# make sure to enable dual stack mode, otherwise the socket might only listen on IPv6
# explicitly set V6ONLY flag - seems to be the default, but just to make sure...
self.socket.setsockopt(octoprint.util.net.IPPROTO_IPV6, octoprint.util.net.IPV6_V6ONLY, 1)
class HTTPServerV6DualStack(HTTPServerV6):
def __init__(self, *args, **kwargs):
HTTPServerV6.__init__(self, *args, **kwargs)
# explicitly unset V6ONLY flag
self.socket.setsockopt(octoprint.util.net.IPPROTO_IPV6, octoprint.util.net.IPV6_V6ONLY, 0)
if ":" in host:
# v6
ServerClass = HTTPServerV6
if host == "::" and not self._v6_only:
ServerClass = HTTPServerV6DualStack
else:
ServerClass = HTTPServerV6SingleStack
else:
# v4
ServerClass = HTTPServer
ServerClass = HTTPServerV4
self._logger.debug("Starting intermediary server on http://{}:{}".format(host if not ":" in host else "[" + host + "]", port))
if host == "::":
if self._v6_only:
self._logger.debug("Starting intermediary server on http://[::]:{port}".format(port=port))
else:
self._logger.debug("Starting intermediary server on http://0.0.0.0:{port} and http://[::]:{port}".format(port=port))
else:
self._logger.debug("Starting intermediary server on http://{}:{}".format(host if not ":" in host else "[" + host + "]", port))
self._intermediary_server = ServerClass((host, port),
lambda *args, **kwargs: IntermediaryServerHandler(rules, *args, **kwargs),