| 1 | #!/usr/bin/python |
| 2 | |
| 3 | import sys, os, getopt |
| 4 | |
| 5 | def 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 | |
| 19 | def usage(out): |
| 20 | out.write("usage: htredir [-hp] TARGET METHOD URL REST\n") |
| 21 | |
| 22 | status = "302 Found" |
| 23 | opts, args = getopt.getopt(sys.argv[1:], "hp") |
| 24 | for 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" |
| 30 | if len(args) != 4: |
| 31 | usage(sys.stderr) |
| 32 | sys.exit(1) |
| 33 | target, method, url, rest = args |
| 34 | scheme = os.getenv("REQ_X_ASH_PROTOCOL") |
| 35 | host = os.getenv("REQ_HOST") |
| 36 | me = url |
| 37 | if me[-len(rest):] == rest: |
| 38 | me = me[:-len(rest)] |
| 39 | tscheme, thost, target = destructurl(target) |
| 40 | if tscheme: scheme = tscheme |
| 41 | if thost: host = thost |
| 42 | if len(target) > 0 and target[0] == "/": |
| 43 | pass |
| 44 | else: |
| 45 | if "/" in me: |
| 46 | p = me.rindex("/") |
| 47 | target = me[:p + 1] + target |
| 48 | if len(target) > 0 and target[0] == "/": |
| 49 | target = target[1:] |
| 50 | if scheme and host: |
| 51 | target = "%s://%s/%s" % (scheme, host, target) |
| 52 | else: |
| 53 | # Illegal, but the only option (the premises are illegal anyway) |
| 54 | pass |
| 55 | |
| 56 | try: |
| 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") |
| 61 | except IOError: |
| 62 | sys.exit(1) |