]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/socks.py
Update the changelog.
[youtubedl] / youtube_dl / socks.py
1 # Public Domain SOCKS proxy protocol implementation
2 # Adapted from https://gist.github.com/bluec0re/cafd3764412967417fd3
3
4 from __future__ import unicode_literals
5
6 # References:
7 # SOCKS4 protocol http://www.openssh.com/txt/socks4.protocol
8 # SOCKS4A protocol http://www.openssh.com/txt/socks4a.protocol
9 # SOCKS5 protocol https://tools.ietf.org/html/rfc1928
10 # SOCKS5 username/password authentication https://tools.ietf.org/html/rfc1929
11
12 import collections
13 import socket
14
15 from .compat import (
16 compat_ord,
17 compat_struct_pack,
18 compat_struct_unpack,
19 )
20
21 __author__ = 'Timo Schmid <coding@timoschmid.de>'
22
23 SOCKS4_VERSION = 4
24 SOCKS4_REPLY_VERSION = 0x00
25 # Excerpt from SOCKS4A protocol:
26 # if the client cannot resolve the destination host's domain name to find its
27 # IP address, it should set the first three bytes of DSTIP to NULL and the last
28 # byte to a non-zero value.
29 SOCKS4_DEFAULT_DSTIP = compat_struct_pack('!BBBB', 0, 0, 0, 0xFF)
30
31 SOCKS5_VERSION = 5
32 SOCKS5_USER_AUTH_VERSION = 0x01
33 SOCKS5_USER_AUTH_SUCCESS = 0x00
34
35
36 class Socks4Command(object):
37 CMD_CONNECT = 0x01
38 CMD_BIND = 0x02
39
40
41 class Socks5Command(Socks4Command):
42 CMD_UDP_ASSOCIATE = 0x03
43
44
45 class Socks5Auth(object):
46 AUTH_NONE = 0x00
47 AUTH_GSSAPI = 0x01
48 AUTH_USER_PASS = 0x02
49 AUTH_NO_ACCEPTABLE = 0xFF # For server response
50
51
52 class Socks5AddressType(object):
53 ATYP_IPV4 = 0x01
54 ATYP_DOMAINNAME = 0x03
55 ATYP_IPV6 = 0x04
56
57
58 class ProxyError(IOError):
59 ERR_SUCCESS = 0x00
60
61 def __init__(self, code=None, msg=None):
62 if code is not None and msg is None:
63 msg = self.CODES.get(code) and 'unknown error'
64 super(ProxyError, self).__init__(code, msg)
65
66
67 class InvalidVersionError(ProxyError):
68 def __init__(self, expected_version, got_version):
69 msg = ('Invalid response version from server. Expected {0:02x} got '
70 '{1:02x}'.format(expected_version, got_version))
71 super(InvalidVersionError, self).__init__(0, msg)
72
73
74 class Socks4Error(ProxyError):
75 ERR_SUCCESS = 90
76
77 CODES = {
78 91: 'request rejected or failed',
79 92: 'request rejected becasue SOCKS server cannot connect to identd on the client',
80 93: 'request rejected because the client program and identd report different user-ids'
81 }
82
83
84 class Socks5Error(ProxyError):
85 ERR_GENERAL_FAILURE = 0x01
86
87 CODES = {
88 0x01: 'general SOCKS server failure',
89 0x02: 'connection not allowed by ruleset',
90 0x03: 'Network unreachable',
91 0x04: 'Host unreachable',
92 0x05: 'Connection refused',
93 0x06: 'TTL expired',
94 0x07: 'Command not supported',
95 0x08: 'Address type not supported',
96 0xFE: 'unknown username or invalid password',
97 0xFF: 'all offered authentication methods were rejected'
98 }
99
100
101 class ProxyType(object):
102 SOCKS4 = 0
103 SOCKS4A = 1
104 SOCKS5 = 2
105
106 Proxy = collections.namedtuple('Proxy', (
107 'type', 'host', 'port', 'username', 'password', 'remote_dns'))
108
109
110 class sockssocket(socket.socket):
111 def __init__(self, *args, **kwargs):
112 self._proxy = None
113 super(sockssocket, self).__init__(*args, **kwargs)
114
115 def setproxy(self, proxytype, addr, port, rdns=True, username=None, password=None):
116 assert proxytype in (ProxyType.SOCKS4, ProxyType.SOCKS4A, ProxyType.SOCKS5)
117
118 self._proxy = Proxy(proxytype, addr, port, username, password, rdns)
119
120 def recvall(self, cnt):
121 data = b''
122 while len(data) < cnt:
123 cur = self.recv(cnt - len(data))
124 if not cur:
125 raise IOError('{0} bytes missing'.format(cnt - len(data)))
126 data += cur
127 return data
128
129 def _recv_bytes(self, cnt):
130 data = self.recvall(cnt)
131 return compat_struct_unpack('!{0}B'.format(cnt), data)
132
133 @staticmethod
134 def _len_and_data(data):
135 return compat_struct_pack('!B', len(data)) + data
136
137 def _check_response_version(self, expected_version, got_version):
138 if got_version != expected_version:
139 self.close()
140 raise InvalidVersionError(expected_version, got_version)
141
142 def _resolve_address(self, destaddr, default, use_remote_dns):
143 try:
144 return socket.inet_aton(destaddr)
145 except socket.error:
146 if use_remote_dns and self._proxy.remote_dns:
147 return default
148 else:
149 return socket.inet_aton(socket.gethostbyname(destaddr))
150
151 def _setup_socks4(self, address, is_4a=False):
152 destaddr, port = address
153
154 ipaddr = self._resolve_address(destaddr, SOCKS4_DEFAULT_DSTIP, use_remote_dns=is_4a)
155
156 packet = compat_struct_pack('!BBH', SOCKS4_VERSION, Socks4Command.CMD_CONNECT, port) + ipaddr
157
158 username = (self._proxy.username or '').encode('utf-8')
159 packet += username + b'\x00'
160
161 if is_4a and self._proxy.remote_dns:
162 packet += destaddr.encode('utf-8') + b'\x00'
163
164 self.sendall(packet)
165
166 version, resp_code, dstport, dsthost = compat_struct_unpack('!BBHI', self.recvall(8))
167
168 self._check_response_version(SOCKS4_REPLY_VERSION, version)
169
170 if resp_code != Socks4Error.ERR_SUCCESS:
171 self.close()
172 raise Socks4Error(resp_code)
173
174 return (dsthost, dstport)
175
176 def _setup_socks4a(self, address):
177 self._setup_socks4(address, is_4a=True)
178
179 def _socks5_auth(self):
180 packet = compat_struct_pack('!B', SOCKS5_VERSION)
181
182 auth_methods = [Socks5Auth.AUTH_NONE]
183 if self._proxy.username and self._proxy.password:
184 auth_methods.append(Socks5Auth.AUTH_USER_PASS)
185
186 packet += compat_struct_pack('!B', len(auth_methods))
187 packet += compat_struct_pack('!{0}B'.format(len(auth_methods)), *auth_methods)
188
189 self.sendall(packet)
190
191 version, method = self._recv_bytes(2)
192
193 self._check_response_version(SOCKS5_VERSION, version)
194
195 if method == Socks5Auth.AUTH_NO_ACCEPTABLE:
196 self.close()
197 raise Socks5Error(method)
198
199 if method == Socks5Auth.AUTH_USER_PASS:
200 username = self._proxy.username.encode('utf-8')
201 password = self._proxy.password.encode('utf-8')
202 packet = compat_struct_pack('!B', SOCKS5_USER_AUTH_VERSION)
203 packet += self._len_and_data(username) + self._len_and_data(password)
204 self.sendall(packet)
205
206 version, status = self._recv_bytes(2)
207
208 self._check_response_version(SOCKS5_USER_AUTH_VERSION, version)
209
210 if status != SOCKS5_USER_AUTH_SUCCESS:
211 self.close()
212 raise Socks5Error(Socks5Error.ERR_GENERAL_FAILURE)
213
214 def _setup_socks5(self, address):
215 destaddr, port = address
216
217 ipaddr = self._resolve_address(destaddr, None, use_remote_dns=True)
218
219 self._socks5_auth()
220
221 reserved = 0
222 packet = compat_struct_pack('!BBB', SOCKS5_VERSION, Socks5Command.CMD_CONNECT, reserved)
223 if ipaddr is None:
224 destaddr = destaddr.encode('utf-8')
225 packet += compat_struct_pack('!B', Socks5AddressType.ATYP_DOMAINNAME)
226 packet += self._len_and_data(destaddr)
227 else:
228 packet += compat_struct_pack('!B', Socks5AddressType.ATYP_IPV4) + ipaddr
229 packet += compat_struct_pack('!H', port)
230
231 self.sendall(packet)
232
233 version, status, reserved, atype = self._recv_bytes(4)
234
235 self._check_response_version(SOCKS5_VERSION, version)
236
237 if status != Socks5Error.ERR_SUCCESS:
238 self.close()
239 raise Socks5Error(status)
240
241 if atype == Socks5AddressType.ATYP_IPV4:
242 destaddr = self.recvall(4)
243 elif atype == Socks5AddressType.ATYP_DOMAINNAME:
244 alen = compat_ord(self.recv(1))
245 destaddr = self.recvall(alen)
246 elif atype == Socks5AddressType.ATYP_IPV6:
247 destaddr = self.recvall(16)
248 destport = compat_struct_unpack('!H', self.recvall(2))[0]
249
250 return (destaddr, destport)
251
252 def _make_proxy(self, connect_func, address):
253 if not self._proxy:
254 return connect_func(self, address)
255
256 result = connect_func(self, (self._proxy.host, self._proxy.port))
257 if result != 0 and result is not None:
258 return result
259 setup_funcs = {
260 ProxyType.SOCKS4: self._setup_socks4,
261 ProxyType.SOCKS4A: self._setup_socks4a,
262 ProxyType.SOCKS5: self._setup_socks5,
263 }
264 setup_funcs[self._proxy.type](address)
265 return result
266
267 def connect(self, address):
268 self._make_proxy(socket.socket.connect, address)
269
270 def connect_ex(self, address):
271 return self._make_proxy(socket.socket.connect_ex, address)