--- /dev/null
+"""Simple HTTP Server.\r
+\r
+This module builds on BaseHTTPServer by implementing the standard GET\r
+and HEAD requests in a fairly straightforward manner.\r
+\r
+"""\r
+\r
+\r
+__version__ = "0.6"\r
+\r
+__all__ = ["SimpleHTTPRequestHandler"]\r
+\r
+import os\r
+import posixpath\r
+import BaseHTTPServer\r
+import urllib\r
+import urlparse\r
+import cgi\r
+import sys\r
+import shutil\r
+import mimetypes\r
+try:\r
+ from cStringIO import StringIO\r
+except ImportError:\r
+ from StringIO import StringIO\r
+\r
+\r
+class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\r
+\r
+ """Simple HTTP request handler with GET and HEAD commands.\r
+\r
+ This serves files from the current directory and any of its\r
+ subdirectories. The MIME type for files is determined by\r
+ calling the .guess_type() method.\r
+\r
+ The GET and HEAD requests are identical except that the HEAD\r
+ request omits the actual contents of the file.\r
+\r
+ """\r
+\r
+ server_version = "SimpleHTTP/" + __version__\r
+\r
+ def do_GET(self):\r
+ """Serve a GET request."""\r
+ f = self.send_head()\r
+ if f:\r
+ try:\r
+ self.copyfile(f, self.wfile)\r
+ finally:\r
+ f.close()\r
+\r
+ def do_HEAD(self):\r
+ """Serve a HEAD request."""\r
+ f = self.send_head()\r
+ if f:\r
+ f.close()\r
+\r
+ def send_head(self):\r
+ """Common code for GET and HEAD commands.\r
+\r
+ This sends the response code and MIME headers.\r
+\r
+ Return value is either a file object (which has to be copied\r
+ to the outputfile by the caller unless the command was HEAD,\r
+ and must be closed by the caller under all circumstances), or\r
+ None, in which case the caller has nothing further to do.\r
+\r
+ """\r
+ path = self.translate_path(self.path)\r
+ f = None\r
+ if os.path.isdir(path):\r
+ parts = urlparse.urlsplit(self.path)\r
+ if not parts.path.endswith('/'):\r
+ # redirect browser - doing basically what apache does\r
+ self.send_response(301)\r
+ new_parts = (parts[0], parts[1], parts[2] + '/',\r
+ parts[3], parts[4])\r
+ new_url = urlparse.urlunsplit(new_parts)\r
+ self.send_header("Location", new_url)\r
+ self.end_headers()\r
+ return None\r
+ for index in "index.html", "index.htm":\r
+ index = os.path.join(path, index)\r
+ if os.path.exists(index):\r
+ path = index\r
+ break\r
+ else:\r
+ return self.list_directory(path)\r
+ ctype = self.guess_type(path)\r
+ try:\r
+ # Always read in binary mode. Opening files in text mode may cause\r
+ # newline translations, making the actual size of the content\r
+ # transmitted *less* than the content-length!\r
+ f = open(path, 'rb')\r
+ except IOError:\r
+ self.send_error(404, "File not found")\r
+ return None\r
+ try:\r
+ self.send_response(200)\r
+ self.send_header("Content-type", ctype)\r
+ fs = os.fstat(f.fileno())\r
+ self.send_header("Content-Length", str(fs[6]))\r
+ self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))\r
+ self.end_headers()\r
+ return f\r
+ except:\r
+ f.close()\r
+ raise\r
+\r
+ def list_directory(self, path):\r
+ """Helper to produce a directory listing (absent index.html).\r
+\r
+ Return value is either a file object, or None (indicating an\r
+ error). In either case, the headers are sent, making the\r
+ interface the same as for send_head().\r
+\r
+ """\r
+ try:\r
+ list = os.listdir(path)\r
+ except os.error:\r
+ self.send_error(404, "No permission to list directory")\r
+ return None\r
+ list.sort(key=lambda a: a.lower())\r
+ f = StringIO()\r
+ displaypath = cgi.escape(urllib.unquote(self.path))\r
+ f.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">')\r
+ f.write("<html>\n<title>Directory listing for %s</title>\n" % displaypath)\r
+ f.write("<body>\n<h2>Directory listing for %s</h2>\n" % displaypath)\r
+ f.write("<hr>\n<ul>\n")\r
+ for name in list:\r
+ fullname = os.path.join(path, name)\r
+ displayname = linkname = name\r
+ # Append / for directories or @ for symbolic links\r
+ if os.path.isdir(fullname):\r
+ displayname = name + "/"\r
+ linkname = name + "/"\r
+ if os.path.islink(fullname):\r
+ displayname = name + "@"\r
+ # Note: a link to a directory displays with @ and links with /\r
+ f.write('<li><a href="%s">%s</a>\n'\r
+ % (urllib.quote(linkname), cgi.escape(displayname)))\r
+ f.write("</ul>\n<hr>\n</body>\n</html>\n")\r
+ length = f.tell()\r
+ f.seek(0)\r
+ self.send_response(200)\r
+ encoding = sys.getfilesystemencoding()\r
+ self.send_header("Content-type", "text/html; charset=%s" % encoding)\r
+ self.send_header("Content-Length", str(length))\r
+ self.end_headers()\r
+ return f\r
+\r
+ def translate_path(self, path):\r
+ """Translate a /-separated PATH to the local filename syntax.\r
+\r
+ Components that mean special things to the local file system\r
+ (e.g. drive or directory names) are ignored. (XXX They should\r
+ probably be diagnosed.)\r
+\r
+ """\r
+ # abandon query parameters\r
+ path = path.split('?',1)[0]\r
+ path = path.split('#',1)[0]\r
+ # Don't forget explicit trailing slash when normalizing. Issue17324\r
+ trailing_slash = path.rstrip().endswith('/')\r
+ path = posixpath.normpath(urllib.unquote(path))\r
+ words = path.split('/')\r
+ words = filter(None, words)\r
+ path = os.getcwd()\r
+ for word in words:\r
+ drive, word = os.path.splitdrive(word)\r
+ head, word = os.path.split(word)\r
+ if word in (os.curdir, os.pardir): continue\r
+ path = os.path.join(path, word)\r
+ if trailing_slash:\r
+ path += '/'\r
+ return path\r
+\r
+ def copyfile(self, source, outputfile):\r
+ """Copy all data between two file objects.\r
+\r
+ The SOURCE argument is a file object open for reading\r
+ (or anything with a read() method) and the DESTINATION\r
+ argument is a file object open for writing (or\r
+ anything with a write() method).\r
+\r
+ The only reason for overriding this would be to change\r
+ the block size or perhaps to replace newlines by CRLF\r
+ -- note however that this the default server uses this\r
+ to copy binary data as well.\r
+\r
+ """\r
+ shutil.copyfileobj(source, outputfile)\r
+\r
+ def guess_type(self, path):\r
+ """Guess the type of a file.\r
+\r
+ Argument is a PATH (a filename).\r
+\r
+ Return value is a string of the form type/subtype,\r
+ usable for a MIME Content-type header.\r
+\r
+ The default implementation looks the file's extension\r
+ up in the table self.extensions_map, using application/octet-stream\r
+ as a default; however it would be permissible (if\r
+ slow) to look inside the data to make a better guess.\r
+\r
+ """\r
+\r
+ base, ext = posixpath.splitext(path)\r
+ if ext in self.extensions_map:\r
+ return self.extensions_map[ext]\r
+ ext = ext.lower()\r
+ if ext in self.extensions_map:\r
+ return self.extensions_map[ext]\r
+ else:\r
+ return self.extensions_map['']\r
+\r
+ if not mimetypes.inited:\r
+ mimetypes.init() # try to read system mime.types\r
+ extensions_map = mimetypes.types_map.copy()\r
+ extensions_map.update({\r
+ '': 'application/octet-stream', # Default\r
+ '.py': 'text/plain',\r
+ '.c': 'text/plain',\r
+ '.h': 'text/plain',\r
+ })\r
+\r
+\r
+def test(HandlerClass = SimpleHTTPRequestHandler,\r
+ ServerClass = BaseHTTPServer.HTTPServer):\r
+ BaseHTTPServer.test(HandlerClass, ServerClass)\r
+\r
+\r
+if __name__ == '__main__':\r
+ test()\r