PageRenderTime 51ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/urllib.py

https://bitbucket.org/marienz/pypy
Python | 1646 lines | 1635 code | 3 blank | 8 comment | 29 complexity | 545691bde0c87415588a0506b9746b5f MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. """Open an arbitrary URL.
  2. See the following document for more info on URLs:
  3. "Names and Addresses, URIs, URLs, URNs, URCs", at
  4. http://www.w3.org/pub/WWW/Addressing/Overview.html
  5. See also the HTTP spec (from which the error codes are derived):
  6. "HTTP - Hypertext Transfer Protocol", at
  7. http://www.w3.org/pub/WWW/Protocols/
  8. Related standards and specs:
  9. - RFC1808: the "relative URL" spec. (authoritative status)
  10. - RFC1738 - the "URL standard". (authoritative status)
  11. - RFC1630 - the "URI spec". (informational status)
  12. The object returned by URLopener().open(file) will differ per
  13. protocol. All you know is that is has methods read(), readline(),
  14. readlines(), fileno(), close() and info(). The read*(), fileno()
  15. and close() methods work like those of open files.
  16. The info() method returns a mimetools.Message object which can be
  17. used to query various info about the object, if available.
  18. (mimetools.Message objects are queried with the getheader() method.)
  19. """
  20. import string
  21. import socket
  22. import os
  23. import time
  24. import sys
  25. from urlparse import urljoin as basejoin
  26. __all__ = ["urlopen", "URLopener", "FancyURLopener", "urlretrieve",
  27. "urlcleanup", "quote", "quote_plus", "unquote", "unquote_plus",
  28. "urlencode", "url2pathname", "pathname2url", "splittag",
  29. "localhost", "thishost", "ftperrors", "basejoin", "unwrap",
  30. "splittype", "splithost", "splituser", "splitpasswd", "splitport",
  31. "splitnport", "splitquery", "splitattr", "splitvalue",
  32. "getproxies"]
  33. __version__ = '1.17' # XXX This version is not always updated :-(
  34. MAXFTPCACHE = 10 # Trim the ftp cache beyond this size
  35. # Helper for non-unix systems
  36. if os.name == 'nt':
  37. from nturl2path import url2pathname, pathname2url
  38. elif os.name == 'riscos':
  39. from rourl2path import url2pathname, pathname2url
  40. else:
  41. def url2pathname(pathname):
  42. """OS-specific conversion from a relative URL of the 'file' scheme
  43. to a file system path; not recommended for general use."""
  44. return unquote(pathname)
  45. def pathname2url(pathname):
  46. """OS-specific conversion from a file system path to a relative URL
  47. of the 'file' scheme; not recommended for general use."""
  48. return quote(pathname)
  49. # This really consists of two pieces:
  50. # (1) a class which handles opening of all sorts of URLs
  51. # (plus assorted utilities etc.)
  52. # (2) a set of functions for parsing URLs
  53. # XXX Should these be separated out into different modules?
  54. # Shortcut for basic usage
  55. _urlopener = None
  56. def urlopen(url, data=None, proxies=None):
  57. """Create a file-like object for the specified URL to read from."""
  58. from warnings import warnpy3k
  59. warnpy3k("urllib.urlopen() has been removed in Python 3.0 in "
  60. "favor of urllib2.urlopen()", stacklevel=2)
  61. global _urlopener
  62. if proxies is not None:
  63. opener = FancyURLopener(proxies=proxies)
  64. elif not _urlopener:
  65. opener = FancyURLopener()
  66. _urlopener = opener
  67. else:
  68. opener = _urlopener
  69. if data is None:
  70. return opener.open(url)
  71. else:
  72. return opener.open(url, data)
  73. def urlretrieve(url, filename=None, reporthook=None, data=None):
  74. global _urlopener
  75. if not _urlopener:
  76. _urlopener = FancyURLopener()
  77. return _urlopener.retrieve(url, filename, reporthook, data)
  78. def urlcleanup():
  79. if _urlopener:
  80. _urlopener.cleanup()
  81. _safe_quoters.clear()
  82. ftpcache.clear()
  83. # check for SSL
  84. try:
  85. import ssl
  86. except:
  87. _have_ssl = False
  88. else:
  89. _have_ssl = True
  90. # exception raised when downloaded size does not match content-length
  91. class ContentTooShortError(IOError):
  92. def __init__(self, message, content):
  93. IOError.__init__(self, message)
  94. self.content = content
  95. ftpcache = {}
  96. class URLopener:
  97. """Class to open URLs.
  98. This is a class rather than just a subroutine because we may need
  99. more than one set of global protocol-specific options.
  100. Note -- this is a base class for those who don't want the
  101. automatic handling of errors type 302 (relocated) and 401
  102. (authorization needed)."""
  103. __tempfiles = None
  104. version = "Python-urllib/%s" % __version__
  105. # Constructor
  106. def __init__(self, proxies=None, **x509):
  107. if proxies is None:
  108. proxies = getproxies()
  109. assert hasattr(proxies, 'has_key'), "proxies must be a mapping"
  110. self.proxies = proxies
  111. self.key_file = x509.get('key_file')
  112. self.cert_file = x509.get('cert_file')
  113. self.addheaders = [('User-Agent', self.version)]
  114. self.__tempfiles = []
  115. self.__unlink = os.unlink # See cleanup()
  116. self.tempcache = None
  117. # Undocumented feature: if you assign {} to tempcache,
  118. # it is used to cache files retrieved with
  119. # self.retrieve(). This is not enabled by default
  120. # since it does not work for changing documents (and I
  121. # haven't got the logic to check expiration headers
  122. # yet).
  123. self.ftpcache = ftpcache
  124. # Undocumented feature: you can use a different
  125. # ftp cache by assigning to the .ftpcache member;
  126. # in case you want logically independent URL openers
  127. # XXX This is not threadsafe. Bah.
  128. def __del__(self):
  129. self.close()
  130. def close(self):
  131. self.cleanup()
  132. def cleanup(self):
  133. # This code sometimes runs when the rest of this module
  134. # has already been deleted, so it can't use any globals
  135. # or import anything.
  136. if self.__tempfiles:
  137. for file in self.__tempfiles:
  138. try:
  139. self.__unlink(file)
  140. except OSError:
  141. pass
  142. del self.__tempfiles[:]
  143. if self.tempcache:
  144. self.tempcache.clear()
  145. def addheader(self, *args):
  146. """Add a header to be used by the HTTP interface only
  147. e.g. u.addheader('Accept', 'sound/basic')"""
  148. self.addheaders.append(args)
  149. # External interface
  150. def open(self, fullurl, data=None):
  151. """Use URLopener().open(file) instead of open(file, 'r')."""
  152. fullurl = unwrap(toBytes(fullurl))
  153. # percent encode url, fixing lame server errors for e.g, like space
  154. # within url paths.
  155. fullurl = quote(fullurl, safe="%/:=&?~#+!$,;'@()*[]|")
  156. if self.tempcache and fullurl in self.tempcache:
  157. filename, headers = self.tempcache[fullurl]
  158. fp = open(filename, 'rb')
  159. return addinfourl(fp, headers, fullurl)
  160. urltype, url = splittype(fullurl)
  161. if not urltype:
  162. urltype = 'file'
  163. if urltype in self.proxies:
  164. proxy = self.proxies[urltype]
  165. urltype, proxyhost = splittype(proxy)
  166. host, selector = splithost(proxyhost)
  167. url = (host, fullurl) # Signal special case to open_*()
  168. else:
  169. proxy = None
  170. name = 'open_' + urltype
  171. self.type = urltype
  172. name = name.replace('-', '_')
  173. if not hasattr(self, name):
  174. if proxy:
  175. return self.open_unknown_proxy(proxy, fullurl, data)
  176. else:
  177. return self.open_unknown(fullurl, data)
  178. try:
  179. if data is None:
  180. return getattr(self, name)(url)
  181. else:
  182. return getattr(self, name)(url, data)
  183. except socket.error, msg:
  184. raise IOError, ('socket error', msg), sys.exc_info()[2]
  185. def open_unknown(self, fullurl, data=None):
  186. """Overridable interface to open unknown URL type."""
  187. type, url = splittype(fullurl)
  188. raise IOError, ('url error', 'unknown url type', type)
  189. def open_unknown_proxy(self, proxy, fullurl, data=None):
  190. """Overridable interface to open unknown URL type."""
  191. type, url = splittype(fullurl)
  192. raise IOError, ('url error', 'invalid proxy for %s' % type, proxy)
  193. # External interface
  194. def retrieve(self, url, filename=None, reporthook=None, data=None):
  195. """retrieve(url) returns (filename, headers) for a local object
  196. or (tempfilename, headers) for a remote object."""
  197. url = unwrap(toBytes(url))
  198. if self.tempcache and url in self.tempcache:
  199. return self.tempcache[url]
  200. type, url1 = splittype(url)
  201. if filename is None and (not type or type == 'file'):
  202. try:
  203. fp = self.open_local_file(url1)
  204. hdrs = fp.info()
  205. fp.close()
  206. return url2pathname(splithost(url1)[1]), hdrs
  207. except IOError:
  208. pass
  209. fp = self.open(url, data)
  210. try:
  211. headers = fp.info()
  212. if filename:
  213. tfp = open(filename, 'wb')
  214. else:
  215. import tempfile
  216. garbage, path = splittype(url)
  217. garbage, path = splithost(path or "")
  218. path, garbage = splitquery(path or "")
  219. path, garbage = splitattr(path or "")
  220. suffix = os.path.splitext(path)[1]
  221. (fd, filename) = tempfile.mkstemp(suffix)
  222. self.__tempfiles.append(filename)
  223. tfp = os.fdopen(fd, 'wb')
  224. try:
  225. result = filename, headers
  226. if self.tempcache is not None:
  227. self.tempcache[url] = result
  228. bs = 1024*8
  229. size = -1
  230. read = 0
  231. blocknum = 0
  232. if reporthook:
  233. if "content-length" in headers:
  234. size = int(headers["Content-Length"])
  235. reporthook(blocknum, bs, size)
  236. while 1:
  237. block = fp.read(bs)
  238. if block == "":
  239. break
  240. read += len(block)
  241. tfp.write(block)
  242. blocknum += 1
  243. if reporthook:
  244. reporthook(blocknum, bs, size)
  245. finally:
  246. tfp.close()
  247. finally:
  248. fp.close()
  249. # raise exception if actual size does not match content-length header
  250. if size >= 0 and read < size:
  251. raise ContentTooShortError("retrieval incomplete: got only %i out "
  252. "of %i bytes" % (read, size), result)
  253. return result
  254. # Each method named open_<type> knows how to open that type of URL
  255. def open_http(self, url, data=None):
  256. """Use HTTP protocol."""
  257. import httplib
  258. user_passwd = None
  259. proxy_passwd= None
  260. if isinstance(url, str):
  261. host, selector = splithost(url)
  262. if host:
  263. user_passwd, host = splituser(host)
  264. host = unquote(host)
  265. realhost = host
  266. else:
  267. host, selector = url
  268. # check whether the proxy contains authorization information
  269. proxy_passwd, host = splituser(host)
  270. # now we proceed with the url we want to obtain
  271. urltype, rest = splittype(selector)
  272. url = rest
  273. user_passwd = None
  274. if urltype.lower() != 'http':
  275. realhost = None
  276. else:
  277. realhost, rest = splithost(rest)
  278. if realhost:
  279. user_passwd, realhost = splituser(realhost)
  280. if user_passwd:
  281. selector = "%s://%s%s" % (urltype, realhost, rest)
  282. if proxy_bypass(realhost):
  283. host = realhost
  284. #print "proxy via http:", host, selector
  285. if not host: raise IOError, ('http error', 'no host given')
  286. if proxy_passwd:
  287. import base64
  288. proxy_auth = base64.b64encode(proxy_passwd).strip()
  289. else:
  290. proxy_auth = None
  291. if user_passwd:
  292. import base64
  293. auth = base64.b64encode(user_passwd).strip()
  294. else:
  295. auth = None
  296. h = httplib.HTTP(host)
  297. if data is not None:
  298. h.putrequest('POST', selector)
  299. h.putheader('Content-Type', 'application/x-www-form-urlencoded')
  300. h.putheader('Content-Length', '%d' % len(data))
  301. else:
  302. h.putrequest('GET', selector)
  303. if proxy_auth: h.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth)
  304. if auth: h.putheader('Authorization', 'Basic %s' % auth)
  305. if realhost: h.putheader('Host', realhost)
  306. for args in self.addheaders: h.putheader(*args)
  307. h.endheaders(data)
  308. errcode, errmsg, headers = h.getreply()
  309. fp = h.getfile()
  310. if errcode == -1:
  311. if fp: fp.close()
  312. # something went wrong with the HTTP status line
  313. raise IOError, ('http protocol error', 0,
  314. 'got a bad status line', None)
  315. # According to RFC 2616, "2xx" code indicates that the client's
  316. # request was successfully received, understood, and accepted.
  317. if (200 <= errcode < 300):
  318. return addinfourl(fp, headers, "http:" + url, errcode)
  319. else:
  320. if data is None:
  321. return self.http_error(url, fp, errcode, errmsg, headers)
  322. else:
  323. return self.http_error(url, fp, errcode, errmsg, headers, data)
  324. def http_error(self, url, fp, errcode, errmsg, headers, data=None):
  325. """Handle http errors.
  326. Derived class can override this, or provide specific handlers
  327. named http_error_DDD where DDD is the 3-digit error code."""
  328. # First check if there's a specific handler for this error
  329. name = 'http_error_%d' % errcode
  330. if hasattr(self, name):
  331. method = getattr(self, name)
  332. if data is None:
  333. result = method(url, fp, errcode, errmsg, headers)
  334. else:
  335. result = method(url, fp, errcode, errmsg, headers, data)
  336. if result: return result
  337. return self.http_error_default(url, fp, errcode, errmsg, headers)
  338. def http_error_default(self, url, fp, errcode, errmsg, headers):
  339. """Default error handler: close the connection and raise IOError."""
  340. void = fp.read()
  341. fp.close()
  342. raise IOError, ('http error', errcode, errmsg, headers)
  343. if _have_ssl:
  344. def open_https(self, url, data=None):
  345. """Use HTTPS protocol."""
  346. import httplib
  347. user_passwd = None
  348. proxy_passwd = None
  349. if isinstance(url, str):
  350. host, selector = splithost(url)
  351. if host:
  352. user_passwd, host = splituser(host)
  353. host = unquote(host)
  354. realhost = host
  355. else:
  356. host, selector = url
  357. # here, we determine, whether the proxy contains authorization information
  358. proxy_passwd, host = splituser(host)
  359. urltype, rest = splittype(selector)
  360. url = rest
  361. user_passwd = None
  362. if urltype.lower() != 'https':
  363. realhost = None
  364. else:
  365. realhost, rest = splithost(rest)
  366. if realhost:
  367. user_passwd, realhost = splituser(realhost)
  368. if user_passwd:
  369. selector = "%s://%s%s" % (urltype, realhost, rest)
  370. #print "proxy via https:", host, selector
  371. if not host: raise IOError, ('https error', 'no host given')
  372. if proxy_passwd:
  373. import base64
  374. proxy_auth = base64.b64encode(proxy_passwd).strip()
  375. else:
  376. proxy_auth = None
  377. if user_passwd:
  378. import base64
  379. auth = base64.b64encode(user_passwd).strip()
  380. else:
  381. auth = None
  382. h = httplib.HTTPS(host, 0,
  383. key_file=self.key_file,
  384. cert_file=self.cert_file)
  385. if data is not None:
  386. h.putrequest('POST', selector)
  387. h.putheader('Content-Type',
  388. 'application/x-www-form-urlencoded')
  389. h.putheader('Content-Length', '%d' % len(data))
  390. else:
  391. h.putrequest('GET', selector)
  392. if proxy_auth: h.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth)
  393. if auth: h.putheader('Authorization', 'Basic %s' % auth)
  394. if realhost: h.putheader('Host', realhost)
  395. for args in self.addheaders: h.putheader(*args)
  396. h.endheaders(data)
  397. errcode, errmsg, headers = h.getreply()
  398. fp = h.getfile()
  399. if errcode == -1:
  400. if fp: fp.close()
  401. # something went wrong with the HTTP status line
  402. raise IOError, ('http protocol error', 0,
  403. 'got a bad status line', None)
  404. # According to RFC 2616, "2xx" code indicates that the client's
  405. # request was successfully received, understood, and accepted.
  406. if (200 <= errcode < 300):
  407. return addinfourl(fp, headers, "https:" + url, errcode)
  408. else:
  409. if data is None:
  410. return self.http_error(url, fp, errcode, errmsg, headers)
  411. else:
  412. return self.http_error(url, fp, errcode, errmsg, headers,
  413. data)
  414. def open_file(self, url):
  415. """Use local file or FTP depending on form of URL."""
  416. if not isinstance(url, str):
  417. raise IOError, ('file error', 'proxy support for file protocol currently not implemented')
  418. if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
  419. return self.open_ftp(url)
  420. else:
  421. return self.open_local_file(url)
  422. def open_local_file(self, url):
  423. """Use local file."""
  424. import mimetypes, mimetools, email.utils
  425. try:
  426. from cStringIO import StringIO
  427. except ImportError:
  428. from StringIO import StringIO
  429. host, file = splithost(url)
  430. localname = url2pathname(file)
  431. try:
  432. stats = os.stat(localname)
  433. except OSError, e:
  434. raise IOError(e.errno, e.strerror, e.filename)
  435. size = stats.st_size
  436. modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
  437. mtype = mimetypes.guess_type(url)[0]
  438. headers = mimetools.Message(StringIO(
  439. 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
  440. (mtype or 'text/plain', size, modified)))
  441. if not host:
  442. urlfile = file
  443. if file[:1] == '/':
  444. urlfile = 'file://' + file
  445. return addinfourl(open(localname, 'rb'),
  446. headers, urlfile)
  447. host, port = splitport(host)
  448. if not port \
  449. and socket.gethostbyname(host) in (localhost(), thishost()):
  450. urlfile = file
  451. if file[:1] == '/':
  452. urlfile = 'file://' + file
  453. return addinfourl(open(localname, 'rb'),
  454. headers, urlfile)
  455. raise IOError, ('local file error', 'not on local host')
  456. def open_ftp(self, url):
  457. """Use FTP protocol."""
  458. if not isinstance(url, str):
  459. raise IOError, ('ftp error', 'proxy support for ftp protocol currently not implemented')
  460. import mimetypes, mimetools
  461. try:
  462. from cStringIO import StringIO
  463. except ImportError:
  464. from StringIO import StringIO
  465. host, path = splithost(url)
  466. if not host: raise IOError, ('ftp error', 'no host given')
  467. host, port = splitport(host)
  468. user, host = splituser(host)
  469. if user: user, passwd = splitpasswd(user)
  470. else: passwd = None
  471. host = unquote(host)
  472. user = user or ''
  473. passwd = passwd or ''
  474. host = socket.gethostbyname(host)
  475. if not port:
  476. import ftplib
  477. port = ftplib.FTP_PORT
  478. else:
  479. port = int(port)
  480. path, attrs = splitattr(path)
  481. path = unquote(path)
  482. dirs = path.split('/')
  483. dirs, file = dirs[:-1], dirs[-1]
  484. if dirs and not dirs[0]: dirs = dirs[1:]
  485. if dirs and not dirs[0]: dirs[0] = '/'
  486. key = user, host, port, '/'.join(dirs)
  487. # XXX thread unsafe!
  488. if len(self.ftpcache) > MAXFTPCACHE:
  489. # Prune the cache, rather arbitrarily
  490. for k in self.ftpcache.keys():
  491. if k != key:
  492. v = self.ftpcache[k]
  493. del self.ftpcache[k]
  494. v.close()
  495. try:
  496. if not key in self.ftpcache:
  497. self.ftpcache[key] = \
  498. ftpwrapper(user, passwd, host, port, dirs)
  499. if not file: type = 'D'
  500. else: type = 'I'
  501. for attr in attrs:
  502. attr, value = splitvalue(attr)
  503. if attr.lower() == 'type' and \
  504. value in ('a', 'A', 'i', 'I', 'd', 'D'):
  505. type = value.upper()
  506. (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
  507. mtype = mimetypes.guess_type("ftp:" + url)[0]
  508. headers = ""
  509. if mtype:
  510. headers += "Content-Type: %s\n" % mtype
  511. if retrlen is not None and retrlen >= 0:
  512. headers += "Content-Length: %d\n" % retrlen
  513. headers = mimetools.Message(StringIO(headers))
  514. return addinfourl(fp, headers, "ftp:" + url)
  515. except ftperrors(), msg:
  516. raise IOError, ('ftp error', msg), sys.exc_info()[2]
  517. def open_data(self, url, data=None):
  518. """Use "data" URL."""
  519. if not isinstance(url, str):
  520. raise IOError, ('data error', 'proxy support for data protocol currently not implemented')
  521. # ignore POSTed data
  522. #
  523. # syntax of data URLs:
  524. # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
  525. # mediatype := [ type "/" subtype ] *( ";" parameter )
  526. # data := *urlchar
  527. # parameter := attribute "=" value
  528. import mimetools
  529. try:
  530. from cStringIO import StringIO
  531. except ImportError:
  532. from StringIO import StringIO
  533. try:
  534. [type, data] = url.split(',', 1)
  535. except ValueError:
  536. raise IOError, ('data error', 'bad data URL')
  537. if not type:
  538. type = 'text/plain;charset=US-ASCII'
  539. semi = type.rfind(';')
  540. if semi >= 0 and '=' not in type[semi:]:
  541. encoding = type[semi+1:]
  542. type = type[:semi]
  543. else:
  544. encoding = ''
  545. msg = []
  546. msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT',
  547. time.gmtime(time.time())))
  548. msg.append('Content-type: %s' % type)
  549. if encoding == 'base64':
  550. import base64
  551. data = base64.decodestring(data)
  552. else:
  553. data = unquote(data)
  554. msg.append('Content-Length: %d' % len(data))
  555. msg.append('')
  556. msg.append(data)
  557. msg = '\n'.join(msg)
  558. f = StringIO(msg)
  559. headers = mimetools.Message(f, 0)
  560. #f.fileno = None # needed for addinfourl
  561. return addinfourl(f, headers, url)
  562. class FancyURLopener(URLopener):
  563. """Derived class with handlers for errors we can handle (perhaps)."""
  564. def __init__(self, *args, **kwargs):
  565. URLopener.__init__(self, *args, **kwargs)
  566. self.auth_cache = {}
  567. self.tries = 0
  568. self.maxtries = 10
  569. def http_error_default(self, url, fp, errcode, errmsg, headers):
  570. """Default error handling -- don't raise an exception."""
  571. return addinfourl(fp, headers, "http:" + url, errcode)
  572. def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
  573. """Error 302 -- relocated (temporarily)."""
  574. self.tries += 1
  575. if self.maxtries and self.tries >= self.maxtries:
  576. if hasattr(self, "http_error_500"):
  577. meth = self.http_error_500
  578. else:
  579. meth = self.http_error_default
  580. self.tries = 0
  581. return meth(url, fp, 500,
  582. "Internal Server Error: Redirect Recursion", headers)
  583. result = self.redirect_internal(url, fp, errcode, errmsg, headers,
  584. data)
  585. self.tries = 0
  586. return result
  587. def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
  588. if 'location' in headers:
  589. newurl = headers['location']
  590. elif 'uri' in headers:
  591. newurl = headers['uri']
  592. else:
  593. return
  594. void = fp.read()
  595. fp.close()
  596. # In case the server sent a relative URL, join with original:
  597. newurl = basejoin(self.type + ":" + url, newurl)
  598. # For security reasons we do not allow redirects to protocols
  599. # other than HTTP, HTTPS or FTP.
  600. newurl_lower = newurl.lower()
  601. if not (newurl_lower.startswith('http://') or
  602. newurl_lower.startswith('https://') or
  603. newurl_lower.startswith('ftp://')):
  604. raise IOError('redirect error', errcode,
  605. errmsg + " - Redirection to url '%s' is not allowed" %
  606. newurl,
  607. headers)
  608. return self.open(newurl)
  609. def http_error_301(self, url, fp, errcode, errmsg, headers, data=None):
  610. """Error 301 -- also relocated (permanently)."""
  611. return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  612. def http_error_303(self, url, fp, errcode, errmsg, headers, data=None):
  613. """Error 303 -- also relocated (essentially identical to 302)."""
  614. return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  615. def http_error_307(self, url, fp, errcode, errmsg, headers, data=None):
  616. """Error 307 -- relocated, but turn POST into error."""
  617. if data is None:
  618. return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  619. else:
  620. return self.http_error_default(url, fp, errcode, errmsg, headers)
  621. def http_error_401(self, url, fp, errcode, errmsg, headers, data=None):
  622. """Error 401 -- authentication required.
  623. This function supports Basic authentication only."""
  624. if not 'www-authenticate' in headers:
  625. URLopener.http_error_default(self, url, fp,
  626. errcode, errmsg, headers)
  627. stuff = headers['www-authenticate']
  628. import re
  629. match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
  630. if not match:
  631. URLopener.http_error_default(self, url, fp,
  632. errcode, errmsg, headers)
  633. scheme, realm = match.groups()
  634. if scheme.lower() != 'basic':
  635. URLopener.http_error_default(self, url, fp,
  636. errcode, errmsg, headers)
  637. name = 'retry_' + self.type + '_basic_auth'
  638. if data is None:
  639. return getattr(self,name)(url, realm)
  640. else:
  641. return getattr(self,name)(url, realm, data)
  642. def http_error_407(self, url, fp, errcode, errmsg, headers, data=None):
  643. """Error 407 -- proxy authentication required.
  644. This function supports Basic authentication only."""
  645. if not 'proxy-authenticate' in headers:
  646. URLopener.http_error_default(self, url, fp,
  647. errcode, errmsg, headers)
  648. stuff = headers['proxy-authenticate']
  649. import re
  650. match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
  651. if not match:
  652. URLopener.http_error_default(self, url, fp,
  653. errcode, errmsg, headers)
  654. scheme, realm = match.groups()
  655. if scheme.lower() != 'basic':
  656. URLopener.http_error_default(self, url, fp,
  657. errcode, errmsg, headers)
  658. name = 'retry_proxy_' + self.type + '_basic_auth'
  659. if data is None:
  660. return getattr(self,name)(url, realm)
  661. else:
  662. return getattr(self,name)(url, realm, data)
  663. def retry_proxy_http_basic_auth(self, url, realm, data=None):
  664. host, selector = splithost(url)
  665. newurl = 'http://' + host + selector
  666. proxy = self.proxies['http']
  667. urltype, proxyhost = splittype(proxy)
  668. proxyhost, proxyselector = splithost(proxyhost)
  669. i = proxyhost.find('@') + 1
  670. proxyhost = proxyhost[i:]
  671. user, passwd = self.get_user_passwd(proxyhost, realm, i)
  672. if not (user or passwd): return None
  673. proxyhost = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + proxyhost
  674. self.proxies['http'] = 'http://' + proxyhost + proxyselector
  675. if data is None:
  676. return self.open(newurl)
  677. else:
  678. return self.open(newurl, data)
  679. def retry_proxy_https_basic_auth(self, url, realm, data=None):
  680. host, selector = splithost(url)
  681. newurl = 'https://' + host + selector
  682. proxy = self.proxies['https']
  683. urltype, proxyhost = splittype(proxy)
  684. proxyhost, proxyselector = splithost(proxyhost)
  685. i = proxyhost.find('@') + 1
  686. proxyhost = proxyhost[i:]
  687. user, passwd = self.get_user_passwd(proxyhost, realm, i)
  688. if not (user or passwd): return None
  689. proxyhost = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + proxyhost
  690. self.proxies['https'] = 'https://' + proxyhost + proxyselector
  691. if data is None:
  692. return self.open(newurl)
  693. else:
  694. return self.open(newurl, data)
  695. def retry_http_basic_auth(self, url, realm, data=None):
  696. host, selector = splithost(url)
  697. i = host.find('@') + 1
  698. host = host[i:]
  699. user, passwd = self.get_user_passwd(host, realm, i)
  700. if not (user or passwd): return None
  701. host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host
  702. newurl = 'http://' + host + selector
  703. if data is None:
  704. return self.open(newurl)
  705. else:
  706. return self.open(newurl, data)
  707. def retry_https_basic_auth(self, url, realm, data=None):
  708. host, selector = splithost(url)
  709. i = host.find('@') + 1
  710. host = host[i:]
  711. user, passwd = self.get_user_passwd(host, realm, i)
  712. if not (user or passwd): return None
  713. host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host
  714. newurl = 'https://' + host + selector
  715. if data is None:
  716. return self.open(newurl)
  717. else:
  718. return self.open(newurl, data)
  719. def get_user_passwd(self, host, realm, clear_cache=0):
  720. key = realm + '@' + host.lower()
  721. if key in self.auth_cache:
  722. if clear_cache:
  723. del self.auth_cache[key]
  724. else:
  725. return self.auth_cache[key]
  726. user, passwd = self.prompt_user_passwd(host, realm)
  727. if user or passwd: self.auth_cache[key] = (user, passwd)
  728. return user, passwd
  729. def prompt_user_passwd(self, host, realm):
  730. """Override this in a GUI environment!"""
  731. import getpass
  732. try:
  733. user = raw_input("Enter username for %s at %s: " % (realm,
  734. host))
  735. passwd = getpass.getpass("Enter password for %s in %s at %s: " %
  736. (user, realm, host))
  737. return user, passwd
  738. except KeyboardInterrupt:
  739. print
  740. return None, None
  741. # Utility functions
  742. _localhost = None
  743. def localhost():
  744. """Return the IP address of the magic hostname 'localhost'."""
  745. global _localhost
  746. if _localhost is None:
  747. _localhost = socket.gethostbyname('localhost')
  748. return _localhost
  749. _thishost = None
  750. def thishost():
  751. """Return the IP address of the current host."""
  752. global _thishost
  753. if _thishost is None:
  754. _thishost = socket.gethostbyname(socket.gethostname())
  755. return _thishost
  756. _ftperrors = None
  757. def ftperrors():
  758. """Return the set of errors raised by the FTP class."""
  759. global _ftperrors
  760. if _ftperrors is None:
  761. import ftplib
  762. _ftperrors = ftplib.all_errors
  763. return _ftperrors
  764. _noheaders = None
  765. def noheaders():
  766. """Return an empty mimetools.Message object."""
  767. global _noheaders
  768. if _noheaders is None:
  769. import mimetools
  770. try:
  771. from cStringIO import StringIO
  772. except ImportError:
  773. from StringIO import StringIO
  774. _noheaders = mimetools.Message(StringIO(), 0)
  775. _noheaders.fp.close() # Recycle file descriptor
  776. return _noheaders
  777. # Utility classes
  778. class ftpwrapper:
  779. """Class used by open_ftp() for cache of open FTP connections."""
  780. def __init__(self, user, passwd, host, port, dirs,
  781. timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
  782. self.user = user
  783. self.passwd = passwd
  784. self.host = host
  785. self.port = port
  786. self.dirs = dirs
  787. self.timeout = timeout
  788. self.init()
  789. def init(self):
  790. import ftplib
  791. self.busy = 0
  792. self.ftp = ftplib.FTP()
  793. self.ftp.connect(self.host, self.port, self.timeout)
  794. self.ftp.login(self.user, self.passwd)
  795. for dir in self.dirs:
  796. self.ftp.cwd(dir)
  797. def retrfile(self, file, type):
  798. import ftplib
  799. self.endtransfer()
  800. if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
  801. else: cmd = 'TYPE ' + type; isdir = 0
  802. try:
  803. self.ftp.voidcmd(cmd)
  804. except ftplib.all_errors:
  805. self.init()
  806. self.ftp.voidcmd(cmd)
  807. conn = None
  808. if file and not isdir:
  809. # Try to retrieve as a file
  810. try:
  811. cmd = 'RETR ' + file
  812. conn = self.ftp.ntransfercmd(cmd)
  813. except ftplib.error_perm, reason:
  814. if str(reason)[:3] != '550':
  815. raise IOError, ('ftp error', reason), sys.exc_info()[2]
  816. if not conn:
  817. # Set transfer mode to ASCII!
  818. self.ftp.voidcmd('TYPE A')
  819. # Try a directory listing. Verify that directory exists.
  820. if file:
  821. pwd = self.ftp.pwd()
  822. try:
  823. try:
  824. self.ftp.cwd(file)
  825. except ftplib.error_perm, reason:
  826. raise IOError, ('ftp error', reason), sys.exc_info()[2]
  827. finally:
  828. self.ftp.cwd(pwd)
  829. cmd = 'LIST ' + file
  830. else:
  831. cmd = 'LIST'
  832. conn = self.ftp.ntransfercmd(cmd)
  833. self.busy = 1
  834. # Pass back both a suitably decorated object and a retrieval length
  835. return (addclosehook(conn[0].makefile('rb'),
  836. self.endtransfer), conn[1])
  837. def endtransfer(self):
  838. if not self.busy:
  839. return
  840. self.busy = 0
  841. try:
  842. self.ftp.voidresp()
  843. except ftperrors():
  844. pass
  845. def close(self):
  846. self.endtransfer()
  847. try:
  848. self.ftp.close()
  849. except ftperrors():
  850. pass
  851. class addbase:
  852. """Base class for addinfo and addclosehook."""
  853. def __init__(self, fp):
  854. self.fp = fp
  855. self.read = self.fp.read
  856. self.readline = self.fp.readline
  857. if hasattr(self.fp, "readlines"): self.readlines = self.fp.readlines
  858. if hasattr(self.fp, "fileno"):
  859. self.fileno = self.fp.fileno
  860. else:
  861. self.fileno = lambda: None
  862. if hasattr(self.fp, "__iter__"):
  863. self.__iter__ = self.fp.__iter__
  864. if hasattr(self.fp, "next"):
  865. self.next = self.fp.next
  866. def __repr__(self):
  867. return '<%s at %r whose fp = %r>' % (self.__class__.__name__,
  868. id(self), self.fp)
  869. def close(self):
  870. self.read = None
  871. self.readline = None
  872. self.readlines = None
  873. self.fileno = None
  874. if self.fp: self.fp.close()
  875. self.fp = None
  876. class addclosehook(addbase):
  877. """Class to add a close hook to an open file."""
  878. def __init__(self, fp, closehook, *hookargs):
  879. addbase.__init__(self, fp)
  880. self.closehook = closehook
  881. self.hookargs = hookargs
  882. def close(self):
  883. addbase.close(self)
  884. if self.closehook:
  885. self.closehook(*self.hookargs)
  886. self.closehook = None
  887. self.hookargs = None
  888. class addinfo(addbase):
  889. """class to add an info() method to an open file."""
  890. def __init__(self, fp, headers):
  891. addbase.__init__(self, fp)
  892. self.headers = headers
  893. def info(self):
  894. return self.headers
  895. class addinfourl(addbase):
  896. """class to add info() and geturl() methods to an open file."""
  897. def __init__(self, fp, headers, url, code=None):
  898. addbase.__init__(self, fp)
  899. self.headers = headers
  900. self.url = url
  901. self.code = code
  902. def info(self):
  903. return self.headers
  904. def getcode(self):
  905. return self.code
  906. def geturl(self):
  907. return self.url
  908. # Utilities to parse URLs (most of these return None for missing parts):
  909. # unwrap('<URL:type://host/path>') --> 'type://host/path'
  910. # splittype('type:opaquestring') --> 'type', 'opaquestring'
  911. # splithost('//host[:port]/path') --> 'host[:port]', '/path'
  912. # splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
  913. # splitpasswd('user:passwd') -> 'user', 'passwd'
  914. # splitport('host:port') --> 'host', 'port'
  915. # splitquery('/path?query') --> '/path', 'query'
  916. # splittag('/path#tag') --> '/path', 'tag'
  917. # splitattr('/path;attr1=value1;attr2=value2;...') ->
  918. # '/path', ['attr1=value1', 'attr2=value2', ...]
  919. # splitvalue('attr=value') --> 'attr', 'value'
  920. # unquote('abc%20def') -> 'abc def'
  921. # quote('abc def') -> 'abc%20def')
  922. try:
  923. unicode
  924. except NameError:
  925. def _is_unicode(x):
  926. return 0
  927. else:
  928. def _is_unicode(x):
  929. return isinstance(x, unicode)
  930. def toBytes(url):
  931. """toBytes(u"URL") --> 'URL'."""
  932. # Most URL schemes require ASCII. If that changes, the conversion
  933. # can be relaxed
  934. if _is_unicode(url):
  935. try:
  936. url = url.encode("ASCII")
  937. except UnicodeError:
  938. raise UnicodeError("URL " + repr(url) +
  939. " contains non-ASCII characters")
  940. return url
  941. def unwrap(url):
  942. """unwrap('<URL:type://host/path>') --> 'type://host/path'."""
  943. url = url.strip()
  944. if url[:1] == '<' and url[-1:] == '>':
  945. url = url[1:-1].strip()
  946. if url[:4] == 'URL:': url = url[4:].strip()
  947. return url
  948. _typeprog = None
  949. def splittype(url):
  950. """splittype('type:opaquestring') --> 'type', 'opaquestring'."""
  951. global _typeprog
  952. if _typeprog is None:
  953. import re
  954. _typeprog = re.compile('^([^/:]+):')
  955. match = _typeprog.match(url)
  956. if match:
  957. scheme = match.group(1)
  958. return scheme.lower(), url[len(scheme) + 1:]
  959. return None, url
  960. _hostprog = None
  961. def splithost(url):
  962. """splithost('//host[:port]/path') --> 'host[:port]', '/path'."""
  963. global _hostprog
  964. if _hostprog is None:
  965. import re
  966. _hostprog = re.compile('^//([^/?]*)(.*)$')
  967. match = _hostprog.match(url)
  968. if match:
  969. host_port = match.group(1)
  970. path = match.group(2)
  971. if path and not path.startswith('/'):
  972. path = '/' + path
  973. return host_port, path
  974. return None, url
  975. _userprog = None
  976. def splituser(host):
  977. """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
  978. global _userprog
  979. if _userprog is None:
  980. import re
  981. _userprog = re.compile('^(.*)@(.*)$')
  982. match = _userprog.match(host)
  983. if match: return match.group(1, 2)
  984. return None, host
  985. _passwdprog = None
  986. def splitpasswd(user):
  987. """splitpasswd('user:passwd') -> 'user', 'passwd'."""
  988. global _passwdprog
  989. if _passwdprog is None:
  990. import re
  991. _passwdprog = re.compile('^([^:]*):(.*)$',re.S)
  992. match = _passwdprog.match(user)
  993. if match: return match.group(1, 2)
  994. return user, None
  995. # splittag('/path#tag') --> '/path', 'tag'
  996. _portprog = None
  997. def splitport(host):
  998. """splitport('host:port') --> 'host', 'port'."""
  999. global _portprog
  1000. if _portprog is None:
  1001. import re
  1002. _portprog = re.compile('^(.*):([0-9]+)$')
  1003. match = _portprog.match(host)
  1004. if match: return match.group(1, 2)
  1005. return host, None
  1006. _nportprog = None
  1007. def splitnport(host, defport=-1):
  1008. """Split host and port, returning numeric port.
  1009. Return given default port if no ':' found; defaults to -1.
  1010. Return numerical port if a valid number are found after ':'.
  1011. Return None if ':' but not a valid number."""
  1012. global _nportprog
  1013. if _nportprog is None:
  1014. import re
  1015. _nportprog = re.compile('^(.*):(.*)$')
  1016. match = _nportprog.match(host)
  1017. if match:
  1018. host, port = match.group(1, 2)
  1019. try:
  1020. if not port: raise ValueError, "no digits"
  1021. nport = int(port)
  1022. except ValueError:
  1023. nport = None
  1024. return host, nport
  1025. return host, defport
  1026. _queryprog = None
  1027. def splitquery(url):
  1028. """splitquery('/path?query') --> '/path', 'query'."""
  1029. global _queryprog
  1030. if _queryprog is None:
  1031. import re
  1032. _queryprog = re.compile('^(.*)\?([^?]*)$')
  1033. match = _queryprog.match(url)
  1034. if match: return match.group(1, 2)
  1035. return url, None
  1036. _tagprog = None
  1037. def splittag(url):
  1038. """splittag('/path#tag') --> '/path', 'tag'."""
  1039. global _tagprog
  1040. if _tagprog is None:
  1041. import re
  1042. _tagprog = re.compile('^(.*)#([^#]*)$')
  1043. match = _tagprog.match(url)
  1044. if match: return match.group(1, 2)
  1045. return url, None
  1046. def splitattr(url):
  1047. """splitattr('/path;attr1=value1;attr2=value2;...') ->
  1048. '/path', ['attr1=value1', 'attr2=value2', ...]."""
  1049. words = url.split(';')
  1050. return words[0], words[1:]
  1051. _valueprog = None
  1052. def splitvalue(attr):
  1053. """splitvalue('attr=value') --> 'attr', 'value'."""
  1054. global _valueprog
  1055. if _valueprog is None:
  1056. import re
  1057. _valueprog = re.compile('^([^=]*)=(.*)$')
  1058. match = _valueprog.match(attr)
  1059. if match: return match.group(1, 2)
  1060. return attr, None
  1061. # urlparse contains a duplicate of this method to avoid a circular import. If
  1062. # you update this method, also update the copy in urlparse. This code
  1063. # duplication does not exist in Python3.
  1064. _hexdig = '0123456789ABCDEFabcdef'
  1065. _hextochr = dict((a + b, chr(int(a + b, 16)))
  1066. for a in _hexdig for b in _hexdig)
  1067. def unquote(s):
  1068. """unquote('abc%20def') -> 'abc def'."""
  1069. res = s.split('%')
  1070. # fastpath
  1071. if len(res) == 1:
  1072. return s
  1073. s = res[0]
  1074. for item in res[1:]:
  1075. try:
  1076. s += _hextochr[item[:2]] + item[2:]
  1077. except KeyError:
  1078. s += '%' + item
  1079. except UnicodeDecodeError:
  1080. s += unichr(int(item[:2], 16)) + item[2:]
  1081. return s
  1082. def unquote_plus(s):
  1083. """unquote('%7e/abc+def') -> '~/abc def'"""
  1084. s = s.replace('+', ' ')
  1085. return unquote(s)
  1086. always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  1087. 'abcdefghijklmnopqrstuvwxyz'
  1088. '0123456789' '_.-')
  1089. _safe_map = {}
  1090. for i, c in zip(xrange(256), str(bytearray(xrange(256)))):
  1091. _safe_map[c] = c if (i < 128 and c in always_safe) else '%{:02X}'.format(i)
  1092. _safe_quoters = {}
  1093. def quote(s, safe='/'):
  1094. """quote('abc def') -> 'abc%20def'
  1095. Each part of a URL, e.g. the path info, the query, etc., has a
  1096. different set of reserved characters that must be quoted.
  1097. RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
  1098. the following reserved characters.
  1099. reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
  1100. "$" | ","
  1101. Each of these characters is reserved in some component of a URL,
  1102. but not necessarily in all of them.
  1103. By default, the quote function is intended for quoting the path
  1104. section of a URL. Thus, it will not encode '/'. This character
  1105. is reserved, but in typical usage the quote function is being
  1106. called on a path where the existing slash characters are used as
  1107. reserved characters.
  1108. """
  1109. # fastpath
  1110. if not s:
  1111. if s is None:
  1112. raise TypeError('None object cannot be quoted')
  1113. return s
  1114. cachekey = (safe, always_safe)
  1115. try:
  1116. (quoter, safe) = _safe_quoters[cachekey]
  1117. except KeyError:
  1118. safe_map = _safe_map.copy()
  1119. safe_map.update([(c, c) for c in safe])
  1120. quoter = safe_map.__getitem__
  1121. safe = always_safe + safe
  1122. _safe_quoters[cachekey] = (quoter, safe)
  1123. if not s.rstrip(safe):
  1124. return s
  1125. return ''.join(map(quoter, s))
  1126. def quote_plus(s, safe=''):
  1127. """Quote the query fragment of a URL; replacing ' ' with '+'"""
  1128. if ' ' in s:
  1129. s = quote(s, safe + ' ')
  1130. return s.replace(' ', '+')
  1131. return quote(s, safe)
  1132. def urlencode(query, doseq=0):
  1133. """Encode a sequence of two-element tuples or dictionary into a URL query string.
  1134. If any values in the query arg are sequences and doseq is true, each
  1135. sequence element is converted to a separate parameter.
  1136. If the query arg is a sequence of two-element tuples, the order of the
  1137. parameters in the output will match the order of parameters in the
  1138. input.
  1139. """
  1140. if hasattr(query,"items"):
  1141. # mapping objects
  1142. query = query.items()
  1143. else:
  1144. # it's a bother at times that strings and string-like objects are
  1145. # sequences...
  1146. try:
  1147. # non-sequence items should not work with len()
  1148. # non-empty strings will fail this
  1149. if len(query) and not isinstance(query[0], tuple):
  1150. raise TypeError
  1151. # zero-length sequences of all types will get here and succeed,
  1152. # but that's a minor nit - since the original implementation
  1153. # allowed empty dicts that type of behavior probably should be
  1154. # preserved for consistency
  1155. except TypeError:
  1156. ty,va,tb = sys.exc_info()
  1157. raise TypeError, "not a valid non-string sequence or mapping object", tb
  1158. l = []
  1159. if not doseq:
  1160. # preserve old behavior
  1161. for k, v in query:
  1162. k = quote_plus(str(k))
  1163. v = quote_plus(str(v))
  1164. l.append(k + '=' + v)
  1165. else:
  1166. for k, v in query:
  1167. k = quote_plus(str(k))
  1168. if isinstance(v, str):
  1169. v = quote_plus(v)
  1170. l.append(k + '=' + v)
  1171. elif _is_unicode(v):
  1172. # is there a reasonable way to convert to ASCII?
  1173. # encode generates a string, but "replace" or "ignore"
  1174. # lose information and "strict" can raise UnicodeError
  1175. v = quote_plus(v.encode("ASCII","replace"))
  1176. l.append(k + '=' + v)
  1177. else:
  1178. try:
  1179. # is this a sufficient test for sequence-ness?
  1180. len(v)
  1181. except TypeError:
  1182. # not a sequence
  1183. v = quote_plus(str(v))
  1184. l.append(k + '=' + v)
  1185. else:
  1186. # loop over the sequence
  1187. for elt in v:
  1188. l.append(k + '=' + quote_plus(str(elt)))
  1189. return '&'.join(l)
  1190. # Proxy handling
  1191. def getproxies_environment():
  1192. """Return a dictionary of scheme -> proxy server URL mappings.
  1193. Scan the environment for variables named <scheme>_proxy;
  1194. this seems to be the standard convention. If you need a
  1195. different way, you can pass a proxies dictionary to the
  1196. [Fancy]URLopener constructor.
  1197. """
  1198. proxies = {}
  1199. for name, value in os.environ.items():
  1200. name = name.lower()
  1201. if value and name[-6:] == '_proxy':
  1202. proxies[name[:-6]] = value
  1203. return proxies
  1204. def proxy_bypass_environment(host):
  1205. """Test if proxies should not be used for a particular host.
  1206. Checks the environment for a variable named no_proxy, which should
  1207. be a list of DNS suffixes separated by commas, or '*' for all hosts.
  1208. """
  1209. no_proxy = os.environ.get('no_proxy', '') or os.environ.get('NO_PROXY', '')
  1210. # '*' is special case for always bypass
  1211. if no_proxy == '*':
  1212. return 1
  1213. # strip port off host
  1214. hostonly, port = splitport(host)
  1215. # check if the host ends with any of the DNS suffixes
  1216. for name in no_proxy.split(','):
  1217. if name and (hostonly.endswith(name) or host.endswith(name)):
  1218. return 1
  1219. # otherwise, don't bypass
  1220. return 0
  1221. if sys.platform == 'darwin':
  1222. from _scproxy import _get_proxy_settings, _get_proxies
  1223. def proxy_bypass_macosx_sysconf(host):
  1224. """
  1225. Return True iff this host shouldn't be accessed using a proxy
  1226. This function uses the MacOSX framework SystemConfiguration
  1227. to fetch the proxy information.
  1228. """
  1229. import re
  1230. import socket
  1231. from fnmatch import fnmatch
  1232. hostonly, port = splitport(host)
  1233. def ip2num(ipAddr):
  1234. parts = ipAddr.split('.')
  1235. parts = map(int, parts)
  1236. if len(parts) != 4:
  1237. parts = (parts + [0, 0, 0, 0])[:4]
  1238. return (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]
  1239. proxy_settings = _get_proxy_settings()
  1240. # Check for simple host names:
  1241. if '.' not in host:
  1242. if proxy_settings['exclude_simple']:

Large files files are truncated, but you can click here to view the full file