wget.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. # ex:ts=4:sw=4:sts=4:et
  2. # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
  3. """
  4. BitBake 'Fetch' implementations
  5. Classes for obtaining upstream sources for the
  6. BitBake build tools.
  7. """
  8. # Copyright (C) 2003, 2004 Chris Larson
  9. #
  10. # This program is free software; you can redistribute it and/or modify
  11. # it under the terms of the GNU General Public License version 2 as
  12. # published by the Free Software Foundation.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License along
  20. # with this program; if not, write to the Free Software Foundation, Inc.,
  21. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  22. #
  23. # Based on functions from the base bb module, Copyright 2003 Holger Schurig
  24. import re
  25. import tempfile
  26. import subprocess
  27. import os
  28. import logging
  29. import bb
  30. import urllib.request, urllib.parse, urllib.error
  31. from bb import data
  32. from bb.fetch2 import FetchMethod
  33. from bb.fetch2 import FetchError
  34. from bb.fetch2 import logger
  35. from bb.fetch2 import runfetchcmd
  36. from bb.utils import export_proxies
  37. from bs4 import BeautifulSoup
  38. from bs4 import SoupStrainer
  39. class Wget(FetchMethod):
  40. """Class to fetch urls via 'wget'"""
  41. def supports(self, ud, d):
  42. """
  43. Check to see if a given url can be fetched with wget.
  44. """
  45. return ud.type in ['http', 'https', 'ftp']
  46. def recommends_checksum(self, urldata):
  47. return True
  48. def urldata_init(self, ud, d):
  49. if 'protocol' in ud.parm:
  50. if ud.parm['protocol'] == 'git':
  51. raise bb.fetch2.ParameterError("Invalid protocol - if you wish to fetch from a git repository using http, you need to instead use the git:// prefix with protocol=http", ud.url)
  52. if 'downloadfilename' in ud.parm:
  53. ud.basename = ud.parm['downloadfilename']
  54. else:
  55. ud.basename = os.path.basename(ud.path)
  56. ud.localfile = data.expand(urllib.parse.unquote(ud.basename), d)
  57. if not ud.localfile:
  58. ud.localfile = data.expand(urllib.parse.unquote(ud.host + ud.path).replace("/", "."), d)
  59. self.basecmd = d.getVar("FETCHCMD_wget", True) or "/usr/bin/env wget -t 2 -T 30 -nv --passive-ftp --no-check-certificate"
  60. def _runwget(self, ud, d, command, quiet):
  61. logger.debug(2, "Fetching %s using command '%s'" % (ud.url, command))
  62. bb.fetch2.check_network_access(d, command)
  63. runfetchcmd(command, d, quiet)
  64. def download(self, ud, d):
  65. """Fetch urls"""
  66. fetchcmd = self.basecmd
  67. if 'downloadfilename' in ud.parm:
  68. dldir = d.getVar("DL_DIR", True)
  69. bb.utils.mkdirhier(os.path.dirname(dldir + os.sep + ud.localfile))
  70. fetchcmd += " -O " + dldir + os.sep + ud.localfile
  71. uri = ud.url.split(";")[0]
  72. if os.path.exists(ud.localpath):
  73. # file exists, but we didnt complete it.. trying again..
  74. fetchcmd += d.expand(" -c -P ${DL_DIR} '%s'" % uri)
  75. else:
  76. fetchcmd += d.expand(" -P ${DL_DIR} '%s'" % uri)
  77. self._runwget(ud, d, fetchcmd, False)
  78. # Sanity check since wget can pretend it succeed when it didn't
  79. # Also, this used to happen if sourceforge sent us to the mirror page
  80. if not os.path.exists(ud.localpath):
  81. raise FetchError("The fetch command returned success for url %s but %s doesn't exist?!" % (uri, ud.localpath), uri)
  82. if os.path.getsize(ud.localpath) == 0:
  83. os.remove(ud.localpath)
  84. raise FetchError("The fetch of %s resulted in a zero size file?! Deleting and failing since this isn't right." % (uri), uri)
  85. return True
  86. def checkstatus(self, fetch, ud, d):
  87. import urllib.request, urllib.error, urllib.parse, socket, http.client
  88. from urllib.response import addinfourl
  89. from bb.fetch2 import FetchConnectionCache
  90. class HTTPConnectionCache(http.client.HTTPConnection):
  91. if fetch.connection_cache:
  92. def connect(self):
  93. """Connect to the host and port specified in __init__."""
  94. sock = fetch.connection_cache.get_connection(self.host, self.port)
  95. if sock:
  96. self.sock = sock
  97. else:
  98. self.sock = socket.create_connection((self.host, self.port),
  99. self.timeout, self.source_address)
  100. fetch.connection_cache.add_connection(self.host, self.port, self.sock)
  101. if self._tunnel_host:
  102. self._tunnel()
  103. class CacheHTTPHandler(urllib.request.HTTPHandler):
  104. def http_open(self, req):
  105. return self.do_open(HTTPConnectionCache, req)
  106. def do_open(self, http_class, req):
  107. """Return an addinfourl object for the request, using http_class.
  108. http_class must implement the HTTPConnection API from httplib.
  109. The addinfourl return value is a file-like object. It also
  110. has methods and attributes including:
  111. - info(): return a mimetools.Message object for the headers
  112. - geturl(): return the original request URL
  113. - code: HTTP status code
  114. """
  115. host = req.host
  116. if not host:
  117. raise urlllib2.URLError('no host given')
  118. h = http_class(host, timeout=req.timeout) # will parse host:port
  119. h.set_debuglevel(self._debuglevel)
  120. headers = dict(req.unredirected_hdrs)
  121. headers.update(dict((k, v) for k, v in list(req.headers.items())
  122. if k not in headers))
  123. # We want to make an HTTP/1.1 request, but the addinfourl
  124. # class isn't prepared to deal with a persistent connection.
  125. # It will try to read all remaining data from the socket,
  126. # which will block while the server waits for the next request.
  127. # So make sure the connection gets closed after the (only)
  128. # request.
  129. # Don't close connection when connection_cache is enabled,
  130. if fetch.connection_cache is None:
  131. headers["Connection"] = "close"
  132. else:
  133. headers["Connection"] = "Keep-Alive" # Works for HTTP/1.0
  134. headers = dict(
  135. (name.title(), val) for name, val in list(headers.items()))
  136. if req._tunnel_host:
  137. tunnel_headers = {}
  138. proxy_auth_hdr = "Proxy-Authorization"
  139. if proxy_auth_hdr in headers:
  140. tunnel_headers[proxy_auth_hdr] = headers[proxy_auth_hdr]
  141. # Proxy-Authorization should not be sent to origin
  142. # server.
  143. del headers[proxy_auth_hdr]
  144. h.set_tunnel(req._tunnel_host, headers=tunnel_headers)
  145. try:
  146. h.request(req.get_method(), req.selector, req.data, headers)
  147. except socket.error as err: # XXX what error?
  148. # Don't close connection when cache is enabled.
  149. if fetch.connection_cache is None:
  150. h.close()
  151. raise urllib.error.URLError(err)
  152. else:
  153. try:
  154. r = h.getresponse(buffering=True)
  155. except TypeError: # buffering kw not supported
  156. r = h.getresponse()
  157. # Pick apart the HTTPResponse object to get the addinfourl
  158. # object initialized properly.
  159. # Wrap the HTTPResponse object in socket's file object adapter
  160. # for Windows. That adapter calls recv(), so delegate recv()
  161. # to read(). This weird wrapping allows the returned object to
  162. # have readline() and readlines() methods.
  163. # XXX It might be better to extract the read buffering code
  164. # out of socket._fileobject() and into a base class.
  165. r.recv = r.read
  166. # no data, just have to read
  167. r.read()
  168. class fp_dummy(object):
  169. def read(self):
  170. return ""
  171. def readline(self):
  172. return ""
  173. def close(self):
  174. pass
  175. resp = addinfourl(fp_dummy(), r.msg, req.get_full_url())
  176. resp.code = r.status
  177. resp.msg = r.reason
  178. # Close connection when server request it.
  179. if fetch.connection_cache is not None:
  180. if 'Connection' in r.msg and r.msg['Connection'] == 'close':
  181. fetch.connection_cache.remove_connection(h.host, h.port)
  182. return resp
  183. class HTTPMethodFallback(urllib.request.BaseHandler):
  184. """
  185. Fallback to GET if HEAD is not allowed (405 HTTP error)
  186. """
  187. def http_error_405(self, req, fp, code, msg, headers):
  188. fp.read()
  189. fp.close()
  190. newheaders = dict((k,v) for k,v in list(req.headers.items())
  191. if k.lower() not in ("content-length", "content-type"))
  192. return self.parent.open(urllib.request.Request(req.get_full_url(),
  193. headers=newheaders,
  194. origin_req_host=req.origin_req_host,
  195. unverifiable=True))
  196. """
  197. Some servers (e.g. GitHub archives, hosted on Amazon S3) return 403
  198. Forbidden when they actually mean 405 Method Not Allowed.
  199. """
  200. http_error_403 = http_error_405
  201. """
  202. Some servers (e.g. FusionForge) returns 406 Not Acceptable when they
  203. actually mean 405 Method Not Allowed.
  204. """
  205. http_error_406 = http_error_405
  206. class FixedHTTPRedirectHandler(urllib.request.HTTPRedirectHandler):
  207. """
  208. urllib2.HTTPRedirectHandler resets the method to GET on redirect,
  209. when we want to follow redirects using the original method.
  210. """
  211. def redirect_request(self, req, fp, code, msg, headers, newurl):
  212. newreq = urllib.request.HTTPRedirectHandler.redirect_request(self, req, fp, code, msg, headers, newurl)
  213. newreq.get_method = lambda: req.get_method()
  214. return newreq
  215. exported_proxies = export_proxies(d)
  216. handlers = [FixedHTTPRedirectHandler, HTTPMethodFallback]
  217. if export_proxies:
  218. handlers.append(urllib.request.ProxyHandler())
  219. handlers.append(CacheHTTPHandler())
  220. # XXX: Since Python 2.7.9 ssl cert validation is enabled by default
  221. # see PEP-0476, this causes verification errors on some https servers
  222. # so disable by default.
  223. import ssl
  224. if hasattr(ssl, '_create_unverified_context'):
  225. handlers.append(urllib.request.HTTPSHandler(context=ssl._create_unverified_context()))
  226. opener = urllib.request.build_opener(*handlers)
  227. try:
  228. uri = ud.url.split(";")[0]
  229. r = urllib.request.Request(uri)
  230. r.get_method = lambda: "HEAD"
  231. opener.open(r)
  232. except urllib.error.URLError as e:
  233. # debug for now to avoid spamming the logs in e.g. remote sstate searches
  234. logger.debug(2, "checkstatus() urlopen failed: %s" % e)
  235. return False
  236. return True
  237. def _parse_path(self, regex, s):
  238. """
  239. Find and group name, version and archive type in the given string s
  240. """
  241. m = regex.search(s)
  242. if m:
  243. pname = ''
  244. pver = ''
  245. ptype = ''
  246. mdict = m.groupdict()
  247. if 'name' in mdict.keys():
  248. pname = mdict['name']
  249. if 'pver' in mdict.keys():
  250. pver = mdict['pver']
  251. if 'type' in mdict.keys():
  252. ptype = mdict['type']
  253. bb.debug(3, "_parse_path: %s, %s, %s" % (pname, pver, ptype))
  254. return (pname, pver, ptype)
  255. return None
  256. def _modelate_version(self, version):
  257. if version[0] in ['.', '-']:
  258. if version[1].isdigit():
  259. version = version[1] + version[0] + version[2:len(version)]
  260. else:
  261. version = version[1:len(version)]
  262. version = re.sub('-', '.', version)
  263. version = re.sub('_', '.', version)
  264. version = re.sub('(rc)+', '.1000.', version)
  265. version = re.sub('(beta)+', '.100.', version)
  266. version = re.sub('(alpha)+', '.10.', version)
  267. if version[0] == 'v':
  268. version = version[1:len(version)]
  269. return version
  270. def _vercmp(self, old, new):
  271. """
  272. Check whether 'new' is newer than 'old' version. We use existing vercmp() for the
  273. purpose. PE is cleared in comparison as it's not for build, and PR is cleared too
  274. for simplicity as it's somehow difficult to get from various upstream format
  275. """
  276. (oldpn, oldpv, oldsuffix) = old
  277. (newpn, newpv, newsuffix) = new
  278. """
  279. Check for a new suffix type that we have never heard of before
  280. """
  281. if (newsuffix):
  282. m = self.suffix_regex_comp.search(newsuffix)
  283. if not m:
  284. bb.warn("%s has a possible unknown suffix: %s" % (newpn, newsuffix))
  285. return False
  286. """
  287. Not our package so ignore it
  288. """
  289. if oldpn != newpn:
  290. return False
  291. oldpv = self._modelate_version(oldpv)
  292. newpv = self._modelate_version(newpv)
  293. return bb.utils.vercmp(("0", oldpv, ""), ("0", newpv, ""))
  294. def _fetch_index(self, uri, ud, d):
  295. """
  296. Run fetch checkstatus to get directory information
  297. """
  298. f = tempfile.NamedTemporaryFile()
  299. agent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.12) Gecko/20101027 Ubuntu/9.10 (karmic) Firefox/3.6.12"
  300. fetchcmd = self.basecmd
  301. fetchcmd += " -O " + f.name + " --user-agent='" + agent + "' '" + uri + "'"
  302. try:
  303. self._runwget(ud, d, fetchcmd, True)
  304. fetchresult = f.read()
  305. except bb.fetch2.BBFetchException:
  306. fetchresult = ""
  307. f.close()
  308. return fetchresult
  309. def _check_latest_version(self, url, package, package_regex, current_version, ud, d):
  310. """
  311. Return the latest version of a package inside a given directory path
  312. If error or no version, return ""
  313. """
  314. valid = 0
  315. version = ['', '', '']
  316. bb.debug(3, "VersionURL: %s" % (url))
  317. soup = BeautifulSoup(self._fetch_index(url, ud, d), "html.parser", parse_only=SoupStrainer("a"))
  318. if not soup:
  319. bb.debug(3, "*** %s NO SOUP" % (url))
  320. return ""
  321. for line in soup.find_all('a', href=True):
  322. bb.debug(3, "line['href'] = '%s'" % (line['href']))
  323. bb.debug(3, "line = '%s'" % (str(line)))
  324. newver = self._parse_path(package_regex, line['href'])
  325. if not newver:
  326. newver = self._parse_path(package_regex, str(line))
  327. if newver:
  328. bb.debug(3, "Upstream version found: %s" % newver[1])
  329. if valid == 0:
  330. version = newver
  331. valid = 1
  332. elif self._vercmp(version, newver) < 0:
  333. version = newver
  334. pupver = re.sub('_', '.', version[1])
  335. bb.debug(3, "*** %s -> UpstreamVersion = %s (CurrentVersion = %s)" %
  336. (package, pupver or "N/A", current_version[1]))
  337. if valid:
  338. return pupver
  339. return ""
  340. def _check_latest_version_by_dir(self, dirver, package, package_regex,
  341. current_version, ud, d):
  342. """
  343. Scan every directory in order to get upstream version.
  344. """
  345. version_dir = ['', '', '']
  346. version = ['', '', '']
  347. dirver_regex = re.compile("(?P<pfx>\D*)(?P<ver>(\d+[\.\-_])+(\d+))")
  348. s = dirver_regex.search(dirver)
  349. if s:
  350. version_dir[1] = s.group('ver')
  351. else:
  352. version_dir[1] = dirver
  353. dirs_uri = bb.fetch.encodeurl([ud.type, ud.host,
  354. ud.path.split(dirver)[0], ud.user, ud.pswd, {}])
  355. bb.debug(3, "DirURL: %s, %s" % (dirs_uri, package))
  356. soup = BeautifulSoup(self._fetch_index(dirs_uri, ud, d), "html.parser", parse_only=SoupStrainer("a"))
  357. if not soup:
  358. return version[1]
  359. for line in soup.find_all('a', href=True):
  360. s = dirver_regex.search(line['href'].strip("/"))
  361. if s:
  362. sver = s.group('ver')
  363. # When prefix is part of the version directory it need to
  364. # ensure that only version directory is used so remove previous
  365. # directories if exists.
  366. #
  367. # Example: pfx = '/dir1/dir2/v' and version = '2.5' the expected
  368. # result is v2.5.
  369. spfx = s.group('pfx').split('/')[-1]
  370. version_dir_new = ['', sver, '']
  371. if self._vercmp(version_dir, version_dir_new) <= 0:
  372. dirver_new = spfx + sver
  373. path = ud.path.replace(dirver, dirver_new, True) \
  374. .split(package)[0]
  375. uri = bb.fetch.encodeurl([ud.type, ud.host, path,
  376. ud.user, ud.pswd, {}])
  377. pupver = self._check_latest_version(uri,
  378. package, package_regex, current_version, ud, d)
  379. if pupver:
  380. version[1] = pupver
  381. version_dir = version_dir_new
  382. return version[1]
  383. def _init_regexes(self, package, ud, d):
  384. """
  385. Match as many patterns as possible such as:
  386. gnome-common-2.20.0.tar.gz (most common format)
  387. gtk+-2.90.1.tar.gz
  388. xf86-input-synaptics-12.6.9.tar.gz
  389. dri2proto-2.3.tar.gz
  390. blktool_4.orig.tar.gz
  391. libid3tag-0.15.1b.tar.gz
  392. unzip552.tar.gz
  393. icu4c-3_6-src.tgz
  394. genext2fs_1.3.orig.tar.gz
  395. gst-fluendo-mp3
  396. """
  397. # match most patterns which uses "-" as separator to version digits
  398. pn_prefix1 = "[a-zA-Z][a-zA-Z0-9]*([-_][a-zA-Z]\w+)*\+?[-_]"
  399. # a loose pattern such as for unzip552.tar.gz
  400. pn_prefix2 = "[a-zA-Z]+"
  401. # a loose pattern such as for 80325-quicky-0.4.tar.gz
  402. pn_prefix3 = "[0-9]+[-]?[a-zA-Z]+"
  403. # Save the Package Name (pn) Regex for use later
  404. pn_regex = "(%s|%s|%s)" % (pn_prefix1, pn_prefix2, pn_prefix3)
  405. # match version
  406. pver_regex = "(([A-Z]*\d+[a-zA-Z]*[\.\-_]*)+)"
  407. # match arch
  408. parch_regex = "-source|_all_"
  409. # src.rpm extension was added only for rpm package. Can be removed if the rpm
  410. # packaged will always be considered as having to be manually upgraded
  411. psuffix_regex = "(tar\.gz|tgz|tar\.bz2|zip|xz|rpm|bz2|orig\.tar\.gz|tar\.xz|src\.tar\.gz|src\.tgz|svnr\d+\.tar\.bz2|stable\.tar\.gz|src\.rpm)"
  412. # match name, version and archive type of a package
  413. package_regex_comp = re.compile("(?P<name>%s?\.?v?)(?P<pver>%s)(?P<arch>%s)?[\.-](?P<type>%s$)"
  414. % (pn_regex, pver_regex, parch_regex, psuffix_regex))
  415. self.suffix_regex_comp = re.compile(psuffix_regex)
  416. # compile regex, can be specific by package or generic regex
  417. pn_regex = d.getVar('UPSTREAM_CHECK_REGEX', True)
  418. if pn_regex:
  419. package_custom_regex_comp = re.compile(pn_regex)
  420. else:
  421. version = self._parse_path(package_regex_comp, package)
  422. if version:
  423. package_custom_regex_comp = re.compile(
  424. "(?P<name>%s)(?P<pver>%s)(?P<arch>%s)?[\.-](?P<type>%s)" %
  425. (re.escape(version[0]), pver_regex, parch_regex, psuffix_regex))
  426. else:
  427. package_custom_regex_comp = None
  428. return package_custom_regex_comp
  429. def latest_versionstring(self, ud, d):
  430. """
  431. Manipulate the URL and try to obtain the latest package version
  432. sanity check to ensure same name and type.
  433. """
  434. package = ud.path.split("/")[-1]
  435. current_version = ['', d.getVar('PV', True), '']
  436. """possible to have no version in pkg name, such as spectrum-fw"""
  437. if not re.search("\d+", package):
  438. current_version[1] = re.sub('_', '.', current_version[1])
  439. current_version[1] = re.sub('-', '.', current_version[1])
  440. return (current_version[1], '')
  441. package_regex = self._init_regexes(package, ud, d)
  442. if package_regex is None:
  443. bb.warn("latest_versionstring: package %s don't match pattern" % (package))
  444. return ('', '')
  445. bb.debug(3, "latest_versionstring, regex: %s" % (package_regex.pattern))
  446. uri = ""
  447. regex_uri = d.getVar("UPSTREAM_CHECK_URI", True)
  448. if not regex_uri:
  449. path = ud.path.split(package)[0]
  450. # search for version matches on folders inside the path, like:
  451. # "5.7" in http://download.gnome.org/sources/${PN}/5.7/${PN}-${PV}.tar.gz
  452. dirver_regex = re.compile("(?P<dirver>[^/]*(\d+\.)*\d+([-_]r\d+)*)/")
  453. m = dirver_regex.search(path)
  454. if m:
  455. pn = d.getVar('PN', True)
  456. dirver = m.group('dirver')
  457. dirver_pn_regex = re.compile("%s\d?" % (re.escape(pn)))
  458. if not dirver_pn_regex.search(dirver):
  459. return (self._check_latest_version_by_dir(dirver,
  460. package, package_regex, current_version, ud, d), '')
  461. uri = bb.fetch.encodeurl([ud.type, ud.host, path, ud.user, ud.pswd, {}])
  462. else:
  463. uri = regex_uri
  464. return (self._check_latest_version(uri, package, package_regex,
  465. current_version, ud, d), '')