1 """Module for handling server-side-include formatted files
3 This module is quite incomplete. I might complete it with more
4 features as I need them. It will probably never be entirely compliant
5 with Apache's version due to architectural differences.
8 import sys, os, io, time, logging, functools
11 log = logging.getLogger("ssi")
13 def parsecmd(text, p):
15 while text[p].isspace(): p += 1
17 while not text[p].isspace():
22 while text[p].isspace(): p += 1
23 if text[p:p + 3] == "-->":
24 return cmd, pars, p + 3
26 while text[p].isalnum():
31 while text[p].isspace(): p += 1
35 while text[p].isspace(): p += 1
37 if q != '"' and q != "'" and q != '`':
47 return None, {}, len(text)
49 class context(object):
50 def __init__(self, out, root):
54 self.vars["DOCUMENT_NAME"] = os.path.basename(root.path)
55 self.vars["DATE_GMT"] = time.asctime(time.gmtime(now))
56 self.vars["DATE_LOCAL"] = time.asctime(time.localtime(now))
57 self.vars["LAST_MODIFIED"] = time.asctime(time.localtime(root.mtime))
59 class ssifile(object):
60 def __init__(self, path):
62 sb = os.stat(self.path)
63 self.cache = (sb.st_mode & 0o010) != 0
64 self.mtime = int(sb.st_mtime)
65 with open(path) as fp:
66 self.parts = self.parse(fp.read())
68 def text(self, text, ctx):
71 def echo(self, var, enc, ctx):
73 ctx.out.write(enc(ctx.vars[var]))
75 def include(self, path, ctx):
77 nest = getfile(os.path.join(os.path.dirname(self.path), path))
79 log.warning("%s: could not find included file %s" % (self.path, path))
83 def process(self, ctx):
84 for part in self.parts:
87 def resolvecmd(self, cmd, pars):
90 return functools.partial(self.include, pars["file"])
91 elif "virtual" in pars:
92 # XXX: For now, just include the file as-is. Change
94 return functools.partial(self.include, pars["virtual"])
96 log.warning("%s: invalid `include' directive" % self.path)
100 log.warning("%s: invalid `echo' directive" % self.path)
102 enc = wsgiutil.htmlquote
103 if "encoding" in pars:
104 if pars["encoding"] == "entity":
105 enc = wsgiutil.htmlquote
106 return functools.partial(self.echo, pars["var"], enc)
108 log.warning("%s: unknown SSI command `%s'" % (self.path, cmd))
111 def parse(self, text):
115 p2 = text.find("<!--#", p)
117 ret.append(functools.partial(self.text, text[p:]))
119 ret.append(functools.partial(self.text, text[p:p2]))
120 cmd, pars, p = parsecmd(text, p2 + 5)
122 cmd = self.resolvecmd(cmd, pars)
129 path = os.path.normpath(path)
130 cf = filecache.get(path)
132 cf = filecache[path] = ssifile(path)
133 elif int(os.stat(path).st_mtime) != cf.mtime:
134 cf = filecache[path] = ssifile(path)
137 def wsgi(env, startreq):
139 if env["PATH_INFO"] != "":
140 return wsgiutil.simpleerror(env, startreq, 404, "Not Found", "The resource specified by the URL does not exist.")
141 root = getfile(env["SCRIPT_FILENAME"])
143 if root.cache and "HTTP_IF_MODIFIED_SINCE" in env:
145 lmt = wsgiutil.phttpdate(env["HTTP_IF_MODIFIED_SINCE"])
146 if root.mtime <= lmt:
147 startreq("304 Not Modified", [("Content-Length", "0")])
153 root.process(context(buf, root))
155 return wsgiutil.simpleerror(env, startreq, 500, "Internal Error", "The server encountered an unpexpected error while handling SSI.")
156 ret = buf.getvalue().encode("utf8")
157 head = [("Content-Type", "text/html; charset=UTF-8"), ("Content-Length", str(len(ret)))]
159 head.append(("Last-Modified", wsgiutil.httpdate(root.mtime)))
160 startreq("200 OK", head)