plumber

Plumber – a modern approach to plumbing
git clone git://r-36.net/plumber
Log | Files | Refs | README | LICENSE

webopener (2552B)


      1 #!/usr/bin/env python3
      2 # coding=utf-8
      3 #
      4 # Copy me if you can.
      5 # by 20h
      6 #
      7 
      8 import sys
      9 import os
     10 import re
     11 import getopt
     12 from subprocess import Popen
     13 import requests
     14 
     15 # URI match, header match, match type, command '%s' % (uri)
     16 MATCH_HEADER	= 1<<0
     17 MATCH_URI	= 1<<1
     18 MATCH_ALL	= 0xFF
     19 
     20 webrules = [
     21 	[".*", {"X-Future": ".*opher.*"}, MATCH_HEADER, os.environ.get('PLUMB_WEB') + " '%s'"],
     22 	[".*", {}, MATCH_ALL, os.environ.get('PLUMB_WEB') + " '%s'"],
     23 ]
     24 
     25 def usage(app):
     26 	app = os.path.basename(app)
     27 	sys.stderr.write("usage: %s [-dhHp] URI\n" % (app))
     28 	sys.exit(1)
     29 
     30 def runcmd(cmd, arg=None):
     31 	fd = open("/dev/null")
     32 	if os.fork() == 0:
     33 		if arg != None:
     34 			cmd = cmd % (arg)
     35 		p = Popen(cmd, shell=True, stdout=fd, stderr=fd)
     36 		p.wait()
     37 
     38 def main(args):
     39 	try:
     40 		opts, largs = getopt.getopt(args[1:], 'hHdp')
     41 	except getopt.GetoptError as err:
     42 		print(str(err))
     43 		usage(args[0])
     44 
     45 	dodebug = False
     46 	printheaders = False 
     47 	dopretend = False
     48 	for o, a in opts:
     49 		if o == "-h":
     50 			usage(args[0])
     51 		elif o == "-d":
     52 			dodebug = True
     53 		elif o == "-H":
     54 			printheaders = True
     55 		elif o == "-p":
     56 			dopretend = True
     57 		else:
     58 			assert False, "unhandled option"
     59 	
     60 	if len(largs) < 1:
     61 		runcmd(webrules[-1][3], "")
     62 		return 0
     63 
     64 	uri = " ".join(largs)
     65 	didprepend = False
     66 	if "http" != uri[0:4]:
     67 		muri = "https://%s" % (uri)
     68 		didprepend = True
     69 	else:
     70 		muri = uri
     71 		
     72 	try:
     73 		req = requests.head(muri)
     74 	except:
     75 		if didprepend == True:
     76 			muri = "http://%s" % (muri[8:])
     77 			try:
     78 				req = requests.head(muri)
     79 			except:
     80 				if dopretend == False:
     81 					runcmd(webrules[-1][3], uri)
     82 				return 0
     83 		else:
     84 			if dopretend == False:
     85 				runcmd(webrules[-1][3], uri)
     86 			return 0
     87 
     88 	if printheaders == True:
     89 		for h in req.headers:
     90 			print("%s: %s" % (h, req.headers[h]))
     91 
     92 	if didprepend == True:
     93 		uri = muri
     94 
     95 	if dodebug == True:
     96 		print("Using '%s'" % (uri))
     97 
     98 	frule = None
     99 	for rule in webrules:
    100 		if (rule[2] & MATCH_URI) > 0:
    101 			if re.search(rule[0], uri) == None:
    102 				continue
    103 
    104 		if (rule[2] & MATCH_HEADER) > 0 and len(rule[1]) > 0:
    105 			didmatch = False
    106 			for header in rule[1]:
    107 				for h in req.headers:
    108 					if re.search(header, h) != None:
    109 						if re.search(rule[1][header],\
    110 								req.headers[h])\
    111 								!= None:
    112 							didmatch = True
    113 						else:
    114 							didmatch = False
    115 			if didmatch == False:
    116 				continue
    117 
    118 		frule = rule
    119 		break
    120 
    121 	if frule == None:
    122 		print("No match found.")
    123 
    124 	if dodebug:
    125 		print("found match: %s -> %s" % (frule[3], uri))
    126 
    127 	if dopretend == False:
    128 		runcmd(frule[3], uri)
    129 
    130 	return 0
    131 
    132 if __name__ == "__main__":
    133 	sys.exit(main(sys.argv))
    134