python: Somewhat integrate async watchers with wsgidir currency.
[ashd.git] / python / htredir
CommitLineData
c3542a65
FT
1#!/usr/bin/python
2
3import sys, os, getopt
4
5def destructurl(url):
6 if "://" in url:
7 p = url.index("://")
8 scheme, url = url[:p], url[p + 3]
9 if "/" in url:
10 p = url.index("/")
11 host, url = url[:p], url[p + 1:]
12 else:
13 host, url = url, ""
14 else:
15 scheme = None
16 host = None
17 return scheme, host, url
18
19def usage(out):
20 out.write("usage: htredir [-hp] TARGET METHOD URL REST\n")
21
22status = "302 Found"
23opts, args = getopt.getopt(sys.argv[1:], "hp")
24for o, a in opts:
25 if o == "-h":
26 usage(sys.stdout)
27 sys.exit(0)
28 elif o == "-p":
29 status = "301 Moved Permanently"
30if len(args) != 4:
31 usage(sys.stderr)
32 sys.exit(1)
33target, method, url, rest = args
ff309bc9
FT
34scheme = os.getenv("REQ_X_ASH_PROTOCOL")
35host = os.getenv("REQ_HOST")
c3542a65
FT
36me = url
37if me[-len(rest):] == rest:
38 me = me[:-len(rest)]
39tscheme, thost, target = destructurl(target)
40if tscheme: scheme = tscheme
41if thost: host = thost
42if len(target) > 0 and target[0] == "/":
43 pass
44else:
45 if "/" in me:
46 p = me.rindex("/")
47 target = me[:p + 1] + target
48if len(target) > 0 and target[0] == "/":
49 target = target[1:]
50if scheme and host:
51 target = "%s://%s/%s" % (scheme, host, target)
52else:
53 # Illegal, but the only option (the premises are illegal anyway)
54 pass
55
d4331238
FT
56try:
57 sys.stdout.write("HTTP/1.1 %s\n" % status)
58 sys.stdout.write("Location: %s\n" % target)
59 sys.stdout.write("Content-Length: 0\n")
60 sys.stdout.write("\n")
61except IOError:
62 sys.exit(1)