1 import time, calendar, collections, binascii, base64
4 400: ("Bad Request", "Invalid HTTP request."),
5 401: ("Unauthorized", "Authentication must be provided for the requested resource."),
6 403: ("Forbidden", "You are not authorized to request the requested resource."),
7 404: ("Not Found", "The requested resource was not found."),
8 405: ("Method Not Allowed", "The request method is not recognized or permitted by the requested resource."),
9 500: ("Server Error", "An internal error occurred."),
10 501: ("Not Implemented", "The requested functionality has not been implemented."),
11 503: ("Service Unavailable", "Service is being denied at this time."),
15 return time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime(ts))
20 if tz[0] != " " or (tz[1] != "+" and tz[1] != "-") or not tz[2:].isdigit():
23 tz = (((tz / 100) * 60) + (tz % 100)) * 60
24 return calendar.timegm(time.strptime(dstr, "%a, %d %b %Y %H:%M:%S")) - tz
28 while p < len(hstr) and hstr[p].isspace():
59 return buf.strip(), pws(p)
61 val, p = token(p, ";")
68 if k == "" or hstr[p:p + 1] != '=':
88 def simpleerror(env, startreq, code, title, msg):
89 buf = """<?xml version="1.0" encoding="US-ASCII"?>
90 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
91 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
100 """ % (title, title, htmlq(msg))
101 buf = buf.encode("us-ascii")
102 startreq("%i %s" % (code, title), [("Content-Type", "text/html"), ("Content-Length", str(len(buf)))])
106 if isinstance(url, str):
107 url = url.encode("utf-8")
109 invalid = b"%;&=+#?/\"'"
111 if c in invalid or (c <= 32) or (c >= 128):
117 class urlerror(ValueError):
123 raise urlerror("Protocol not found in absolute URL `%s'" % url)
125 l = url.find("/", p + 3)
127 raise urlerror("Local part not found in absolute URL `%s'" % url)
134 query = local[q + 1:]
136 return proto, host, local, query
138 def consurl(proto, host, local, query=""):
139 if len(local) < 1 and local[0] != '/':
140 raise urlerror("Local part of URL must begin with a slash")
141 ret = "%s://%s%s" % (proto, host, local)
146 def appendurl(url, other):
149 proto, host, local, query = parseurl(url)
150 if len(other) > 0 and other[0] == '/':
151 return consurl(proto, host, other)
154 return consurl(proto, host, local[:p + 1] + other)
157 host = req.ihead.get("Host", None)
159 raise Exception("Could not reconstruct URL because no Host header was sent")
163 return "%s://%s/" % (proto, host)
167 if req.uriname[0] != '/':
168 raise Exception("Malformed local part when reconstructing URL")
169 return siteurl(req) + req.uriname[1:]
171 def requrl(req, qs=True):
173 if req.uri[0] != '/':
174 raise Exception("Malformed local part when reconstructing URL")
180 return siteurl(req) + pf
182 def parstring(pars={}, **augment):
192 if buf != "": buf += "&"
193 buf += urlq(key) + "=" + urlq(str(val))
194 for key, val in augment.items():
197 if buf != "": buf += "&"
198 buf += urlq(key) + "=" + urlq(str(val))
201 def parurl(url, pars={}, **augment):
202 qs = parstring(pars, **augment)
204 return url + ("&" if "?" in url else "?") + qs
208 # Wrap these, since binascii is a bit funky. :P
210 return base64.b16encode(bs).decode("us-ascii")
212 if not isinstance(es, collections.ByteString):
214 es = es.encode("us-ascii")
216 raise binascii.Error("non-ascii character in hex-string")
217 return base64.b16decode(es)
219 return base64.b32encode(bs).decode("us-ascii")
221 if not isinstance(es, collections.ByteString):
223 es = es.encode("us-ascii")
225 raise binascii.Error("non-ascii character in base32-string")
226 if (len(es) % 8) != 0:
227 es += b"=" * (8 - (len(es) % 8))
228 es = es.upper() # The whole point of Base32 is that it's case-insensitive :P
229 return base64.b32decode(es)
231 return base64.b64encode(bs).decode("us-ascii")
233 if not isinstance(es, collections.ByteString):
235 es = es.encode("us-ascii")
237 raise binascii.Error("non-ascii character in base64-string")
238 if (len(es) % 4) != 0:
239 es += b"=" * (4 - (len(es) % 4))
240 return base64.b64decode(es)
246 for c in range(ord('0'), ord('9') + 1):
248 for c in range(ord('A'), ord('Z') + 1):
250 for c in range(ord('a'), ord('z') + 1):
253 _quoprisafe = _quoprisafe()
254 def quopri(s, charset="utf-8"):
255 bv = s.encode(charset)
256 qn = sum(not _quoprisafe[b] for b in bv)
260 return "=?%s?B?%s?=" % (charset, enb64(bv))
262 return "=?%s?Q?%s?=" % (charset, "".join(chr(b) if _quoprisafe[b] else "=%02X" % b for b in bv))
264 class mimeparam(object):
265 def __init__(self, name, val, fallback=None, charset="utf-8", lang=""):
268 self.fallback = fallback
269 self.charset = charset
273 self.name.encode("ascii")
275 self.val.encode("ascii")
279 return "%s=%s" % (self.name, self.val)
280 val = self.val.encode(self.charset)
281 self.charset.encode("ascii")
282 self.lang.encode("ascii")
284 if self.fallback is not None:
285 self.fallback.encode("ascii")
286 ret += "%s=%s; " % (self.name, self.fallback)
287 ret += "%s*=%s'%s'%s" % (self.name, self.charset, self.lang, urlq(val))
290 class mimeheader(object):
291 def __init__(self, name, val, *, mime_charset="utf-8", mime_lang="", **params):
295 self.charset = mime_charset
296 self.lang = mime_lang
297 for k, v in params.items():
300 def __getitem__(self, nm):
301 return self.params[nm.lower()]
303 def __setitem__(self, nm, val):
304 if not isinstance(val, mimeparam):
305 val = mimeparam(nm, val, charset=self.charset, lang=self.lang)
306 self.params[nm.lower()] = val
308 def __delitem__(self, nm):
309 del self.params[nm.lower()]
314 parts.append(quopri(self.val))
315 parts.extend(str(x) for x in self.params.values())
316 return("; ".join(parts))
319 if self.name is None:
321 return "%s: %s" % (self.name, self.value())