wget.py 25 KB

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