compat_urllib_parse_unquote: crash fix: only decode valid hex
[youtube-dl] / youtube_dl / compat.py
1 from __future__ import unicode_literals
2
3 import collections
4 import getpass
5 import optparse
6 import os
7 import re
8 import shutil
9 import socket
10 import subprocess
11 import sys
12 import itertools
13
14
15 try:
16     import urllib.request as compat_urllib_request
17 except ImportError:  # Python 2
18     import urllib2 as compat_urllib_request
19
20 try:
21     import urllib.error as compat_urllib_error
22 except ImportError:  # Python 2
23     import urllib2 as compat_urllib_error
24
25 try:
26     import urllib.parse as compat_urllib_parse
27 except ImportError:  # Python 2
28     import urllib as compat_urllib_parse
29
30 try:
31     from urllib.parse import urlparse as compat_urllib_parse_urlparse
32 except ImportError:  # Python 2
33     from urlparse import urlparse as compat_urllib_parse_urlparse
34
35 try:
36     import urllib.parse as compat_urlparse
37 except ImportError:  # Python 2
38     import urlparse as compat_urlparse
39
40 try:
41     import http.cookiejar as compat_cookiejar
42 except ImportError:  # Python 2
43     import cookielib as compat_cookiejar
44
45 try:
46     import html.entities as compat_html_entities
47 except ImportError:  # Python 2
48     import htmlentitydefs as compat_html_entities
49
50 try:
51     import http.client as compat_http_client
52 except ImportError:  # Python 2
53     import httplib as compat_http_client
54
55 try:
56     from urllib.error import HTTPError as compat_HTTPError
57 except ImportError:  # Python 2
58     from urllib2 import HTTPError as compat_HTTPError
59
60 try:
61     from urllib.request import urlretrieve as compat_urlretrieve
62 except ImportError:  # Python 2
63     from urllib import urlretrieve as compat_urlretrieve
64
65
66 try:
67     from subprocess import DEVNULL
68     compat_subprocess_get_DEVNULL = lambda: DEVNULL
69 except ImportError:
70     compat_subprocess_get_DEVNULL = lambda: open(os.path.devnull, 'w')
71
72 try:
73     import http.server as compat_http_server
74 except ImportError:
75     import BaseHTTPServer as compat_http_server
76
77 try:
78     from urllib.parse import unquote as compat_urllib_parse_unquote
79 except ImportError:
80     def compat_urllib_parse_unquote(string, encoding='utf-8', errors='replace'):
81         if string == '':
82             return string
83         res = string.split('%')
84         if len(res) == 1:
85             return string
86         if encoding is None:
87             encoding = 'utf-8'
88         if errors is None:
89             errors = 'replace'
90         # pct_sequence: contiguous sequence of percent-encoded bytes, decoded
91         pct_sequence = b''
92         string = res[0]
93         for item in res[1:]:
94             try:
95                 if not item:
96                     raise ValueError
97                 if not re.match('[0-9a-fA-F][0-9a-fA-F]',item[:2]):
98                     raise ValueError
99                 pct_sequence += item[:2].decode('hex')
100                 rest = item[2:]
101                 if not rest:
102                     # This segment was just a single percent-encoded character.
103                     # May be part of a sequence of code units, so delay decoding.
104                     # (Stored in pct_sequence).
105                     continue
106             except ValueError:
107                 rest = '%' + item
108             # Encountered non-percent-encoded characters. Flush the current
109             # pct_sequence.
110             string += pct_sequence.decode(encoding, errors) + rest
111             pct_sequence = b''
112         if pct_sequence:
113             # Flush the final pct_sequence
114             string += pct_sequence.decode(encoding, errors)
115         return string
116
117 try:
118     compat_str = unicode  # Python 2
119 except NameError:
120     compat_str = str
121
122 try:
123     compat_basestring = basestring  # Python 2
124 except NameError:
125     compat_basestring = str
126
127 try:
128     compat_chr = unichr  # Python 2
129 except NameError:
130     compat_chr = chr
131
132 try:
133     from xml.etree.ElementTree import ParseError as compat_xml_parse_error
134 except ImportError:  # Python 2.6
135     from xml.parsers.expat import ExpatError as compat_xml_parse_error
136
137
138 try:
139     from urllib.parse import parse_qs as compat_parse_qs
140 except ImportError:  # Python 2
141     # HACK: The following is the correct parse_qs implementation from cpython 3's stdlib.
142     # Python 2's version is apparently totally broken
143
144     def _parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
145                    encoding='utf-8', errors='replace'):
146         qs, _coerce_result = qs, compat_str
147         pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
148         r = []
149         for name_value in pairs:
150             if not name_value and not strict_parsing:
151                 continue
152             nv = name_value.split('=', 1)
153             if len(nv) != 2:
154                 if strict_parsing:
155                     raise ValueError("bad query field: %r" % (name_value,))
156                 # Handle case of a control-name with no equal sign
157                 if keep_blank_values:
158                     nv.append('')
159                 else:
160                     continue
161             if len(nv[1]) or keep_blank_values:
162                 name = nv[0].replace('+', ' ')
163                 name = compat_urllib_parse_unquote(
164                     name, encoding=encoding, errors=errors)
165                 name = _coerce_result(name)
166                 value = nv[1].replace('+', ' ')
167                 value = compat_urllib_parse_unquote(
168                     value, encoding=encoding, errors=errors)
169                 value = _coerce_result(value)
170                 r.append((name, value))
171         return r
172
173     def compat_parse_qs(qs, keep_blank_values=False, strict_parsing=False,
174                         encoding='utf-8', errors='replace'):
175         parsed_result = {}
176         pairs = _parse_qsl(qs, keep_blank_values, strict_parsing,
177                            encoding=encoding, errors=errors)
178         for name, value in pairs:
179             if name in parsed_result:
180                 parsed_result[name].append(value)
181             else:
182                 parsed_result[name] = [value]
183         return parsed_result
184
185 try:
186     from shlex import quote as shlex_quote
187 except ImportError:  # Python < 3.3
188     def shlex_quote(s):
189         if re.match(r'^[-_\w./]+$', s):
190             return s
191         else:
192             return "'" + s.replace("'", "'\"'\"'") + "'"
193
194
195 def compat_ord(c):
196     if type(c) is int:
197         return c
198     else:
199         return ord(c)
200
201
202 if sys.version_info >= (3, 0):
203     compat_getenv = os.getenv
204     compat_expanduser = os.path.expanduser
205 else:
206     # Environment variables should be decoded with filesystem encoding.
207     # Otherwise it will fail if any non-ASCII characters present (see #3854 #3217 #2918)
208
209     def compat_getenv(key, default=None):
210         from .utils import get_filesystem_encoding
211         env = os.getenv(key, default)
212         if env:
213             env = env.decode(get_filesystem_encoding())
214         return env
215
216     # HACK: The default implementations of os.path.expanduser from cpython do not decode
217     # environment variables with filesystem encoding. We will work around this by
218     # providing adjusted implementations.
219     # The following are os.path.expanduser implementations from cpython 2.7.8 stdlib
220     # for different platforms with correct environment variables decoding.
221
222     if os.name == 'posix':
223         def compat_expanduser(path):
224             """Expand ~ and ~user constructions.  If user or $HOME is unknown,
225             do nothing."""
226             if not path.startswith('~'):
227                 return path
228             i = path.find('/', 1)
229             if i < 0:
230                 i = len(path)
231             if i == 1:
232                 if 'HOME' not in os.environ:
233                     import pwd
234                     userhome = pwd.getpwuid(os.getuid()).pw_dir
235                 else:
236                     userhome = compat_getenv('HOME')
237             else:
238                 import pwd
239                 try:
240                     pwent = pwd.getpwnam(path[1:i])
241                 except KeyError:
242                     return path
243                 userhome = pwent.pw_dir
244             userhome = userhome.rstrip('/')
245             return (userhome + path[i:]) or '/'
246     elif os.name == 'nt' or os.name == 'ce':
247         def compat_expanduser(path):
248             """Expand ~ and ~user constructs.
249
250             If user or $HOME is unknown, do nothing."""
251             if path[:1] != '~':
252                 return path
253             i, n = 1, len(path)
254             while i < n and path[i] not in '/\\':
255                 i = i + 1
256
257             if 'HOME' in os.environ:
258                 userhome = compat_getenv('HOME')
259             elif 'USERPROFILE' in os.environ:
260                 userhome = compat_getenv('USERPROFILE')
261             elif 'HOMEPATH' not in os.environ:
262                 return path
263             else:
264                 try:
265                     drive = compat_getenv('HOMEDRIVE')
266                 except KeyError:
267                     drive = ''
268                 userhome = os.path.join(drive, compat_getenv('HOMEPATH'))
269
270             if i != 1:  # ~user
271                 userhome = os.path.join(os.path.dirname(userhome), path[1:i])
272
273             return userhome + path[i:]
274     else:
275         compat_expanduser = os.path.expanduser
276
277
278 if sys.version_info < (3, 0):
279     def compat_print(s):
280         from .utils import preferredencoding
281         print(s.encode(preferredencoding(), 'xmlcharrefreplace'))
282 else:
283     def compat_print(s):
284         assert isinstance(s, compat_str)
285         print(s)
286
287
288 try:
289     subprocess_check_output = subprocess.check_output
290 except AttributeError:
291     def subprocess_check_output(*args, **kwargs):
292         assert 'input' not in kwargs
293         p = subprocess.Popen(*args, stdout=subprocess.PIPE, **kwargs)
294         output, _ = p.communicate()
295         ret = p.poll()
296         if ret:
297             raise subprocess.CalledProcessError(ret, p.args, output=output)
298         return output
299
300 if sys.version_info < (3, 0) and sys.platform == 'win32':
301     def compat_getpass(prompt, *args, **kwargs):
302         if isinstance(prompt, compat_str):
303             from .utils import preferredencoding
304             prompt = prompt.encode(preferredencoding())
305         return getpass.getpass(prompt, *args, **kwargs)
306 else:
307     compat_getpass = getpass.getpass
308
309 # Old 2.6 and 2.7 releases require kwargs to be bytes
310 try:
311     def _testfunc(x):
312         pass
313     _testfunc(**{'x': 0})
314 except TypeError:
315     def compat_kwargs(kwargs):
316         return dict((bytes(k), v) for k, v in kwargs.items())
317 else:
318     compat_kwargs = lambda kwargs: kwargs
319
320
321 if sys.version_info < (2, 7):
322     def compat_socket_create_connection(address, timeout, source_address=None):
323         host, port = address
324         err = None
325         for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
326             af, socktype, proto, canonname, sa = res
327             sock = None
328             try:
329                 sock = socket.socket(af, socktype, proto)
330                 sock.settimeout(timeout)
331                 if source_address:
332                     sock.bind(source_address)
333                 sock.connect(sa)
334                 return sock
335             except socket.error as _:
336                 err = _
337                 if sock is not None:
338                     sock.close()
339         if err is not None:
340             raise err
341         else:
342             raise socket.error("getaddrinfo returns an empty list")
343 else:
344     compat_socket_create_connection = socket.create_connection
345
346
347 # Fix https://github.com/rg3/youtube-dl/issues/4223
348 # See http://bugs.python.org/issue9161 for what is broken
349 def workaround_optparse_bug9161():
350     op = optparse.OptionParser()
351     og = optparse.OptionGroup(op, 'foo')
352     try:
353         og.add_option('-t')
354     except TypeError:
355         real_add_option = optparse.OptionGroup.add_option
356
357         def _compat_add_option(self, *args, **kwargs):
358             enc = lambda v: (
359                 v.encode('ascii', 'replace') if isinstance(v, compat_str)
360                 else v)
361             bargs = [enc(a) for a in args]
362             bkwargs = dict(
363                 (k, enc(v)) for k, v in kwargs.items())
364             return real_add_option(self, *bargs, **bkwargs)
365         optparse.OptionGroup.add_option = _compat_add_option
366
367 if hasattr(shutil, 'get_terminal_size'):  # Python >= 3.3
368     compat_get_terminal_size = shutil.get_terminal_size
369 else:
370     _terminal_size = collections.namedtuple('terminal_size', ['columns', 'lines'])
371
372     def compat_get_terminal_size():
373         columns = compat_getenv('COLUMNS', None)
374         if columns:
375             columns = int(columns)
376         else:
377             columns = None
378         lines = compat_getenv('LINES', None)
379         if lines:
380             lines = int(lines)
381         else:
382             lines = None
383
384         try:
385             sp = subprocess.Popen(
386                 ['stty', 'size'],
387                 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
388             out, err = sp.communicate()
389             lines, columns = map(int, out.split())
390         except Exception:
391             pass
392         return _terminal_size(columns, lines)
393
394 try:
395     itertools.count(start=0, step=1)
396     compat_itertools_count = itertools.count
397 except TypeError:  # Python 2.6
398     def compat_itertools_count(start=0, step=1):
399         n = start
400         while True:
401             yield n
402             n += step
403
404 __all__ = [
405     'compat_HTTPError',
406     'compat_basestring',
407     'compat_chr',
408     'compat_cookiejar',
409     'compat_expanduser',
410     'compat_get_terminal_size',
411     'compat_getenv',
412     'compat_getpass',
413     'compat_html_entities',
414     'compat_http_client',
415     'compat_http_server',
416     'compat_itertools_count',
417     'compat_kwargs',
418     'compat_ord',
419     'compat_parse_qs',
420     'compat_print',
421     'compat_socket_create_connection',
422     'compat_str',
423     'compat_subprocess_get_DEVNULL',
424     'compat_urllib_error',
425     'compat_urllib_parse',
426     'compat_urllib_parse_unquote',
427     'compat_urllib_parse_urlparse',
428     'compat_urllib_request',
429     'compat_urlparse',
430     'compat_urlretrieve',
431     'compat_xml_parse_error',
432     'shlex_quote',
433     'subprocess_check_output',
434     'workaround_optparse_bug9161',
435 ]