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