blob: ea10fb7e927a0b3f12efbf3921563e7e59d7a500 [file] [log] [blame]
Guido van Rossume7e578f1995-08-04 04:00:20 +00001"""Simple HTTP Server.
2
3This module builds on BaseHTTPServer by implementing the standard GET
4and HEAD requests in a fairly straightforward manner.
5
6"""
7
8
Guido van Rossum077153e2001-01-14 23:21:25 +00009__version__ = "0.6"
Guido van Rossume7e578f1995-08-04 04:00:20 +000010
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000011__all__ = ["SimpleHTTPRequestHandler"]
Guido van Rossume7e578f1995-08-04 04:00:20 +000012
13import os
Guido van Rossume7e578f1995-08-04 04:00:20 +000014import posixpath
Guido van Rossume7e578f1995-08-04 04:00:20 +000015import BaseHTTPServer
Guido van Rossumd7b147b1999-11-16 19:04:32 +000016import urllib
Georg Brandl45ab2332006-01-13 17:05:56 +000017import urlparse
Guido van Rossum57af0722000-05-09 14:57:09 +000018import cgi
Moshe Zadka37c03ff2000-07-29 05:15:56 +000019import shutil
Guido van Rossum077153e2001-01-14 23:21:25 +000020import mimetypes
Raymond Hettingera6172712004-12-31 19:15:26 +000021try:
22 from cStringIO import StringIO
23except ImportError:
24 from StringIO import StringIO
Guido van Rossume7e578f1995-08-04 04:00:20 +000025
26
Guido van Rossume7e578f1995-08-04 04:00:20 +000027class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
28
29 """Simple HTTP request handler with GET and HEAD commands.
30
31 This serves files from the current directory and any of its
Andrew M. Kuchlingb839c1f2004-08-07 19:02:19 +000032 subdirectories. The MIME type for files is determined by
33 calling the .guess_type() method.
Guido van Rossume7e578f1995-08-04 04:00:20 +000034
35 The GET and HEAD requests are identical except that the HEAD
36 request omits the actual contents of the file.
37
38 """
39
40 server_version = "SimpleHTTP/" + __version__
41
42 def do_GET(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000043 """Serve a GET request."""
44 f = self.send_head()
45 if f:
46 self.copyfile(f, self.wfile)
47 f.close()
Guido van Rossume7e578f1995-08-04 04:00:20 +000048
49 def do_HEAD(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000050 """Serve a HEAD request."""
51 f = self.send_head()
52 if f:
53 f.close()
Guido van Rossume7e578f1995-08-04 04:00:20 +000054
55 def send_head(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000056 """Common code for GET and HEAD commands.
Guido van Rossume7e578f1995-08-04 04:00:20 +000057
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000058 This sends the response code and MIME headers.
Guido van Rossume7e578f1995-08-04 04:00:20 +000059
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000060 Return value is either a file object (which has to be copied
61 to the outputfile by the caller unless the command was HEAD,
62 and must be closed by the caller under all circumstances), or
63 None, in which case the caller has nothing further to do.
Guido van Rossume7e578f1995-08-04 04:00:20 +000064
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000065 """
66 path = self.translate_path(self.path)
Guido van Rossum1d10f3e2000-05-21 16:25:29 +000067 f = None
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000068 if os.path.isdir(path):
Guido van Rossum1d10f3e2000-05-21 16:25:29 +000069 for index in "index.html", "index.htm":
70 index = os.path.join(path, index)
71 if os.path.exists(index):
72 path = index
73 break
74 else:
75 return self.list_directory(path)
76 ctype = self.guess_type(path)
77 if ctype.startswith('text/'):
78 mode = 'r'
Guido van Rossum57af0722000-05-09 14:57:09 +000079 else:
Guido van Rossum1d10f3e2000-05-21 16:25:29 +000080 mode = 'rb'
81 try:
82 f = open(path, mode)
83 except IOError:
84 self.send_error(404, "File not found")
85 return None
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000086 self.send_response(200)
Guido van Rossum57af0722000-05-09 14:57:09 +000087 self.send_header("Content-type", ctype)
Martin v. Löwis587c98c2002-03-17 18:37:22 +000088 self.send_header("Content-Length", str(os.fstat(f.fileno())[6]))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000089 self.end_headers()
90 return f
Guido van Rossume7e578f1995-08-04 04:00:20 +000091
Guido van Rossum57af0722000-05-09 14:57:09 +000092 def list_directory(self, path):
Guido van Rossum1d10f3e2000-05-21 16:25:29 +000093 """Helper to produce a directory listing (absent index.html).
94
95 Return value is either a file object, or None (indicating an
96 error). In either case, the headers are sent, making the
97 interface the same as for send_head().
98
99 """
Guido van Rossum57af0722000-05-09 14:57:09 +0000100 try:
101 list = os.listdir(path)
102 except os.error:
Jeremy Hylton5b48c452001-01-26 17:08:32 +0000103 self.send_error(404, "No permission to list directory")
Guido van Rossum57af0722000-05-09 14:57:09 +0000104 return None
Raymond Hettinger6b59f5f2003-10-16 05:53:16 +0000105 list.sort(key=lambda a: a.lower())
Guido van Rossum57af0722000-05-09 14:57:09 +0000106 f = StringIO()
Georg Brandl6ee69522005-12-16 19:36:08 +0000107 displaypath = cgi.escape(urllib.unquote(self.path))
108 f.write("<title>Directory listing for %s</title>\n" % displaypath)
109 f.write("<h2>Directory listing for %s</h2>\n" % displaypath)
Guido van Rossum57af0722000-05-09 14:57:09 +0000110 f.write("<hr>\n<ul>\n")
111 for name in list:
112 fullname = os.path.join(path, name)
Johannes Gijsbers6d63a8d2004-08-21 10:43:29 +0000113 displayname = linkname = name
Guido van Rossum1d10f3e2000-05-21 16:25:29 +0000114 # Append / for directories or @ for symbolic links
115 if os.path.isdir(fullname):
116 displayname = name + "/"
Guido van Rossum1d105d12000-09-04 15:55:31 +0000117 linkname = name + "/"
Guido van Rossum57af0722000-05-09 14:57:09 +0000118 if os.path.islink(fullname):
119 displayname = name + "@"
Guido van Rossum1d10f3e2000-05-21 16:25:29 +0000120 # Note: a link to a directory displays with @ and links with /
Johannes Gijsbers6d63a8d2004-08-21 10:43:29 +0000121 f.write('<li><a href="%s">%s</a>\n'
122 % (urllib.quote(linkname), cgi.escape(displayname)))
Guido van Rossum57af0722000-05-09 14:57:09 +0000123 f.write("</ul>\n<hr>\n")
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000124 length = f.tell()
Guido van Rossum57af0722000-05-09 14:57:09 +0000125 f.seek(0)
Guido van Rossum1d10f3e2000-05-21 16:25:29 +0000126 self.send_response(200)
127 self.send_header("Content-type", "text/html")
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000128 self.send_header("Content-Length", str(length))
Guido van Rossum1d10f3e2000-05-21 16:25:29 +0000129 self.end_headers()
Guido van Rossum57af0722000-05-09 14:57:09 +0000130 return f
131
Guido van Rossume7e578f1995-08-04 04:00:20 +0000132 def translate_path(self, path):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000133 """Translate a /-separated PATH to the local filename syntax.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000134
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000135 Components that mean special things to the local file system
136 (e.g. drive or directory names) are ignored. (XXX They should
137 probably be diagnosed.)
Guido van Rossume7e578f1995-08-04 04:00:20 +0000138
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000139 """
Georg Brandl45ab2332006-01-13 17:05:56 +0000140 # abandon query parameters
141 path = urlparse.urlparse(path)[2]
Guido van Rossumd7b147b1999-11-16 19:04:32 +0000142 path = posixpath.normpath(urllib.unquote(path))
Eric S. Raymond304b6a32001-02-09 10:26:06 +0000143 words = path.split('/')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000144 words = filter(None, words)
145 path = os.getcwd()
146 for word in words:
147 drive, word = os.path.splitdrive(word)
148 head, word = os.path.split(word)
149 if word in (os.curdir, os.pardir): continue
150 path = os.path.join(path, word)
151 return path
Guido van Rossume7e578f1995-08-04 04:00:20 +0000152
153 def copyfile(self, source, outputfile):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000154 """Copy all data between two file objects.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000155
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000156 The SOURCE argument is a file object open for reading
157 (or anything with a read() method) and the DESTINATION
158 argument is a file object open for writing (or
159 anything with a write() method).
Guido van Rossume7e578f1995-08-04 04:00:20 +0000160
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000161 The only reason for overriding this would be to change
162 the block size or perhaps to replace newlines by CRLF
163 -- note however that this the default server uses this
164 to copy binary data as well.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000165
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000166 """
Moshe Zadka37c03ff2000-07-29 05:15:56 +0000167 shutil.copyfileobj(source, outputfile)
Guido van Rossume7e578f1995-08-04 04:00:20 +0000168
169 def guess_type(self, path):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000170 """Guess the type of a file.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000171
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000172 Argument is a PATH (a filename).
Guido van Rossume7e578f1995-08-04 04:00:20 +0000173
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000174 Return value is a string of the form type/subtype,
175 usable for a MIME Content-type header.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000176
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000177 The default implementation looks the file's extension
Andrew M. Kuchlingb839c1f2004-08-07 19:02:19 +0000178 up in the table self.extensions_map, using application/octet-stream
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000179 as a default; however it would be permissible (if
180 slow) to look inside the data to make a better guess.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000181
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000182 """
Guido van Rossume7e578f1995-08-04 04:00:20 +0000183
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000184 base, ext = posixpath.splitext(path)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000185 if ext in self.extensions_map:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000186 return self.extensions_map[ext]
Eric S. Raymondbf97c9d2001-02-09 10:18:37 +0000187 ext = ext.lower()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000188 if ext in self.extensions_map:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000189 return self.extensions_map[ext]
190 else:
191 return self.extensions_map['']
Guido van Rossume7e578f1995-08-04 04:00:20 +0000192
Guido van Rossum077153e2001-01-14 23:21:25 +0000193 extensions_map = mimetypes.types_map.copy()
194 extensions_map.update({
195 '': 'application/octet-stream', # Default
196 '.py': 'text/plain',
197 '.c': 'text/plain',
198 '.h': 'text/plain',
199 })
Guido van Rossume7e578f1995-08-04 04:00:20 +0000200
201
202def test(HandlerClass = SimpleHTTPRequestHandler,
Guido van Rossum5c3b3841998-12-07 04:08:30 +0000203 ServerClass = BaseHTTPServer.HTTPServer):
Guido van Rossume7e578f1995-08-04 04:00:20 +0000204 BaseHTTPServer.test(HandlerClass, ServerClass)
205
206
207if __name__ == '__main__':
208 test()