2011-06-24 14:31:29 +02:00
|
|
|
###
|
|
|
|
# Copyright (c) 2011, Valentin Lorentz
|
|
|
|
# All rights reserved.
|
|
|
|
#
|
|
|
|
# Redistribution and use in source and binary forms, with or without
|
|
|
|
# modification, are permitted provided that the following conditions are met:
|
|
|
|
#
|
|
|
|
# * Redistributions of source code must retain the above copyright notice,
|
|
|
|
# this list of conditions, and the following disclaimer.
|
|
|
|
# * Redistributions in binary form must reproduce the above copyright notice,
|
|
|
|
# this list of conditions, and the following disclaimer in the
|
|
|
|
# documentation and/or other materials provided with the distribution.
|
|
|
|
# * Neither the name of the author of this software nor the name of
|
|
|
|
# contributors to this software may be used to endorse or promote products
|
|
|
|
# derived from this software without specific prior written consent.
|
|
|
|
#
|
|
|
|
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
|
|
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
|
|
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
|
|
|
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
|
|
|
|
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
|
|
|
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
|
|
|
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
|
|
|
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
|
|
|
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
|
|
|
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
|
|
|
# POSSIBILITY OF SUCH DAMAGE.
|
|
|
|
###
|
|
|
|
|
|
|
|
"""
|
|
|
|
An embedded and centralized HTTP server for Supybot's plugins.
|
|
|
|
"""
|
|
|
|
|
2012-09-03 10:35:54 +02:00
|
|
|
import os
|
2011-06-25 11:37:10 +02:00
|
|
|
import cgi
|
2012-09-30 18:54:30 +02:00
|
|
|
import socket
|
2015-03-03 09:02:29 +01:00
|
|
|
from threading import Thread
|
2011-06-24 14:31:29 +02:00
|
|
|
|
|
|
|
import supybot.log as log
|
|
|
|
import supybot.conf as conf
|
|
|
|
import supybot.world as world
|
2015-08-11 16:50:23 +02:00
|
|
|
import supybot.utils.minisix as minisix
|
2011-06-25 14:27:44 +02:00
|
|
|
from supybot.i18n import PluginInternationalization
|
|
|
|
_ = PluginInternationalization()
|
2011-06-24 14:31:29 +02:00
|
|
|
|
2015-08-10 17:55:25 +02:00
|
|
|
if minisix.PY2:
|
|
|
|
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
|
|
|
|
else:
|
|
|
|
from http.server import HTTPServer, BaseHTTPRequestHandler
|
|
|
|
|
2011-06-24 14:31:29 +02:00
|
|
|
configGroup = conf.supybot.servers.http
|
|
|
|
|
2011-07-03 16:16:19 +02:00
|
|
|
class RequestNotHandled(Exception):
|
|
|
|
pass
|
2011-06-24 14:31:29 +02:00
|
|
|
|
2013-03-11 16:38:21 +01:00
|
|
|
DEFAULT_TEMPLATES = {
|
2013-03-09 20:52:35 +01:00
|
|
|
'index.html': """\
|
2014-05-25 12:50:39 +02:00
|
|
|
<!DOCTYPE html>
|
|
|
|
<html>
|
|
|
|
<head>
|
|
|
|
<meta charset="UTF-8" />
|
2013-03-09 20:52:35 +01:00
|
|
|
<title>""" + _('Supybot Web server index') + """</title>
|
2013-06-01 10:11:44 +02:00
|
|
|
<link rel="stylesheet" type="text/css" href="/default.css" media="screen" />
|
2013-03-09 20:52:35 +01:00
|
|
|
</head>
|
2013-03-11 19:44:26 +01:00
|
|
|
<body class="purelisting">
|
|
|
|
<h1>Supybot web server index</h1>
|
2013-03-09 20:52:35 +01:00
|
|
|
<p>""" + _('Here is a list of the plugins that have a Web interface:') +\
|
|
|
|
"""
|
|
|
|
</p>
|
|
|
|
%(list)s
|
|
|
|
</body>
|
|
|
|
</html>""",
|
2013-03-11 19:44:26 +01:00
|
|
|
'generic/error.html': """\
|
2014-05-25 12:50:39 +02:00
|
|
|
<!DOCTYPE html>
|
|
|
|
<html>
|
2013-03-11 19:44:26 +01:00
|
|
|
<head>
|
2014-05-25 12:50:39 +02:00
|
|
|
<meta charset="UTF-8" />
|
2013-03-11 19:44:26 +01:00
|
|
|
<title>%(title)s</title>
|
|
|
|
<link rel="stylesheet" href="/default.css" />
|
|
|
|
</head>
|
|
|
|
<body class="error">
|
|
|
|
<h1>Error</h1>
|
|
|
|
<p>%(error)s</p>
|
|
|
|
</body>
|
|
|
|
</html>""",
|
|
|
|
'default.css': """\
|
|
|
|
body {
|
|
|
|
background-color: #F0F0F0;
|
|
|
|
}
|
|
|
|
|
|
|
|
/************************************
|
|
|
|
* Classes that plugins should use. *
|
|
|
|
************************************/
|
|
|
|
|
|
|
|
/* Error pages */
|
|
|
|
body.error {
|
|
|
|
text-align: center;
|
|
|
|
}
|
|
|
|
body.error p {
|
|
|
|
background-color: #FFE0E0;
|
|
|
|
border: 1px #FFA0A0 solid;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* Pages that only contain a list. */
|
|
|
|
.purelisting {
|
|
|
|
text-align: center;
|
|
|
|
}
|
2013-05-31 17:55:56 +02:00
|
|
|
.purelisting ul {
|
|
|
|
margin: 0;
|
|
|
|
padding: 0;
|
|
|
|
}
|
2013-03-11 19:44:26 +01:00
|
|
|
.purelisting ul li {
|
2013-05-31 17:55:56 +02:00
|
|
|
margin: 0;
|
|
|
|
padding: 0;
|
2013-03-11 19:44:26 +01:00
|
|
|
list-style-type: none;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* Pages that only contain a table. */
|
|
|
|
.puretable {
|
|
|
|
text-align: center;
|
|
|
|
}
|
|
|
|
.puretable table
|
|
|
|
{
|
|
|
|
width: 100%;
|
|
|
|
border-collapse: collapse;
|
|
|
|
text-align: center;
|
|
|
|
}
|
|
|
|
|
|
|
|
.puretable table th
|
|
|
|
{
|
|
|
|
/*color: #039;*/
|
|
|
|
padding: 10px 8px;
|
|
|
|
border-bottom: 2px solid #6678b1;
|
|
|
|
}
|
|
|
|
|
|
|
|
.puretable table td
|
|
|
|
{
|
|
|
|
padding: 9px 8px 0px 8px;
|
|
|
|
border-bottom: 1px solid #ccc;
|
|
|
|
}
|
|
|
|
|
|
|
|
""",
|
2013-03-09 20:52:35 +01:00
|
|
|
'robots.txt': """""",
|
|
|
|
}
|
|
|
|
|
2013-03-11 16:38:21 +01:00
|
|
|
def set_default_templates(defaults):
|
|
|
|
for filename, content in defaults.items():
|
|
|
|
path = conf.supybot.directories.data.web.dirize(filename)
|
|
|
|
if os.path.isfile(path + '.example'):
|
|
|
|
os.unlink(path + '.example')
|
2013-03-11 19:44:26 +01:00
|
|
|
if not os.path.isdir(os.path.dirname(path)):
|
|
|
|
os.makedirs(os.path.dirname(path))
|
2013-03-11 16:38:21 +01:00
|
|
|
with open(path + '.example', 'a') as fd:
|
2013-03-09 20:52:35 +01:00
|
|
|
fd.write(content)
|
2013-03-11 16:38:21 +01:00
|
|
|
set_default_templates(DEFAULT_TEMPLATES)
|
2013-03-09 20:52:35 +01:00
|
|
|
|
|
|
|
def get_template(filename):
|
|
|
|
path = conf.supybot.directories.data.web.dirize(filename)
|
2013-03-11 16:38:21 +01:00
|
|
|
if os.path.isfile(path):
|
2014-01-03 17:44:01 +01:00
|
|
|
with open(path, 'r') as fd:
|
|
|
|
return fd.read()
|
2013-03-11 16:38:21 +01:00
|
|
|
else:
|
|
|
|
assert os.path.isfile(path + '.example'), path + '.example'
|
2014-01-03 17:44:01 +01:00
|
|
|
with open(path + '.example', 'r') as fd:
|
|
|
|
return fd.read()
|
2013-03-09 20:52:35 +01:00
|
|
|
|
2011-06-24 14:31:29 +02:00
|
|
|
class SupyHTTPRequestHandler(BaseHTTPRequestHandler):
|
2011-06-25 11:37:10 +02:00
|
|
|
def do_X(self, callbackMethod, *args, **kwargs):
|
2011-06-24 14:31:29 +02:00
|
|
|
if self.path == '/':
|
|
|
|
callback = SupyIndex()
|
2013-06-01 10:11:44 +02:00
|
|
|
elif self.path in ('/robots.txt',):
|
2013-06-01 10:32:36 +02:00
|
|
|
callback = Static('text/plain; charset=utf-8')
|
2013-06-01 10:11:44 +02:00
|
|
|
elif self.path in ('/default.css',):
|
|
|
|
callback = Static('text/css')
|
2012-09-03 10:35:54 +02:00
|
|
|
elif self.path == '/favicon.ico':
|
|
|
|
callback = Favicon()
|
2011-06-24 14:31:29 +02:00
|
|
|
else:
|
|
|
|
subdir = self.path.split('/')[1]
|
|
|
|
try:
|
2011-06-24 15:32:22 +02:00
|
|
|
callback = self.server.callbacks[subdir]
|
2011-06-24 14:31:29 +02:00
|
|
|
except KeyError:
|
|
|
|
callback = Supy404()
|
|
|
|
|
|
|
|
# Some shortcuts
|
|
|
|
for name in ('send_response', 'send_header', 'end_headers', 'rfile',
|
2011-06-25 11:37:10 +02:00
|
|
|
'wfile', 'headers'):
|
2011-06-24 14:31:29 +02:00
|
|
|
setattr(callback, name, getattr(self, name))
|
2011-06-25 11:37:10 +02:00
|
|
|
# We call doX, because this is more supybotic than do_X.
|
2013-03-11 19:44:26 +01:00
|
|
|
path = self.path
|
|
|
|
if not callback.fullpath:
|
2013-03-21 18:31:53 +01:00
|
|
|
path = '/' + path.split('/', 2)[-1]
|
2013-03-11 19:44:26 +01:00
|
|
|
getattr(callback, callbackMethod)(self, path,
|
2011-06-25 11:37:10 +02:00
|
|
|
*args, **kwargs)
|
|
|
|
|
|
|
|
def do_GET(self):
|
|
|
|
self.do_X('doGet')
|
|
|
|
|
|
|
|
def do_POST(self):
|
2011-07-03 16:16:19 +02:00
|
|
|
if 'Content-Type' not in self.headers:
|
|
|
|
self.headers['Content-Type'] = 'application/x-www-form-urlencoded'
|
2014-10-14 22:59:00 +02:00
|
|
|
if self.headers['Content-Type'] == 'application/x-www-form-urlencoded':
|
|
|
|
form = cgi.FieldStorage(
|
|
|
|
fp=self.rfile,
|
|
|
|
headers=self.headers,
|
|
|
|
environ={'REQUEST_METHOD':'POST',
|
|
|
|
'CONTENT_TYPE':self.headers['Content-Type'],
|
|
|
|
})
|
|
|
|
else:
|
2015-08-17 21:46:33 +02:00
|
|
|
content_length = int(self.headers.get('Content-Length', '0'))
|
|
|
|
form = self.rfile.read(content_length)
|
2011-06-25 11:37:10 +02:00
|
|
|
self.do_X('doPost', form=form)
|
|
|
|
|
|
|
|
def do_HEAD(self):
|
|
|
|
self.do_X('doHead')
|
|
|
|
|
2015-08-21 22:35:51 +02:00
|
|
|
def address_string(self):
|
2015-09-24 15:38:42 +02:00
|
|
|
s = BaseHTTPRequestHandler.address_string(self)
|
2015-08-21 22:35:51 +02:00
|
|
|
|
|
|
|
# Strip IPv4-mapped IPv6 addresses such as ::ffff:127.0.0.1
|
2015-08-22 11:18:07 +02:00
|
|
|
prefix = '::ffff:'
|
|
|
|
if s.startswith(prefix):
|
|
|
|
s = s[len(prefix):]
|
|
|
|
|
|
|
|
return s
|
2011-06-24 14:31:29 +02:00
|
|
|
|
|
|
|
def log_message(self, format, *args):
|
|
|
|
log.info('HTTP request: %s - %s' %
|
|
|
|
(self.address_string(), format % args))
|
|
|
|
|
2015-08-11 16:50:23 +02:00
|
|
|
class SupyHTTPServerCallback(log.Firewalled):
|
2011-06-24 14:52:01 +02:00
|
|
|
"""This is a base class that should be overriden by any plugin that want
|
|
|
|
to have a Web interface."""
|
2013-07-07 13:26:13 +02:00
|
|
|
__firewalled__ = {'doGet': None,
|
|
|
|
'doPost': None,
|
|
|
|
'doHead': None,
|
|
|
|
'doPut': None,
|
|
|
|
'doDelete': None,
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2013-03-11 19:44:26 +01:00
|
|
|
fullpath = False
|
2011-06-24 14:31:29 +02:00
|
|
|
name = "Unnamed plugin"
|
2011-06-25 14:27:44 +02:00
|
|
|
defaultResponse = _("""
|
2011-06-24 14:31:29 +02:00
|
|
|
This is a default response of the Supybot HTTP server. If you see this
|
2011-08-06 18:53:53 +02:00
|
|
|
message, it probably means you are developing a plugin, and you have
|
2011-06-25 14:27:44 +02:00
|
|
|
neither overriden this message or defined an handler for this query.""")
|
2011-06-24 14:31:29 +02:00
|
|
|
|
2015-08-09 00:23:03 +02:00
|
|
|
if minisix.PY3:
|
2014-08-04 15:21:27 +02:00
|
|
|
def write(self, b):
|
|
|
|
if isinstance(b, str):
|
|
|
|
b = b.encode()
|
|
|
|
self.wfile.write(b)
|
|
|
|
else:
|
|
|
|
def write(self, s):
|
|
|
|
self.wfile.write(s)
|
|
|
|
|
2016-01-05 18:25:35 +01:00
|
|
|
def doGetOrHead(self, handler, path, write_content):
|
2016-01-05 18:05:36 +01:00
|
|
|
response = self.defaultResponse.encode()
|
2016-01-05 18:01:39 +01:00
|
|
|
handler.send_response(405)
|
2013-06-01 10:32:36 +02:00
|
|
|
self.send_header('Content-Type', 'text/plain; charset=utf-8; charset=utf-8')
|
2016-01-05 18:05:36 +01:00
|
|
|
self.send_header('Content-Length', len(response))
|
2011-06-24 14:31:29 +02:00
|
|
|
self.end_headers()
|
2016-01-05 18:25:35 +01:00
|
|
|
if write_content:
|
|
|
|
self.wfile.write(response)
|
|
|
|
|
|
|
|
def doGet(self, handler, path):
|
|
|
|
self.doGetOrHead(handler, path, write_content=True)
|
|
|
|
def doHead(self, handler, path):
|
|
|
|
self.doGetOrHead(handler, path, write_content=False)
|
2011-06-24 14:31:29 +02:00
|
|
|
|
2016-01-05 18:25:35 +01:00
|
|
|
doPost = doGet
|
2011-06-25 11:37:10 +02:00
|
|
|
|
2020-05-09 19:14:56 +02:00
|
|
|
def doWellKnown(self, handler, path):
|
|
|
|
"""Handles GET request to /.well-known/"""
|
|
|
|
return None
|
|
|
|
|
2014-01-02 18:20:15 +01:00
|
|
|
def doHook(self, handler, subdir):
|
|
|
|
"""Method called when hooking this callback."""
|
|
|
|
pass
|
2011-06-24 14:31:29 +02:00
|
|
|
def doUnhook(self, handler):
|
|
|
|
"""Method called when unhooking this callback."""
|
|
|
|
pass
|
|
|
|
|
|
|
|
class Supy404(SupyHTTPServerCallback):
|
2011-06-24 14:52:01 +02:00
|
|
|
"""A 404 Not Found error."""
|
2011-06-24 14:31:29 +02:00
|
|
|
name = "Error 404"
|
2013-03-11 19:44:26 +01:00
|
|
|
fullpath = True
|
2011-06-25 14:27:44 +02:00
|
|
|
response = _("""
|
2011-06-24 14:31:29 +02:00
|
|
|
I am a pretty clever IRC bot, but I suck at serving Web pages, particulary
|
|
|
|
if I don't know what to serve.
|
|
|
|
What I'm saying is you just triggered a 404 Not Found, and I am not
|
2011-06-25 14:27:44 +02:00
|
|
|
trained to help you in such a case.""")
|
2016-01-05 18:25:35 +01:00
|
|
|
def doGetOrHead(self, handler, path, write_content):
|
2016-01-05 18:05:36 +01:00
|
|
|
response = self.response
|
|
|
|
if minisix.PY3:
|
|
|
|
response = response.encode()
|
2011-06-24 14:31:29 +02:00
|
|
|
handler.send_response(404)
|
2013-06-01 10:32:36 +02:00
|
|
|
self.send_header('Content-Type', 'text/plain; charset=utf-8; charset=utf-8')
|
2011-06-24 14:31:29 +02:00
|
|
|
self.send_header('Content-Length', len(self.response))
|
|
|
|
self.end_headers()
|
2016-01-05 18:25:35 +01:00
|
|
|
if write_content:
|
|
|
|
self.wfile.write(response)
|
2011-06-25 11:37:10 +02:00
|
|
|
|
2011-06-24 14:31:29 +02:00
|
|
|
class SupyIndex(SupyHTTPServerCallback):
|
2011-06-24 14:52:01 +02:00
|
|
|
"""Displays the index of available plugins."""
|
2011-06-24 14:31:29 +02:00
|
|
|
name = "index"
|
2011-06-25 14:27:44 +02:00
|
|
|
defaultResponse = _("Request not handled.")
|
2016-01-05 18:25:35 +01:00
|
|
|
def doGetOrHead(self, handler, path, write_content):
|
2011-06-24 14:31:29 +02:00
|
|
|
plugins = [x for x in handler.server.callbacks.items()]
|
|
|
|
if plugins == []:
|
2011-06-25 14:27:44 +02:00
|
|
|
plugins = _('No plugins available.')
|
2011-06-24 14:31:29 +02:00
|
|
|
else:
|
2013-03-09 20:52:35 +01:00
|
|
|
plugins = '<ul class="plugins"><li>%s</li></ul>' % '</li><li>'.join(
|
2011-10-02 12:11:30 +02:00
|
|
|
['<a href="/%s/">%s</a>' % (x,y.name) for x,y in plugins])
|
2013-03-09 20:52:35 +01:00
|
|
|
response = get_template('index.html') % {'list': plugins}
|
2016-01-05 18:05:36 +01:00
|
|
|
if minisix.PY3:
|
|
|
|
response = response.encode()
|
2011-06-24 14:31:29 +02:00
|
|
|
handler.send_response(200)
|
2013-06-01 10:32:36 +02:00
|
|
|
self.send_header('Content-Type', 'text/html; charset=utf-8')
|
2011-06-24 14:31:29 +02:00
|
|
|
self.send_header('Content-Length', len(response))
|
|
|
|
self.end_headers()
|
2016-01-05 18:25:35 +01:00
|
|
|
if write_content:
|
|
|
|
self.wfile.write(response)
|
2011-06-24 14:31:29 +02:00
|
|
|
|
2013-03-11 19:44:26 +01:00
|
|
|
class Static(SupyHTTPServerCallback):
|
|
|
|
"""Serves static files."""
|
|
|
|
fullpath = True
|
|
|
|
name = 'static'
|
2011-10-29 12:13:09 +02:00
|
|
|
defaultResponse = _('Request not handled')
|
2013-06-01 10:32:36 +02:00
|
|
|
def __init__(self, mimetype='text/plain; charset=utf-8'):
|
2013-06-01 10:11:44 +02:00
|
|
|
super(Static, self).__init__()
|
|
|
|
self._mimetype = mimetype
|
2016-01-05 18:25:35 +01:00
|
|
|
def doGetOrHead(self, handler, path, write_content):
|
2013-03-11 19:44:26 +01:00
|
|
|
response = get_template(path)
|
2016-01-05 18:05:36 +01:00
|
|
|
if minisix.PY3:
|
|
|
|
response = response.encode()
|
2011-10-29 12:13:09 +02:00
|
|
|
handler.send_response(200)
|
2013-06-01 10:11:44 +02:00
|
|
|
self.send_header('Content-type', self._mimetype)
|
2011-10-29 12:13:09 +02:00
|
|
|
self.send_header('Content-Length', len(response))
|
|
|
|
self.end_headers()
|
2016-01-05 18:25:35 +01:00
|
|
|
if write_content:
|
|
|
|
self.wfile.write(response)
|
2011-10-29 12:13:09 +02:00
|
|
|
|
2012-09-03 10:35:54 +02:00
|
|
|
class Favicon(SupyHTTPServerCallback):
|
|
|
|
"""Services the favicon.ico file to browsers."""
|
|
|
|
name = 'favicon'
|
|
|
|
defaultResponse = _('Request not handled')
|
2016-01-05 18:25:35 +01:00
|
|
|
def doGetOrHead(self, handler, path, write_content):
|
2014-04-15 20:39:44 +02:00
|
|
|
response = None
|
2012-09-03 10:35:54 +02:00
|
|
|
file_path = conf.supybot.servers.http.favicon()
|
|
|
|
if file_path:
|
|
|
|
try:
|
2014-04-02 19:34:04 +02:00
|
|
|
icon = open(file_path, 'rb')
|
2014-04-02 19:18:20 +02:00
|
|
|
response = icon.read()
|
2012-09-03 10:35:54 +02:00
|
|
|
except IOError:
|
|
|
|
pass
|
2014-01-03 17:44:01 +01:00
|
|
|
finally:
|
|
|
|
icon.close()
|
2014-04-02 19:18:20 +02:00
|
|
|
if response is not None:
|
2012-09-03 10:35:54 +02:00
|
|
|
# I have no idea why, but this headers are already sent.
|
2015-08-31 15:38:35 +02:00
|
|
|
# filename = file_path.rsplit(os.sep, 1)[1]
|
|
|
|
# if '.' in filename:
|
|
|
|
# ext = filename.rsplit('.', 1)[1]
|
|
|
|
# else:
|
|
|
|
# ext = 'ico'
|
2012-09-03 10:35:54 +02:00
|
|
|
# self.send_header('Content-Length', len(response))
|
|
|
|
# self.send_header('Content-type', 'image/' + ext)
|
2012-09-19 20:59:44 +02:00
|
|
|
# self.end_headers()
|
2016-01-05 18:25:35 +01:00
|
|
|
if write_content:
|
|
|
|
self.wfile.write(response)
|
2012-09-03 10:35:54 +02:00
|
|
|
else:
|
|
|
|
response = _('No favicon set.')
|
2016-01-05 18:05:36 +01:00
|
|
|
if minisix.PY3:
|
|
|
|
response = response.encode()
|
2012-09-03 10:35:54 +02:00
|
|
|
handler.send_response(404)
|
2013-06-01 10:32:36 +02:00
|
|
|
self.send_header('Content-type', 'text/plain; charset=utf-8')
|
2012-09-03 10:35:54 +02:00
|
|
|
self.send_header('Content-Length', len(response))
|
|
|
|
self.end_headers()
|
2016-01-05 18:25:35 +01:00
|
|
|
if write_content:
|
|
|
|
self.wfile.write(response)
|
2012-09-03 10:35:54 +02:00
|
|
|
|
2020-05-09 19:14:56 +02:00
|
|
|
class SupyWellKnown(SupyHTTPServerCallback):
|
|
|
|
"""Serves /.well-known/ resources."""
|
|
|
|
name = 'well-known'
|
|
|
|
defaultResponse = _('Request not handled')
|
|
|
|
|
|
|
|
def doGetOrHead(self, handler, path, write_content):
|
|
|
|
for callback in handler.server.callbacks.values():
|
|
|
|
resp = callback.doWellKnown(handler, path)
|
|
|
|
if resp:
|
|
|
|
(status, headers, content) = resp
|
|
|
|
handler.send_response(status)
|
|
|
|
for header in headers.items():
|
|
|
|
self.send_header(*header)
|
|
|
|
self.end_headers()
|
|
|
|
if write_content:
|
|
|
|
self.wfile.write(content)
|
|
|
|
return
|
|
|
|
|
|
|
|
handler.send_response(404)
|
|
|
|
self.end_headers()
|
|
|
|
|
2020-05-09 22:17:28 +02:00
|
|
|
|
|
|
|
DEFAULT_CALLBACKS = {'.well-known': SupyWellKnown()}
|
|
|
|
|
|
|
|
|
|
|
|
class RealSupyHTTPServer(HTTPServer):
|
|
|
|
# TODO: make this configurable
|
|
|
|
timeout = 0.5
|
|
|
|
running = False
|
|
|
|
|
|
|
|
def __init__(self, address, protocol, callback):
|
|
|
|
self.protocol = protocol
|
|
|
|
if protocol == 4:
|
|
|
|
self.address_family = socket.AF_INET
|
|
|
|
elif protocol == 6:
|
|
|
|
self.address_family = socket.AF_INET6
|
|
|
|
else:
|
|
|
|
raise AssertionError(protocol)
|
|
|
|
HTTPServer.__init__(self, address, callback)
|
|
|
|
self.callbacks = DEFAULT_CALLBACKS.copy()
|
|
|
|
|
|
|
|
def server_bind(self):
|
|
|
|
if self.protocol == 6:
|
|
|
|
v = conf.supybot.servers.http.singleStack()
|
|
|
|
self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, v)
|
|
|
|
HTTPServer.server_bind(self)
|
|
|
|
|
|
|
|
def hook(self, subdir, callback):
|
|
|
|
if subdir in self.callbacks:
|
|
|
|
log.warning(('The HTTP subdirectory `%s` was already hooked but '
|
|
|
|
'has been claimed by another plugin (or maybe you '
|
|
|
|
'reloaded the plugin and it didn\'t properly unhook. '
|
|
|
|
'Forced unhook.') % subdir)
|
|
|
|
self.callbacks[subdir] = callback
|
|
|
|
callback.doHook(self, subdir)
|
|
|
|
def unhook(self, subdir):
|
|
|
|
callback = self.callbacks.pop(subdir, None)
|
|
|
|
if callback:
|
|
|
|
callback.doUnhook(self)
|
|
|
|
return callback
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return 'server at %s %i' % self.server_address[0:2]
|
|
|
|
|
|
|
|
class TestSupyHTTPServer(RealSupyHTTPServer):
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
self.callbacks = {}
|
|
|
|
def serve_forever(self, *args, **kwargs):
|
|
|
|
pass
|
|
|
|
def shutdown(self, *args, **kwargs):
|
|
|
|
pass
|
|
|
|
|
|
|
|
if world.testing:
|
|
|
|
SupyHTTPServer = TestSupyHTTPServer
|
|
|
|
else:
|
|
|
|
SupyHTTPServer = RealSupyHTTPServer
|
|
|
|
|
2013-05-31 17:55:35 +02:00
|
|
|
http_servers = []
|
2011-06-24 14:31:29 +02:00
|
|
|
|
|
|
|
def startServer():
|
|
|
|
"""Starts the HTTP server. Shouldn't be called from other modules.
|
|
|
|
The callback should be an instance of a child of SupyHTTPServerCallback."""
|
2012-09-30 18:54:30 +02:00
|
|
|
global http_servers
|
|
|
|
addresses4 = [(4, (x, configGroup.port()))
|
2017-10-28 09:50:12 +02:00
|
|
|
for x in configGroup.hosts4() if x != '']
|
2012-09-30 18:54:30 +02:00
|
|
|
addresses6 = [(6, (x, configGroup.port()))
|
2017-10-28 09:50:12 +02:00
|
|
|
for x in configGroup.hosts6() if x != '']
|
2012-09-30 18:54:30 +02:00
|
|
|
http_servers = []
|
|
|
|
for protocol, address in (addresses4 + addresses6):
|
2021-03-09 23:14:23 +01:00
|
|
|
try:
|
|
|
|
server = SupyHTTPServer(address, protocol, SupyHTTPRequestHandler)
|
|
|
|
except OSError as e:
|
|
|
|
log.error(
|
|
|
|
'Failed to start HTTP server with protocol %s at address: %s',
|
|
|
|
protocol, address, e)
|
|
|
|
if e.args[0] == 98:
|
|
|
|
log.error(
|
|
|
|
'This means the port (and address) is already in use by an '
|
|
|
|
'other process. Either find the process using the port '
|
|
|
|
'and stop it, or change the port configured in '
|
|
|
|
'supybot.servers.http.port.')
|
|
|
|
continue
|
|
|
|
except:
|
|
|
|
log.exception(
|
|
|
|
"Failed to start HTTP server with protocol %s at address",
|
|
|
|
protocol, address)
|
|
|
|
continue
|
2012-09-30 18:54:30 +02:00
|
|
|
Thread(target=server.serve_forever, name='HTTP Server').start()
|
|
|
|
http_servers.append(server)
|
|
|
|
log.info('Starting HTTP server: %s' % str(server))
|
2011-06-24 14:31:29 +02:00
|
|
|
|
|
|
|
def stopServer():
|
|
|
|
"""Stops the HTTP server. Should be run only from this module or from
|
|
|
|
when the bot is dying (ie. from supybot.world)"""
|
2012-09-30 18:54:30 +02:00
|
|
|
global http_servers
|
2013-05-31 17:55:35 +02:00
|
|
|
for server in http_servers:
|
|
|
|
log.info('Stopping HTTP server: %s' % str(server))
|
|
|
|
server.shutdown()
|
|
|
|
server = None
|
2011-06-24 14:31:29 +02:00
|
|
|
|
|
|
|
if configGroup.keepAlive():
|
|
|
|
startServer()
|
|
|
|
|
|
|
|
def hook(subdir, callback):
|
|
|
|
"""Sets a callback for a given subdir."""
|
2013-05-31 17:55:35 +02:00
|
|
|
if not http_servers:
|
2011-06-24 14:31:29 +02:00
|
|
|
startServer()
|
2012-09-30 18:54:30 +02:00
|
|
|
assert isinstance(http_servers, list)
|
|
|
|
for server in http_servers:
|
|
|
|
server.hook(subdir, callback)
|
2011-06-24 14:31:29 +02:00
|
|
|
|
|
|
|
def unhook(subdir):
|
|
|
|
"""Unsets the callback assigned to the given subdir, and return it."""
|
2012-09-30 18:54:30 +02:00
|
|
|
global http_servers
|
|
|
|
assert isinstance(http_servers, list)
|
2019-09-15 08:02:10 +02:00
|
|
|
for server in list(http_servers):
|
2015-08-31 15:38:35 +02:00
|
|
|
server.unhook(subdir)
|
2020-05-09 19:14:56 +02:00
|
|
|
if len(set(server.callbacks) - set(DEFAULT_CALLBACKS)) <= 0 \
|
|
|
|
and not configGroup.keepAlive():
|
2012-09-30 18:54:30 +02:00
|
|
|
server.shutdown()
|
|
|
|
http_servers.remove(server)
|