From 7e0b187cb8596a5d910b00f5108051f97d406a8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 6 Apr 2018 17:47:51 +0200 Subject: [PATCH 01/15] Bundle sockjs-tornado dependency It appears to be unmaintained at the moment, and the current version is incompatible to Tornado 5. Instead of monkey patching ad infinitum we instead bundle the dependency in the new vendor sub package. --- setup.py | 3 +- src/octoprint/server/__init__.py | 3 +- src/octoprint/server/util/sockjs.py | 118 +---- src/octoprint/vendor/__init__.py | 0 src/octoprint/vendor/sockjs/__init__.py | 5 + .../vendor/sockjs/tornado/__init__.py | 4 + .../vendor/sockjs/tornado/basehandler.py | 130 ++++++ src/octoprint/vendor/sockjs/tornado/conn.py | 70 +++ .../vendor/sockjs/tornado/migrate.py | 34 ++ .../vendor/sockjs/tornado/periodic.py | 76 ++++ src/octoprint/vendor/sockjs/tornado/proto.py | 50 +++ src/octoprint/vendor/sockjs/tornado/router.py | 208 +++++++++ .../vendor/sockjs/tornado/session.py | 419 ++++++++++++++++++ .../vendor/sockjs/tornado/sessioncontainer.py | 159 +++++++ src/octoprint/vendor/sockjs/tornado/static.py | 133 ++++++ src/octoprint/vendor/sockjs/tornado/stats.py | 123 +++++ .../sockjs/tornado/transports/__init__.py | 11 + .../vendor/sockjs/tornado/transports/base.py | 22 + .../sockjs/tornado/transports/eventsource.py | 52 +++ .../sockjs/tornado/transports/htmlfile.py | 86 ++++ .../vendor/sockjs/tornado/transports/jsonp.py | 127 ++++++ .../sockjs/tornado/transports/pollingbase.py | 72 +++ .../sockjs/tornado/transports/rawwebsocket.py | 93 ++++ .../tornado/transports/streamingbase.py | 47 ++ .../sockjs/tornado/transports/websocket.py | 105 +++++ .../vendor/sockjs/tornado/transports/xhr.py | 95 ++++ .../sockjs/tornado/transports/xhrstreaming.py | 51 +++ src/octoprint/vendor/sockjs/tornado/util.py | 50 +++ .../vendor/sockjs/tornado/websocket.py | 36 ++ 29 files changed, 2273 insertions(+), 109 deletions(-) create mode 100644 src/octoprint/vendor/__init__.py create mode 100644 src/octoprint/vendor/sockjs/__init__.py create mode 100644 src/octoprint/vendor/sockjs/tornado/__init__.py create mode 100644 src/octoprint/vendor/sockjs/tornado/basehandler.py create mode 100644 src/octoprint/vendor/sockjs/tornado/conn.py create mode 100644 src/octoprint/vendor/sockjs/tornado/migrate.py create mode 100644 src/octoprint/vendor/sockjs/tornado/periodic.py create mode 100644 src/octoprint/vendor/sockjs/tornado/proto.py create mode 100644 src/octoprint/vendor/sockjs/tornado/router.py create mode 100644 src/octoprint/vendor/sockjs/tornado/session.py create mode 100644 src/octoprint/vendor/sockjs/tornado/sessioncontainer.py create mode 100644 src/octoprint/vendor/sockjs/tornado/static.py create mode 100644 src/octoprint/vendor/sockjs/tornado/stats.py create mode 100644 src/octoprint/vendor/sockjs/tornado/transports/__init__.py create mode 100644 src/octoprint/vendor/sockjs/tornado/transports/base.py create mode 100644 src/octoprint/vendor/sockjs/tornado/transports/eventsource.py create mode 100644 src/octoprint/vendor/sockjs/tornado/transports/htmlfile.py create mode 100644 src/octoprint/vendor/sockjs/tornado/transports/jsonp.py create mode 100644 src/octoprint/vendor/sockjs/tornado/transports/pollingbase.py create mode 100644 src/octoprint/vendor/sockjs/tornado/transports/rawwebsocket.py create mode 100644 src/octoprint/vendor/sockjs/tornado/transports/streamingbase.py create mode 100644 src/octoprint/vendor/sockjs/tornado/transports/websocket.py create mode 100644 src/octoprint/vendor/sockjs/tornado/transports/xhr.py create mode 100644 src/octoprint/vendor/sockjs/tornado/transports/xhrstreaming.py create mode 100644 src/octoprint/vendor/sockjs/tornado/util.py create mode 100644 src/octoprint/vendor/sockjs/tornado/websocket.py diff --git a/setup.py b/setup.py index 6f2c9e699..e6ef62729 100644 --- a/setup.py +++ b/setup.py @@ -20,7 +20,8 @@ INSTALL_REQUIRES = [ # version, hence we need to pin to a lower version for now. See #1697 "werkzeug>=0.8.3,<0.9", "tornado>=5.0.1,<6", - "sockjs-tornado>=1.0.3,<1.1", + #"sockjs-tornado>=1.0.3,<1.1", # current version is incompatible to tornado 5, we use a + # vendored one "PyYAML>=3.10,<3.11", "Flask-Login>=0.2.2,<0.3", "Flask-Principal>=0.3.5,<0.4", diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 8b25d9a29..f727db996 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -6,7 +6,7 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import uuid -from sockjs.tornado import SockJSRouter +from octoprint.vendor.sockjs.tornado import SockJSRouter from flask import Flask, g, request, session, Blueprint, Request, Response, current_app from flask_login import LoginManager, current_user, session_protected, user_logged_out from flask_principal import Principal, Permission, RoleNeed, identity_loaded, identity_changed, UserNeed, AnonymousIdentity @@ -241,7 +241,6 @@ class Server(object): pluginManager = self._plugin_manager # monkey patch a bunch of stuff - util.sockjs.fix_tornado5_compatibility() util.tornado.fix_json_encode() util.flask.enable_additional_translations(additional_folders=[self._settings.getBaseFolder("translations")]) diff --git a/src/octoprint/server/util/sockjs.py b/src/octoprint/server/util/sockjs.py index d67a0fd35..7debafa0e 100644 --- a/src/octoprint/server/util/sockjs.py +++ b/src/octoprint/server/util/sockjs.py @@ -7,10 +7,10 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import logging import threading -import sockjs.tornado -import sockjs.tornado.session -import sockjs.tornado.proto -import sockjs.tornado.util +import octoprint.vendor.sockjs.tornado +import octoprint.vendor.sockjs.tornado.session +import octoprint.vendor.sockjs.tornado.proto +import octoprint.vendor.sockjs.tornado.util import time import octoprint.timelapse @@ -28,103 +28,9 @@ import wrapt import json -def fix_tornado5_compatibility(): - """ - Monkey patches sockjs tornado dependency to fix tornado 5.x compatibility - - See https://github.com/mrjoes/sockjs-tornado/issues/113 for reason. - - We need to first patch StatsCollector since that also gets used by SockJSRouter. - """ - - import sockjs.tornado.router - import sockjs.tornado.stats - from tornado import ioloop, version_info - - def fixed_stats_init(self, io_loop): - ### Copied from sockjs.tornado.stats.StatsCollector.__init__ - - # Sessions - self.sess_active = 0 - - # Avoid circular reference - self.sess_transports = dict() - - # Connections - self.conn_active = 0 - self.conn_ps = sockjs.tornado.stats.MovingAverage() - - # Packets - self.pack_sent_ps = sockjs.tornado.stats.MovingAverage() - self.pack_recv_ps = sockjs.tornado.stats.MovingAverage() - - self._callback = ioloop.PeriodicCallback(self._update, - 1000) - self._callback.start() - - sockjs.tornado.stats.StatsCollector.__init__ = fixed_stats_init - - def fixed_router_init(self, connection, prefix="", user_settings=dict(), io_loop=None, session_kls=None): - ### Copied from sockjs.tornado.router.SockJSRouter.__init__ - - # TODO: Version check - if version_info[0] < 2: - raise Exception('sockjs-tornado requires Tornado 2.0 or higher.') - - # Store connection class - self._connection = connection - - # Initialize io_loop - self.io_loop = io_loop or ioloop.IOLoop.instance() - - # Settings - self.settings = sockjs.tornado.router.DEFAULT_SETTINGS.copy() - if user_settings: - self.settings.update(user_settings) - - self.websockets_enabled = 'websocket' not in self.settings['disabled_transports'] - self.cookie_needed = self.settings['jsessionid'] - - # Sessions - self._session_kls = session_kls if session_kls else sockjs.tornado.router.session.Session - self._sessions = sockjs.tornado.router.sessioncontainer.SessionContainer() - - check_interval = self.settings['session_check_interval'] * 1000 - self._sessions_cleanup = ioloop.PeriodicCallback(self._sessions.expire, - check_interval) - self._sessions_cleanup.start() - - # Stats - self.stats = sockjs.tornado.stats.StatsCollector(self.io_loop) - - # Initialize URLs - base = prefix + r'/[^/.]+/(?P[^/.]+)' - - # Generate global handler URLs - self._transport_urls = [('%s/%s$' % (base, p[0]), p[1], dict(server=self)) - for p in sockjs.tornado.router.GLOBAL_HANDLERS] - - for k, v in sockjs.tornado.router.TRANSPORTS.items(): - if k in self.settings['disabled_transports']: - continue - - # Only version 1 is supported - self._transport_urls.append( - (r'%s/%s$' % (base, k), - v, - dict(server=self)) - ) - - # Generate static URLs - self._transport_urls.extend([('%s%s' % (prefix, k), v, dict(server=self)) - for k, v in sockjs.tornado.router.STATIC_HANDLERS.items()]) - - sockjs.tornado.router.SockJSRouter.__init__ = fixed_router_init - - -class ThreadSafeSession(sockjs.tornado.session.Session): +class ThreadSafeSession(octoprint.vendor.sockjs.tornado.session.Session): def __init__(self, conn, server, session_id, expiry=None): - sockjs.tornado.session.Session.__init__(self, conn, server, session_id, expiry=expiry) + octoprint.vendor.sockjs.tornado.session.Session.__init__(self, conn, server, session_id, expiry=expiry) def set_handler(self, handler, start_heartbeat=True): if getattr(handler, "__orig_send_pack", None) is None: @@ -138,10 +44,10 @@ class ThreadSafeSession(sockjs.tornado.session.Session): handler.send_pack = send_pack setattr(handler, "__orig_send_pack", orig_send_pack) - return sockjs.tornado.session.Session.set_handler(self, handler, start_heartbeat=start_heartbeat) + return octoprint.vendor.sockjs.tornado.session.Session.set_handler(self, handler, start_heartbeat=start_heartbeat) def remove_handler(self, handler): - result = sockjs.tornado.session.Session.remove_handler(self, handler) + result = octoprint.vendor.sockjs.tornado.session.Session.remove_handler(self, handler) if getattr(handler, "__orig_send_pack", None) is not None: handler.send_pack = getattr(handler, "__orig_send_pack") @@ -152,18 +58,18 @@ class ThreadSafeSession(sockjs.tornado.session.Session): class JsonEncodingSessionWrapper(wrapt.ObjectProxy): def send_message(self, msg, stats=True, binary=False): - self.send_jsonified(json.dumps(sockjs.tornado.util.bytes_to_str(msg), + self.send_jsonified(json.dumps(octoprint.vendor.sockjs.tornado.util.bytes_to_str(msg), separators=(',', ':'), default=JsonEncoding.encode), stats) -class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.PrinterCallback): +class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, octoprint.printer.PrinterCallback): def __init__(self, printer, fileManager, analysisQueue, userManager, eventManager, pluginManager, session): - if isinstance(session, sockjs.tornado.session.Session): + if isinstance(session, octoprint.vendor.sockjs.tornado.session.Session): session = JsonEncodingSessionWrapper(session) - sockjs.tornado.SockJSConnection.__init__(self, session) + octoprint.vendor.sockjs.tornado.SockJSConnection.__init__(self, session) self._logger = logging.getLogger(__name__) diff --git a/src/octoprint/vendor/__init__.py b/src/octoprint/vendor/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/src/octoprint/vendor/sockjs/__init__.py b/src/octoprint/vendor/sockjs/__init__.py new file mode 100644 index 000000000..956b5aec4 --- /dev/null +++ b/src/octoprint/vendor/sockjs/__init__.py @@ -0,0 +1,5 @@ +try: + __import__('pkg_resources').declare_namespace(__name__) +except ImportError: + from pkgutil import extend_path + __path__ = extend_path(__path__, __name__) diff --git a/src/octoprint/vendor/sockjs/tornado/__init__.py b/src/octoprint/vendor/sockjs/tornado/__init__.py new file mode 100644 index 000000000..d27dfa2f6 --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/__init__.py @@ -0,0 +1,4 @@ +# -*- coding: utf-8 -*- + +from .router import SockJSRouter +from .conn import SockJSConnection diff --git a/src/octoprint/vendor/sockjs/tornado/basehandler.py b/src/octoprint/vendor/sockjs/tornado/basehandler.py new file mode 100644 index 000000000..b388db68a --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/basehandler.py @@ -0,0 +1,130 @@ +# -*- coding: utf-8 -*- +""" + sockjs.tornado.basehandler + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Various base http handlers +""" + +import datetime +import socket +import logging + +from tornado.web import asynchronous, RequestHandler + +CACHE_TIME = 31536000 + +LOG = logging.getLogger("tornado.general") + +class BaseHandler(RequestHandler): + """Base request handler with set of helpers.""" + def initialize(self, server): + """Initialize request + + `server` + SockJSRouter instance. + """ + self.server = server + self.logged = False + + # Statistics + def prepare(self): + """Increment connection count""" + self.logged = True + self.server.stats.on_conn_opened() + + def _log_disconnect(self): + """Decrement connection count""" + if self.logged: + self.server.stats.on_conn_closed() + self.logged = False + + def finish(self, chunk=None): + """Tornado `finish` handler""" + self._log_disconnect() + + super(BaseHandler, self).finish(chunk) + + def on_connection_close(self): + """Tornado `on_connection_close` handler""" + self._log_disconnect() + + # Various helpers + def enable_cache(self): + """Enable client-side caching for the current request""" + self.set_header('Cache-Control', 'max-age=%d, public' % CACHE_TIME) + + d = datetime.datetime.now() + datetime.timedelta(seconds=CACHE_TIME) + self.set_header('Expires', d.strftime('%a, %d %b %Y %H:%M:%S')) + + self.set_header('access-control-max-age', CACHE_TIME) + + def disable_cache(self): + """Disable client-side cache for the current request""" + self.set_header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0') + + def handle_session_cookie(self): + """Handle JSESSIONID cookie logic""" + # If JSESSIONID support is disabled in the settings, ignore cookie logic + if not self.server.settings['jsessionid']: + return + + cookie = self.cookies.get('JSESSIONID') + + if not cookie: + cv = 'dummy' + else: + cv = cookie.value + + self.set_cookie('JSESSIONID', cv) + + def safe_finish(self): + """Finish session. If it will blow up - connection was set to Keep-Alive and + client dropped connection, ignore any IOError or socket error.""" + try: + self.finish() + except (socket.error, IOError): + # We don't want to raise IOError exception if finish() call fails. + # It can happen if connection is set to Keep-Alive, but client + # closes connection after receiving response. + LOG.debug('Ignoring IOError in safe_finish()') + pass + + +class PreflightHandler(BaseHandler): + """CORS preflight handler""" + + @asynchronous + def options(self, *args, **kwargs): + """XHR cross-domain OPTIONS handler""" + self.enable_cache() + self.handle_session_cookie() + self.preflight() + + if self.verify_origin(): + allowed_methods = getattr(self, 'access_methods', 'OPTIONS, POST') + self.set_header('Access-Control-Allow-Methods', allowed_methods) + self.set_header('Allow', allowed_methods) + + self.set_status(204) + else: + # Set forbidden + self.set_status(403) + + self.finish() + + def preflight(self): + """Handles request authentication""" + origin = self.request.headers.get('Origin', '*') + self.set_header('Access-Control-Allow-Origin', origin) + + headers = self.request.headers.get('Access-Control-Request-Headers') + if headers: + self.set_header('Access-Control-Allow-Headers', headers) + + self.set_header('Access-Control-Allow-Credentials', 'true') + + def verify_origin(self): + """Verify if request can be served""" + # TODO: Verify origin + return True diff --git a/src/octoprint/vendor/sockjs/tornado/conn.py b/src/octoprint/vendor/sockjs/tornado/conn.py new file mode 100644 index 000000000..466cb56b0 --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/conn.py @@ -0,0 +1,70 @@ +# -*- coding: utf-8 -*- +""" + sockjs.tornado.conn + ~~~~~~~~~~~~~~~~~~~ + + SockJS connection interface +""" + + +class SockJSConnection(object): + def __init__(self, session): + """Connection constructor. + + `session` + Associated session + """ + self.session = session + + # Public API + def on_open(self, request): + """Default on_open() handler. + + Override when you need to do some initialization or request validation. + If you return False, connection will be rejected. + + You can also throw Tornado HTTPError to close connection. + + `request` + ``ConnectionInfo`` object which contains caller IP address, query string + parameters and cookies associated with this request (if any). + """ + pass + + def on_message(self, message): + """Default on_message handler. Must be overridden in your application""" + raise NotImplementedError() + + def on_close(self): + """Default on_close handler.""" + pass + + def send(self, message, binary=False): + """Send message to the client. + + `message` + Message to send. + """ + if not self.is_closed: + self.session.send_message(message, binary=binary) + + def broadcast(self, clients, message): + """Broadcast message to the one or more clients. + Use this method if you want to send same message to lots of clients, as + it contains several optimizations and will work fast than just having loop + in your code. + + `clients` + Clients iterable + `message` + Message to send. + """ + self.session.broadcast(clients, message) + + def close(self): + self.session.close() + + @property + def is_closed(self): + """Check if connection was closed""" + return self.session.is_closed diff --git a/src/octoprint/vendor/sockjs/tornado/migrate.py b/src/octoprint/vendor/sockjs/tornado/migrate.py new file mode 100644 index 000000000..8dc3c8137 --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/migrate.py @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- +""" + sockjs.tornado.migrate + ~~~~~~~~~~~~~~~~~~~~~~ + + `tornado.websocket` to `sockjs.tornado` migration helper. +""" + +from octoprint.vendor.sockjs.tornado import conn + + +class WebsocketHandler(conn.SockJSConnection): + """If you already use Tornado websockets for your application and + want try sockjs-tornado, change your handlers to derive from this + WebsocketHandler class. There are some limitations, for example + only self.request only contains remote_ip, cookies and arguments + collection""" + def open(self): + """open handler""" + pass + + def on_open(self, info): + """sockjs-tornado on_open handler""" + # Store some properties + self.ip = info.ip + + # Create fake request object + self.request = info + + # Call open + self.open() + + def write_message(self, msg): + self.send(msg) diff --git a/src/octoprint/vendor/sockjs/tornado/periodic.py b/src/octoprint/vendor/sockjs/tornado/periodic.py new file mode 100644 index 000000000..bae9a92b4 --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/periodic.py @@ -0,0 +1,76 @@ +# -*- coding: utf-8 -*- +""" + sockjs.tornado.periodic + ~~~~~~~~~~~~~~~~~~~~~~~ + + This module implements customized PeriodicCallback from tornado with + support of the sliding window. +""" + +import time +import logging + +LOG = logging.getLogger("tornado.general") + +class Callback(object): + """Custom implementation of the Tornado.Callback with support + of callback timeout delays. + """ + def __init__(self, callback, callback_time, io_loop): + """Constructor. + + `callback` + Callback function + `callback_time` + Callback timeout value (in milliseconds) + `io_loop` + io_loop instance + """ + self.callback = callback + self.callback_time = callback_time + self.io_loop = io_loop + self._running = False + + self.next_run = None + + def calculate_next_run(self): + """Caltulate next scheduled run""" + return time.time() + self.callback_time / 1000.0 + + def start(self, timeout=None): + """Start callbacks""" + self._running = True + + if timeout is None: + timeout = self.calculate_next_run() + + self.io_loop.add_timeout(timeout, self._run) + + def stop(self): + """Stop callbacks""" + self._running = False + + def delay(self): + """Delay callback""" + self.next_run = self.calculate_next_run() + + def _run(self): + if not self._running: + return + + # Support for shifting callback window + if self.next_run is not None and time.time() < self.next_run: + self.start(self.next_run) + self.next_run = None + return + + next_call = None + try: + next_call = self.callback() + except (KeyboardInterrupt, SystemExit): + raise + except: + LOG.error("Error in periodic callback", exc_info=True) + + if self._running: + self.start(next_call) diff --git a/src/octoprint/vendor/sockjs/tornado/proto.py b/src/octoprint/vendor/sockjs/tornado/proto.py new file mode 100644 index 000000000..f56088403 --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/proto.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +""" + sockjs.tornado.proto + ~~~~~~~~~~~~~~~~~~~~ + + SockJS protocol related functions +""" +import logging + +LOG = logging.getLogger("tornado.general") + +# TODO: Add support for ujson module once they can accept unicode strings + +# Try to find best json encoder available +try: + # Check for simplejson + import simplejson + + json_encode = lambda data: simplejson.dumps(data, separators=(',', ':')) + json_decode = lambda data: simplejson.loads(data) + JSONDecodeError = ValueError + + LOG.debug('sockjs.tornado will use simplejson module') +except ImportError: + # Use slow json + import json + + LOG.debug('sockjs.tornado will use json module') + + json_encode = lambda data: json.dumps(data, separators=(',', ':')) + json_decode = lambda data: json.loads(data) + JSONDecodeError = ValueError + +# Protocol handlers +CONNECT = 'o' +DISCONNECT = 'c' +MESSAGE = 'm' +HEARTBEAT = 'h' + + +# Various protocol helpers +def disconnect(code, reason): + """Return SockJS packet with code and close reason + + `code` + Closing code + `reason` + Closing reason + """ + return 'c[%d,"%s"]' % (code, reason) diff --git a/src/octoprint/vendor/sockjs/tornado/router.py b/src/octoprint/vendor/sockjs/tornado/router.py new file mode 100644 index 000000000..e20619e89 --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/router.py @@ -0,0 +1,208 @@ +# -*- coding: utf-8 -*- +""" + sockjs.tornado.router + ~~~~~~~~~~~~~~~~~~~~~ + + SockJS protocol router implementation. +""" + +from tornado import ioloop, version_info + +from octoprint.vendor.sockjs.tornado import transports, session, sessioncontainer, static, stats, proto + + +DEFAULT_SETTINGS = { + # Sessions check interval in seconds + 'session_check_interval': 1, + # Session expiration in seconds + 'disconnect_delay': 5, + # Heartbeat time in seconds. Do not change this value unless + # you absolutely sure that new value will work. + 'heartbeat_delay': 25, + # Enabled protocols + 'disabled_transports': [], + # SockJS location + 'sockjs_url': 'https://cdn.jsdelivr.net/sockjs/0.3/sockjs.min.js', + # Max response body size + 'response_limit': 128 * 1024, + # Enable or disable JSESSIONID cookie handling + 'jsessionid': True, + # Should sockjs-tornado flush messages immediately or queue then and + # flush on next ioloop tick + 'immediate_flush': True, + # Enable or disable Nagle for persistent transports + 'disable_nagle': True, + # Enable IP checks for polling transports. If enabled, all subsequent + # polling calls should be from the same IP address. + 'verify_ip': True, + # list of allowed origins for websocket connections + # or "*" - accept all websocket connections + 'websocket_allow_origin': "*" + } + +GLOBAL_HANDLERS = [ + ('xhr_send', transports.XhrSendHandler), + ('jsonp_send', transports.JSONPSendHandler) +] + +TRANSPORTS = { + 'websocket': transports.WebSocketTransport, + 'xhr': transports.XhrPollingTransport, + 'xhr_streaming': transports.XhrStreamingTransport, + 'jsonp': transports.JSONPTransport, + 'eventsource': transports.EventSourceTransport, + 'htmlfile': transports.HtmlFileTransport +} + +STATIC_HANDLERS = { + '/chunking_test': static.ChunkingTestHandler, + '/info': static.InfoHandler, + '/iframe[0-9-.a-z_]*.html': static.IFrameHandler, + '/websocket': transports.RawWebSocketTransport, + '/?': static.GreetingsHandler +} + + +class SockJSRouter(object): + """SockJS protocol router""" + def __init__(self, + connection, + prefix='', + user_settings=dict(), + io_loop=None, + session_kls=None): + """Constructor. + + `connection` + SockJSConnection class + `prefix` + Connection prefix + `user_settings` + Settings dictionary + `io_loop` + Optional IOLoop instance + """ + + # TODO: Version check + if version_info[0] < 2: + raise Exception('sockjs-tornado requires Tornado 2.0 or higher.') + + # Store connection class + self._connection = connection + + # Initialize io_loop + self.io_loop = io_loop or ioloop.IOLoop.instance() + + # Settings + self.settings = DEFAULT_SETTINGS.copy() + if user_settings: + self.settings.update(user_settings) + + self.websockets_enabled = 'websocket' not in self.settings['disabled_transports'] + self.cookie_needed = self.settings['jsessionid'] + + # Sessions + self._session_kls = session_kls if session_kls else session.Session + self._sessions = sessioncontainer.SessionContainer() + + check_interval = self.settings['session_check_interval'] * 1000 + self._sessions_cleanup = ioloop.PeriodicCallback(self._sessions.expire, + check_interval) + self._sessions_cleanup.start() + + # Stats + self.stats = stats.StatsCollector(self.io_loop) + + # Initialize URLs + base = prefix + r'/[^/.]+/(?P[^/.]+)' + + # Generate global handler URLs + self._transport_urls = [('%s/%s$' % (base, p[0]), p[1], dict(server=self)) + for p in GLOBAL_HANDLERS] + + for k, v in TRANSPORTS.items(): + if k in self.settings['disabled_transports']: + continue + + # Only version 1 is supported + self._transport_urls.append( + (r'%s/%s$' % (base, k), + v, + dict(server=self)) + ) + + # Generate static URLs + self._transport_urls.extend([('%s%s' % (prefix, k), v, dict(server=self)) + for k, v in STATIC_HANDLERS.items()]) + + @property + def urls(self): + """List of the URLs to be added to the Tornado application""" + return self._transport_urls + + def apply_routes(self, routes): + """Feed list of the URLs to the routes list. Returns list""" + routes.extend(self._transport_urls) + return routes + + def create_session(self, session_id, register=True): + """Creates new session object and returns it. + + `request` + Request that created the session. Will be used to get query string + parameters and cookies + `register` + Should be session registered in a storage. Websockets don't + need it. + """ + # TODO: Possible optimization here for settings.get + s = self._session_kls(self._connection, + self, + session_id, + self.settings.get('disconnect_delay') + ) + + if register: + self._sessions.add(s) + + return s + + def get_session(self, session_id): + """Get session by session id + + `session_id` + Session id + """ + return self._sessions.get(session_id) + + def get_connection_class(self): + """Return associated connection class""" + return self._connection + + # Broadcast helper + def broadcast(self, clients, msg): + """Optimized `broadcast` implementation. Depending on type of the session, will json-encode + message once and will call either `send_message` or `send_jsonifed`. + + `clients` + Clients iterable + `msg` + Message to send + """ + json_msg = None + + count = 0 + + for c in clients: + sess = c.session + if not sess.is_closed: + if sess.send_expects_json: + if json_msg is None: + json_msg = proto.json_encode(msg) + sess.send_jsonified(json_msg, False) + else: + sess.send_message(msg, stats=False) + + count += 1 + + self.stats.on_pack_sent(count) diff --git a/src/octoprint/vendor/sockjs/tornado/session.py b/src/octoprint/vendor/sockjs/tornado/session.py new file mode 100644 index 000000000..9568a82ee --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/session.py @@ -0,0 +1,419 @@ +# -*- coding: utf-8 -*- +""" + sockjs.tornado.session + ~~~~~~~~~~~~~~~~~~~~~~ + + SockJS session implementation. +""" + +import logging + +from octoprint.vendor.sockjs.tornado import sessioncontainer, periodic, proto +from octoprint.vendor.sockjs.tornado.util import bytes_to_str + +LOG = logging.getLogger("tornado.general") + + +class ConnectionInfo(object): + """Connection information object. + + Will be passed to the ``on_open`` handler of your connection class. + + Has few properties: + + `ip` + Caller IP address + `cookies` + Collection of cookies + `arguments` + Collection of the query string arguments + `headers` + Collection of headers sent by the browser that established this + connection + `path` + Request uri path + """ + def __init__(self, ip, cookies, arguments, headers, path): + self.ip = ip + self.cookies = cookies + self.arguments = arguments + self.headers = headers + self.path = path + + def get_argument(self, name): + """Return single argument by name""" + val = self.arguments.get(name) + if val: + return val[0] + return None + + def get_cookie(self, name): + """Return single cookie by its name""" + return self.cookies.get(name) + + def get_header(self, name): + """Return single header by its name""" + return self.headers.get(name) + + +# Session states +CONNECTING = 0 +OPEN = 1 +CLOSING = 2 +CLOSED = 3 + + +class BaseSession(object): + """Base session implementation class""" + def __init__(self, conn, server): + """Base constructor. + + `conn` + Connection class + `server` + SockJSRouter instance + """ + self.server = server + self.stats = server.stats + + self.send_expects_json = False + + self.handler = None + self.state = CONNECTING + + self.conn_info = None + + self.conn = conn(self) + + self.close_reason = None + + def set_handler(self, handler): + """Set transport handler + ``handler`` + Handler, should derive from the `sockjs.tornado.transports.base.BaseTransportMixin`. + """ + if self.handler is not None: + raise Exception('Attempted to overwrite BaseSession handler') + + self.handler = handler + self.transport_name = self.handler.name + + if self.conn_info is None: + self.conn_info = handler.get_conn_info() + self.stats.on_sess_opened(self.transport_name) + + return True + + def verify_state(self): + """Verify if session was not yet opened. If it is, open it and call connections `on_open`""" + if self.state == CONNECTING: + self.state = OPEN + + self.conn.on_open(self.conn_info) + + def remove_handler(self, handler): + """Remove active handler from the session + + `handler` + Handler to remove + """ + # Attempt to remove another handler + if self.handler != handler: + raise Exception('Attempted to remove invalid handler') + + self.handler = None + + def close(self, code=3000, message='Go away!'): + """Close session or endpoint connection. + + `code` + Closing code + `message` + Close message + """ + if self.state != CLOSED: + try: + self.conn.on_close() + except: + LOG.debug("Failed to call on_close().", exc_info=True) + finally: + self.state = CLOSED + self.close_reason = (code, message) + self.conn = None + + # Bump stats + self.stats.on_sess_closed(self.transport_name) + + # If we have active handler, notify that session was closed + if self.handler is not None: + self.handler.session_closed() + + def delayed_close(self): + """Delayed close - won't close immediately, but on next ioloop tick.""" + self.state = CLOSING + self.server.io_loop.add_callback(self.close) + + def get_close_reason(self): + """Return last close reason tuple. + + For example: + + if self.session.is_closed: + code, reason = self.session.get_close_reason() + + """ + if self.close_reason: + return self.close_reason + + return (3000, 'Go away!') + + @property + def is_closed(self): + """Check if session was closed.""" + return self.state == CLOSED or self.state == CLOSING + + def send_message(self, msg, stats=True, binary=False): + """Send or queue outgoing message + + `msg` + Message to send + `stats` + If set to True, will update statistics after operation completes + """ + raise NotImplemented() + + def send_jsonified(self, msg, stats=True): + """Send or queue outgoing message which was json-encoded before. Used by the `broadcast` + method. + + `msg` + JSON-encoded message to send + `stats` + If set to True, will update statistics after operation completes + """ + raise NotImplemented() + + def broadcast(self, clients, msg): + """Optimized `broadcast` implementation. Depending on type of the session, will json-encode + message once and will call either `send_message` or `send_jsonifed`. + + `clients` + Clients iterable + `msg` + Message to send + """ + self.server.broadcast(clients, msg) + + +class Session(BaseSession, sessioncontainer.SessionMixin): + """SockJS session implementation. + """ + + def __init__(self, conn, server, session_id, expiry=None): + """Session constructor. + + `conn` + Default connection class + `server` + `SockJSRouter` instance + `session_id` + Session id + `expiry` + Session expiry time + """ + # Initialize session + sessioncontainer.SessionMixin.__init__(self, session_id, expiry) + BaseSession.__init__(self, conn, server) + + self.send_queue = '' + self.send_expects_json = True + + # Heartbeat related stuff + self._heartbeat_timer = None + self._heartbeat_interval = self.server.settings['heartbeat_delay'] * 1000 + + self._immediate_flush = self.server.settings['immediate_flush'] + self._pending_flush = False + + self._verify_ip = self.server.settings['verify_ip'] + + # Session callbacks + def on_delete(self, forced): + """Session expiration callback + + `forced` + If session item explicitly deleted, forced will be set to True. If + item expired, will be set to False. + """ + # Do not remove connection if it was not forced and there's running connection + if not forced and self.handler is not None and not self.is_closed: + self.promote() + else: + self.close() + + # Add session + def set_handler(self, handler, start_heartbeat=True): + """Set active handler for the session + + `handler` + Associate active Tornado handler with the session + `start_heartbeat` + Should session start heartbeat immediately + """ + # Check if session already has associated handler + if self.handler is not None: + handler.send_pack(proto.disconnect(2010, "Another connection still open")) + return False + + if self._verify_ip and self.conn_info is not None: + # If IP address doesn't match - refuse connection + if handler.request.remote_ip != self.conn_info.ip: + LOG.error('Attempted to attach to session %s (%s) from different IP (%s)' % ( + self.session_id, + self.conn_info.ip, + handler.request.remote_ip + )) + + handler.send_pack(proto.disconnect(2010, "Attempted to connect to session from different IP")) + return False + + if (self.state == CLOSING or self.state == CLOSED) and not self.send_queue: + handler.send_pack(proto.disconnect(*self.get_close_reason())) + return False + + # Associate handler and promote session + super(Session, self).set_handler(handler) + + self.promote() + + if start_heartbeat: + self.start_heartbeat() + + return True + + def verify_state(self): + """Verify if session was not yet opened. If it is, open it and call connections `on_open`""" + # If we're in CONNECTING state - send 'o' message to the client + if self.state == CONNECTING: + self.handler.send_pack(proto.CONNECT) + + # Call parent implementation + super(Session, self).verify_state() + + def remove_handler(self, handler): + """Detach active handler from the session + + `handler` + Handler to remove + """ + super(Session, self).remove_handler(handler) + + self.promote() + self.stop_heartbeat() + + def send_message(self, msg, stats=True, binary=False): + """Send or queue outgoing message + + `msg` + Message to send + `stats` + If set to True, will update statistics after operation completes + """ + self.send_jsonified(proto.json_encode(bytes_to_str(msg)), stats) + + def send_jsonified(self, msg, stats=True): + """Send JSON-encoded message + + `msg` + JSON encoded string to send + `stats` + If set to True, will update statistics after operation completes + """ + msg = bytes_to_str(msg) + + if self._immediate_flush: + if self.handler and self.handler.active and not self.send_queue: + # Send message right away + self.handler.send_pack('a[%s]' % msg) + else: + if self.send_queue: + self.send_queue += ',' + self.send_queue += msg + + self.flush() + else: + if self.send_queue: + self.send_queue += ',' + self.send_queue += msg + + if not self._pending_flush: + self.server.io_loop.add_callback(self.flush) + self._pending_flush = True + + if stats: + self.stats.on_pack_sent(1) + + def flush(self): + """Flush message queue if there's an active connection running""" + self._pending_flush = False + + if self.handler is None or not self.handler.active or not self.send_queue: + return + + self.handler.send_pack('a[%s]' % self.send_queue) + self.send_queue = '' + + def close(self, code=3000, message='Go away!'): + """Close session. + + `code` + Closing code + `message` + Closing message + """ + if self.state != CLOSED: + # Notify handler + if self.handler is not None: + self.handler.send_pack(proto.disconnect(code, message)) + + super(Session, self).close(code, message) + + # Heartbeats + def start_heartbeat(self): + """Reset hearbeat timer""" + self.stop_heartbeat() + + self._heartbeat_timer = periodic.Callback(self._heartbeat, + self._heartbeat_interval, + self.server.io_loop) + self._heartbeat_timer.start() + + def stop_heartbeat(self): + """Stop active heartbeat""" + if self._heartbeat_timer is not None: + self._heartbeat_timer.stop() + self._heartbeat_timer = None + + def delay_heartbeat(self): + """Delay active heartbeat""" + if self._heartbeat_timer is not None: + self._heartbeat_timer.delay() + + def _heartbeat(self): + """Heartbeat callback""" + if self.handler is not None: + self.handler.send_pack(proto.HEARTBEAT) + else: + self.stop_heartbeat() + + def on_messages(self, msg_list): + """Handle incoming messages + + `msg_list` + Message list to process + """ + self.stats.on_pack_recv(len(msg_list)) + + for msg in msg_list: + if self.state == OPEN: + self.conn.on_message(msg) diff --git a/src/octoprint/vendor/sockjs/tornado/sessioncontainer.py b/src/octoprint/vendor/sockjs/tornado/sessioncontainer.py new file mode 100644 index 000000000..831c1bd4b --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/sessioncontainer.py @@ -0,0 +1,159 @@ +# -*- coding: utf-8 -*- +""" + sockjs.tornado.sessioncontainer + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Simple heapq-based session implementation with sliding expiration window + support. +""" + +from heapq import heappush, heappop +from time import time +from hashlib import md5 +from random import random + + +def _random_key(): + """Return random session key""" + i = md5() + i.update('%s%s' % (random(), time())) + return i.hexdigest() + + +class SessionMixin(object): + """Represents one session object stored in the session container. + Derive from this object to store additional data. + """ + + def __init__(self, session_id=None, expiry=None): + """Constructor. + + ``session_id`` + Optional session id. If not provided, will generate + new session id. + ``expiry`` + Expiration time. If not provided, will never expire. + """ + self.session_id = session_id or _random_key() + self.promoted = None + self.expiry = expiry + + if self.expiry is not None: + self.expiry_date = time() + self.expiry + + def is_alive(self): + """Check if session is still alive""" + return self.expiry_date > time() + + def promote(self): + """Mark object as alive, so it won't be collected during next + run of the garbage collector. + """ + if self.expiry is not None: + self.promoted = time() + self.expiry + + def on_delete(self, forced): + """Triggered when object was expired or deleted.""" + pass + + def __lt__(self, other): + return self.expiry_date < other.expiry_date + + __cmp__ = __lt__ + + def __repr__(self): + return '%f %s %d' % (getattr(self, 'expiry_date', -1), + self.session_id, + self.promoted or 0) + + +class SessionContainer(object): + """Session container object. + + If we will implement sessions with Tornado timeouts, for polling transports + it will be nightmare - if load will be high, number of discarded timeouts + will be huge and will be huge performance hit, as Tornado will have to + clean them up all the time. + """ + def __init__(self): + self._items = dict() + self._queue = [] + + def add(self, session): + """Add session to the container. + + `session` + Session object + """ + self._items[session.session_id] = session + + if session.expiry is not None: + heappush(self._queue, session) + + def get(self, session_id): + """Return session object or None if it is not available + + `session_id` + Session identifier + """ + return self._items.get(session_id, None) + + def remove(self, session_id): + """Remove session object from the container + + `session_id` + Session identifier + """ + session = self._items.get(session_id, None) + + if session is not None: + session.promoted = -1 + session.on_delete(True) + del self._items[session_id] + return True + + return False + + def expire(self, current_time=None): + """Expire any old entries + + `current_time` + Optional time to be used to clean up queue (can be used in unit tests) + """ + if not self._queue: + return + + if current_time is None: + current_time = time() + + while self._queue: + # Get top most item + top = self._queue[0] + + # Early exit if item was not promoted and its expiration time + # is greater than now. + if top.promoted is None and top.expiry_date > current_time: + break + + # Pop item from the stack + top = heappop(self._queue) + + need_reschedule = (top.promoted is not None + and top.promoted > current_time) + + # Give chance to reschedule + if not need_reschedule: + top.promoted = None + top.on_delete(False) + + need_reschedule = (top.promoted is not None + and top.promoted > current_time) + + # If item is promoted and expiration time somewhere in future + # just reschedule it + if need_reschedule: + top.expiry_date = top.promoted + top.promoted = None + heappush(self._queue, top) + else: + del self._items[top.session_id] diff --git a/src/octoprint/vendor/sockjs/tornado/static.py b/src/octoprint/vendor/sockjs/tornado/static.py new file mode 100644 index 000000000..77656040a --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/static.py @@ -0,0 +1,133 @@ +# -*- coding: utf-8 -*- +""" + sockjs.tornado.static + ~~~~~~~~~~~~~~~~~~~~~ + + Various static handlers required for SockJS to function properly. +""" + +import time +import hashlib +import random +import sys + +from tornado.web import asynchronous + +from octoprint.vendor.sockjs.tornado.basehandler import BaseHandler, PreflightHandler +from octoprint.vendor.sockjs.tornado.proto import json_encode +from octoprint.vendor.sockjs.tornado.util import MAXSIZE, str_to_bytes + +IFRAME_TEXT = ''' + + + + + + + + +

Don't panic!

+

This is a SockJS hidden iframe. It's used for cross domain magic.

+ +'''.strip() + + +class IFrameHandler(BaseHandler): + """SockJS IFrame page handler""" + def get(self): + data = str_to_bytes(IFRAME_TEXT % self.server.settings['sockjs_url']) + + hsh = hashlib.md5(data).hexdigest() + + value = self.request.headers.get('If-None-Match') + if value: + if value.find(hsh) != -1: + # TODO: Fix me? Right now it is a hack to remove content-type + # header + self.clear() + del self._headers['Content-Type'] + + self.set_status(304) + return + + self.enable_cache() + + self.set_header('Etag', hsh) + self.write(data) + + +class GreetingsHandler(BaseHandler): + """SockJS greetings page handler""" + + def initialize(self, server): + self.server = server + + def get(self): + self.enable_cache() + + self.set_header('Content-Type', 'text/plain; charset=UTF-8') + self.write('Welcome to SockJS!\n') + + +class ChunkingTestHandler(PreflightHandler): + """SockJS chunking test handler""" + + # Step timeouts according to sockjs documentation + steps = [0.005, 0.025, 0.125, 0.625, 3.125] + + def initialize(self, server): + self.server = server + self.step = 0 + self.io_loop = server.io_loop + + @asynchronous + def post(self): + self.preflight() + self.set_header('Content-Type', 'application/javascript; charset=UTF-8') + + # Send one 'h' immediately + self.write('h\n') + self.flush() + + # Send 2048 spaces followed by 'h' + self.write(' ' * 2048 + 'h\n') + self.flush() + + # Send 'h' with different timeouts + def run_step(): + try: + self.write('h\n') + self.flush() + + self.step += 1 + if self.step < len(self.steps): + self.io_loop.add_timeout(time.time() + self.steps[self.step], + run_step) + else: + self.finish() + except IOError: + pass + + self.io_loop.add_timeout(time.time() + self.steps[0], run_step) + + +class InfoHandler(PreflightHandler): + """SockJS 0.2+ /info handler""" + def initialize(self, server): + self.server = server + self.access_methods = 'OPTIONS, GET' + + def get(self): + self.preflight() + self.disable_cache() + self.set_header('Content-Type', 'application/json; charset=UTF-8') + + options = dict(websocket=self.server.websockets_enabled, + cookie_needed=self.server.cookie_needed, + origins=['*:*'], + entropy=random.randint(0, MAXSIZE)) + + self.write(json_encode(options)) diff --git a/src/octoprint/vendor/sockjs/tornado/stats.py b/src/octoprint/vendor/sockjs/tornado/stats.py new file mode 100644 index 000000000..33f1fd509 --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/stats.py @@ -0,0 +1,123 @@ +from collections import deque + +from tornado import ioloop + + +class MovingAverage(object): + """Moving average class implementation""" + def __init__(self, period=10): + """Constructor. + + `period` + Moving window size. Average will be calculated + from the data in the window. + """ + self.period = period + self.stream = deque() + self.sum = 0 + self.accumulator = 0 + self.last_average = 0 + + def add(self, n): + """Add value to the current accumulator + + `n` + Value to add + """ + self.accumulator += n + + def flush(self): + """Add accumulator to the moving average queue + and reset it. For example, called by the StatsCollector + once per second to calculate per-second average. + """ + n = self.accumulator + self.accumulator = 0 + + stream = self.stream + stream.append(n) + self.sum += n + + streamlen = len(stream) + + if streamlen > self.period: + self.sum -= stream.popleft() + streamlen -= 1 + + if streamlen == 0: + self.last_average = 0 + else: + self.last_average = self.sum / float(streamlen) + + +class StatsCollector(object): + def __init__(self, io_loop): + # Sessions + self.sess_active = 0 + + # Avoid circular reference + self.sess_transports = dict() + + # Connections + self.conn_active = 0 + self.conn_ps = MovingAverage() + + # Packets + self.pack_sent_ps = MovingAverage() + self.pack_recv_ps = MovingAverage() + + self._callback = ioloop.PeriodicCallback(self._update, + 1000) + self._callback.start() + + def _update(self): + self.conn_ps.flush() + + self.pack_sent_ps.flush() + self.pack_recv_ps.flush() + + def dump(self): + """Return dictionary with current statistical information""" + data = dict( + # Sessions + sessions_active=self.sess_active, + + # Connections + connections_active=self.conn_active, + connections_ps=self.conn_ps.last_average, + + # Packets + packets_sent_ps=self.pack_sent_ps.last_average, + packets_recv_ps=self.pack_recv_ps.last_average + ) + + for k, v in self.sess_transports.items(): + data['transp_' + k] = v + + return data + + # Various event callbacks + def on_sess_opened(self, transport): + self.sess_active += 1 + + if transport not in self.sess_transports: + self.sess_transports[transport] = 0 + + self.sess_transports[transport] += 1 + + def on_sess_closed(self, transport): + self.sess_active -= 1 + self.sess_transports[transport] -= 1 + + def on_conn_opened(self): + self.conn_active += 1 + self.conn_ps.add(1) + + def on_conn_closed(self): + self.conn_active -= 1 + + def on_pack_sent(self, num): + self.pack_sent_ps.add(num) + + def on_pack_recv(self, num): + self.pack_recv_ps.add(num) diff --git a/src/octoprint/vendor/sockjs/tornado/transports/__init__.py b/src/octoprint/vendor/sockjs/tornado/transports/__init__.py new file mode 100644 index 000000000..f6824a7c7 --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/transports/__init__.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- + +import octoprint.vendor.sockjs.tornado.transports.pollingbase + +from .xhr import XhrPollingTransport, XhrSendHandler +from .jsonp import JSONPTransport, JSONPSendHandler +from .websocket import WebSocketTransport +from .xhrstreaming import XhrStreamingTransport +from .eventsource import EventSourceTransport +from .htmlfile import HtmlFileTransport +from .rawwebsocket import RawWebSocketTransport diff --git a/src/octoprint/vendor/sockjs/tornado/transports/base.py b/src/octoprint/vendor/sockjs/tornado/transports/base.py new file mode 100644 index 000000000..6ab8a360f --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/transports/base.py @@ -0,0 +1,22 @@ +from octoprint.vendor.sockjs.tornado import session + + +class BaseTransportMixin(object): + """Base transport. + + Implements few methods that session expects to see in each transport. + """ + + name = 'override_me_please' + + def get_conn_info(self): + """Return `ConnectionInfo` object from current transport""" + return session.ConnectionInfo(self.request.remote_ip, + self.request.cookies, + self.request.arguments, + self.request.headers, + self.request.path) + + def session_closed(self): + """Called by the session, when it gets closed""" + pass diff --git a/src/octoprint/vendor/sockjs/tornado/transports/eventsource.py b/src/octoprint/vendor/sockjs/tornado/transports/eventsource.py new file mode 100644 index 000000000..ed6ecbee4 --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/transports/eventsource.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +""" + sockjs.tornado.transports.eventsource + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + EventSource transport implementation. +""" + +from tornado.web import asynchronous + +from octoprint.vendor.sockjs.tornado.transports import streamingbase + + +class EventSourceTransport(streamingbase.StreamingTransportBase): + name = 'eventsource' + + @asynchronous + def get(self, session_id): + # Start response + self.preflight() + self.handle_session_cookie() + self.disable_cache() + + self.set_header('Content-Type', 'text/event-stream; charset=UTF-8') + self.write('\r\n') + self.flush() + + if not self._attach_session(session_id): + self.finish() + return + + if self.session: + self.session.flush() + + def send_pack(self, message, binary=False): + if binary: + raise Exception('binary not supported for EventSourceTransport') + + msg = 'data: %s\r\n\r\n' % message + + self.active = False + + try: + self.notify_sent(len(msg)) + + self.write(msg) + self.flush(callback=self.send_complete) + except IOError: + # If connection dropped, make sure we close offending session instead + # of propagating error all way up. + self.session.delayed_close() + self._detach() diff --git a/src/octoprint/vendor/sockjs/tornado/transports/htmlfile.py b/src/octoprint/vendor/sockjs/tornado/transports/htmlfile.py new file mode 100644 index 000000000..fbea68fff --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/transports/htmlfile.py @@ -0,0 +1,86 @@ +# -*- coding: utf-8 -*- +""" + sockjs.tornado.transports.htmlfile + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + HtmlFile transport implementation. +""" + +from tornado.web import asynchronous + +from octoprint.vendor.sockjs.tornado import proto +from octoprint.vendor.sockjs.tornado.transports import streamingbase + +# HTMLFILE template +HTMLFILE_HEAD = r''' + + + + +

Don't panic!

+ +'''.strip() +HTMLFILE_HEAD += ' ' * (1024 - len(HTMLFILE_HEAD) + 14) +HTMLFILE_HEAD += '\r\n\r\n' + + +class HtmlFileTransport(streamingbase.StreamingTransportBase): + name = 'htmlfile' + + def initialize(self, server): + super(HtmlFileTransport, self).initialize(server) + + @asynchronous + def get(self, session_id): + # Start response + self.preflight() + self.handle_session_cookie() + self.disable_cache() + self.set_header('Content-Type', 'text/html; charset=UTF-8') + + # Grab callback parameter + callback = self.get_argument('c', None) + if not callback: + self.write('"callback" parameter required') + self.set_status(500) + self.finish() + return + + # TODO: Fix me - use parameter + self.write(HTMLFILE_HEAD % callback) + self.flush() + + # Now try to attach to session + if not self._attach_session(session_id): + self.finish() + return + + # Flush any pending messages + if self.session: + self.session.flush() + + def send_pack(self, message, binary=False): + if binary: + raise Exception('binary not supported for HtmlFileTransport') + + # TODO: Just do escaping + msg = '\r\n' % proto.json_encode(message) + + self.active = False + + try: + self.notify_sent(len(message)) + + self.write(msg) + self.flush(callback=self.send_complete) + except IOError: + # If connection dropped, make sure we close offending session instead + # of propagating error all way up. + self.session.delayed_close() + self._detach() diff --git a/src/octoprint/vendor/sockjs/tornado/transports/jsonp.py b/src/octoprint/vendor/sockjs/tornado/transports/jsonp.py new file mode 100644 index 000000000..d63ef2322 --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/transports/jsonp.py @@ -0,0 +1,127 @@ +# -*- coding: utf-8 -*- +""" + sockjs.tornado.transports.jsonp + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + JSONP transport implementation. +""" +import logging + +from tornado.web import asynchronous + +from octoprint.vendor.sockjs.tornado import proto +from octoprint.vendor.sockjs.tornado.transports import pollingbase +from octoprint.vendor.sockjs.tornado.util import bytes_to_str, unquote_plus + +LOG = logging.getLogger("tornado.general") + +class JSONPTransport(pollingbase.PollingTransportBase): + name = 'jsonp' + + @asynchronous + def get(self, session_id): + # Start response + self.handle_session_cookie() + self.disable_cache() + + # Grab callback parameter + self.callback = self.get_argument('c', None) + if not self.callback: + self.write('"callback" parameter required') + self.set_status(500) + self.finish() + return + + # Get or create session without starting heartbeat + if not self._attach_session(session_id, False): + return + + # Might get already detached because connection was closed in on_open + if not self.session: + return + + if not self.session.send_queue: + self.session.start_heartbeat() + else: + self.session.flush() + + def send_pack(self, message, binary=False): + if binary: + raise Exception('binary not supported for JSONPTransport') + + self.active = False + + try: + # TODO: Just escape + msg = '%s(%s);\r\n' % (self.callback, proto.json_encode(message)) + + self.set_header('Content-Type', 'application/javascript; charset=UTF-8') + self.set_header('Content-Length', len(msg)) + + # TODO: Fix me + self.set_header('Etag', 'dummy') + + self.write(msg) + self.flush(callback=self.send_complete) + except IOError: + # If connection dropped, make sure we close offending session instead + # of propagating error all way up. + self.session.delayed_close() + + +class JSONPSendHandler(pollingbase.PollingTransportBase): + def post(self, session_id): + self.preflight() + self.handle_session_cookie() + self.disable_cache() + + session = self._get_session(session_id) + + if session is None or session.is_closed: + self.set_status(404) + return + + data = bytes_to_str(self.request.body) + + ctype = self.request.headers.get('Content-Type', '').lower() + if ctype == 'application/x-www-form-urlencoded': + if not data.startswith('d='): + LOG.exception('jsonp_send: Invalid payload.') + + self.write("Payload expected.") + self.set_status(500) + return + + data = unquote_plus(data[2:]) + + if not data: + LOG.debug('jsonp_send: Payload expected.') + + self.write("Payload expected.") + self.set_status(500) + return + + try: + messages = proto.json_decode(data) + except: + # TODO: Proper error handling + LOG.debug('jsonp_send: Invalid json encoding') + + self.write("Broken JSON encoding.") + self.set_status(500) + return + + try: + session.on_messages(messages) + except Exception: + LOG.exception('jsonp_send: on_message() failed') + + session.close() + + self.write('Message handler failed.') + self.set_status(500) + return + + self.write('ok') + self.set_header('Content-Type', 'text/plain; charset=UTF-8') + self.set_status(200) diff --git a/src/octoprint/vendor/sockjs/tornado/transports/pollingbase.py b/src/octoprint/vendor/sockjs/tornado/transports/pollingbase.py new file mode 100644 index 000000000..9c01782a8 --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/transports/pollingbase.py @@ -0,0 +1,72 @@ +# -*- coding: utf-8 -*- +""" + sockjs.tornado.transports.pollingbase + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Polling transports base +""" + +from octoprint.vendor.sockjs.tornado import basehandler +from octoprint.vendor.sockjs.tornado.transports import base + + +class PollingTransportBase(basehandler.PreflightHandler, base.BaseTransportMixin): + """Polling transport handler base class""" + def initialize(self, server): + super(PollingTransportBase, self).initialize(server) + + self.session = None + self.active = True + + def _get_session(self, session_id): + return self.server.get_session(session_id) + + def _attach_session(self, session_id, start_heartbeat=False): + session = self._get_session(session_id) + + if session is None: + session = self.server.create_session(session_id) + + # Try to attach to the session + if not session.set_handler(self, start_heartbeat): + return False + + self.session = session + + # Verify if session is properly opened + session.verify_state() + + return True + + def _detach(self): + """Detach from the session""" + if self.session: + self.session.remove_handler(self) + self.session = None + + def check_xsrf_cookie(self): + pass + + def send_message(self, message, binary=False): + """Called by the session when some data is available""" + raise NotImplementedError() + + def session_closed(self): + """Called by the session when it was closed""" + self._detach() + self.safe_finish() + + def on_connection_close(self): + # If connection was dropped by the client, close session. + # In all other cases, connection will be closed by the server. + if self.session is not None: + self.session.close(1002, 'Connection interrupted') + + super(PollingTransportBase, self).on_connection_close() + + def send_complete(self): + self._detach() + + # Avoid race condition when waiting for write callback and session getting closed in between + if not self._finished: + self.safe_finish() diff --git a/src/octoprint/vendor/sockjs/tornado/transports/rawwebsocket.py b/src/octoprint/vendor/sockjs/tornado/transports/rawwebsocket.py new file mode 100644 index 000000000..d5dd6efc7 --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/transports/rawwebsocket.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +""" + sockjs.tornado.transports.rawwebsocket + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Raw websocket transport implementation +""" +import logging +import socket + +from octoprint.vendor.sockjs.tornado import websocket, session +from octoprint.vendor.sockjs.tornado.transports import base + +LOG = logging.getLogger("tornado.general") + +class RawSession(session.BaseSession): + """Raw session without any sockjs protocol encoding/decoding. Simply + works as a proxy between `SockJSConnection` class and `RawWebSocketTransport`.""" + def send_message(self, msg, stats=True, binary=False): + self.handler.send_pack(msg, binary) + + def on_message(self, msg): + self.conn.on_message(msg) + + +class RawWebSocketTransport(websocket.SockJSWebSocketHandler, base.BaseTransportMixin): + """Raw Websocket transport""" + name = 'rawwebsocket' + + def initialize(self, server): + self.server = server + self.session = None + self.active = True + + def open(self): + # Stats + self.server.stats.on_conn_opened() + + # Disable nagle if needed + if self.server.settings['disable_nagle']: + self.stream.socket.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1) + + # Create and attach to session + self.session = RawSession(self.server.get_connection_class(), self.server) + self.session.set_handler(self) + self.session.verify_state() + + def _detach(self): + if self.session is not None: + self.session.remove_handler(self) + self.session = None + + def on_message(self, message): + # SockJS requires that empty messages should be ignored + if not message or not self.session: + return + + try: + self.session.on_message(message) + except Exception: + LOG.exception('RawWebSocket') + + # Close running connection + self.abort_connection() + + def on_close(self): + # Close session if websocket connection was closed + if self.session is not None: + # Stats + self.server.stats.on_conn_closed() + + session = self.session + self._detach() + session.close() + + def send_pack(self, message, binary=False): + # Send message + try: + self.write_message(message, binary) + except IOError: + self.server.io_loop.add_callback(self.on_close) + + def session_closed(self): + try: + self.close(*self.session.get_close_reason()) + except IOError: + pass + finally: + self._detach() + + # Websocket overrides + def allow_draft76(self): + return True diff --git a/src/octoprint/vendor/sockjs/tornado/transports/streamingbase.py b/src/octoprint/vendor/sockjs/tornado/transports/streamingbase.py new file mode 100644 index 000000000..4172401c2 --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/transports/streamingbase.py @@ -0,0 +1,47 @@ +from octoprint.vendor.sockjs.tornado.transports import pollingbase + + +class StreamingTransportBase(pollingbase.PollingTransportBase): + def initialize(self, server): + super(StreamingTransportBase, self).initialize(server) + + self.amount_limit = self.server.settings['response_limit'] + + # HTTP 1.0 client might send keep-alive + if hasattr(self.request, 'connection') and not self.request.supports_http_1_1(): + self.request.connection.no_keep_alive = True + + def notify_sent(self, data_len): + """ + Update amount of data sent + """ + self.amount_limit -= data_len + + def should_finish(self): + """ + Check if transport should close long running connection after + sending X bytes to the client. + + `data_len` + Amount of data that was sent + """ + if self.amount_limit <= 0: + return True + + return False + + def send_complete(self): + """ + Verify if connection should be closed based on amount of data that was sent. + """ + self.active = True + + if self.should_finish(): + self._detach() + + # Avoid race condition when waiting for write callback and session getting closed in between + if not self._finished: + self.safe_finish() + else: + if self.session: + self.session.flush() diff --git a/src/octoprint/vendor/sockjs/tornado/transports/websocket.py b/src/octoprint/vendor/sockjs/tornado/transports/websocket.py new file mode 100644 index 000000000..8df3a2901 --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/transports/websocket.py @@ -0,0 +1,105 @@ +# -*- coding: utf-8 -*- +""" + sockjs.tornado.transports.websocket + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Websocket transport implementation +""" +import logging +import socket + +from octoprint.vendor.sockjs.tornado import proto, websocket +from octoprint.vendor.sockjs.tornado.transports import base +from octoprint.vendor.sockjs.tornado.util import bytes_to_str + +LOG = logging.getLogger("tornado.general") + +class WebSocketTransport(websocket.SockJSWebSocketHandler, base.BaseTransportMixin): + """Websocket transport""" + name = 'websocket' + + def initialize(self, server): + self.server = server + self.session = None + self.active = True + + def open(self, session_id): + # Stats + self.server.stats.on_conn_opened() + + # Disable nagle + if self.server.settings['disable_nagle']: + self.stream.set_nodelay(True) + + # Handle session + self.session = self.server.create_session(session_id, register=False) + + if not self.session.set_handler(self): + self.close() + return + + self.session.verify_state() + + if self.session: + self.session.flush() + + def _detach(self): + if self.session is not None: + self.session.remove_handler(self) + self.session = None + + def on_message(self, message): + # SockJS requires that empty messages should be ignored + if not message or not self.session: + return + + try: + msg = proto.json_decode(bytes_to_str(message)) + + if isinstance(msg, list): + self.session.on_messages(msg) + else: + self.session.on_messages((msg,)) + except Exception: + LOG.exception('WebSocket') + + # Close session on exception + #self.session.close() + + # Close running connection + self.abort_connection() + + def on_close(self): + # Close session if websocket connection was closed + if self.session is not None: + # Stats + self.server.stats.on_conn_closed() + + # Detach before closing session + session = self.session + self._detach() + session.close() + + def send_pack(self, message, binary=False): + # Send message + try: + self.write_message(message, binary) + except IOError: + self.server.io_loop.add_callback(self.on_close) + + def session_closed(self): + # If session was closed by the application, terminate websocket + # connection as well. + try: + self.close() + except IOError: + pass + finally: + self._detach() + + # Websocket overrides + def allow_draft76(self): + return True + + def auto_decode(self): + return False diff --git a/src/octoprint/vendor/sockjs/tornado/transports/xhr.py b/src/octoprint/vendor/sockjs/tornado/transports/xhr.py new file mode 100644 index 000000000..01e01b21c --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/transports/xhr.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- +""" + sockjs.tornado.transports.xhr + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Xhr-Polling transport implementation +""" +import logging + +from tornado.web import asynchronous + +from octoprint.vendor.sockjs.tornado import proto +from octoprint.vendor.sockjs.tornado.transports import pollingbase +from octoprint.vendor.sockjs.tornado.util import bytes_to_str + +LOG = logging.getLogger("tornado.general") + +class XhrPollingTransport(pollingbase.PollingTransportBase): + """xhr-polling transport implementation""" + name = 'xhr' + + @asynchronous + def post(self, session_id): + # Start response + self.preflight() + self.handle_session_cookie() + self.disable_cache() + + # Get or create session without starting heartbeat + if not self._attach_session(session_id, False): + return + + # Might get already detached because connection was closed in on_open + if not self.session: + return + + if not self.session.send_queue: + self.session.start_heartbeat() + else: + self.session.flush() + + def send_pack(self, message, binary=False): + if binary: + raise Exception('binary not supported for XhrPollingTransport') + + self.active = False + + try: + self.set_header('Content-Type', 'application/javascript; charset=UTF-8') + self.set_header('Content-Length', len(message) + 1) + self.write(message + '\n') + self.flush(callback=self.send_complete) + except IOError: + # If connection dropped, make sure we close offending session instead + # of propagating error all way up. + self.session.delayed_close() + + +class XhrSendHandler(pollingbase.PollingTransportBase): + def post(self, session_id): + self.preflight() + self.handle_session_cookie() + self.disable_cache() + + session = self._get_session(session_id) + + if session is None or session.is_closed: + self.set_status(404) + return + + data = self.request.body + if not data: + self.write("Payload expected.") + self.set_status(500) + return + + try: + messages = proto.json_decode(bytes_to_str(data)) + except: + # TODO: Proper error handling + self.write("Broken JSON encoding.") + self.set_status(500) + return + + try: + session.on_messages(messages) + except Exception: + LOG.exception('XHR incoming') + session.close() + + self.set_status(500) + return + + self.set_status(204) + self.set_header('Content-Type', 'text/plain; charset=UTF-8') diff --git a/src/octoprint/vendor/sockjs/tornado/transports/xhrstreaming.py b/src/octoprint/vendor/sockjs/tornado/transports/xhrstreaming.py new file mode 100644 index 000000000..be8329c25 --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/transports/xhrstreaming.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +""" + sockjs.tornado.transports.xhrstreaming + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Xhr-Streaming transport implementation +""" + +from tornado.web import asynchronous + +from octoprint.vendor.sockjs.tornado.transports import streamingbase + + +class XhrStreamingTransport(streamingbase.StreamingTransportBase): + name = 'xhr_streaming' + + @asynchronous + def post(self, session_id): + # Handle cookie + self.preflight() + self.handle_session_cookie() + self.disable_cache() + self.set_header('Content-Type', 'application/javascript; charset=UTF-8') + + # Send prelude and flush any pending messages + self.write('h' * 2048 + '\n') + self.flush() + + if not self._attach_session(session_id, False): + self.finish() + return + + if self.session: + self.session.flush() + + def send_pack(self, message, binary=False): + if binary: + raise Exception('binary not supported for XhrStreamingTransport') + + self.active = False + + try: + self.notify_sent(len(message)) + + self.write(message + '\n') + self.flush(callback=self.send_complete) + except IOError: + # If connection dropped, make sure we close offending session instead + # of propagating error all way up. + self.session.delayed_close() + self._detach() diff --git a/src/octoprint/vendor/sockjs/tornado/util.py b/src/octoprint/vendor/sockjs/tornado/util.py new file mode 100644 index 000000000..0911258ac --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/util.py @@ -0,0 +1,50 @@ +import sys + +PY3 = sys.version_info[0] == 3 + +if PY3: + MAXSIZE = sys.maxsize + + def bytes_to_str(b): + if isinstance(b, bytes): + return str(b, 'utf8') + return b + + def str_to_bytes(s): + if isinstance(s, bytes): + return s + return s.encode('utf8') + + import urllib.parse + unquote_plus = urllib.parse.unquote_plus +else: + if sys.platform == "java": + # Jython always uses 32 bits. + MAXSIZE = int((1 << 31) - 1) + else: + # It's possible to have sizeof(long) != sizeof(Py_ssize_t). + class X(object): + def __len__(self): + return 1 << 31 + try: + len(X()) + except OverflowError: + # 32-bit + MAXSIZE = int((1 << 31) - 1) + else: + # 64-bit + MAXSIZE = int((1 << 63) - 1) + del X + + def bytes_to_str(s): + if isinstance(s, unicode): + return s.encode('utf-8') + return s + + def str_to_bytes(s): + if isinstance(s, unicode): + return s.encode('utf8') + return s + + import urllib + unquote_plus = urllib.unquote_plus diff --git a/src/octoprint/vendor/sockjs/tornado/websocket.py b/src/octoprint/vendor/sockjs/tornado/websocket.py new file mode 100644 index 000000000..6dc450fca --- /dev/null +++ b/src/octoprint/vendor/sockjs/tornado/websocket.py @@ -0,0 +1,36 @@ +import tornado +from tornado import escape, gen, websocket + +try: + from urllib.parse import urlparse # py3 +except ImportError: + from urlparse import urlparse # py2 + + +class SockJSWebSocketHandler(websocket.WebSocketHandler): + if tornado.version_info[0] == 4 and tornado.version_info[1] > 1: + def get_compression_options(self): + # let tornado use compression when Sec-WebSocket-Extensions:permessage-deflate is provided + return {} + + SUPPORTED_METHODS = ('GET',) + + def check_origin(self, origin): + # let tornado first check if connection from the same domain + same_domain = super(SockJSWebSocketHandler, self).check_origin(origin) + if same_domain: + return True + + # this is cross-origin connection - check using SockJS server settings + allow_origin = self.server.settings.get("websocket_allow_origin", "*") + if allow_origin == "*": + return True + else: + parsed_origin = urlparse(origin) + origin = parsed_origin.netloc + origin = origin.lower() + return origin in allow_origin + + def abort_connection(self): + if self.ws_connection: + self.ws_connection._abort() From 75de062b55c3aef7b250bf71c2ca5747860c3330 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 10 Apr 2018 18:09:55 +0200 Subject: [PATCH 02/15] Safety Plugin: Add detection of Anycubic Mega Identified by "Author: (Jolly, xxxxxxxx.CO.)" in startup messages. --- .../plugins/printer_safety_check/__init__.py | 44 ++++++++++++++----- 1 file changed, 34 insertions(+), 10 deletions(-) diff --git a/src/octoprint/plugins/printer_safety_check/__init__.py b/src/octoprint/plugins/printer_safety_check/__init__.py index 431892cf6..0d28f1d88 100644 --- a/src/octoprint/plugins/printer_safety_check/__init__.py +++ b/src/octoprint/plugins/printer_safety_check/__init__.py @@ -23,8 +23,14 @@ Learn more at https://faq.octoprint.org/warning-{warning_type} """ +ANETA8_FIRMWARE_NAME = "ANET_A8_".lower() +ANYCUBIC_AUTHOR = "| Author: (Jolly, xxxxxxxx.CO.)".lower() + SAFETY_CHECKS = { - "firmware-unsafe": (lambda name, data: name and name.lower().startswith("anet_a8_"),) + "firmware-unsafe": dict(m115=(lambda name, data: name and name.lower().startswith(ANETA8_FIRMWARE_NAME),), + received=(lambda line: line and ANYCUBIC_AUTHOR in line.lower(),), + message=u"Your printer's firmware is known to lack mandatory safety features (e.g. " \ + u"thermal runaway protection). This is a fire risk.") } class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin, @@ -35,6 +41,7 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin, # noinspection PyMissingConstructor def __init__(self): self._warnings = dict() + self._scan_received = True ##~~ TemplatePlugin API @@ -58,7 +65,8 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin, def on_event(self, event, payload): if event == Events.FIRMWARE_DATA: - self._analyze_firmware_data(payload.get("name"), payload.get("data")) + self._run_checks("m115", payload.get("name"), payload.get("data")) + self._scan_received = False elif event == Events.DISCONNECTED: self._reset_warnings() @@ -69,23 +77,36 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin, return flask.make_response("Insufficient rights", 403) return flask.jsonify(self._warnings) + ##~~ GCODE received hook handler + + def on_gcode_received(self, comm_instance, line, *args, **kwargs): + if self._scan_received: + self._run_checks("received", line) + return line + ##~~ Helpers - def _analyze_firmware_data(self, name, data): + def _run_checks(self, check_type, *args, **kwargs): changes = False - for warning_type, checks in SAFETY_CHECKS.items(): - if any(x(name, data) for x in checks): - message = u"Your printer's firmware is known to lack mandatory safety features (e.g. " \ - u"thermal runaway protection). This is a fire risk." - self._log_to_terminal(TERMINAL_SAFETY_WARNING.format(message="\n".join(textwrap.wrap(message, 75)), - warning_type=warning_type)) - self._warnings[warning_type] = message + for warning_type, check_data in SAFETY_CHECKS.items(): + checks = check_data.get(check_type) + message = check_data.get("message") + if not checks or not message: + continue + + if any(x(*args, **kwargs) for x in checks): + self._register_warning(warning_type, message) changes = True if changes: self._ping_clients() + def _register_warning(self, warning_type, message): + self._log_to_terminal(TERMINAL_SAFETY_WARNING.format(message="\n".join(textwrap.wrap(message, 75)), + warning_type=warning_type)) + self._warnings[warning_type] = message + def _reset_warnings(self): self._warnings.clear() self._ping_clients() @@ -107,4 +128,7 @@ __plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will n "issue and inform you about that fact.") __plugin_license__ = "AGPLv3" __plugin_implementation__ = PrinterSafetyCheckPlugin() +__plugin_hooks__ = { + "octoprint.comm.protocol.gcode.received": __plugin_implementation__.on_gcode_received +} From 58bbbc2ad94f4b9d8a0321087a49ad1ce3023a83 Mon Sep 17 00:00:00 2001 From: Vitor de Miranda Henrique Date: Tue, 10 Apr 2018 16:19:55 -0500 Subject: [PATCH 03/15] Update hooks.rst Fix Software Update plugin link, it was pointing to an old github page --> https://github.com/OctoPrint/OctoPrint-SoftwareUpdate instead of the bundled plugin--> https://github.com/foosel/OctoPrint/tree/master/src/octoprint/plugins/softwareupdate --- docs/plugins/hooks.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst index 18d63f75f..f3a5607f5 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -66,7 +66,7 @@ the general type of script for which to look for additions ("gcode") and the scr return a 2-tuple of prefix and postfix if has something for either of those, otherwise ``None``. OctoPrint will then take care to add prefix and suffix as necessary after a small round of preprocessing. -Plugins can easily add their own hooks too. For example, the `Software Update Plugin `_ +Plugins can easily add their own hooks too. For example, the `Software Update Plugin `_ declares a custom hook "octoprint.plugin.softwareupdate.check_config" which other plugins can add handlers for in order to register themselves with the Software Update Plugin by returning their own update check configuration. From 6f224bd825f4c9bab1d3eb109540420ca564532f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 11 Apr 2018 11:12:56 +0200 Subject: [PATCH 04/15] Workaround for typo & whitespace in Malyan M115 responses NAME. instead of NAME:, whitespace between key and value component. --- src/octoprint/util/comm.py | 18 ++++++++++++++---- tests/util/test_comm_helpers.py | 15 ++++++++++++++- 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index d4cbc4799..7737b7dc8 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -192,7 +192,7 @@ Groups will be as follows: * ``value``: reported position value """ -regex_firmware_splitter = re.compile("\s*([A-Z0-9_]+):") +regex_firmware_splitter = re.compile("\s*([A-Z0-9_]+):\s*") """Regex to use for splitting M115 responses.""" regex_resend_linenumber = re.compile("(N|N:)?(?P%s)" % regex_int_pattern) @@ -1662,7 +1662,7 @@ class MachineCom(object): pass ##~~ firmware name & version - elif "NAME:" in line: + elif "NAME:" in line or line.startswith("NAME."): # looks like a response to M115 data = parse_firmware_line(line) firmware_name = data.get("FIRMWARE_NAME") @@ -1672,7 +1672,11 @@ class MachineCom(object): # report its firmware name properly in response to M115. Wonderful - why stick to established # protocol when you can do your own thing, right? # - # Example: NAME: Malyan VER: 2.9 MODEL: M200 HW: HA02 + # Examples: + # + # NAME: Malyan VER: 2.9 MODEL: M200 HW: HA02 + # NAME. Malyan VER: 3.8 MODEL: M100 HW: HB02 + # NAME. Malyan VER: 3.7 MODEL: M300 HW: HG01 # # We do a bit of manual fiddling around here to circumvent that issue and get ourselves a # reliable firmware name (NAME + VER) out of the Malyan M115 response. @@ -4013,10 +4017,16 @@ def parse_firmware_line(line): dict: a dictionary with the parsed data """ + if line.startswith("NAME."): + # Good job Malyan. Why use a : when you can also just use a ., right? Let's revert that. + line = list(line) + line[4] = ":" + line = "".join(line) + result = dict() split_line = regex_firmware_splitter.split(line.strip())[1:] # first entry is empty start of trimmed string for key, value in chunks(split_line, 2): - result[key] = value + result[key] = value.strip() return result def parse_capability_line(line): diff --git a/tests/util/test_comm_helpers.py b/tests/util/test_comm_helpers.py index 10ab72122..119ff406d 100644 --- a/tests/util/test_comm_helpers.py +++ b/tests/util/test_comm_helpers.py @@ -259,7 +259,20 @@ class TestCommHelpers(unittest.TestCase): @data( ("KEY1:Value 1 FIRMWARE_NAME:Some Firmware With Spaces KEY2:Value 2", - dict(KEY1="Value 1", KEY2="Value 2", FIRMWARE_NAME="Some Firmware With Spaces")) + dict(KEY1="Value 1", KEY2="Value 2", FIRMWARE_NAME="Some Firmware With Spaces")), + ("NAME: Malyan VER: 2.9 MODEL: M200 HW: HA02", + dict(NAME="Malyan", VER="2.9", MODEL="M200", HW="HA02")), + ("NAME. Malyan VER: 3.8 MODEL: M100 HW: HB02", + dict(NAME="Malyan", VER="3.8", MODEL="M100", HW="HB02")), + ("NAME. Malyan VER: 3.7 MODEL: M300 HW: HG01", + dict(NAME="Malyan", VER="3.7", MODEL="M300", HW="HG01")), + ("FIRMWARE_NAME:Marlin 1.1.0 From Archive SOURCE_CODE_URL:http:// ... PROTOCOL_VERSION:1.0 MACHINE_TYPE:www.cxsw3d.com EXTRUDER_COUNT:1 UUID:00000000-0000-0000-0000-000000000000", + dict(FIRMWARE_NAME="Marlin 1.1.0 From Archive", + SOURCE_CODE_URL="http:// ...", + PROTOCOL_VERSION="1.0", + MACHINE_TYPE="www.cxsw3d.com", + EXTRUDER_COUNT="1", + UUID="00000000-0000-0000-0000-000000000000")) ) @unpack def test_parse_firmware_line(self, line, expected): From f3128a15d916610446ce1559b64d7cc5c819d1e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 11 Apr 2018 11:15:18 +0200 Subject: [PATCH 05/15] Safety Plugin: Add Malyan M200 & CR-10S Malyan M200 identified by firmware name "Malyan" and model "M200". Printer also known as Monoprice Select Mini, see also ID strings in #2271. CR-10S identified by "Author: (CR-10Slanguage)". --- .../plugins/printer_safety_check/__init__.py | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/src/octoprint/plugins/printer_safety_check/__init__.py b/src/octoprint/plugins/printer_safety_check/__init__.py index 0d28f1d88..3d563d806 100644 --- a/src/octoprint/plugins/printer_safety_check/__init__.py +++ b/src/octoprint/plugins/printer_safety_check/__init__.py @@ -23,12 +23,24 @@ Learn more at https://faq.octoprint.org/warning-{warning_type} """ -ANETA8_FIRMWARE_NAME = "ANET_A8_".lower() -ANYCUBIC_AUTHOR = "| Author: (Jolly, xxxxxxxx.CO.)".lower() +# Anet A8 +ANETA8_M115_TEST = lambda name, data: name and name.lower().startswith("anet_a8_") + +# Anycubic MEGA +ANYCUBIC_AUTHOR1 = "| Author: (Jolly, xxxxxxxx.CO.)".lower() +ANYCUBIC_AUTHOR2 = "| Author: (**Jolly, xxxxxxxx.CO.**)".lower() +ANYCUBIC_RECEIVED_TEST = lambda line: line and (ANYCUBIC_AUTHOR1 in line.lower() or ANYCUBIC_AUTHOR2 in line.lower()) + +# Creality CR-10s +CR10S_AUTHOR = " | Author: (CR-10Slanguage)".lower() +CR10S_RECEIVED_TEST = lambda line: line and CR10S_AUTHOR in line.lower() + +# Malyan M200 aka Monoprice Select Mini +MALYANM200_M115_TEST = lambda name, data: name and name.lower().startswith("malyan") and data.get("MODEL") == "M200" SAFETY_CHECKS = { - "firmware-unsafe": dict(m115=(lambda name, data: name and name.lower().startswith(ANETA8_FIRMWARE_NAME),), - received=(lambda line: line and ANYCUBIC_AUTHOR in line.lower(),), + "firmware-unsafe": dict(m115=(ANETA8_M115_TEST, MALYANM200_M115_TEST), + received=(ANYCUBIC_RECEIVED_TEST, CR10S_RECEIVED_TEST), message=u"Your printer's firmware is known to lack mandatory safety features (e.g. " \ u"thermal runaway protection). This is a fire risk.") } From c4d8e344d13581f7ee47241f7543c6bf7383b721 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 11 Apr 2018 11:15:46 +0200 Subject: [PATCH 06/15] Remove wrongly placed whitespace --- src/octoprint/settings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 9e6f13a04..492f1b810 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -403,7 +403,7 @@ default_settings = { "resetLines": ['start', 'Marlin: Virtual Marlin!', '\x80', 'SD card ok'], "preparedOks": [], "okFormatString": "ok", - "m115FormatString": "FIRMWARE_NAME: {firmware_name} PROTOCOL_VERSION:1.0", + "m115FormatString": "FIRMWARE_NAME:{firmware_name} PROTOCOL_VERSION:1.0", "m115ReportCapabilities": False, "capabilities": { "AUTOREPORT_TEMP": True, From 258f3725bf3b565e00aab30df9aa84b2c299b771 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 11 Apr 2018 18:43:23 +0200 Subject: [PATCH 07/15] Minor adjustments for Tornado 5 --- src/octoprint/server/__init__.py | 6 ++++-- src/octoprint/vendor/sockjs/tornado/router.py | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index f727db996..3cc9bdde8 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -490,7 +490,7 @@ class Server(object): ## Tornado initialization starts here ioloop = IOLoop() - ioloop.install() + ioloop.make_current() self._router = SockJSRouter(self._create_socket_connection, "/sockjs", session_kls=util.sockjs.ThreadSafeSession) @@ -760,7 +760,9 @@ class Server(object): except (KeyboardInterrupt, SystemExit): pass except: - self._logger.fatal("Now that is embarrassing... Something really really went wrong here. Please report this including the stacktrace below in OctoPrint's bugtracker. Thanks!") + self._logger.fatal("Now that is embarrassing... Something really really went wrong here. Please report " + "this including reproduction steps, octoprint.log and the stacktrace below in " + "OctoPrint's bugtracker. Thanks!") self._logger.exception("Stacktrace follows:") def _create_socket_connection(self, session): diff --git a/src/octoprint/vendor/sockjs/tornado/router.py b/src/octoprint/vendor/sockjs/tornado/router.py index e20619e89..103c346ad 100644 --- a/src/octoprint/vendor/sockjs/tornado/router.py +++ b/src/octoprint/vendor/sockjs/tornado/router.py @@ -91,7 +91,7 @@ class SockJSRouter(object): self._connection = connection # Initialize io_loop - self.io_loop = io_loop or ioloop.IOLoop.instance() + self.io_loop = io_loop or ioloop.IOLoop.current() # Settings self.settings = DEFAULT_SETTINGS.copy() From a5d541dafccff41fcfb0bc7cd0485e2dda2d40cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 11 Apr 2018 18:47:08 +0200 Subject: [PATCH 08/15] Fix sockjs not working behind haproxy For some reason the websocket connection runs into a timeout, the xhr transport doesn't properly take over, and then stuff takes ages to realign again. Only happens under Tornado 5, doesn't happen under Tornado 4.5 Increasing the timeout for now instead of pinning to Tornado 4.5 in the hopes that might still be figured out. Incredibly weird though. --- src/octoprint/static/js/lib/sockjs.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/static/js/lib/sockjs.js b/src/octoprint/static/js/lib/sockjs.js index f168d5f7b..52431ec9e 100644 --- a/src/octoprint/static/js/lib/sockjs.js +++ b/src/octoprint/static/js/lib/sockjs.js @@ -818,7 +818,7 @@ SockJS.prototype._connect = function() { } // calculate timeout based on RTO and round trips. Default to 5s - var timeoutMs = (this._rto * Transport.roundTrips) || 5000; + var timeoutMs = (this._rto * Transport.roundTrips * 2) || 5000; this._transportTimeoutId = setTimeout(this._transportTimeout.bind(this), timeoutMs); debug('using timeout', timeoutMs); From a33b037364d3adc624ba3733fe6d4723c92b324d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 12 Apr 2018 11:55:14 +0200 Subject: [PATCH 09/15] Fix ItemListHelper throwing an error on undefined items Just fall back to an empty list. Fixed #2572 (at least the bit that isn't a broken nginx config) --- src/octoprint/static/js/app/helpers.js | 1 + 1 file changed, 1 insertion(+) diff --git a/src/octoprint/static/js/app/helpers.js b/src/octoprint/static/js/app/helpers.js index 98a1e5741..7517ad1e2 100644 --- a/src/octoprint/static/js/app/helpers.js +++ b/src/octoprint/static/js/app/helpers.js @@ -27,6 +27,7 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor }; self.updateItems = function(items) { + if (items === undefined) items = []; self.allItems = items; self.allSize(items.length); self._updateItems(); From 132614045c82e0ed684b510e3c02b84a5ed87c96 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 12 Apr 2018 12:08:19 +0200 Subject: [PATCH 10/15] Early detection & logging of broken files response Fixes #2572 --- .../static/js/app/viewmodels/files.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/octoprint/static/js/app/viewmodels/files.js b/src/octoprint/static/js/app/viewmodels/files.js index 1ffcd1eb4..8d3a0afb9 100644 --- a/src/octoprint/static/js/app/viewmodels/files.js +++ b/src/octoprint/static/js/app/viewmodels/files.js @@ -276,6 +276,20 @@ $(function() { self.allItems(files); + // Sanity check file list - see #2572 + var nonrecursive = false; + _.each(files, function(file) { + if (file.type === "folder" && file.children === undefined) { + nonrecursive = true; + } + }); + if (nonrecursive) { + log.error("At least one folder doesn't have a 'children' element defined. That means the file list request " + + "wasn't actually made with 'recursive=true' in the query.\n\n" + + "This can happen on wrong reverse proxy configs that " + + "swallow up query parameters, see https://github.com/foosel/OctoPrint/issues/2572"); + } + if (!switchToPath) { var currentPath = self.currentPath(); if (currentPath === undefined) { @@ -318,6 +332,11 @@ $(function() { }; self.changeFolder = function(data) { + if (data.children === undefined) { + log.error("Can't switch to folder '" + data.path + "', no children available"); + return; + } + self.currentPath(data.path); self.listHelper.updateItems(data.children); self.highlightCurrentFilename(); From 9c923be5f05f433a1bd3d050f6cd83e3eb5d0ae2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 12 Apr 2018 13:19:02 +0200 Subject: [PATCH 11/15] Better solution for the Tornado 5 + SockJS + haproxy issue Looks like Nagle's algorithm was the cause. Adding option http-no-delay to haproxy.cfg solves the problem without modification of the timeout, however that is not an option for the thousands of instances already deployed in the field. So instead we add 300ms to the roundtrip based connection timeout, that should hopefully get around any Nagle-induced delays (usually between 40 and 200ms according to various sites on the net). --- src/octoprint/static/js/lib/sockjs.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/octoprint/static/js/lib/sockjs.js b/src/octoprint/static/js/lib/sockjs.js index 52431ec9e..dff4b42c7 100644 --- a/src/octoprint/static/js/lib/sockjs.js +++ b/src/octoprint/static/js/lib/sockjs.js @@ -817,8 +817,8 @@ SockJS.prototype._connect = function() { } } - // calculate timeout based on RTO and round trips. Default to 5s - var timeoutMs = (this._rto * Transport.roundTrips * 2) || 5000; + // calculate timeout based on RTO and round trips, compensate for potential nagle. Default to 5s. + var timeoutMs = (this._rto * Transport.roundTrips + 300) || 5000; this._transportTimeoutId = setTimeout(this._transportTimeout.bind(this), timeoutMs); debug('using timeout', timeoutMs); From 8076e59861e8ee66e6be7c344c10fb00b3e3c138 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 13 Apr 2018 15:31:01 +0200 Subject: [PATCH 12/15] Add hotfix branch type & set to tag tracking --- .versioneer-lookup | 1 + 1 file changed, 1 insertion(+) diff --git a/.versioneer-lookup b/.versioneer-lookup index dac4980c5..64c127d0c 100644 --- a/.versioneer-lookup +++ b/.versioneer-lookup @@ -11,6 +11,7 @@ master meta/.* rc/.* +hotfix/.* prerelease # neither should disconnected checkouts, e.g. 'git checkout ' From 45d8c288831fd98a2e9146ff16f1f105c1c553c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 13 Apr 2018 15:31:44 +0200 Subject: [PATCH 13/15] Pin psutil to 5.4.3 Fixes #2577 --- setup.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 643e82b96..765ed5bee 100644 --- a/setup.py +++ b/setup.py @@ -40,7 +40,8 @@ INSTALL_REQUIRES = [ "pkginfo>=1.2.1,<1.3", "requests>=2.18.4,<3", "semantic_version>=2.4.2,<2.5", - "psutil>=5.4.1,<6", + "psutil==5.4.3", # 5.4.4 introduced a breaking change concerning installing under non current + # setuptools versions. Pinning to 5.4.3 for now to work around this. "Click>=6.2,<6.3", "awesome-slugify>=1.6.5,<1.7", "feedparser>=5.2.1,<5.3", From c55c568bbddf5112facf6aa3a173d500936b6cbf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 13 Apr 2018 15:35:28 +0200 Subject: [PATCH 14/15] Preparing release of 1.3.8 --- CHANGELOG.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 560a28bbf..7660f4901 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # OctoPrint Changelog +## 1.3.8 (2018-04-13) + +### Bug fixes + + * [#2577](https://github.com/foosel/OctoPrint/issues/2577) - Pin `psutil` dependency to version 5.4.3 since 5.4.4 as released today introduces a breaking change. + +([Commits](https://github.com/foosel/OctoPrint/compare/1.3.7...1.3.8)) + ## 1.3.7 (2018-04-09) ### Improvements From 6a8a1c31e353996fced57afa63d0f2ab3a79f95b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 13 Apr 2018 17:08:19 +0200 Subject: [PATCH 15/15] maintenance is now 1.3.9.dev --- .versioneer-lookup | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.versioneer-lookup b/.versioneer-lookup index 6169322c5..acbff62a1 100644 --- a/.versioneer-lookup +++ b/.versioneer-lookup @@ -18,11 +18,11 @@ prerelease HEAD \(detached.* -# maintenance is currently the branch for preparation of maintenance release 1.3.8 +# maintenance is currently the branch for preparation of maintenance release 1.3.9 # so are any fix/... and improve/... branches -maintenance 1.3.8 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev -fix/.* 1.3.8 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev -improve/.* 1.3.8 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev +maintenance 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev +fix/.* 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev +improve/.* 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev # staging/maintenance is currently the branch for preparation of 1.3.7rc5 # so is regressionfix/...