PageRenderTime 57ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/urllib.py

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