2011-03-26 20:27:08 +00:00
|
|
|
#!/usr/bin/env python
|
2010-04-01 00:21:03 +01:00
|
|
|
|
2010-04-30 22:41:09 +01:00
|
|
|
'''
|
|
|
|
A WebSocket to TCP socket proxy with support for "wss://" encryption.
|
2011-05-18 17:09:10 +01:00
|
|
|
Copyright 2011 Joel Martin
|
2010-07-17 18:05:58 +01:00
|
|
|
Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3)
|
2010-04-30 22:41:09 +01:00
|
|
|
|
|
|
|
You can make a cert/key with openssl using:
|
|
|
|
openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem
|
|
|
|
as taken from http://docs.python.org/dev/library/ssl.html#certificates
|
|
|
|
|
|
|
|
'''
|
|
|
|
|
2018-07-04 10:06:57 +01:00
|
|
|
import signal, socket, optparse, time, os, sys, subprocess, logging, errno, ssl
|
2017-11-10 10:18:32 +00:00
|
|
|
try:
|
2019-04-02 16:03:08 +01:00
|
|
|
from socketserver import ThreadingMixIn
|
2017-11-10 10:18:32 +00:00
|
|
|
except ImportError:
|
2019-04-02 16:03:08 +01:00
|
|
|
from SocketServer import ThreadingMixIn
|
2017-11-10 10:18:32 +00:00
|
|
|
|
|
|
|
try:
|
|
|
|
from http.server import HTTPServer
|
|
|
|
except ImportError:
|
|
|
|
from BaseHTTPServer import HTTPServer
|
|
|
|
|
2015-04-05 01:11:13 +01:00
|
|
|
import select
|
2016-09-16 17:50:55 +01:00
|
|
|
from websockify import websockifyserver
|
2015-08-25 21:44:24 +01:00
|
|
|
from websockify import auth_plugins as auth
|
2012-10-30 13:34:47 +00:00
|
|
|
try:
|
|
|
|
from urllib.parse import parse_qs, urlparse
|
2017-11-10 10:18:32 +00:00
|
|
|
except ImportError:
|
2012-10-30 13:34:47 +00:00
|
|
|
from cgi import parse_qs
|
|
|
|
from urlparse import urlparse
|
2010-04-01 00:21:03 +01:00
|
|
|
|
2016-09-16 17:50:55 +01:00
|
|
|
class ProxyRequestHandler(websockifyserver.WebSockifyRequestHandler):
|
2016-09-15 18:51:26 +01:00
|
|
|
|
|
|
|
buffer_size = 65536
|
Try to solve https://github.com/kanaka/websockify/issues/71 by
refactoring. Basically, we are dividing WebSocketServer into two
classes: One request handler following the SocketServer Requesthandler
API, and one optional server engine. The standard Python SocketServer
engine can also be used.
websocketproxy.py has been updated to match the API change. I've also
added a new option --libserver in order to use the Python built in
server instead.
I've done a lot of testing with the new code. This includes: verbose,
daemon, run-once, timeout, idle-timeout, ssl, web, libserver. I've
tested both Python 2 and 3. I've also tested websocket.py in another
external service.
Code details follows:
* The new request handler class is called WebSocketRequestHandler,
inheriting SimpleHTTPRequestHandler.
* The service engine is called WebSocketServer, just like before.
* do_websocket_handshake: Using send_header() etc, instead of manually
sending HTTP response.
* A new method called handle_websocket() upgrades the connection to
WebSocket, if requested. Otherwise, it returns False. A typical
application use is:
def do_GET(self):
if not self.handle_websocket():
# handle normal requests
* new_client has been renamed to new_websocket_client, in order to
have a better name in the SocketServer/HTTPServer request handler
hierarchy.
* Note that in the request handler, configuration variables must be
provided by the "server" object, ie self.server.target_host.
2013-03-14 15:07:40 +00:00
|
|
|
|
2013-03-14 15:00:11 +00:00
|
|
|
traffic_legend = """
|
|
|
|
Traffic Legend:
|
|
|
|
} - Client receive
|
|
|
|
}. - Client receive partial
|
|
|
|
{ - Target receive
|
2013-12-17 13:20:14 +00:00
|
|
|
|
2013-03-14 15:00:11 +00:00
|
|
|
> - Target send
|
|
|
|
>. - Target send partial
|
|
|
|
< - Client send
|
|
|
|
<. - Client send partial
|
|
|
|
"""
|
2015-08-25 21:44:24 +01:00
|
|
|
|
|
|
|
def send_auth_error(self, ex):
|
|
|
|
self.send_response(ex.code, ex.msg)
|
|
|
|
self.send_header('Content-Type', 'text/html')
|
|
|
|
for name, val in ex.headers.items():
|
|
|
|
self.send_header(name, val)
|
|
|
|
|
|
|
|
self.end_headers()
|
|
|
|
|
|
|
|
def validate_connection(self):
|
2018-07-05 00:48:08 +01:00
|
|
|
if not self.server.token_plugin:
|
|
|
|
return
|
2016-02-16 13:42:27 +00:00
|
|
|
|
2018-07-05 00:48:08 +01:00
|
|
|
host, port = self.get_target(self.server.token_plugin)
|
|
|
|
if host == 'unix_socket':
|
|
|
|
self.server.unix_target = port
|
2015-08-25 21:44:24 +01:00
|
|
|
|
2018-07-05 00:48:08 +01:00
|
|
|
else:
|
|
|
|
self.server.target_host = host
|
|
|
|
self.server.target_port = port
|
|
|
|
|
|
|
|
def auth_connection(self):
|
|
|
|
if not self.server.auth_plugin:
|
|
|
|
return
|
|
|
|
|
|
|
|
try:
|
|
|
|
# get client certificate data
|
|
|
|
client_cert_data = self.request.getpeercert()
|
|
|
|
# extract subject information
|
|
|
|
client_cert_subject = client_cert_data['subject']
|
|
|
|
# flatten data structure
|
|
|
|
client_cert_subject = dict([x[0] for x in client_cert_subject])
|
|
|
|
# add common name to headers (apache +StdEnvVars style)
|
|
|
|
self.headers['SSL_CLIENT_S_DN_CN'] = client_cert_subject['commonName']
|
|
|
|
except (TypeError, AttributeError, KeyError):
|
|
|
|
# not a SSL connection or client presented no certificate with valid data
|
|
|
|
pass
|
2017-08-29 20:24:32 +01:00
|
|
|
|
2018-07-05 00:48:08 +01:00
|
|
|
try:
|
|
|
|
self.server.auth_plugin.authenticate(
|
|
|
|
headers=self.headers, target_host=self.server.target_host,
|
|
|
|
target_port=self.server.target_port)
|
|
|
|
except auth.AuthenticationError:
|
|
|
|
ex = sys.exc_info()[1]
|
|
|
|
self.send_auth_error(ex)
|
|
|
|
raise
|
2013-03-14 15:00:11 +00:00
|
|
|
|
Try to solve https://github.com/kanaka/websockify/issues/71 by
refactoring. Basically, we are dividing WebSocketServer into two
classes: One request handler following the SocketServer Requesthandler
API, and one optional server engine. The standard Python SocketServer
engine can also be used.
websocketproxy.py has been updated to match the API change. I've also
added a new option --libserver in order to use the Python built in
server instead.
I've done a lot of testing with the new code. This includes: verbose,
daemon, run-once, timeout, idle-timeout, ssl, web, libserver. I've
tested both Python 2 and 3. I've also tested websocket.py in another
external service.
Code details follows:
* The new request handler class is called WebSocketRequestHandler,
inheriting SimpleHTTPRequestHandler.
* The service engine is called WebSocketServer, just like before.
* do_websocket_handshake: Using send_header() etc, instead of manually
sending HTTP response.
* A new method called handle_websocket() upgrades the connection to
WebSocket, if requested. Otherwise, it returns False. A typical
application use is:
def do_GET(self):
if not self.handle_websocket():
# handle normal requests
* new_client has been renamed to new_websocket_client, in order to
have a better name in the SocketServer/HTTPServer request handler
hierarchy.
* Note that in the request handler, configuration variables must be
provided by the "server" object, ie self.server.target_host.
2013-03-14 15:07:40 +00:00
|
|
|
def new_websocket_client(self):
|
2011-01-08 21:29:01 +00:00
|
|
|
"""
|
|
|
|
Called after a new WebSocket connection has been established.
|
|
|
|
"""
|
2015-08-25 21:44:24 +01:00
|
|
|
# Checking for a token is done in validate_connection()
|
2015-04-28 21:17:47 +01:00
|
|
|
|
2011-01-08 21:29:01 +00:00
|
|
|
# Connect to the target
|
Try to solve https://github.com/kanaka/websockify/issues/71 by
refactoring. Basically, we are dividing WebSocketServer into two
classes: One request handler following the SocketServer Requesthandler
API, and one optional server engine. The standard Python SocketServer
engine can also be used.
websocketproxy.py has been updated to match the API change. I've also
added a new option --libserver in order to use the Python built in
server instead.
I've done a lot of testing with the new code. This includes: verbose,
daemon, run-once, timeout, idle-timeout, ssl, web, libserver. I've
tested both Python 2 and 3. I've also tested websocket.py in another
external service.
Code details follows:
* The new request handler class is called WebSocketRequestHandler,
inheriting SimpleHTTPRequestHandler.
* The service engine is called WebSocketServer, just like before.
* do_websocket_handshake: Using send_header() etc, instead of manually
sending HTTP response.
* A new method called handle_websocket() upgrades the connection to
WebSocket, if requested. Otherwise, it returns False. A typical
application use is:
def do_GET(self):
if not self.handle_websocket():
# handle normal requests
* new_client has been renamed to new_websocket_client, in order to
have a better name in the SocketServer/HTTPServer request handler
hierarchy.
* Note that in the request handler, configuration variables must be
provided by the "server" object, ie self.server.target_host.
2013-03-14 15:07:40 +00:00
|
|
|
if self.server.wrap_cmd:
|
|
|
|
msg = "connecting to command: '%s' (port %s)" % (" ".join(self.server.wrap_cmd), self.server.target_port)
|
|
|
|
elif self.server.unix_target:
|
|
|
|
msg = "connecting to unix socket: %s" % self.server.unix_target
|
2012-05-22 15:09:07 +01:00
|
|
|
else:
|
2012-05-28 12:09:07 +01:00
|
|
|
msg = "connecting to: %s:%s" % (
|
Try to solve https://github.com/kanaka/websockify/issues/71 by
refactoring. Basically, we are dividing WebSocketServer into two
classes: One request handler following the SocketServer Requesthandler
API, and one optional server engine. The standard Python SocketServer
engine can also be used.
websocketproxy.py has been updated to match the API change. I've also
added a new option --libserver in order to use the Python built in
server instead.
I've done a lot of testing with the new code. This includes: verbose,
daemon, run-once, timeout, idle-timeout, ssl, web, libserver. I've
tested both Python 2 and 3. I've also tested websocket.py in another
external service.
Code details follows:
* The new request handler class is called WebSocketRequestHandler,
inheriting SimpleHTTPRequestHandler.
* The service engine is called WebSocketServer, just like before.
* do_websocket_handshake: Using send_header() etc, instead of manually
sending HTTP response.
* A new method called handle_websocket() upgrades the connection to
WebSocket, if requested. Otherwise, it returns False. A typical
application use is:
def do_GET(self):
if not self.handle_websocket():
# handle normal requests
* new_client has been renamed to new_websocket_client, in order to
have a better name in the SocketServer/HTTPServer request handler
hierarchy.
* Note that in the request handler, configuration variables must be
provided by the "server" object, ie self.server.target_host.
2013-03-14 15:07:40 +00:00
|
|
|
self.server.target_host, self.server.target_port)
|
2012-09-20 15:46:04 +01:00
|
|
|
|
Try to solve https://github.com/kanaka/websockify/issues/71 by
refactoring. Basically, we are dividing WebSocketServer into two
classes: One request handler following the SocketServer Requesthandler
API, and one optional server engine. The standard Python SocketServer
engine can also be used.
websocketproxy.py has been updated to match the API change. I've also
added a new option --libserver in order to use the Python built in
server instead.
I've done a lot of testing with the new code. This includes: verbose,
daemon, run-once, timeout, idle-timeout, ssl, web, libserver. I've
tested both Python 2 and 3. I've also tested websocket.py in another
external service.
Code details follows:
* The new request handler class is called WebSocketRequestHandler,
inheriting SimpleHTTPRequestHandler.
* The service engine is called WebSocketServer, just like before.
* do_websocket_handshake: Using send_header() etc, instead of manually
sending HTTP response.
* A new method called handle_websocket() upgrades the connection to
WebSocket, if requested. Otherwise, it returns False. A typical
application use is:
def do_GET(self):
if not self.handle_websocket():
# handle normal requests
* new_client has been renamed to new_websocket_client, in order to
have a better name in the SocketServer/HTTPServer request handler
hierarchy.
* Note that in the request handler, configuration variables must be
provided by the "server" object, ie self.server.target_host.
2013-03-14 15:07:40 +00:00
|
|
|
if self.server.ssl_target:
|
2012-05-23 15:20:08 +01:00
|
|
|
msg += " (using SSL)"
|
Try to solve https://github.com/kanaka/websockify/issues/71 by
refactoring. Basically, we are dividing WebSocketServer into two
classes: One request handler following the SocketServer Requesthandler
API, and one optional server engine. The standard Python SocketServer
engine can also be used.
websocketproxy.py has been updated to match the API change. I've also
added a new option --libserver in order to use the Python built in
server instead.
I've done a lot of testing with the new code. This includes: verbose,
daemon, run-once, timeout, idle-timeout, ssl, web, libserver. I've
tested both Python 2 and 3. I've also tested websocket.py in another
external service.
Code details follows:
* The new request handler class is called WebSocketRequestHandler,
inheriting SimpleHTTPRequestHandler.
* The service engine is called WebSocketServer, just like before.
* do_websocket_handshake: Using send_header() etc, instead of manually
sending HTTP response.
* A new method called handle_websocket() upgrades the connection to
WebSocket, if requested. Otherwise, it returns False. A typical
application use is:
def do_GET(self):
if not self.handle_websocket():
# handle normal requests
* new_client has been renamed to new_websocket_client, in order to
have a better name in the SocketServer/HTTPServer request handler
hierarchy.
* Note that in the request handler, configuration variables must be
provided by the "server" object, ie self.server.target_host.
2013-03-14 15:07:40 +00:00
|
|
|
self.log_message(msg)
|
2012-05-23 15:20:08 +01:00
|
|
|
|
2018-10-23 15:31:57 +01:00
|
|
|
try:
|
|
|
|
tsock = websockifyserver.WebSockifyServer.socket(self.server.target_host,
|
|
|
|
self.server.target_port,
|
|
|
|
connect=True,
|
|
|
|
use_ssl=self.server.ssl_target,
|
|
|
|
unix_socket=self.server.unix_target)
|
2020-02-27 14:54:29 +00:00
|
|
|
except Exception as e:
|
|
|
|
self.log_message("Failed to connect to %s:%s: %s",
|
|
|
|
self.server.target_host, self.server.target_port, e)
|
2018-10-23 15:31:57 +01:00
|
|
|
raise self.CClose(1011, "Failed to connect to downstream server")
|
2011-07-07 17:45:19 +01:00
|
|
|
|
2016-06-02 13:43:26 +01:00
|
|
|
self.request.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
|
|
|
|
if not self.server.wrap_cmd and not self.server.unix_target:
|
|
|
|
tsock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
|
|
|
|
|
2013-10-14 18:55:37 +01:00
|
|
|
self.print_traffic(self.traffic_legend)
|
2011-01-08 21:29:01 +00:00
|
|
|
|
2011-05-02 04:17:04 +01:00
|
|
|
# Start proxying
|
2011-01-08 21:29:01 +00:00
|
|
|
try:
|
2011-05-02 04:17:04 +01:00
|
|
|
self.do_proxy(tsock)
|
2017-11-10 10:18:32 +00:00
|
|
|
finally:
|
2011-01-13 18:22:22 +00:00
|
|
|
if tsock:
|
2011-06-26 19:26:59 +01:00
|
|
|
tsock.shutdown(socket.SHUT_RDWR)
|
2011-01-13 18:22:22 +00:00
|
|
|
tsock.close()
|
Introduce Token Plugins
Token plugins provide a generic interface for transforming a token
into a `(host, port)` tuple.
The plugin name is specified using the '--token-plugin' option,
and may either be the name of a class from `websockify.token_plugins`,
or a fully qualified python path to the token plugin class (see below).
An optional plugin parameter can be specified using the '--token-source'
option (a value of `None` will be used if no '--token-source' option is
passed).
Token plugins should inherit from `websockify.token_plugins.BasePlugin`,
and should implement the `lookup(token)` method. The value of the
'--token-source' option is available as `self.source`.
Several plugins are included by default. The `ReadOnlyTokenFile`
and `TokenFile` plugins implement functionality from '--target-config'
(with the former only reading the file(s) once, and the latter reading
them every time). The 'BaseTokenAPI' plugin fetches the value from
an API, returning the result of `process_result(response_object)`.
By default, `process_result` simply returns the text of the response,
but may be overriden. The `JSONTokenAPI` does just this, returning
the 'host' and 'port' values from the response JSON object.
The old '--target-config' option is now deprecated, and maps to the
`TokenFile` plugin under the hood.
Also-Authored-By: James Portman (@james-portman)
Closes #157
2015-03-26 20:01:57 +00:00
|
|
|
if self.verbose:
|
2014-03-18 14:21:13 +00:00
|
|
|
self.log_message("%s:%s: Closed target",
|
|
|
|
self.server.target_host, self.server.target_port)
|
2011-01-08 21:29:01 +00:00
|
|
|
|
2018-07-05 00:54:19 +01:00
|
|
|
def get_target(self, target_plugin):
|
2012-07-13 01:10:12 +01:00
|
|
|
"""
|
2018-07-05 00:54:19 +01:00
|
|
|
Gets a token from either the path or the host,
|
|
|
|
depending on --host-token, and looks up a target
|
|
|
|
for that token using the token plugin. Used by
|
|
|
|
validate_connection() to set target_host and target_port.
|
2012-07-13 01:10:12 +01:00
|
|
|
"""
|
|
|
|
# The files in targets contain the lines
|
2012-07-13 01:34:27 +01:00
|
|
|
# in the form of token: host:port
|
2012-07-13 01:10:12 +01:00
|
|
|
|
2018-07-05 00:54:19 +01:00
|
|
|
if self.host_token:
|
2018-07-12 20:21:08 +01:00
|
|
|
# Use hostname as token
|
2018-07-05 00:54:19 +01:00
|
|
|
token = self.headers.get('Host')
|
2012-07-13 01:10:12 +01:00
|
|
|
|
2018-07-12 20:21:08 +01:00
|
|
|
# Remove port from hostname, as it'll always be the one where
|
|
|
|
# websockify listens (unless something between the client and
|
|
|
|
# websockify is redirecting traffic, but that's beside the point)
|
|
|
|
if token:
|
|
|
|
token = token.partition(':')[0]
|
|
|
|
|
2018-07-05 00:54:19 +01:00
|
|
|
else:
|
|
|
|
# Extract the token parameter from url
|
|
|
|
args = parse_qs(urlparse(self.path)[4]) # 4 is the query from url
|
2012-07-13 01:10:12 +01:00
|
|
|
|
2018-07-05 00:54:19 +01:00
|
|
|
if 'token' in args and len(args['token']):
|
|
|
|
token = args['token'][0].rstrip('\n')
|
|
|
|
else:
|
|
|
|
token = None
|
|
|
|
|
|
|
|
if token is None:
|
|
|
|
raise self.server.EClose("Token not present")
|
2012-07-13 01:10:12 +01:00
|
|
|
|
Introduce Token Plugins
Token plugins provide a generic interface for transforming a token
into a `(host, port)` tuple.
The plugin name is specified using the '--token-plugin' option,
and may either be the name of a class from `websockify.token_plugins`,
or a fully qualified python path to the token plugin class (see below).
An optional plugin parameter can be specified using the '--token-source'
option (a value of `None` will be used if no '--token-source' option is
passed).
Token plugins should inherit from `websockify.token_plugins.BasePlugin`,
and should implement the `lookup(token)` method. The value of the
'--token-source' option is available as `self.source`.
Several plugins are included by default. The `ReadOnlyTokenFile`
and `TokenFile` plugins implement functionality from '--target-config'
(with the former only reading the file(s) once, and the latter reading
them every time). The 'BaseTokenAPI' plugin fetches the value from
an API, returning the result of `process_result(response_object)`.
By default, `process_result` simply returns the text of the response,
but may be overriden. The `JSONTokenAPI` does just this, returning
the 'host' and 'port' values from the response JSON object.
The old '--target-config' option is now deprecated, and maps to the
`TokenFile` plugin under the hood.
Also-Authored-By: James Portman (@james-portman)
Closes #157
2015-03-26 20:01:57 +00:00
|
|
|
result_pair = target_plugin.lookup(token)
|
2012-07-13 01:10:12 +01:00
|
|
|
|
Introduce Token Plugins
Token plugins provide a generic interface for transforming a token
into a `(host, port)` tuple.
The plugin name is specified using the '--token-plugin' option,
and may either be the name of a class from `websockify.token_plugins`,
or a fully qualified python path to the token plugin class (see below).
An optional plugin parameter can be specified using the '--token-source'
option (a value of `None` will be used if no '--token-source' option is
passed).
Token plugins should inherit from `websockify.token_plugins.BasePlugin`,
and should implement the `lookup(token)` method. The value of the
'--token-source' option is available as `self.source`.
Several plugins are included by default. The `ReadOnlyTokenFile`
and `TokenFile` plugins implement functionality from '--target-config'
(with the former only reading the file(s) once, and the latter reading
them every time). The 'BaseTokenAPI' plugin fetches the value from
an API, returning the result of `process_result(response_object)`.
By default, `process_result` simply returns the text of the response,
but may be overriden. The `JSONTokenAPI` does just this, returning
the 'host' and 'port' values from the response JSON object.
The old '--target-config' option is now deprecated, and maps to the
`TokenFile` plugin under the hood.
Also-Authored-By: James Portman (@james-portman)
Closes #157
2015-03-26 20:01:57 +00:00
|
|
|
if result_pair is not None:
|
|
|
|
return result_pair
|
2012-07-13 01:34:27 +01:00
|
|
|
else:
|
Introduce Token Plugins
Token plugins provide a generic interface for transforming a token
into a `(host, port)` tuple.
The plugin name is specified using the '--token-plugin' option,
and may either be the name of a class from `websockify.token_plugins`,
or a fully qualified python path to the token plugin class (see below).
An optional plugin parameter can be specified using the '--token-source'
option (a value of `None` will be used if no '--token-source' option is
passed).
Token plugins should inherit from `websockify.token_plugins.BasePlugin`,
and should implement the `lookup(token)` method. The value of the
'--token-source' option is available as `self.source`.
Several plugins are included by default. The `ReadOnlyTokenFile`
and `TokenFile` plugins implement functionality from '--target-config'
(with the former only reading the file(s) once, and the latter reading
them every time). The 'BaseTokenAPI' plugin fetches the value from
an API, returning the result of `process_result(response_object)`.
By default, `process_result` simply returns the text of the response,
but may be overriden. The `JSONTokenAPI` does just this, returning
the 'host' and 'port' values from the response JSON object.
The old '--target-config' option is now deprecated, and maps to the
`TokenFile` plugin under the hood.
Also-Authored-By: James Portman (@james-portman)
Closes #157
2015-03-26 20:01:57 +00:00
|
|
|
raise self.server.EClose("Token '%s' not found" % token)
|
2012-07-13 01:10:12 +01:00
|
|
|
|
2011-05-02 04:17:04 +01:00
|
|
|
def do_proxy(self, target):
|
2011-01-08 21:29:01 +00:00
|
|
|
"""
|
|
|
|
Proxy client WebSocket to normal target socket.
|
|
|
|
"""
|
|
|
|
cqueue = []
|
2011-05-02 04:17:04 +01:00
|
|
|
c_pend = 0
|
2011-01-08 21:29:01 +00:00
|
|
|
tqueue = []
|
2013-03-14 14:23:44 +00:00
|
|
|
rlist = [self.request, target]
|
2011-01-08 21:29:01 +00:00
|
|
|
|
2015-04-10 19:14:31 +01:00
|
|
|
if self.server.heartbeat:
|
|
|
|
now = time.time()
|
|
|
|
self.heartbeat = now + self.server.heartbeat
|
|
|
|
else:
|
|
|
|
self.heartbeat = None
|
|
|
|
|
2011-01-08 21:29:01 +00:00
|
|
|
while True:
|
|
|
|
wlist = []
|
|
|
|
|
2015-04-10 19:14:31 +01:00
|
|
|
if self.heartbeat is not None:
|
|
|
|
now = time.time()
|
|
|
|
if now > self.heartbeat:
|
|
|
|
self.heartbeat = now + self.server.heartbeat
|
|
|
|
self.send_ping()
|
|
|
|
|
2011-01-08 21:29:01 +00:00
|
|
|
if tqueue: wlist.append(target)
|
2013-03-14 14:23:44 +00:00
|
|
|
if cqueue or c_pend: wlist.append(self.request)
|
2015-04-05 01:11:13 +01:00
|
|
|
try:
|
|
|
|
ins, outs, excepts = select.select(rlist, wlist, [], 1)
|
|
|
|
except (select.error, OSError):
|
|
|
|
exc = sys.exc_info()[1]
|
|
|
|
if hasattr(exc, 'errno'):
|
|
|
|
err = exc.errno
|
|
|
|
else:
|
|
|
|
err = exc[0]
|
|
|
|
|
|
|
|
if err != errno.EINTR:
|
|
|
|
raise
|
|
|
|
else:
|
|
|
|
continue
|
|
|
|
|
2011-01-08 21:29:01 +00:00
|
|
|
if excepts: raise Exception("Socket exception")
|
|
|
|
|
2013-03-14 14:23:44 +00:00
|
|
|
if self.request in outs:
|
2012-10-29 23:12:54 +00:00
|
|
|
# Send queued target data to the client
|
|
|
|
c_pend = self.send_frames(cqueue)
|
|
|
|
|
|
|
|
cqueue = []
|
|
|
|
|
2013-03-14 14:23:44 +00:00
|
|
|
if self.request in ins:
|
2012-10-29 23:12:54 +00:00
|
|
|
# Receive client data, decode it, and queue for target
|
|
|
|
bufs, closed = self.recv_frames()
|
|
|
|
tqueue.extend(bufs)
|
|
|
|
|
|
|
|
if closed:
|
|
|
|
# TODO: What about blocking on client socket?
|
Introduce Token Plugins
Token plugins provide a generic interface for transforming a token
into a `(host, port)` tuple.
The plugin name is specified using the '--token-plugin' option,
and may either be the name of a class from `websockify.token_plugins`,
or a fully qualified python path to the token plugin class (see below).
An optional plugin parameter can be specified using the '--token-source'
option (a value of `None` will be used if no '--token-source' option is
passed).
Token plugins should inherit from `websockify.token_plugins.BasePlugin`,
and should implement the `lookup(token)` method. The value of the
'--token-source' option is available as `self.source`.
Several plugins are included by default. The `ReadOnlyTokenFile`
and `TokenFile` plugins implement functionality from '--target-config'
(with the former only reading the file(s) once, and the latter reading
them every time). The 'BaseTokenAPI' plugin fetches the value from
an API, returning the result of `process_result(response_object)`.
By default, `process_result` simply returns the text of the response,
but may be overriden. The `JSONTokenAPI` does just this, returning
the 'host' and 'port' values from the response JSON object.
The old '--target-config' option is now deprecated, and maps to the
`TokenFile` plugin under the hood.
Also-Authored-By: James Portman (@james-portman)
Closes #157
2015-03-26 20:01:57 +00:00
|
|
|
if self.verbose:
|
2014-03-18 14:21:13 +00:00
|
|
|
self.log_message("%s:%s: Client closed connection",
|
|
|
|
self.server.target_host, self.server.target_port)
|
2012-10-29 23:12:54 +00:00
|
|
|
raise self.CClose(closed['code'], closed['reason'])
|
|
|
|
|
|
|
|
|
2011-01-08 21:29:01 +00:00
|
|
|
if target in outs:
|
|
|
|
# Send queued client data to the target
|
|
|
|
dat = tqueue.pop(0)
|
|
|
|
sent = target.send(dat)
|
|
|
|
if sent == len(dat):
|
2013-10-14 18:55:37 +01:00
|
|
|
self.print_traffic(">")
|
2011-01-08 21:29:01 +00:00
|
|
|
else:
|
|
|
|
# requeue the remaining data
|
|
|
|
tqueue.insert(0, dat[sent:])
|
2013-10-14 18:55:37 +01:00
|
|
|
self.print_traffic(".>")
|
2011-01-08 21:29:01 +00:00
|
|
|
|
|
|
|
|
|
|
|
if target in ins:
|
|
|
|
# Receive target data, encode it and queue for client
|
|
|
|
buf = target.recv(self.buffer_size)
|
2018-01-25 14:46:41 +00:00
|
|
|
if len(buf) == 0:
|
Try to solve https://github.com/kanaka/websockify/issues/71 by
refactoring. Basically, we are dividing WebSocketServer into two
classes: One request handler following the SocketServer Requesthandler
API, and one optional server engine. The standard Python SocketServer
engine can also be used.
websocketproxy.py has been updated to match the API change. I've also
added a new option --libserver in order to use the Python built in
server instead.
I've done a lot of testing with the new code. This includes: verbose,
daemon, run-once, timeout, idle-timeout, ssl, web, libserver. I've
tested both Python 2 and 3. I've also tested websocket.py in another
external service.
Code details follows:
* The new request handler class is called WebSocketRequestHandler,
inheriting SimpleHTTPRequestHandler.
* The service engine is called WebSocketServer, just like before.
* do_websocket_handshake: Using send_header() etc, instead of manually
sending HTTP response.
* A new method called handle_websocket() upgrades the connection to
WebSocket, if requested. Otherwise, it returns False. A typical
application use is:
def do_GET(self):
if not self.handle_websocket():
# handle normal requests
* new_client has been renamed to new_websocket_client, in order to
have a better name in the SocketServer/HTTPServer request handler
hierarchy.
* Note that in the request handler, configuration variables must be
provided by the "server" object, ie self.server.target_host.
2013-03-14 15:07:40 +00:00
|
|
|
if self.verbose:
|
2014-03-18 14:21:13 +00:00
|
|
|
self.log_message("%s:%s: Target closed connection",
|
|
|
|
self.server.target_host, self.server.target_port)
|
2012-04-25 19:44:01 +01:00
|
|
|
raise self.CClose(1000, "Target closed")
|
2011-01-08 21:29:01 +00:00
|
|
|
|
2011-05-02 04:17:04 +01:00
|
|
|
cqueue.append(buf)
|
2013-10-14 18:55:37 +01:00
|
|
|
self.print_traffic("{")
|
2011-01-08 21:29:01 +00:00
|
|
|
|
2016-09-16 17:50:55 +01:00
|
|
|
class WebSocketProxy(websockifyserver.WebSockifyServer):
|
2013-03-20 10:30:38 +00:00
|
|
|
"""
|
|
|
|
Proxy traffic to and from a WebSockets client to a normal TCP
|
2017-01-28 13:50:48 +00:00
|
|
|
socket server target.
|
2013-03-20 10:30:38 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
buffer_size = 65536
|
|
|
|
|
2013-03-20 10:34:46 +00:00
|
|
|
def __init__(self, RequestHandlerClass=ProxyRequestHandler, *args, **kwargs):
|
2013-03-20 10:30:38 +00:00
|
|
|
# Save off proxy specific options
|
|
|
|
self.target_host = kwargs.pop('target_host', None)
|
|
|
|
self.target_port = kwargs.pop('target_port', None)
|
|
|
|
self.wrap_cmd = kwargs.pop('wrap_cmd', None)
|
|
|
|
self.wrap_mode = kwargs.pop('wrap_mode', None)
|
|
|
|
self.unix_target = kwargs.pop('unix_target', None)
|
|
|
|
self.ssl_target = kwargs.pop('ssl_target', None)
|
2015-04-10 19:14:31 +01:00
|
|
|
self.heartbeat = kwargs.pop('heartbeat', None)
|
Introduce Token Plugins
Token plugins provide a generic interface for transforming a token
into a `(host, port)` tuple.
The plugin name is specified using the '--token-plugin' option,
and may either be the name of a class from `websockify.token_plugins`,
or a fully qualified python path to the token plugin class (see below).
An optional plugin parameter can be specified using the '--token-source'
option (a value of `None` will be used if no '--token-source' option is
passed).
Token plugins should inherit from `websockify.token_plugins.BasePlugin`,
and should implement the `lookup(token)` method. The value of the
'--token-source' option is available as `self.source`.
Several plugins are included by default. The `ReadOnlyTokenFile`
and `TokenFile` plugins implement functionality from '--target-config'
(with the former only reading the file(s) once, and the latter reading
them every time). The 'BaseTokenAPI' plugin fetches the value from
an API, returning the result of `process_result(response_object)`.
By default, `process_result` simply returns the text of the response,
but may be overriden. The `JSONTokenAPI` does just this, returning
the 'host' and 'port' values from the response JSON object.
The old '--target-config' option is now deprecated, and maps to the
`TokenFile` plugin under the hood.
Also-Authored-By: James Portman (@james-portman)
Closes #157
2015-03-26 20:01:57 +00:00
|
|
|
|
2015-04-28 22:08:36 +01:00
|
|
|
self.token_plugin = kwargs.pop('token_plugin', None)
|
2018-07-05 00:54:19 +01:00
|
|
|
self.host_token = kwargs.pop('host_token', None)
|
2015-04-28 22:08:36 +01:00
|
|
|
self.auth_plugin = kwargs.pop('auth_plugin', None)
|
2015-04-28 21:17:47 +01:00
|
|
|
|
2013-03-20 10:30:38 +00:00
|
|
|
# Last 3 timestamps command was run
|
|
|
|
self.wrap_times = [0, 0, 0]
|
|
|
|
|
|
|
|
if self.wrap_cmd:
|
2013-11-27 12:33:30 +00:00
|
|
|
wsdir = os.path.dirname(sys.argv[0])
|
|
|
|
rebinder_path = [os.path.join(wsdir, "..", "lib"),
|
|
|
|
os.path.join(wsdir, "..", "lib", "websockify"),
|
2020-12-04 12:55:58 +00:00
|
|
|
os.path.join(wsdir, ".."),
|
2013-11-27 12:33:30 +00:00
|
|
|
wsdir]
|
2013-03-20 10:30:38 +00:00
|
|
|
self.rebinder = None
|
|
|
|
|
|
|
|
for rdir in rebinder_path:
|
|
|
|
rpath = os.path.join(rdir, "rebind.so")
|
|
|
|
if os.path.exists(rpath):
|
|
|
|
self.rebinder = rpath
|
|
|
|
break
|
|
|
|
|
|
|
|
if not self.rebinder:
|
|
|
|
raise Exception("rebind.so not found, perhaps you need to run make")
|
|
|
|
self.rebinder = os.path.abspath(self.rebinder)
|
|
|
|
|
|
|
|
self.target_host = "127.0.0.1" # Loopback
|
|
|
|
# Find a free high port
|
|
|
|
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
|
|
sock.bind(('', 0))
|
|
|
|
self.target_port = sock.getsockname()[1]
|
|
|
|
sock.close()
|
|
|
|
|
|
|
|
os.environ.update({
|
|
|
|
"LD_PRELOAD": self.rebinder,
|
|
|
|
"REBIND_OLD_PORT": str(kwargs['listen_port']),
|
|
|
|
"REBIND_NEW_PORT": str(self.target_port)})
|
|
|
|
|
2016-09-16 17:50:55 +01:00
|
|
|
websockifyserver.WebSockifyServer.__init__(self, RequestHandlerClass, *args, **kwargs)
|
2013-03-20 10:30:38 +00:00
|
|
|
|
|
|
|
def run_wrap_cmd(self):
|
2013-11-28 08:05:24 +00:00
|
|
|
self.msg("Starting '%s'", " ".join(self.wrap_cmd))
|
2013-03-20 10:30:38 +00:00
|
|
|
self.wrap_times.append(time.time())
|
|
|
|
self.wrap_times.pop(0)
|
|
|
|
self.cmd = subprocess.Popen(
|
|
|
|
self.wrap_cmd, env=os.environ, preexec_fn=_subprocess_setup)
|
|
|
|
self.spawn_message = True
|
|
|
|
|
|
|
|
def started(self):
|
|
|
|
"""
|
|
|
|
Called after Websockets server startup (i.e. after daemonize)
|
|
|
|
"""
|
|
|
|
# Need to call wrapped command after daemonization so we can
|
|
|
|
# know when the wrapped command exits
|
|
|
|
if self.wrap_cmd:
|
|
|
|
dst_string = "'%s' (port %s)" % (" ".join(self.wrap_cmd), self.target_port)
|
|
|
|
elif self.unix_target:
|
|
|
|
dst_string = self.unix_target
|
|
|
|
else:
|
|
|
|
dst_string = "%s:%s" % (self.target_host, self.target_port)
|
|
|
|
|
2017-07-31 15:16:24 +01:00
|
|
|
if self.listen_fd != None:
|
|
|
|
src_string = "inetd"
|
|
|
|
else:
|
|
|
|
src_string = "%s:%s" % (self.listen_host, self.listen_port)
|
|
|
|
|
Introduce Token Plugins
Token plugins provide a generic interface for transforming a token
into a `(host, port)` tuple.
The plugin name is specified using the '--token-plugin' option,
and may either be the name of a class from `websockify.token_plugins`,
or a fully qualified python path to the token plugin class (see below).
An optional plugin parameter can be specified using the '--token-source'
option (a value of `None` will be used if no '--token-source' option is
passed).
Token plugins should inherit from `websockify.token_plugins.BasePlugin`,
and should implement the `lookup(token)` method. The value of the
'--token-source' option is available as `self.source`.
Several plugins are included by default. The `ReadOnlyTokenFile`
and `TokenFile` plugins implement functionality from '--target-config'
(with the former only reading the file(s) once, and the latter reading
them every time). The 'BaseTokenAPI' plugin fetches the value from
an API, returning the result of `process_result(response_object)`.
By default, `process_result` simply returns the text of the response,
but may be overriden. The `JSONTokenAPI` does just this, returning
the 'host' and 'port' values from the response JSON object.
The old '--target-config' option is now deprecated, and maps to the
`TokenFile` plugin under the hood.
Also-Authored-By: James Portman (@james-portman)
Closes #157
2015-03-26 20:01:57 +00:00
|
|
|
if self.token_plugin:
|
2017-07-31 15:16:24 +01:00
|
|
|
msg = " - proxying from %s to targets generated by %s" % (
|
|
|
|
src_string, type(self.token_plugin).__name__)
|
2013-03-20 10:30:38 +00:00
|
|
|
else:
|
2017-07-31 15:16:24 +01:00
|
|
|
msg = " - proxying from %s to %s" % (
|
|
|
|
src_string, dst_string)
|
2013-03-20 10:30:38 +00:00
|
|
|
|
|
|
|
if self.ssl_target:
|
|
|
|
msg += " (using SSL)"
|
|
|
|
|
2013-11-28 08:05:24 +00:00
|
|
|
self.msg("%s", msg)
|
2013-03-20 10:30:38 +00:00
|
|
|
|
|
|
|
if self.wrap_cmd:
|
|
|
|
self.run_wrap_cmd()
|
|
|
|
|
|
|
|
def poll(self):
|
|
|
|
# If we are wrapping a command, check it's status
|
|
|
|
|
|
|
|
if self.wrap_cmd and self.cmd:
|
|
|
|
ret = self.cmd.poll()
|
|
|
|
if ret != None:
|
|
|
|
self.vmsg("Wrapped command exited (or daemon). Returned %s" % ret)
|
|
|
|
self.cmd = None
|
|
|
|
|
|
|
|
if self.wrap_cmd and self.cmd == None:
|
|
|
|
# Response to wrapped command being gone
|
|
|
|
if self.wrap_mode == "ignore":
|
|
|
|
pass
|
|
|
|
elif self.wrap_mode == "exit":
|
|
|
|
sys.exit(ret)
|
|
|
|
elif self.wrap_mode == "respawn":
|
|
|
|
now = time.time()
|
|
|
|
avg = sum(self.wrap_times)/len(self.wrap_times)
|
|
|
|
if (now - avg) < 10:
|
|
|
|
# 3 times in the last 10 seconds
|
|
|
|
if self.spawn_message:
|
2013-11-28 08:05:24 +00:00
|
|
|
self.warn("Command respawning too fast")
|
2013-03-20 10:30:38 +00:00
|
|
|
self.spawn_message = False
|
|
|
|
else:
|
|
|
|
self.run_wrap_cmd()
|
2011-05-02 04:17:04 +01:00
|
|
|
|
2012-09-20 15:46:04 +01:00
|
|
|
|
|
|
|
def _subprocess_setup():
|
|
|
|
# Python installs a SIGPIPE handler by default. This is usually not what
|
|
|
|
# non-Python successfulbprocesses expect.
|
|
|
|
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
|
|
|
|
|
|
|
|
|
2018-07-04 10:06:57 +01:00
|
|
|
try :
|
|
|
|
# First try SSL options for Python 3.4 and above
|
|
|
|
SSL_OPTIONS = {
|
|
|
|
'default': ssl.OP_ALL,
|
|
|
|
'tlsv1_1': ssl.PROTOCOL_TLS | ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 |
|
|
|
|
ssl.OP_NO_TLSv1,
|
|
|
|
'tlsv1_2': ssl.PROTOCOL_TLS | ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 |
|
|
|
|
ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1,
|
|
|
|
'tlsv1_3': ssl.PROTOCOL_TLS | ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 |
|
|
|
|
ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1 | ssl.OP_NO_TLSv1_2,
|
|
|
|
}
|
|
|
|
except AttributeError:
|
|
|
|
try:
|
|
|
|
# Python 3.3 uses a different scheme for SSL options
|
|
|
|
# tlsv1_3 is not supported on older Python versions
|
|
|
|
SSL_OPTIONS = {
|
|
|
|
'default': ssl.OP_ALL,
|
|
|
|
'tlsv1_1': ssl.PROTOCOL_TLSv1 | ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 |
|
|
|
|
ssl.OP_NO_TLSv1,
|
|
|
|
'tlsv1_2': ssl.PROTOCOL_TLSv1 | ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 |
|
|
|
|
ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1,
|
|
|
|
}
|
|
|
|
except AttributeError:
|
|
|
|
# Python 2.6 does not support TLS v1.2, and uses a different scheme
|
|
|
|
# for SSL options
|
|
|
|
SSL_OPTIONS = {
|
|
|
|
'default': ssl.PROTOCOL_SSLv23,
|
|
|
|
'tlsv1_1': ssl.PROTOCOL_TLSv1,
|
|
|
|
}
|
|
|
|
|
|
|
|
def select_ssl_version(version):
|
|
|
|
"""Returns SSL options for the most secure TSL version available on this
|
|
|
|
Python version"""
|
|
|
|
if version in SSL_OPTIONS:
|
|
|
|
return SSL_OPTIONS[version]
|
|
|
|
else:
|
|
|
|
# It so happens that version names sorted lexicographically form a list
|
|
|
|
# from the least to the most secure
|
|
|
|
keys = list(SSL_OPTIONS.keys())
|
|
|
|
keys.sort()
|
|
|
|
fallback = keys[-1]
|
|
|
|
logger = logging.getLogger(WebSocketProxy.log_prefix)
|
|
|
|
logger.warn("TLS version %s unsupported. Falling back to %s",
|
|
|
|
version, fallback)
|
|
|
|
|
|
|
|
return SSL_OPTIONS[fallback]
|
|
|
|
|
2018-07-05 00:50:48 +01:00
|
|
|
def websockify_init():
|
|
|
|
# Setup basic logging to stderr.
|
2013-10-14 18:55:37 +01:00
|
|
|
logger = logging.getLogger(WebSocketProxy.log_prefix)
|
|
|
|
logger.propagate = False
|
|
|
|
logger.setLevel(logging.INFO)
|
2018-07-05 00:50:48 +01:00
|
|
|
stderr_handler = logging.StreamHandler()
|
|
|
|
stderr_handler.setLevel(logging.DEBUG)
|
|
|
|
log_formatter = logging.Formatter("%(message)s")
|
|
|
|
stderr_handler.setFormatter(log_formatter)
|
|
|
|
logger.addHandler(stderr_handler)
|
2013-10-14 18:55:37 +01:00
|
|
|
|
2018-07-05 00:50:48 +01:00
|
|
|
# Setup optparse.
|
wsproxy, wstelnet: wrap command, WS telnet client.
wswrapper:
Getting the wswrapper.c LD_PRELOAD model working has turned out to
involve too many dark corners of the glibc/POSIX file descriptor
space. I realized that 95% of what I want can be accomplished by
adding a "wrap command" mode to wsproxy.
The code is still there for now, but consider it experimental at
best. Minor fix to dup2 and add dup and dup3 logging.
wsproxy Wrap Command:
In wsproxy wrap command mode, a command line is specified instead
of a target address and port. wsproxy then uses a much simpler
LD_PRELOAD library, rebind.so, to move intercept any bind() system
calls made by the program. If the bind() call is for the wsproxy
listen port number then the real bind() system call is issued for
an alternate (free high) port on loopback/localhost. wsproxy then
forwards from the listen address/port to the moved port.
The --wrap-mode argument takes three options that determine the
behavior of wsproxy when the wrapped command returns an exit code
(exit or daemonizing): ignore, exit, respawn.
For example, this runs vncserver on turns port 5901 into
a WebSockets port (rebind.so must be built first):
./utils/wsproxy.py --wrap-mode=ignore 5901 -- vncserver :1
The vncserver command backgrounds itself so the wrap mode is set
to "ignore" so that wsproxy keeps running even after it receives
an exit code from vncserver.
wstelnet:
To demonstrate the wrap command mode, I added WebSockets telnet
client.
For example, this runs telnetd (krb5-telnetd) on turns port 2023
into a WebSockets port (using "respawn" mode since telnetd exits
after each connection closes):
sudo ./utils/wsproxy.py --wrap-mode=respawn 2023 -- telnetd -debug 2023
Then the utils/wstelnet.html page can be used to connect to the
telnetd server on port 2023. The telnet client includes VT100.js
(from http://code.google.com/p/sshconsole) which handles the
terminal emulation and rendering.
rebind:
The rebind LD_PRELOAD library is used by wsproxy in wrap command
mode to intercept bind() system calls and move the port to
a different port on loopback/localhost. The rebind.so library can
be built by running make in the utils directory.
The rebind library can be used separately from wsproxy by setting
the REBIND_OLD_PORT and REBIND_NEW_PORT environment variables
prior to executing a command. For example:
export export REBIND_PORT_OLD="23"
export export REBIND_PORT_NEW="65023"
LD_PRELOAD=./rebind.so telnetd -debug 23
Alternately, the rebind script does the same thing:
rebind 23 65023 telnetd -debug 23
Other changes/notes:
- wsproxy no longer daemonizes by default. Remove -f/--foreground
option and add -D/--deamon option.
- When wsproxy is used to wrap a command in "respawn" mode, the
command will not be respawn more often than 3 times within 10
seconds.
- Move getKeysym routine out of Canvas object so that it can be called
directly.
2011-01-12 19:15:11 +00:00
|
|
|
usage = "\n %prog [options]"
|
2012-07-11 15:00:13 +01:00
|
|
|
usage += " [source_addr:]source_port [target_addr:target_port]"
|
wsproxy, wstelnet: wrap command, WS telnet client.
wswrapper:
Getting the wswrapper.c LD_PRELOAD model working has turned out to
involve too many dark corners of the glibc/POSIX file descriptor
space. I realized that 95% of what I want can be accomplished by
adding a "wrap command" mode to wsproxy.
The code is still there for now, but consider it experimental at
best. Minor fix to dup2 and add dup and dup3 logging.
wsproxy Wrap Command:
In wsproxy wrap command mode, a command line is specified instead
of a target address and port. wsproxy then uses a much simpler
LD_PRELOAD library, rebind.so, to move intercept any bind() system
calls made by the program. If the bind() call is for the wsproxy
listen port number then the real bind() system call is issued for
an alternate (free high) port on loopback/localhost. wsproxy then
forwards from the listen address/port to the moved port.
The --wrap-mode argument takes three options that determine the
behavior of wsproxy when the wrapped command returns an exit code
(exit or daemonizing): ignore, exit, respawn.
For example, this runs vncserver on turns port 5901 into
a WebSockets port (rebind.so must be built first):
./utils/wsproxy.py --wrap-mode=ignore 5901 -- vncserver :1
The vncserver command backgrounds itself so the wrap mode is set
to "ignore" so that wsproxy keeps running even after it receives
an exit code from vncserver.
wstelnet:
To demonstrate the wrap command mode, I added WebSockets telnet
client.
For example, this runs telnetd (krb5-telnetd) on turns port 2023
into a WebSockets port (using "respawn" mode since telnetd exits
after each connection closes):
sudo ./utils/wsproxy.py --wrap-mode=respawn 2023 -- telnetd -debug 2023
Then the utils/wstelnet.html page can be used to connect to the
telnetd server on port 2023. The telnet client includes VT100.js
(from http://code.google.com/p/sshconsole) which handles the
terminal emulation and rendering.
rebind:
The rebind LD_PRELOAD library is used by wsproxy in wrap command
mode to intercept bind() system calls and move the port to
a different port on loopback/localhost. The rebind.so library can
be built by running make in the utils directory.
The rebind library can be used separately from wsproxy by setting
the REBIND_OLD_PORT and REBIND_NEW_PORT environment variables
prior to executing a command. For example:
export export REBIND_PORT_OLD="23"
export export REBIND_PORT_NEW="65023"
LD_PRELOAD=./rebind.so telnetd -debug 23
Alternately, the rebind script does the same thing:
rebind 23 65023 telnetd -debug 23
Other changes/notes:
- wsproxy no longer daemonizes by default. Remove -f/--foreground
option and add -D/--deamon option.
- When wsproxy is used to wrap a command in "respawn" mode, the
command will not be respawn more often than 3 times within 10
seconds.
- Move getKeysym routine out of Canvas object so that it can be called
directly.
2011-01-12 19:15:11 +00:00
|
|
|
usage += "\n %prog [options]"
|
|
|
|
usage += " [source_addr:]source_port -- WRAP_COMMAND_LINE"
|
2010-06-16 18:37:03 +01:00
|
|
|
parser = optparse.OptionParser(usage=usage)
|
2010-09-11 21:10:54 +01:00
|
|
|
parser.add_option("--verbose", "-v", action="store_true",
|
2013-10-14 18:55:37 +01:00
|
|
|
help="verbose messages")
|
|
|
|
parser.add_option("--traffic", action="store_true",
|
|
|
|
help="per frame traffic")
|
2010-06-16 19:58:00 +01:00
|
|
|
parser.add_option("--record",
|
2010-09-23 14:17:00 +01:00
|
|
|
help="record sessions to FILE.[session_number]", metavar="FILE")
|
wsproxy, wstelnet: wrap command, WS telnet client.
wswrapper:
Getting the wswrapper.c LD_PRELOAD model working has turned out to
involve too many dark corners of the glibc/POSIX file descriptor
space. I realized that 95% of what I want can be accomplished by
adding a "wrap command" mode to wsproxy.
The code is still there for now, but consider it experimental at
best. Minor fix to dup2 and add dup and dup3 logging.
wsproxy Wrap Command:
In wsproxy wrap command mode, a command line is specified instead
of a target address and port. wsproxy then uses a much simpler
LD_PRELOAD library, rebind.so, to move intercept any bind() system
calls made by the program. If the bind() call is for the wsproxy
listen port number then the real bind() system call is issued for
an alternate (free high) port on loopback/localhost. wsproxy then
forwards from the listen address/port to the moved port.
The --wrap-mode argument takes three options that determine the
behavior of wsproxy when the wrapped command returns an exit code
(exit or daemonizing): ignore, exit, respawn.
For example, this runs vncserver on turns port 5901 into
a WebSockets port (rebind.so must be built first):
./utils/wsproxy.py --wrap-mode=ignore 5901 -- vncserver :1
The vncserver command backgrounds itself so the wrap mode is set
to "ignore" so that wsproxy keeps running even after it receives
an exit code from vncserver.
wstelnet:
To demonstrate the wrap command mode, I added WebSockets telnet
client.
For example, this runs telnetd (krb5-telnetd) on turns port 2023
into a WebSockets port (using "respawn" mode since telnetd exits
after each connection closes):
sudo ./utils/wsproxy.py --wrap-mode=respawn 2023 -- telnetd -debug 2023
Then the utils/wstelnet.html page can be used to connect to the
telnetd server on port 2023. The telnet client includes VT100.js
(from http://code.google.com/p/sshconsole) which handles the
terminal emulation and rendering.
rebind:
The rebind LD_PRELOAD library is used by wsproxy in wrap command
mode to intercept bind() system calls and move the port to
a different port on loopback/localhost. The rebind.so library can
be built by running make in the utils directory.
The rebind library can be used separately from wsproxy by setting
the REBIND_OLD_PORT and REBIND_NEW_PORT environment variables
prior to executing a command. For example:
export export REBIND_PORT_OLD="23"
export export REBIND_PORT_NEW="65023"
LD_PRELOAD=./rebind.so telnetd -debug 23
Alternately, the rebind script does the same thing:
rebind 23 65023 telnetd -debug 23
Other changes/notes:
- wsproxy no longer daemonizes by default. Remove -f/--foreground
option and add -D/--deamon option.
- When wsproxy is used to wrap a command in "respawn" mode, the
command will not be respawn more often than 3 times within 10
seconds.
- Move getKeysym routine out of Canvas object so that it can be called
directly.
2011-01-12 19:15:11 +00:00
|
|
|
parser.add_option("--daemon", "-D",
|
|
|
|
dest="daemon", action="store_true",
|
|
|
|
help="become a daemon (background process)")
|
2011-09-22 21:52:02 +01:00
|
|
|
parser.add_option("--run-once", action="store_true",
|
|
|
|
help="handle a single WebSocket connection and exit")
|
|
|
|
parser.add_option("--timeout", type=int, default=0,
|
|
|
|
help="after TIMEOUT seconds exit when not connected")
|
2012-08-31 15:24:09 +01:00
|
|
|
parser.add_option("--idle-timeout", type=int, default=0,
|
|
|
|
help="server exits after TIMEOUT seconds if there are no "
|
|
|
|
"active connections")
|
2010-11-06 15:55:09 +00:00
|
|
|
parser.add_option("--cert", default="self.pem",
|
|
|
|
help="SSL certificate file")
|
|
|
|
parser.add_option("--key", default=None,
|
|
|
|
help="SSL key file (if separate from cert)")
|
2019-03-04 08:31:01 +00:00
|
|
|
parser.add_option("--key-password", default=None,
|
2019-03-02 16:21:28 +00:00
|
|
|
help="SSL key password")
|
2010-06-16 19:58:00 +01:00
|
|
|
parser.add_option("--ssl-only", action="store_true",
|
2012-05-23 15:20:08 +01:00
|
|
|
help="disallow non-encrypted client connections")
|
2012-05-20 18:56:58 +01:00
|
|
|
parser.add_option("--ssl-target", action="store_true",
|
2012-05-23 15:20:08 +01:00
|
|
|
help="connect to SSL target as SSL client")
|
2017-08-29 20:24:32 +01:00
|
|
|
parser.add_option("--verify-client", action="store_true",
|
|
|
|
help="require encrypted client to present a valid certificate "
|
|
|
|
"(needs Python 2.7.9 or newer or Python 3.4 or newer)")
|
|
|
|
parser.add_option("--cafile", metavar="FILE",
|
|
|
|
help="file of concatenated certificates of authorities trusted "
|
|
|
|
"for validating clients (only effective with --verify-client). "
|
|
|
|
"If omitted, system default list of CAs is used.")
|
2018-07-04 10:06:57 +01:00
|
|
|
parser.add_option("--ssl-version", type="choice", default="default",
|
|
|
|
choices=["default", "tlsv1_1", "tlsv1_2", "tlsv1_3"], action="store",
|
|
|
|
help="minimum TLS version to use (default, tlsv1_1, tlsv1_2, tlsv1_3)")
|
|
|
|
parser.add_option("--ssl-ciphers", action="store",
|
|
|
|
help="list of ciphers allowed for connection. For a list of "
|
|
|
|
"supported ciphers run `openssl ciphers`")
|
2012-05-31 15:17:51 +01:00
|
|
|
parser.add_option("--unix-target",
|
|
|
|
help="connect to unix socket target", metavar="FILE")
|
2017-07-31 15:16:24 +01:00
|
|
|
parser.add_option("--inetd",
|
|
|
|
help="inetd mode, receive listening socket from stdin", action="store_true")
|
2011-01-07 00:26:54 +00:00
|
|
|
parser.add_option("--web", default=None, metavar="DIR",
|
|
|
|
help="run webserver on same port. Serve files from DIR.")
|
2018-07-05 00:48:08 +01:00
|
|
|
parser.add_option("--web-auth", action="store_true",
|
|
|
|
help="require authentication to access webserver.")
|
wsproxy, wstelnet: wrap command, WS telnet client.
wswrapper:
Getting the wswrapper.c LD_PRELOAD model working has turned out to
involve too many dark corners of the glibc/POSIX file descriptor
space. I realized that 95% of what I want can be accomplished by
adding a "wrap command" mode to wsproxy.
The code is still there for now, but consider it experimental at
best. Minor fix to dup2 and add dup and dup3 logging.
wsproxy Wrap Command:
In wsproxy wrap command mode, a command line is specified instead
of a target address and port. wsproxy then uses a much simpler
LD_PRELOAD library, rebind.so, to move intercept any bind() system
calls made by the program. If the bind() call is for the wsproxy
listen port number then the real bind() system call is issued for
an alternate (free high) port on loopback/localhost. wsproxy then
forwards from the listen address/port to the moved port.
The --wrap-mode argument takes three options that determine the
behavior of wsproxy when the wrapped command returns an exit code
(exit or daemonizing): ignore, exit, respawn.
For example, this runs vncserver on turns port 5901 into
a WebSockets port (rebind.so must be built first):
./utils/wsproxy.py --wrap-mode=ignore 5901 -- vncserver :1
The vncserver command backgrounds itself so the wrap mode is set
to "ignore" so that wsproxy keeps running even after it receives
an exit code from vncserver.
wstelnet:
To demonstrate the wrap command mode, I added WebSockets telnet
client.
For example, this runs telnetd (krb5-telnetd) on turns port 2023
into a WebSockets port (using "respawn" mode since telnetd exits
after each connection closes):
sudo ./utils/wsproxy.py --wrap-mode=respawn 2023 -- telnetd -debug 2023
Then the utils/wstelnet.html page can be used to connect to the
telnetd server on port 2023. The telnet client includes VT100.js
(from http://code.google.com/p/sshconsole) which handles the
terminal emulation and rendering.
rebind:
The rebind LD_PRELOAD library is used by wsproxy in wrap command
mode to intercept bind() system calls and move the port to
a different port on loopback/localhost. The rebind.so library can
be built by running make in the utils directory.
The rebind library can be used separately from wsproxy by setting
the REBIND_OLD_PORT and REBIND_NEW_PORT environment variables
prior to executing a command. For example:
export export REBIND_PORT_OLD="23"
export export REBIND_PORT_NEW="65023"
LD_PRELOAD=./rebind.so telnetd -debug 23
Alternately, the rebind script does the same thing:
rebind 23 65023 telnetd -debug 23
Other changes/notes:
- wsproxy no longer daemonizes by default. Remove -f/--foreground
option and add -D/--deamon option.
- When wsproxy is used to wrap a command in "respawn" mode, the
command will not be respawn more often than 3 times within 10
seconds.
- Move getKeysym routine out of Canvas object so that it can be called
directly.
2011-01-12 19:15:11 +00:00
|
|
|
parser.add_option("--wrap-mode", default="exit", metavar="MODE",
|
|
|
|
choices=["exit", "ignore", "respawn"],
|
|
|
|
help="action to take when the wrapped program exits "
|
|
|
|
"or daemonizes: exit (default), ignore, respawn")
|
2012-06-26 12:57:50 +01:00
|
|
|
parser.add_option("--prefer-ipv6", "-6",
|
|
|
|
action="store_true", dest="source_is_ipv6",
|
|
|
|
help="prefer IPv6 when resolving source_addr")
|
Introduce Token Plugins
Token plugins provide a generic interface for transforming a token
into a `(host, port)` tuple.
The plugin name is specified using the '--token-plugin' option,
and may either be the name of a class from `websockify.token_plugins`,
or a fully qualified python path to the token plugin class (see below).
An optional plugin parameter can be specified using the '--token-source'
option (a value of `None` will be used if no '--token-source' option is
passed).
Token plugins should inherit from `websockify.token_plugins.BasePlugin`,
and should implement the `lookup(token)` method. The value of the
'--token-source' option is available as `self.source`.
Several plugins are included by default. The `ReadOnlyTokenFile`
and `TokenFile` plugins implement functionality from '--target-config'
(with the former only reading the file(s) once, and the latter reading
them every time). The 'BaseTokenAPI' plugin fetches the value from
an API, returning the result of `process_result(response_object)`.
By default, `process_result` simply returns the text of the response,
but may be overriden. The `JSONTokenAPI` does just this, returning
the 'host' and 'port' values from the response JSON object.
The old '--target-config' option is now deprecated, and maps to the
`TokenFile` plugin under the hood.
Also-Authored-By: James Portman (@james-portman)
Closes #157
2015-03-26 20:01:57 +00:00
|
|
|
parser.add_option("--libserver", action="store_true",
|
|
|
|
help="use Python library SocketServer engine")
|
2012-07-13 19:17:56 +01:00
|
|
|
parser.add_option("--target-config", metavar="FILE",
|
|
|
|
dest="target_cfg",
|
|
|
|
help="Configuration file containing valid targets "
|
|
|
|
"in the form 'token: host:port' or, alternatively, a "
|
Introduce Token Plugins
Token plugins provide a generic interface for transforming a token
into a `(host, port)` tuple.
The plugin name is specified using the '--token-plugin' option,
and may either be the name of a class from `websockify.token_plugins`,
or a fully qualified python path to the token plugin class (see below).
An optional plugin parameter can be specified using the '--token-source'
option (a value of `None` will be used if no '--token-source' option is
passed).
Token plugins should inherit from `websockify.token_plugins.BasePlugin`,
and should implement the `lookup(token)` method. The value of the
'--token-source' option is available as `self.source`.
Several plugins are included by default. The `ReadOnlyTokenFile`
and `TokenFile` plugins implement functionality from '--target-config'
(with the former only reading the file(s) once, and the latter reading
them every time). The 'BaseTokenAPI' plugin fetches the value from
an API, returning the result of `process_result(response_object)`.
By default, `process_result` simply returns the text of the response,
but may be overriden. The `JSONTokenAPI` does just this, returning
the 'host' and 'port' values from the response JSON object.
The old '--target-config' option is now deprecated, and maps to the
`TokenFile` plugin under the hood.
Also-Authored-By: James Portman (@james-portman)
Closes #157
2015-03-26 20:01:57 +00:00
|
|
|
"directory containing configuration files of this form "
|
|
|
|
"(DEPRECATED: use `--token-plugin TokenFile --token-source "
|
|
|
|
" path/to/token/file` instead)")
|
2018-07-05 00:53:09 +01:00
|
|
|
parser.add_option("--token-plugin", default=None, metavar="CLASS",
|
|
|
|
help="use a Python class, usually one from websockify.token_plugins, "
|
|
|
|
"such as TokenFile, to process tokens into host:port pairs")
|
Introduce Token Plugins
Token plugins provide a generic interface for transforming a token
into a `(host, port)` tuple.
The plugin name is specified using the '--token-plugin' option,
and may either be the name of a class from `websockify.token_plugins`,
or a fully qualified python path to the token plugin class (see below).
An optional plugin parameter can be specified using the '--token-source'
option (a value of `None` will be used if no '--token-source' option is
passed).
Token plugins should inherit from `websockify.token_plugins.BasePlugin`,
and should implement the `lookup(token)` method. The value of the
'--token-source' option is available as `self.source`.
Several plugins are included by default. The `ReadOnlyTokenFile`
and `TokenFile` plugins implement functionality from '--target-config'
(with the former only reading the file(s) once, and the latter reading
them every time). The 'BaseTokenAPI' plugin fetches the value from
an API, returning the result of `process_result(response_object)`.
By default, `process_result` simply returns the text of the response,
but may be overriden. The `JSONTokenAPI` does just this, returning
the 'host' and 'port' values from the response JSON object.
The old '--target-config' option is now deprecated, and maps to the
`TokenFile` plugin under the hood.
Also-Authored-By: James Portman (@james-portman)
Closes #157
2015-03-26 20:01:57 +00:00
|
|
|
parser.add_option("--token-source", default=None, metavar="ARG",
|
2018-07-05 00:53:09 +01:00
|
|
|
help="an argument to be passed to the token plugin "
|
Introduce Token Plugins
Token plugins provide a generic interface for transforming a token
into a `(host, port)` tuple.
The plugin name is specified using the '--token-plugin' option,
and may either be the name of a class from `websockify.token_plugins`,
or a fully qualified python path to the token plugin class (see below).
An optional plugin parameter can be specified using the '--token-source'
option (a value of `None` will be used if no '--token-source' option is
passed).
Token plugins should inherit from `websockify.token_plugins.BasePlugin`,
and should implement the `lookup(token)` method. The value of the
'--token-source' option is available as `self.source`.
Several plugins are included by default. The `ReadOnlyTokenFile`
and `TokenFile` plugins implement functionality from '--target-config'
(with the former only reading the file(s) once, and the latter reading
them every time). The 'BaseTokenAPI' plugin fetches the value from
an API, returning the result of `process_result(response_object)`.
By default, `process_result` simply returns the text of the response,
but may be overriden. The `JSONTokenAPI` does just this, returning
the 'host' and 'port' values from the response JSON object.
The old '--target-config' option is now deprecated, and maps to the
`TokenFile` plugin under the hood.
Also-Authored-By: James Portman (@james-portman)
Closes #157
2015-03-26 20:01:57 +00:00
|
|
|
"on instantiation")
|
2018-07-05 00:54:19 +01:00
|
|
|
parser.add_option("--host-token", action="store_true",
|
|
|
|
help="use the host HTTP header as token instead of the "
|
|
|
|
"token URL query parameter")
|
2018-07-05 00:53:09 +01:00
|
|
|
parser.add_option("--auth-plugin", default=None, metavar="CLASS",
|
|
|
|
help="use a Python class, usually one from websockify.auth_plugins, "
|
|
|
|
"such as BasicHTTPAuth, to determine if a connection is allowed")
|
2015-04-28 21:17:47 +01:00
|
|
|
parser.add_option("--auth-source", default=None, metavar="ARG",
|
2018-07-05 00:53:09 +01:00
|
|
|
help="an argument to be passed to the auth plugin "
|
2015-04-28 21:17:47 +01:00
|
|
|
"on instantiation")
|
2018-07-05 00:53:09 +01:00
|
|
|
parser.add_option("--heartbeat", type=int, default=0, metavar="INTERVAL",
|
|
|
|
help="send a ping to the client every INTERVAL seconds")
|
2015-10-15 14:40:53 +01:00
|
|
|
parser.add_option("--log-file", metavar="FILE",
|
|
|
|
dest="log_file",
|
|
|
|
help="File where logs will be saved")
|
2018-07-05 00:50:48 +01:00
|
|
|
parser.add_option("--syslog", default=None, metavar="SERVER",
|
|
|
|
help="Log to syslog server. SERVER can be local socket, "
|
|
|
|
"such as /dev/log, or a UDP host:port pair.")
|
2018-08-24 03:07:14 +01:00
|
|
|
parser.add_option("--legacy-syslog", action="store_true",
|
|
|
|
help="Use the old syslog protocol instead of RFC 5424. "
|
|
|
|
"Use this if the messages produced by websockify seem abnormal.")
|
Introduce Token Plugins
Token plugins provide a generic interface for transforming a token
into a `(host, port)` tuple.
The plugin name is specified using the '--token-plugin' option,
and may either be the name of a class from `websockify.token_plugins`,
or a fully qualified python path to the token plugin class (see below).
An optional plugin parameter can be specified using the '--token-source'
option (a value of `None` will be used if no '--token-source' option is
passed).
Token plugins should inherit from `websockify.token_plugins.BasePlugin`,
and should implement the `lookup(token)` method. The value of the
'--token-source' option is available as `self.source`.
Several plugins are included by default. The `ReadOnlyTokenFile`
and `TokenFile` plugins implement functionality from '--target-config'
(with the former only reading the file(s) once, and the latter reading
them every time). The 'BaseTokenAPI' plugin fetches the value from
an API, returning the result of `process_result(response_object)`.
By default, `process_result` simply returns the text of the response,
but may be overriden. The `JSONTokenAPI` does just this, returning
the 'host' and 'port' values from the response JSON object.
The old '--target-config' option is now deprecated, and maps to the
`TokenFile` plugin under the hood.
Also-Authored-By: James Portman (@james-portman)
Closes #157
2015-03-26 20:01:57 +00:00
|
|
|
|
2011-01-08 21:29:01 +00:00
|
|
|
(opts, args) = parser.parse_args()
|
2010-06-01 23:58:14 +01:00
|
|
|
|
2018-08-24 03:07:14 +01:00
|
|
|
|
|
|
|
# Validate options.
|
|
|
|
|
|
|
|
if opts.token_source and not opts.token_plugin:
|
|
|
|
parser.error("You must use --token-plugin to use --token-source")
|
|
|
|
|
|
|
|
if opts.host_token and not opts.token_plugin:
|
|
|
|
parser.error("You must use --token-plugin to use --host-token")
|
|
|
|
|
|
|
|
if opts.auth_source and not opts.auth_plugin:
|
|
|
|
parser.error("You must use --auth-plugin to use --auth-source")
|
|
|
|
|
|
|
|
if opts.web_auth and not opts.auth_plugin:
|
|
|
|
parser.error("You must use --auth-plugin to use --web-auth")
|
|
|
|
|
|
|
|
if opts.web_auth and not opts.web:
|
|
|
|
parser.error("You must use --web to use --web-auth")
|
|
|
|
|
|
|
|
if opts.legacy_syslog and not opts.syslog:
|
|
|
|
parser.error("You must use --syslog to use --legacy-syslog")
|
|
|
|
|
|
|
|
|
2018-07-04 10:06:57 +01:00
|
|
|
opts.ssl_options = select_ssl_version(opts.ssl_version)
|
|
|
|
del opts.ssl_version
|
|
|
|
|
2018-08-24 03:07:14 +01:00
|
|
|
|
2015-10-15 14:40:53 +01:00
|
|
|
if opts.log_file:
|
2018-07-05 00:50:48 +01:00
|
|
|
# Setup logging to user-specified file.
|
2015-10-15 14:40:53 +01:00
|
|
|
opts.log_file = os.path.abspath(opts.log_file)
|
2018-07-05 00:50:48 +01:00
|
|
|
log_file_handler = logging.FileHandler(opts.log_file)
|
|
|
|
log_file_handler.setLevel(logging.DEBUG)
|
|
|
|
log_file_handler.setFormatter(log_formatter)
|
|
|
|
logger.addHandler(log_file_handler)
|
2015-10-15 14:40:53 +01:00
|
|
|
|
|
|
|
del opts.log_file
|
|
|
|
|
2018-07-05 00:50:48 +01:00
|
|
|
if opts.syslog:
|
|
|
|
# Determine how to connect to syslog...
|
|
|
|
if opts.syslog.count(':'):
|
|
|
|
# User supplied a host:port pair.
|
|
|
|
syslog_host, syslog_port = opts.syslog.rsplit(':', 1)
|
|
|
|
try:
|
|
|
|
syslog_port = int(syslog_port)
|
|
|
|
except ValueError:
|
|
|
|
parser.error("Error parsing syslog port")
|
|
|
|
syslog_dest = (syslog_host, syslog_port)
|
|
|
|
else:
|
|
|
|
# User supplied a local socket file.
|
|
|
|
syslog_dest = os.path.abspath(opts.syslog)
|
|
|
|
|
2018-08-24 03:07:14 +01:00
|
|
|
from websockify.sysloghandler import WebsockifySysLogHandler
|
2018-07-05 00:50:48 +01:00
|
|
|
|
|
|
|
# Determine syslog facility.
|
|
|
|
if opts.daemon:
|
2018-08-24 03:07:14 +01:00
|
|
|
syslog_facility = WebsockifySysLogHandler.LOG_DAEMON
|
2018-07-05 00:50:48 +01:00
|
|
|
else:
|
2018-08-24 03:07:14 +01:00
|
|
|
syslog_facility = WebsockifySysLogHandler.LOG_USER
|
2018-07-05 00:50:48 +01:00
|
|
|
|
|
|
|
# Start logging to syslog.
|
2018-08-24 03:07:14 +01:00
|
|
|
syslog_handler = WebsockifySysLogHandler(address=syslog_dest,
|
|
|
|
facility=syslog_facility,
|
|
|
|
ident='websockify',
|
|
|
|
legacy=opts.legacy_syslog)
|
2018-07-05 00:50:48 +01:00
|
|
|
syslog_handler.setLevel(logging.DEBUG)
|
|
|
|
syslog_handler.setFormatter(log_formatter)
|
|
|
|
logger.addHandler(syslog_handler)
|
|
|
|
|
|
|
|
del opts.syslog
|
2018-08-24 03:07:14 +01:00
|
|
|
del opts.legacy_syslog
|
2018-07-05 00:50:48 +01:00
|
|
|
|
2013-10-14 18:55:37 +01:00
|
|
|
if opts.verbose:
|
2018-07-05 00:50:48 +01:00
|
|
|
logger.setLevel(logging.DEBUG)
|
|
|
|
|
|
|
|
|
Introduce Token Plugins
Token plugins provide a generic interface for transforming a token
into a `(host, port)` tuple.
The plugin name is specified using the '--token-plugin' option,
and may either be the name of a class from `websockify.token_plugins`,
or a fully qualified python path to the token plugin class (see below).
An optional plugin parameter can be specified using the '--token-source'
option (a value of `None` will be used if no '--token-source' option is
passed).
Token plugins should inherit from `websockify.token_plugins.BasePlugin`,
and should implement the `lookup(token)` method. The value of the
'--token-source' option is available as `self.source`.
Several plugins are included by default. The `ReadOnlyTokenFile`
and `TokenFile` plugins implement functionality from '--target-config'
(with the former only reading the file(s) once, and the latter reading
them every time). The 'BaseTokenAPI' plugin fetches the value from
an API, returning the result of `process_result(response_object)`.
By default, `process_result` simply returns the text of the response,
but may be overriden. The `JSONTokenAPI` does just this, returning
the 'host' and 'port' values from the response JSON object.
The old '--target-config' option is now deprecated, and maps to the
`TokenFile` plugin under the hood.
Also-Authored-By: James Portman (@james-portman)
Closes #157
2015-03-26 20:01:57 +00:00
|
|
|
# Transform to absolute path as daemon may chdir
|
|
|
|
if opts.target_cfg:
|
|
|
|
opts.target_cfg = os.path.abspath(opts.target_cfg)
|
|
|
|
|
|
|
|
if opts.target_cfg:
|
|
|
|
opts.token_plugin = 'TokenFile'
|
|
|
|
opts.token_source = opts.target_cfg
|
2015-04-09 16:36:37 +01:00
|
|
|
|
|
|
|
del opts.target_cfg
|
Introduce Token Plugins
Token plugins provide a generic interface for transforming a token
into a `(host, port)` tuple.
The plugin name is specified using the '--token-plugin' option,
and may either be the name of a class from `websockify.token_plugins`,
or a fully qualified python path to the token plugin class (see below).
An optional plugin parameter can be specified using the '--token-source'
option (a value of `None` will be used if no '--token-source' option is
passed).
Token plugins should inherit from `websockify.token_plugins.BasePlugin`,
and should implement the `lookup(token)` method. The value of the
'--token-source' option is available as `self.source`.
Several plugins are included by default. The `ReadOnlyTokenFile`
and `TokenFile` plugins implement functionality from '--target-config'
(with the former only reading the file(s) once, and the latter reading
them every time). The 'BaseTokenAPI' plugin fetches the value from
an API, returning the result of `process_result(response_object)`.
By default, `process_result` simply returns the text of the response,
but may be overriden. The `JSONTokenAPI` does just this, returning
the 'host' and 'port' values from the response JSON object.
The old '--target-config' option is now deprecated, and maps to the
`TokenFile` plugin under the hood.
Also-Authored-By: James Portman (@james-portman)
Closes #157
2015-03-26 20:01:57 +00:00
|
|
|
|
wsproxy, wstelnet: wrap command, WS telnet client.
wswrapper:
Getting the wswrapper.c LD_PRELOAD model working has turned out to
involve too many dark corners of the glibc/POSIX file descriptor
space. I realized that 95% of what I want can be accomplished by
adding a "wrap command" mode to wsproxy.
The code is still there for now, but consider it experimental at
best. Minor fix to dup2 and add dup and dup3 logging.
wsproxy Wrap Command:
In wsproxy wrap command mode, a command line is specified instead
of a target address and port. wsproxy then uses a much simpler
LD_PRELOAD library, rebind.so, to move intercept any bind() system
calls made by the program. If the bind() call is for the wsproxy
listen port number then the real bind() system call is issued for
an alternate (free high) port on loopback/localhost. wsproxy then
forwards from the listen address/port to the moved port.
The --wrap-mode argument takes three options that determine the
behavior of wsproxy when the wrapped command returns an exit code
(exit or daemonizing): ignore, exit, respawn.
For example, this runs vncserver on turns port 5901 into
a WebSockets port (rebind.so must be built first):
./utils/wsproxy.py --wrap-mode=ignore 5901 -- vncserver :1
The vncserver command backgrounds itself so the wrap mode is set
to "ignore" so that wsproxy keeps running even after it receives
an exit code from vncserver.
wstelnet:
To demonstrate the wrap command mode, I added WebSockets telnet
client.
For example, this runs telnetd (krb5-telnetd) on turns port 2023
into a WebSockets port (using "respawn" mode since telnetd exits
after each connection closes):
sudo ./utils/wsproxy.py --wrap-mode=respawn 2023 -- telnetd -debug 2023
Then the utils/wstelnet.html page can be used to connect to the
telnetd server on port 2023. The telnet client includes VT100.js
(from http://code.google.com/p/sshconsole) which handles the
terminal emulation and rendering.
rebind:
The rebind LD_PRELOAD library is used by wsproxy in wrap command
mode to intercept bind() system calls and move the port to
a different port on loopback/localhost. The rebind.so library can
be built by running make in the utils directory.
The rebind library can be used separately from wsproxy by setting
the REBIND_OLD_PORT and REBIND_NEW_PORT environment variables
prior to executing a command. For example:
export export REBIND_PORT_OLD="23"
export export REBIND_PORT_NEW="65023"
LD_PRELOAD=./rebind.so telnetd -debug 23
Alternately, the rebind script does the same thing:
rebind 23 65023 telnetd -debug 23
Other changes/notes:
- wsproxy no longer daemonizes by default. Remove -f/--foreground
option and add -D/--deamon option.
- When wsproxy is used to wrap a command in "respawn" mode, the
command will not be respawn more often than 3 times within 10
seconds.
- Move getKeysym routine out of Canvas object so that it can be called
directly.
2011-01-12 19:15:11 +00:00
|
|
|
if sys.argv.count('--'):
|
|
|
|
opts.wrap_cmd = args[1:]
|
|
|
|
else:
|
|
|
|
opts.wrap_cmd = None
|
2011-01-08 21:29:01 +00:00
|
|
|
|
2016-09-16 17:50:55 +01:00
|
|
|
if not websockifyserver.ssl and opts.ssl_target:
|
2012-05-20 18:56:58 +01:00
|
|
|
parser.error("SSL target requested and Python SSL module not loaded.");
|
2012-09-20 15:46:04 +01:00
|
|
|
|
2011-01-08 21:29:01 +00:00
|
|
|
if opts.ssl_only and not os.path.exists(opts.cert):
|
|
|
|
parser.error("SSL only and %s not found" % opts.cert)
|
|
|
|
|
2017-07-31 15:16:24 +01:00
|
|
|
if opts.inetd:
|
|
|
|
opts.listen_fd = sys.stdin.fileno()
|
2010-06-16 18:37:03 +01:00
|
|
|
else:
|
2017-07-31 15:16:24 +01:00
|
|
|
if len(args) < 1:
|
|
|
|
parser.error("Too few arguments")
|
|
|
|
arg = args.pop(0)
|
|
|
|
# Parse host:port and convert ports to numbers
|
|
|
|
if arg.count(':') > 0:
|
|
|
|
opts.listen_host, opts.listen_port = arg.rsplit(':', 1)
|
|
|
|
opts.listen_host = opts.listen_host.strip('[]')
|
|
|
|
else:
|
|
|
|
opts.listen_host, opts.listen_port = '', arg
|
2011-07-07 21:13:02 +01:00
|
|
|
|
2017-11-10 10:18:32 +00:00
|
|
|
try:
|
|
|
|
opts.listen_port = int(opts.listen_port)
|
|
|
|
except ValueError:
|
|
|
|
parser.error("Error parsing listen port")
|
2017-07-31 15:16:24 +01:00
|
|
|
|
|
|
|
del opts.inetd
|
2011-07-07 21:13:02 +01:00
|
|
|
|
Introduce Token Plugins
Token plugins provide a generic interface for transforming a token
into a `(host, port)` tuple.
The plugin name is specified using the '--token-plugin' option,
and may either be the name of a class from `websockify.token_plugins`,
or a fully qualified python path to the token plugin class (see below).
An optional plugin parameter can be specified using the '--token-source'
option (a value of `None` will be used if no '--token-source' option is
passed).
Token plugins should inherit from `websockify.token_plugins.BasePlugin`,
and should implement the `lookup(token)` method. The value of the
'--token-source' option is available as `self.source`.
Several plugins are included by default. The `ReadOnlyTokenFile`
and `TokenFile` plugins implement functionality from '--target-config'
(with the former only reading the file(s) once, and the latter reading
them every time). The 'BaseTokenAPI' plugin fetches the value from
an API, returning the result of `process_result(response_object)`.
By default, `process_result` simply returns the text of the response,
but may be overriden. The `JSONTokenAPI` does just this, returning
the 'host' and 'port' values from the response JSON object.
The old '--target-config' option is now deprecated, and maps to the
`TokenFile` plugin under the hood.
Also-Authored-By: James Portman (@james-portman)
Closes #157
2015-03-26 20:01:57 +00:00
|
|
|
if opts.wrap_cmd or opts.unix_target or opts.token_plugin:
|
wsproxy, wstelnet: wrap command, WS telnet client.
wswrapper:
Getting the wswrapper.c LD_PRELOAD model working has turned out to
involve too many dark corners of the glibc/POSIX file descriptor
space. I realized that 95% of what I want can be accomplished by
adding a "wrap command" mode to wsproxy.
The code is still there for now, but consider it experimental at
best. Minor fix to dup2 and add dup and dup3 logging.
wsproxy Wrap Command:
In wsproxy wrap command mode, a command line is specified instead
of a target address and port. wsproxy then uses a much simpler
LD_PRELOAD library, rebind.so, to move intercept any bind() system
calls made by the program. If the bind() call is for the wsproxy
listen port number then the real bind() system call is issued for
an alternate (free high) port on loopback/localhost. wsproxy then
forwards from the listen address/port to the moved port.
The --wrap-mode argument takes three options that determine the
behavior of wsproxy when the wrapped command returns an exit code
(exit or daemonizing): ignore, exit, respawn.
For example, this runs vncserver on turns port 5901 into
a WebSockets port (rebind.so must be built first):
./utils/wsproxy.py --wrap-mode=ignore 5901 -- vncserver :1
The vncserver command backgrounds itself so the wrap mode is set
to "ignore" so that wsproxy keeps running even after it receives
an exit code from vncserver.
wstelnet:
To demonstrate the wrap command mode, I added WebSockets telnet
client.
For example, this runs telnetd (krb5-telnetd) on turns port 2023
into a WebSockets port (using "respawn" mode since telnetd exits
after each connection closes):
sudo ./utils/wsproxy.py --wrap-mode=respawn 2023 -- telnetd -debug 2023
Then the utils/wstelnet.html page can be used to connect to the
telnetd server on port 2023. The telnet client includes VT100.js
(from http://code.google.com/p/sshconsole) which handles the
terminal emulation and rendering.
rebind:
The rebind LD_PRELOAD library is used by wsproxy in wrap command
mode to intercept bind() system calls and move the port to
a different port on loopback/localhost. The rebind.so library can
be built by running make in the utils directory.
The rebind library can be used separately from wsproxy by setting
the REBIND_OLD_PORT and REBIND_NEW_PORT environment variables
prior to executing a command. For example:
export export REBIND_PORT_OLD="23"
export export REBIND_PORT_NEW="65023"
LD_PRELOAD=./rebind.so telnetd -debug 23
Alternately, the rebind script does the same thing:
rebind 23 65023 telnetd -debug 23
Other changes/notes:
- wsproxy no longer daemonizes by default. Remove -f/--foreground
option and add -D/--deamon option.
- When wsproxy is used to wrap a command in "respawn" mode, the
command will not be respawn more often than 3 times within 10
seconds.
- Move getKeysym routine out of Canvas object so that it can be called
directly.
2011-01-12 19:15:11 +00:00
|
|
|
opts.target_host = None
|
|
|
|
opts.target_port = None
|
|
|
|
else:
|
2017-07-31 15:16:24 +01:00
|
|
|
if len(args) < 1:
|
|
|
|
parser.error("Too few arguments")
|
|
|
|
arg = args.pop(0)
|
|
|
|
if arg.count(':') > 0:
|
|
|
|
opts.target_host, opts.target_port = arg.rsplit(':', 1)
|
2012-06-26 12:55:19 +01:00
|
|
|
opts.target_host = opts.target_host.strip('[]')
|
wsproxy, wstelnet: wrap command, WS telnet client.
wswrapper:
Getting the wswrapper.c LD_PRELOAD model working has turned out to
involve too many dark corners of the glibc/POSIX file descriptor
space. I realized that 95% of what I want can be accomplished by
adding a "wrap command" mode to wsproxy.
The code is still there for now, but consider it experimental at
best. Minor fix to dup2 and add dup and dup3 logging.
wsproxy Wrap Command:
In wsproxy wrap command mode, a command line is specified instead
of a target address and port. wsproxy then uses a much simpler
LD_PRELOAD library, rebind.so, to move intercept any bind() system
calls made by the program. If the bind() call is for the wsproxy
listen port number then the real bind() system call is issued for
an alternate (free high) port on loopback/localhost. wsproxy then
forwards from the listen address/port to the moved port.
The --wrap-mode argument takes three options that determine the
behavior of wsproxy when the wrapped command returns an exit code
(exit or daemonizing): ignore, exit, respawn.
For example, this runs vncserver on turns port 5901 into
a WebSockets port (rebind.so must be built first):
./utils/wsproxy.py --wrap-mode=ignore 5901 -- vncserver :1
The vncserver command backgrounds itself so the wrap mode is set
to "ignore" so that wsproxy keeps running even after it receives
an exit code from vncserver.
wstelnet:
To demonstrate the wrap command mode, I added WebSockets telnet
client.
For example, this runs telnetd (krb5-telnetd) on turns port 2023
into a WebSockets port (using "respawn" mode since telnetd exits
after each connection closes):
sudo ./utils/wsproxy.py --wrap-mode=respawn 2023 -- telnetd -debug 2023
Then the utils/wstelnet.html page can be used to connect to the
telnetd server on port 2023. The telnet client includes VT100.js
(from http://code.google.com/p/sshconsole) which handles the
terminal emulation and rendering.
rebind:
The rebind LD_PRELOAD library is used by wsproxy in wrap command
mode to intercept bind() system calls and move the port to
a different port on loopback/localhost. The rebind.so library can
be built by running make in the utils directory.
The rebind library can be used separately from wsproxy by setting
the REBIND_OLD_PORT and REBIND_NEW_PORT environment variables
prior to executing a command. For example:
export export REBIND_PORT_OLD="23"
export export REBIND_PORT_NEW="65023"
LD_PRELOAD=./rebind.so telnetd -debug 23
Alternately, the rebind script does the same thing:
rebind 23 65023 telnetd -debug 23
Other changes/notes:
- wsproxy no longer daemonizes by default. Remove -f/--foreground
option and add -D/--deamon option.
- When wsproxy is used to wrap a command in "respawn" mode, the
command will not be respawn more often than 3 times within 10
seconds.
- Move getKeysym routine out of Canvas object so that it can be called
directly.
2011-01-12 19:15:11 +00:00
|
|
|
else:
|
2012-05-31 15:17:51 +01:00
|
|
|
parser.error("Error parsing target")
|
2017-11-10 10:18:32 +00:00
|
|
|
|
|
|
|
try:
|
|
|
|
opts.target_port = int(opts.target_port)
|
|
|
|
except ValueError:
|
|
|
|
parser.error("Error parsing target port")
|
2010-06-01 23:58:14 +01:00
|
|
|
|
2017-07-31 15:16:24 +01:00
|
|
|
if len(args) > 0 and opts.wrap_cmd == None:
|
|
|
|
parser.error("Too many arguments")
|
|
|
|
|
2015-04-28 22:08:36 +01:00
|
|
|
if opts.token_plugin is not None:
|
|
|
|
if '.' not in opts.token_plugin:
|
|
|
|
opts.token_plugin = (
|
|
|
|
'websockify.token_plugins.%s' % opts.token_plugin)
|
|
|
|
|
|
|
|
token_plugin_module, token_plugin_cls = opts.token_plugin.rsplit('.', 1)
|
|
|
|
|
|
|
|
__import__(token_plugin_module)
|
|
|
|
token_plugin_cls = getattr(sys.modules[token_plugin_module], token_plugin_cls)
|
|
|
|
|
|
|
|
opts.token_plugin = token_plugin_cls(opts.token_source)
|
|
|
|
|
|
|
|
del opts.token_source
|
|
|
|
|
|
|
|
if opts.auth_plugin is not None:
|
|
|
|
if '.' not in opts.auth_plugin:
|
|
|
|
opts.auth_plugin = 'websockify.auth_plugins.%s' % opts.auth_plugin
|
|
|
|
|
|
|
|
auth_plugin_module, auth_plugin_cls = opts.auth_plugin.rsplit('.', 1)
|
|
|
|
|
|
|
|
__import__(auth_plugin_module)
|
|
|
|
auth_plugin_cls = getattr(sys.modules[auth_plugin_module], auth_plugin_cls)
|
|
|
|
|
|
|
|
opts.auth_plugin = auth_plugin_cls(opts.auth_source)
|
|
|
|
|
|
|
|
del opts.auth_source
|
|
|
|
|
2011-01-08 21:29:01 +00:00
|
|
|
# Create and start the WebSockets proxy
|
Try to solve https://github.com/kanaka/websockify/issues/71 by
refactoring. Basically, we are dividing WebSocketServer into two
classes: One request handler following the SocketServer Requesthandler
API, and one optional server engine. The standard Python SocketServer
engine can also be used.
websocketproxy.py has been updated to match the API change. I've also
added a new option --libserver in order to use the Python built in
server instead.
I've done a lot of testing with the new code. This includes: verbose,
daemon, run-once, timeout, idle-timeout, ssl, web, libserver. I've
tested both Python 2 and 3. I've also tested websocket.py in another
external service.
Code details follows:
* The new request handler class is called WebSocketRequestHandler,
inheriting SimpleHTTPRequestHandler.
* The service engine is called WebSocketServer, just like before.
* do_websocket_handshake: Using send_header() etc, instead of manually
sending HTTP response.
* A new method called handle_websocket() upgrades the connection to
WebSocket, if requested. Otherwise, it returns False. A typical
application use is:
def do_GET(self):
if not self.handle_websocket():
# handle normal requests
* new_client has been renamed to new_websocket_client, in order to
have a better name in the SocketServer/HTTPServer request handler
hierarchy.
* Note that in the request handler, configuration variables must be
provided by the "server" object, ie self.server.target_host.
2013-03-14 15:07:40 +00:00
|
|
|
libserver = opts.libserver
|
|
|
|
del opts.libserver
|
|
|
|
if libserver:
|
|
|
|
# Use standard Python SocketServer framework
|
2013-03-20 10:34:46 +00:00
|
|
|
server = LibProxyServer(**opts.__dict__)
|
2013-03-18 12:25:53 +00:00
|
|
|
server.serve_forever()
|
Try to solve https://github.com/kanaka/websockify/issues/71 by
refactoring. Basically, we are dividing WebSocketServer into two
classes: One request handler following the SocketServer Requesthandler
API, and one optional server engine. The standard Python SocketServer
engine can also be used.
websocketproxy.py has been updated to match the API change. I've also
added a new option --libserver in order to use the Python built in
server instead.
I've done a lot of testing with the new code. This includes: verbose,
daemon, run-once, timeout, idle-timeout, ssl, web, libserver. I've
tested both Python 2 and 3. I've also tested websocket.py in another
external service.
Code details follows:
* The new request handler class is called WebSocketRequestHandler,
inheriting SimpleHTTPRequestHandler.
* The service engine is called WebSocketServer, just like before.
* do_websocket_handshake: Using send_header() etc, instead of manually
sending HTTP response.
* A new method called handle_websocket() upgrades the connection to
WebSocket, if requested. Otherwise, it returns False. A typical
application use is:
def do_GET(self):
if not self.handle_websocket():
# handle normal requests
* new_client has been renamed to new_websocket_client, in order to
have a better name in the SocketServer/HTTPServer request handler
hierarchy.
* Note that in the request handler, configuration variables must be
provided by the "server" object, ie self.server.target_host.
2013-03-14 15:07:40 +00:00
|
|
|
else:
|
|
|
|
# Use internal service framework
|
2013-03-20 10:34:46 +00:00
|
|
|
server = WebSocketProxy(**opts.__dict__)
|
2013-03-18 12:25:53 +00:00
|
|
|
server.start_server()
|
Try to solve https://github.com/kanaka/websockify/issues/71 by
refactoring. Basically, we are dividing WebSocketServer into two
classes: One request handler following the SocketServer Requesthandler
API, and one optional server engine. The standard Python SocketServer
engine can also be used.
websocketproxy.py has been updated to match the API change. I've also
added a new option --libserver in order to use the Python built in
server instead.
I've done a lot of testing with the new code. This includes: verbose,
daemon, run-once, timeout, idle-timeout, ssl, web, libserver. I've
tested both Python 2 and 3. I've also tested websocket.py in another
external service.
Code details follows:
* The new request handler class is called WebSocketRequestHandler,
inheriting SimpleHTTPRequestHandler.
* The service engine is called WebSocketServer, just like before.
* do_websocket_handshake: Using send_header() etc, instead of manually
sending HTTP response.
* A new method called handle_websocket() upgrades the connection to
WebSocket, if requested. Otherwise, it returns False. A typical
application use is:
def do_GET(self):
if not self.handle_websocket():
# handle normal requests
* new_client has been renamed to new_websocket_client, in order to
have a better name in the SocketServer/HTTPServer request handler
hierarchy.
* Note that in the request handler, configuration variables must be
provided by the "server" object, ie self.server.target_host.
2013-03-14 15:07:40 +00:00
|
|
|
|
|
|
|
|
2019-04-02 16:03:08 +01:00
|
|
|
class LibProxyServer(ThreadingMixIn, HTTPServer):
|
Try to solve https://github.com/kanaka/websockify/issues/71 by
refactoring. Basically, we are dividing WebSocketServer into two
classes: One request handler following the SocketServer Requesthandler
API, and one optional server engine. The standard Python SocketServer
engine can also be used.
websocketproxy.py has been updated to match the API change. I've also
added a new option --libserver in order to use the Python built in
server instead.
I've done a lot of testing with the new code. This includes: verbose,
daemon, run-once, timeout, idle-timeout, ssl, web, libserver. I've
tested both Python 2 and 3. I've also tested websocket.py in another
external service.
Code details follows:
* The new request handler class is called WebSocketRequestHandler,
inheriting SimpleHTTPRequestHandler.
* The service engine is called WebSocketServer, just like before.
* do_websocket_handshake: Using send_header() etc, instead of manually
sending HTTP response.
* A new method called handle_websocket() upgrades the connection to
WebSocket, if requested. Otherwise, it returns False. A typical
application use is:
def do_GET(self):
if not self.handle_websocket():
# handle normal requests
* new_client has been renamed to new_websocket_client, in order to
have a better name in the SocketServer/HTTPServer request handler
hierarchy.
* Note that in the request handler, configuration variables must be
provided by the "server" object, ie self.server.target_host.
2013-03-14 15:07:40 +00:00
|
|
|
"""
|
2013-03-18 12:22:48 +00:00
|
|
|
Just like WebSocketProxy, but uses standard Python SocketServer
|
Try to solve https://github.com/kanaka/websockify/issues/71 by
refactoring. Basically, we are dividing WebSocketServer into two
classes: One request handler following the SocketServer Requesthandler
API, and one optional server engine. The standard Python SocketServer
engine can also be used.
websocketproxy.py has been updated to match the API change. I've also
added a new option --libserver in order to use the Python built in
server instead.
I've done a lot of testing with the new code. This includes: verbose,
daemon, run-once, timeout, idle-timeout, ssl, web, libserver. I've
tested both Python 2 and 3. I've also tested websocket.py in another
external service.
Code details follows:
* The new request handler class is called WebSocketRequestHandler,
inheriting SimpleHTTPRequestHandler.
* The service engine is called WebSocketServer, just like before.
* do_websocket_handshake: Using send_header() etc, instead of manually
sending HTTP response.
* A new method called handle_websocket() upgrades the connection to
WebSocket, if requested. Otherwise, it returns False. A typical
application use is:
def do_GET(self):
if not self.handle_websocket():
# handle normal requests
* new_client has been renamed to new_websocket_client, in order to
have a better name in the SocketServer/HTTPServer request handler
hierarchy.
* Note that in the request handler, configuration variables must be
provided by the "server" object, ie self.server.target_host.
2013-03-14 15:07:40 +00:00
|
|
|
framework.
|
|
|
|
"""
|
|
|
|
|
2013-03-20 10:34:46 +00:00
|
|
|
def __init__(self, RequestHandlerClass=ProxyRequestHandler, **kwargs):
|
Try to solve https://github.com/kanaka/websockify/issues/71 by
refactoring. Basically, we are dividing WebSocketServer into two
classes: One request handler following the SocketServer Requesthandler
API, and one optional server engine. The standard Python SocketServer
engine can also be used.
websocketproxy.py has been updated to match the API change. I've also
added a new option --libserver in order to use the Python built in
server instead.
I've done a lot of testing with the new code. This includes: verbose,
daemon, run-once, timeout, idle-timeout, ssl, web, libserver. I've
tested both Python 2 and 3. I've also tested websocket.py in another
external service.
Code details follows:
* The new request handler class is called WebSocketRequestHandler,
inheriting SimpleHTTPRequestHandler.
* The service engine is called WebSocketServer, just like before.
* do_websocket_handshake: Using send_header() etc, instead of manually
sending HTTP response.
* A new method called handle_websocket() upgrades the connection to
WebSocket, if requested. Otherwise, it returns False. A typical
application use is:
def do_GET(self):
if not self.handle_websocket():
# handle normal requests
* new_client has been renamed to new_websocket_client, in order to
have a better name in the SocketServer/HTTPServer request handler
hierarchy.
* Note that in the request handler, configuration variables must be
provided by the "server" object, ie self.server.target_host.
2013-03-14 15:07:40 +00:00
|
|
|
# Save off proxy specific options
|
|
|
|
self.target_host = kwargs.pop('target_host', None)
|
|
|
|
self.target_port = kwargs.pop('target_port', None)
|
|
|
|
self.wrap_cmd = kwargs.pop('wrap_cmd', None)
|
|
|
|
self.wrap_mode = kwargs.pop('wrap_mode', None)
|
|
|
|
self.unix_target = kwargs.pop('unix_target', None)
|
|
|
|
self.ssl_target = kwargs.pop('ssl_target', None)
|
2015-04-09 16:36:37 +01:00
|
|
|
self.token_plugin = kwargs.pop('token_plugin', None)
|
2015-04-28 21:17:47 +01:00
|
|
|
self.auth_plugin = kwargs.pop('auth_plugin', None)
|
2015-04-10 19:14:31 +01:00
|
|
|
self.heartbeat = kwargs.pop('heartbeat', None)
|
2015-04-09 16:36:37 +01:00
|
|
|
|
|
|
|
self.token_plugin = None
|
2015-04-28 21:17:47 +01:00
|
|
|
self.auth_plugin = None
|
Try to solve https://github.com/kanaka/websockify/issues/71 by
refactoring. Basically, we are dividing WebSocketServer into two
classes: One request handler following the SocketServer Requesthandler
API, and one optional server engine. The standard Python SocketServer
engine can also be used.
websocketproxy.py has been updated to match the API change. I've also
added a new option --libserver in order to use the Python built in
server instead.
I've done a lot of testing with the new code. This includes: verbose,
daemon, run-once, timeout, idle-timeout, ssl, web, libserver. I've
tested both Python 2 and 3. I've also tested websocket.py in another
external service.
Code details follows:
* The new request handler class is called WebSocketRequestHandler,
inheriting SimpleHTTPRequestHandler.
* The service engine is called WebSocketServer, just like before.
* do_websocket_handshake: Using send_header() etc, instead of manually
sending HTTP response.
* A new method called handle_websocket() upgrades the connection to
WebSocket, if requested. Otherwise, it returns False. A typical
application use is:
def do_GET(self):
if not self.handle_websocket():
# handle normal requests
* new_client has been renamed to new_websocket_client, in order to
have a better name in the SocketServer/HTTPServer request handler
hierarchy.
* Note that in the request handler, configuration variables must be
provided by the "server" object, ie self.server.target_host.
2013-03-14 15:07:40 +00:00
|
|
|
self.daemon = False
|
|
|
|
|
|
|
|
# Server configuration
|
|
|
|
listen_host = kwargs.pop('listen_host', '')
|
|
|
|
listen_port = kwargs.pop('listen_port', None)
|
|
|
|
web = kwargs.pop('web', '')
|
|
|
|
|
|
|
|
# Configuration affecting base request handler
|
|
|
|
self.only_upgrade = not web
|
|
|
|
self.verbose = kwargs.pop('verbose', False)
|
|
|
|
record = kwargs.pop('record', '')
|
|
|
|
if record:
|
|
|
|
self.record = os.path.abspath(record)
|
|
|
|
self.run_once = kwargs.pop('run_once', False)
|
|
|
|
self.handler_id = 0
|
|
|
|
|
|
|
|
for arg in kwargs.keys():
|
|
|
|
print("warning: option %s ignored when using --libserver" % arg)
|
|
|
|
|
|
|
|
if web:
|
|
|
|
os.chdir(web)
|
Introduce Token Plugins
Token plugins provide a generic interface for transforming a token
into a `(host, port)` tuple.
The plugin name is specified using the '--token-plugin' option,
and may either be the name of a class from `websockify.token_plugins`,
or a fully qualified python path to the token plugin class (see below).
An optional plugin parameter can be specified using the '--token-source'
option (a value of `None` will be used if no '--token-source' option is
passed).
Token plugins should inherit from `websockify.token_plugins.BasePlugin`,
and should implement the `lookup(token)` method. The value of the
'--token-source' option is available as `self.source`.
Several plugins are included by default. The `ReadOnlyTokenFile`
and `TokenFile` plugins implement functionality from '--target-config'
(with the former only reading the file(s) once, and the latter reading
them every time). The 'BaseTokenAPI' plugin fetches the value from
an API, returning the result of `process_result(response_object)`.
By default, `process_result` simply returns the text of the response,
but may be overriden. The `JSONTokenAPI` does just this, returning
the 'host' and 'port' values from the response JSON object.
The old '--target-config' option is now deprecated, and maps to the
`TokenFile` plugin under the hood.
Also-Authored-By: James Portman (@james-portman)
Closes #157
2015-03-26 20:01:57 +00:00
|
|
|
|
|
|
|
HTTPServer.__init__(self, (listen_host, listen_port),
|
2013-03-20 14:09:58 +00:00
|
|
|
RequestHandlerClass)
|
Try to solve https://github.com/kanaka/websockify/issues/71 by
refactoring. Basically, we are dividing WebSocketServer into two
classes: One request handler following the SocketServer Requesthandler
API, and one optional server engine. The standard Python SocketServer
engine can also be used.
websocketproxy.py has been updated to match the API change. I've also
added a new option --libserver in order to use the Python built in
server instead.
I've done a lot of testing with the new code. This includes: verbose,
daemon, run-once, timeout, idle-timeout, ssl, web, libserver. I've
tested both Python 2 and 3. I've also tested websocket.py in another
external service.
Code details follows:
* The new request handler class is called WebSocketRequestHandler,
inheriting SimpleHTTPRequestHandler.
* The service engine is called WebSocketServer, just like before.
* do_websocket_handshake: Using send_header() etc, instead of manually
sending HTTP response.
* A new method called handle_websocket() upgrades the connection to
WebSocket, if requested. Otherwise, it returns False. A typical
application use is:
def do_GET(self):
if not self.handle_websocket():
# handle normal requests
* new_client has been renamed to new_websocket_client, in order to
have a better name in the SocketServer/HTTPServer request handler
hierarchy.
* Note that in the request handler, configuration variables must be
provided by the "server" object, ie self.server.target_host.
2013-03-14 15:07:40 +00:00
|
|
|
|
|
|
|
|
|
|
|
def process_request(self, request, client_address):
|
|
|
|
"""Override process_request to implement a counter"""
|
|
|
|
self.handler_id += 1
|
2019-05-15 13:58:47 +01:00
|
|
|
ThreadingMixIn.process_request(self, request, client_address)
|
Try to solve https://github.com/kanaka/websockify/issues/71 by
refactoring. Basically, we are dividing WebSocketServer into two
classes: One request handler following the SocketServer Requesthandler
API, and one optional server engine. The standard Python SocketServer
engine can also be used.
websocketproxy.py has been updated to match the API change. I've also
added a new option --libserver in order to use the Python built in
server instead.
I've done a lot of testing with the new code. This includes: verbose,
daemon, run-once, timeout, idle-timeout, ssl, web, libserver. I've
tested both Python 2 and 3. I've also tested websocket.py in another
external service.
Code details follows:
* The new request handler class is called WebSocketRequestHandler,
inheriting SimpleHTTPRequestHandler.
* The service engine is called WebSocketServer, just like before.
* do_websocket_handshake: Using send_header() etc, instead of manually
sending HTTP response.
* A new method called handle_websocket() upgrades the connection to
WebSocket, if requested. Otherwise, it returns False. A typical
application use is:
def do_GET(self):
if not self.handle_websocket():
# handle normal requests
* new_client has been renamed to new_websocket_client, in order to
have a better name in the SocketServer/HTTPServer request handler
hierarchy.
* Note that in the request handler, configuration variables must be
provided by the "server" object, ie self.server.target_host.
2013-03-14 15:07:40 +00:00
|
|
|
|
2012-02-18 08:43:12 +00:00
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
websockify_init()
|