etc: Add environment option to run init.d/ashd silently.
[ashd.git] / python3 / scgi-wsgi3
index 9befb25..a8fccf0 100755 (executable)
@@ -1,23 +1,32 @@
 #!/usr/bin/python3
 
-import sys, os, getopt
+import sys, os, getopt, logging, collections
 import socket
-import ashd.scgi
+import ashd.scgi, ashd.serve
+try:
+    import pdm.srv
+except:
+    pdm = None
 
 def usage(out):
-    out.write("usage: scgi-wsgi [-hA] [-p MODPATH] [-T [HOST:]PORT] HANDLER-MODULE [ARGS...]\n")
+    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")
 
 sk = None
+hspec = "free", {}
 modwsgi_compat = False
-opts, args = getopt.getopt(sys.argv[1:], "+hAp:T:")
+setlog = True
+opts, args = getopt.getopt(sys.argv[1:], "+hALp:t:T:m:")
 for o, a in opts:
     if o == "-h":
         usage(sys.stdout)
         sys.exit(0)
     elif o == "-p":
         sys.path.insert(0, a)
+    elif o == "-L":
+        setlog = False
     elif o == "-T":
         sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+        sk.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
         p = a.rfind(":")
         if p < 0:
             bindhost = "localhost"
@@ -29,9 +38,16 @@ for o, a in opts:
         sk.listen(32)
     elif o == "-A":
         modwsgi_compat = True
+    elif o == "-m":
+        if pdm is not None:
+            pdm.srv.listen(a)
+    elif o == "-t":
+        hspec = ashd.serve.parsehspec(a)
 if len(args) < 1:
     usage(sys.stderr)
     sys.exit(1)
+if setlog:
+    logging.basicConfig(format="scgi-wsgi3(%(name)s): %(levelname)s: %(message)s")
 
 if sk is None:
     # This is suboptimal, since the socket on stdin is not necessarily
@@ -42,17 +58,96 @@ if sk is None:
 try:
     handlermod = __import__(args[0], fromlist = ["dummy"])
 except ImportError as exc:
-    sys.stderr.write("scgi-wsgi: handler %s not found: %s\n" % (args[0], exc.args[0]))
+    sys.stderr.write("scgi-wsgi3: handler %s not found: %s\n" % (args[0], exc.args[0]))
     sys.exit(1)
 if not modwsgi_compat:
     if not hasattr(handlermod, "wmain"):
-        sys.stderr.write("scgi-wsgi: handler %s has no `wmain' function\n" % args[0])
+        sys.stderr.write("scgi-wsgi3: handler %s has no `wmain' function\n" % args[0])
         sys.exit(1)
     handler = handlermod.wmain(*args[1:])
 else:
     if not hasattr(handlermod, "application"):
-        sys.stderr.write("scgi-wsgi: handler %s has no `application' object\n" % args[0])
+        sys.stderr.write("scgi-wsgi3: handler %s has no `application' object\n" % args[0])
         sys.exit(1)
     handler = handlermod.application
 
-ashd.scgi.servescgi(sk, ashd.scgi.wrapwsgi(handler))
+def mkenv(head, sk):
+    try:
+        env = ashd.scgi.decodehead(head, "utf-8")
+        env["wsgi.uri_encoding"] = "utf-8"
+    except UnicodeError:
+        env = ashd.scgi.decodehead(head, "latin-1")
+        env["wsgi.uri_encoding"] = "latin-1"
+    env["wsgi.version"] = 1, 0
+    if "HTTP_X_ASH_PROTOCOL" in env:
+        env["wsgi.url_scheme"] = env["HTTP_X_ASH_PROTOCOL"]
+    elif "HTTPS" in env:
+        env["wsgi.url_scheme"] = "https"
+    else:
+        env["wsgi.url_scheme"] = "http"
+    env["wsgi.input"] = sk
+    env["wsgi.errors"] = sys.stderr
+    env["wsgi.multithread"] = True
+    env["wsgi.multiprocess"] = False
+    env["wsgi.run_once"] = False
+    return env
+
+def recode(thing):
+    if isinstance(thing, collections.ByteString):
+        return thing
+    else:
+        return str(thing).encode("latin-1")
+
+class request(ashd.serve.wsgirequest):
+    def __init__(self, *, sk, **kw):
+        super().__init__(**kw)
+        self.bsk = sk.dup()
+        self.sk = self.bsk.makefile("rwb")
+
+    def mkenv(self):
+        return mkenv(ashd.scgi.readhead(self.sk), self.sk)
+
+    def handlewsgi(self, env, startreq):
+        return handler(env, startreq)
+
+    def fileno(self):
+        return self.bsk.fileno()
+
+    def writehead(self, status, headers):
+        w = self.buffer.extend
+        w(b"Status: " + recode(status) + b"\n")
+        for nm, val in headers:
+            w(recode(nm) + b": " + recode(val) + b"\n")
+        w(b"\n")
+
+    def flush(self):
+        try:
+            ret = self.bsk.send(self.buffer, socket.MSG_DONTWAIT)
+            self.buffer[:ret] = b""
+        except IOError:
+            raise ashd.serve.closed()
+
+    def close(self):
+        self.sk.close()
+        self.bsk.close()
+
+if hspec[0] not in ashd.serve.names:
+    sys.stderr.write("scgi-wsgi3: no such request handler: %s\n" % hspec[0])
+    sys.exit(1)
+hclass = ashd.serve.names[hspec[0]]
+try:
+    hargs = hclass.parseargs(**hspec[1])
+except ValueError as exc:
+    sys.stderr.write("scgi-wsgi3: %s\n" % exc)
+    sys.exit(1)
+
+reqhandler = hclass(**hargs)
+try:
+    while True:
+        nsk, addr = sk.accept()
+        try:
+            reqhandler.handle(request(sk=nsk, handler=reqhandler))
+        finally:
+            nsk.close()
+finally:
+    reqhandler.close()