3 import sys, os, getopt, logging, collections
5 import ashd.scgi, ashd.serve
12 out.write("usage: scgi-wsgi3 [-hAL] [-m PDM-SPEC] [-p MODPATH] [-t REQUEST-HANDLER[:PAR[=VAL](,PAR[=VAL])...]] [-T [HOST:]PORT] HANDLER-MODULE [ARGS...]\n")
16 modwsgi_compat = False
18 opts, args = getopt.getopt(sys.argv[1:], "+hALp:t:T:m:")
28 sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
29 sk.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
32 bindhost = "localhost"
36 bindport = int(a[p + 1:])
37 sk.bind((bindhost, bindport))
45 hspec = ashd.serve.parsehspec(a)
50 logging.basicConfig(format="scgi-wsgi3(%(name)s): %(levelname)s: %(message)s")
53 # This is suboptimal, since the socket on stdin is not necessarily
54 # AF_UNIX, but Python does not seem to offer any way around it,
56 sk = socket.fromfd(0, socket.AF_UNIX, socket.SOCK_STREAM)
59 handlermod = __import__(args[0], fromlist = ["dummy"])
60 except ImportError as exc:
61 sys.stderr.write("scgi-wsgi3: handler %s not found: %s\n" % (args[0], exc.args[0]))
63 if not modwsgi_compat:
64 if not hasattr(handlermod, "wmain"):
65 sys.stderr.write("scgi-wsgi3: handler %s has no `wmain' function\n" % args[0])
67 handler = handlermod.wmain(*args[1:])
69 if not hasattr(handlermod, "application"):
70 sys.stderr.write("scgi-wsgi3: handler %s has no `application' object\n" % args[0])
72 handler = handlermod.application
76 env = ashd.scgi.decodehead(head, "utf-8")
77 env["wsgi.uri_encoding"] = "utf-8"
79 env = ashd.scgi.decodehead(head, "latin-1")
80 env["wsgi.uri_encoding"] = "latin-1"
81 env["wsgi.version"] = 1, 0
82 if "HTTP_X_ASH_PROTOCOL" in env:
83 env["wsgi.url_scheme"] = env["HTTP_X_ASH_PROTOCOL"]
85 env["wsgi.url_scheme"] = "https"
87 env["wsgi.url_scheme"] = "http"
88 env["wsgi.input"] = sk
89 env["wsgi.errors"] = sys.stderr
90 env["wsgi.multithread"] = True
91 env["wsgi.multiprocess"] = False
92 env["wsgi.run_once"] = False
96 if isinstance(thing, collections.ByteString):
99 return str(thing).encode("latin-1")
101 class request(ashd.serve.wsgirequest):
102 def __init__(self, *, sk, **kw):
103 super().__init__(**kw)
105 self.sk = self.bsk.makefile("rwb")
108 return mkenv(ashd.scgi.readhead(self.sk), self.sk)
110 def handlewsgi(self, env, startreq):
111 return handler(env, startreq)
114 return self.bsk.fileno()
116 def writehead(self, status, headers):
117 w = self.buffer.extend
118 w(b"Status: " + recode(status) + b"\n")
119 for nm, val in headers:
120 w(recode(nm) + b": " + recode(val) + b"\n")
125 ret = self.bsk.send(self.buffer, socket.MSG_DONTWAIT)
126 self.buffer[:ret] = b""
128 raise ashd.serve.closed()
134 if hspec[0] not in ashd.serve.names:
135 sys.stderr.write("scgi-wsgi3: no such request handler: %s\n" % hspec[0])
137 hclass = ashd.serve.names[hspec[0]]
139 hargs = hclass.parseargs(**hspec[1])
140 except ValueError as exc:
141 sys.stderr.write("scgi-wsgi3: %s\n" % exc)
144 reqhandler = hclass(**hargs)
147 nsk, addr = sk.accept()
149 reqhandler.handle(request(sk=nsk, handler=reqhandler))