]> code.delx.au - webdl/blob - autosocks.py
Added license
[webdl] / autosocks.py
1 import subprocess
2 import sys
3
4
5 def detect_gnome():
6 """ Gnome via python-gconf """
7 from gconf import client_get_default
8 gconf_client = client_get_default()
9 mode = gconf_client.get_string("/system/proxy/mode")
10 if mode != "manual":
11 return None, None
12 host = gconf_client.get_string("/system/proxy/socks_host")
13 port = gconf_client.get_int("/system/proxy/socks_port")
14 return host, port
15
16 def detect_osx():
17 """ OS X 10.5 and up via PyObjC """
18 from SystemConfiguration import SCDynamicStoreCopyProxies
19 osx_proxy = SCDynamicStoreCopyProxies(None)
20 if osx_proxy.get("SOCKSEnable"):
21 host = osx_proxy.get("SOCKSProxy")
22 port = int(osx_proxy.get("SOCKSPort"))
23 return host, port
24 return None, None
25
26 def detect_kde():
27 """ KDE via command line, why no python bindings for KDE proxy settings? """
28 if os.environ.get("KDE_FULL_SESSION") != "true":
29 return None, None
30 p = subprocess.Popen(
31 [
32 "kreadconfig",
33 "--file",
34 "kioslaverc",
35 "--group",
36 "Proxy Settings",
37 "--key",
38 "socksProxy",
39 ],
40 shell=True,
41 stdout=subprocess.PIPE,
42 )
43 host, port = p.stdout.readline()[:-1].split(":")
44 p.close()
45 port = int(port)
46 return host, port
47
48 def detect_env():
49 """ fallback to environment variables """
50 socks_environ = os.environ.get("SOCKS_SERVER")
51 if not socks_environ:
52 return None, None
53 host, port = socks_environ
54 port = int(port)
55 return host, port
56
57
58 def configure_socks(host, port):
59 """ hijack socket.socket using SocksiPy """
60 try:
61 import socks, socket
62 except ImportError:
63 print >>sys.stderr, "Failed to use configured SOCKS proxy:", host, port
64 print >>sys.stderr, "Try installing SocksiPy: http://socksipy.sf.net"
65 return False
66
67 socket.socket = socks.socksocket
68 socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, host, port)
69 return True
70
71
72 def try_autosocks():
73 functions = [
74 detect_gnome,
75 detect_osx,
76 detect_kde,
77 detect_env,
78 ]
79 for func in functions:
80 host, port = None, None
81 try:
82 host, port = func()
83 except Exception, e:
84 pass
85 if host is not None and port is not None:
86 return configure_socks(host, port)
87 return False
88