Skip to content

Instantly share code, notes, and snippets.

@purpleidea
Created December 18, 2017 11:29
Show Gist options
  • Save purpleidea/7255c478e5f350a4f0a6690078d02619 to your computer and use it in GitHub Desktop.
Save purpleidea/7255c478e5f350a4f0a6690078d02619 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
"""
HTTPDaemon simple non-blocking, threaded HTTPD server
Example:
serveraddr = ('', 8000)
server = MultiThreadedHTTPServer(serveraddr, SimpleHTTPServer.SimpleHTTPRequestHandler)
server.serve_forever() # blocks here
print 'Server has quit.'
Example:
serveraddr = ('', 8000)
workingdir = '/tmp'
server = HTTPDaemon(serveraddr, workingdir)
server.start() # doesn't block here
print 'Server is running...'
Example:
serveraddr = ('', 8000)
workingdir = '/tmp'
logger = self.logobj.get_log('foo') # python 'logging'
server = HTTPDaemon(serveraddr, workingdir, logger)
server.start() # doesn't block here
print 'Server is running...'
"""
# HTTPDaemon
# Copyright (C) 2013 James Shubin
# Written by James Shubin <james@shubin.ca>
# Portions Copyright (C) 2009-2010 Xyne (GPLv2+) # thanks Xyne!
# Portions Copyright (C) 2011 Sean Goller (GPLv2+) # thanks Sean!
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import urllib
import httplib
import posixpath
import threading
threading._DummyThread._Thread__stop = lambda x: 13 # XXX: bug fix
import SocketServer
import BaseHTTPServer
import SimpleHTTPServer
#import cgi
#import shutil
import mimetypes
#try:
# from cStringIO import StringIO
#except ImportError:
# from StringIO import StringIO
class RangeHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""Simple HTTP request handler with GET and HEAD commands.
This serves files from the current directory and any of its
subdirectories. The MIME type for files is determined by
calling the .guess_type() method.
The GET and HEAD requests are identical except that the HEAD
request omits the actual contents of the file."""
def do_GET(self):
"""Serve a GET request."""
f, start_range, end_range = self.send_head()
self.server.log.debug("Got values of %s and %s" % (start_range, end_range))
if f:
f.seek(start_range, 0)
chunk = 0x1000
total = 0
while chunk > 0:
if start_range + chunk > end_range:
chunk = end_range - start_range
try:
self.wfile.write(f.read(chunk))
except:
break
total += chunk
start_range += chunk
f.close()
def do_HEAD(self):
"""Serve a HEAD request."""
if self.path.startswith(self.server.magic):
self.server.log.debug("Got magic HEAD request: %s" % self.path)
func = self.server.callback # <type 'instancemethod'>
if callable(func) and func(self.path):
self.send_response(200)
self.end_headers()
else:
# TODO: should i choose a different http code ?
self.send_error(404, 'Request failed.')
return
# regular head processing...
f, start_range, end_range = self.send_head()
if f:
f.close()
def send_head(self):
"""Common code for GET and HEAD commands.
This sends the response code and MIME headers.
Return value is either a file object (which has to be copied
to the outputfile by the caller unless the command was HEAD,
and must be closed by the caller under all circumstances), or
None, in which case the caller has nothing further to do."""
path = self.translate_path(self.path)
f = None
if os.path.isdir(path):
if not self.path.endswith('/'):
# redirect browser - doing basically what apache does
self.send_response(301)
self.send_header("Location", self.path + "/")
self.end_headers()
return (None, 0, 0)
for index in "index.html", "index.htm":
index = os.path.join(path, index)
if os.path.exists(index):
path = index
break
else: # run if the for loop does not run a break...
#return self.list_directory(path)
self.send_error(404, "No permission to list directory")
return (None, 0, 0)
ctype = self.guess_type(path)
try:
# Always read in binary mode. Opening files in text mode may cause
# newline translations, making the actual size of the content
# transmitted *less* than the content-length!
f = open(path, 'rb')
except IOError:
self.send_error(404, "File not found")
return (None, 0, 0)
if "Range" in self.headers:
self.send_response(206)
else:
self.send_response(200)
self.send_header("Content-type", ctype)
fs = os.fstat(f.fileno())
size = int(fs[6])
start_range = 0
end_range = size
self.send_header("Accept-Ranges", "bytes")
if "Range" in self.headers:
s, e = self.headers['range'][6:].split('-', 1)
sl = len(s)
el = len(e)
if sl > 0:
start_range = int(s)
if el > 0:
end_range = int(e) + 1
elif el > 0:
ei = int(e)
if ei < size:
start_range = size - ei
self.send_header("Content-Range", 'bytes ' + str(start_range) + '-' + str(end_range - 1) + '/' + str(size))
self.send_header("Content-Length", end_range - start_range)
self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
self.end_headers()
self.server.log.debug("Sending Bytes %d to %d" % (start_range, end_range))
return (f, start_range, end_range)
# NOTE: the following are unnecessary parts of the RangeHTTPServer code base
# def list_directory(self, path):
# """Helper to produce a directory listing (absent index.html).
#
# Return value is either a file object, or None (indicating an
# error). In either case, the headers are sent, making the
# interface the same as for send_head()."""
# try:
# list = os.listdir(path)
# except os.error:
# self.send_error(404, "No permission to list directory")
# return None
# list.sort(key=lambda a: a.lower())
# f = StringIO()
# displaypath = cgi.escape(urllib.unquote(self.path))
# f.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">')
# f.write("<html>\n<title>Directory listing for %s</title>\n" % displaypath)
# f.write("<body>\n<h2>Directory listing for %s</h2>\n" % displaypath)
# f.write("<hr>\n<ul>\n")
# for name in list:
# fullname = os.path.join(path, name)
# displayname = linkname = name
# # Append / for directories or @ for symbolic links
# if os.path.isdir(fullname):
# displayname = name + "/"
# linkname = name + "/"
# if os.path.islink(fullname):
# displayname = name + "@"
# # Note: a link to a directory displays with @ and links with /
# f.write('<li><a href="%s">%s</a>\n'% (urllib.quote(linkname), cgi.escape(displayname)))
#
# f.write("</ul>\n<hr>\n</body>\n</html>\n")
# length = f.tell()
# f.seek(0)
# self.send_response(200)
# self.send_header("Content-type", "text/html")
# self.send_header("Content-Length", str(length))
# self.end_headers()
# return (f, 0, length)
#
# def translate_path(self, path):
# """Translate a /-separated PATH to the local filename syntax.
#
# Components that mean special things to the local file system
# (e.g. drive or directory names) are ignored. (XXX They should
# probably be diagnosed.)"""
# # abandon query parameters
# path = path.split('?',1)[0]
# path = path.split('#',1)[0]
# path = posixpath.normpath(urllib.unquote(path))
# words = path.split('/')
# words = filter(None, words)
# path = os.getcwd()
# for word in words:
# drive, word = os.path.splitdrive(word)
# head, word = os.path.split(word)
# if word in (os.curdir, os.pardir): continue
# path = os.path.join(path, word)
# return path
#
# def copyfile(self, source, outputfile):
# """Copy all data between two file objects.
#
# The SOURCE argument is a file object open for reading
# (or anything with a read() method) and the DESTINATION
# argument is a file object open for writing (or
# anything with a write() method).
#
# The only reason for overriding this would be to change
# the block size or perhaps to replace newlines by CRLF
# -- note however that this the default server uses this
# to copy binary data as well."""
# shutil.copyfileobj(source, outputfile)
#
def guess_type(self, path):
"""Guess the type of a file.
Argument is a PATH (a filename).
Return value is a string of the form type/subtype,
usable for a MIME Content-type header.
The default implementation looks the file's extension
up in the table self.extensions_map, using application/octet-stream
as a default; however it would be permissible (if
slow) to look inside the data to make a better guess."""
base, ext = posixpath.splitext(path)
if ext in self.extensions_map:
return self.extensions_map[ext]
ext = ext.lower()
if ext in self.extensions_map:
return self.extensions_map[ext]
else:
return self.extensions_map['']
if not mimetypes.inited:
mimetypes.init() # try to read system mime.types
extensions_map = mimetypes.types_map.copy()
extensions_map.update({
'': 'application/octet-stream', # Default
'.py': 'text/plain',
'.c': 'text/plain',
'.h': 'text/plain',
'.mp4': 'video/mp4',
'.ogg': 'video/ogg',
})
#class StoppableHttpRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
class StoppableRangeHttpRequestHandler(RangeHTTPRequestHandler):
server_version = 'MacaronicHTTP/0.1' # optional
def do_QUIT(self):
"""Send 200 OK response, and set server.stop to True"""
self.send_response(200)
self.end_headers()
self.server.stop = True
def translate_path(self, path):
"""Translate a /-separated PATH to the local filename syntax.
Components that mean special things to the local file system
(e.g. drive or directory names) are ignored. (XXX They should
probably be diagnosed.)
"""
# abandon query parameters
path = path.split('?',1)[0]
path = path.split('#',1)[0]
path = posixpath.normpath(urllib.unquote(path))
words = path.split('/')
words = filter(None, words)
if self.server.working_directory is None: path = os.getcwd()
else: path = self.server.working_directory # pull data in
for word in words:
drive, word = os.path.splitdrive(word)
head, word = os.path.split(word)
if word in (os.curdir, os.pardir): continue
path = os.path.join(path, word)
return path
# TODO: try getting SocketServer.ForkingMixIn to work as an alternate to SocketServer.ThreadingMixIn
class MultiThreadedHTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
#request_queue_size = 50 # TODO: does this work?
#timeout = None # TODO: does this work?
def serve_forever(self):
"""Introduce stop functionality."""
self.stop = False
while not self.stop:
#print 'x' # we can do something on each request
self.handle_request()
class HTTPDaemon(threading.Thread):
def __init__(self, serveraddr, workingdir=None, logger=None, callback=None, magic='/magic?'):
threading.Thread.__init__(self, name='HTTPDaemon')
self.daemon = True
#self._server = MultiThreadedHTTPServer(serveraddr, SimpleHTTPServer.SimpleHTTPRequestHandler) # works
#self._server = MultiThreadedHTTPServer(serveraddr, StoppableHttpRequestHandler)
self._server = MultiThreadedHTTPServer(serveraddr, StoppableRangeHttpRequestHandler)
self._server.working_directory = workingdir
self._server.log = logger
self._server.callback = callback
self._server.magic = magic # prefix to initiate callback
def run(self):
self._server.serve_forever()
def stop_server(port):
"""send QUIT request to http server running on localhost:<port>"""
conn = httplib.HTTPConnection('localhost:%d' % port) # TODO: if server is listening on a specific IP address, will this work? I think no. Add specifying an IP too.
conn.request('QUIT', '/')
conn.getresponse()
#def test(HandlerClass=RangeHTTPRequestHandler,
# ServerClass=BaseHTTPServer.HTTPServer):
# BaseHTTPServer.test(HandlerClass, ServerClass)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment