__init__.py 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770
  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. # Copyright (C) 2012 Intel Corporation
  10. #
  11. # This program is free software; you can redistribute it and/or modify
  12. # it under the terms of the GNU General Public License version 2 as
  13. # published by the Free Software Foundation.
  14. #
  15. # This program is distributed in the hope that it will be useful,
  16. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. # GNU General Public License for more details.
  19. #
  20. # You should have received a copy of the GNU General Public License along
  21. # with this program; if not, write to the Free Software Foundation, Inc.,
  22. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  23. #
  24. # Based on functions from the base bb module, Copyright 2003 Holger Schurig
  25. import os, re
  26. import signal
  27. import logging
  28. import urllib.request, urllib.parse, urllib.error
  29. if 'git' not in urllib.parse.uses_netloc:
  30. urllib.parse.uses_netloc.append('git')
  31. import operator
  32. import collections
  33. import subprocess
  34. import pickle
  35. import bb.persist_data, bb.utils
  36. import bb.checksum
  37. from bb import data
  38. import bb.process
  39. __version__ = "2"
  40. _checksum_cache = bb.checksum.FileChecksumCache()
  41. logger = logging.getLogger("BitBake.Fetcher")
  42. class BBFetchException(Exception):
  43. """Class all fetch exceptions inherit from"""
  44. def __init__(self, message):
  45. self.msg = message
  46. Exception.__init__(self, message)
  47. def __str__(self):
  48. return self.msg
  49. class UntrustedUrl(BBFetchException):
  50. """Exception raised when encountering a host not listed in BB_ALLOWED_NETWORKS"""
  51. def __init__(self, url, message=''):
  52. if message:
  53. msg = message
  54. else:
  55. msg = "The URL: '%s' is not trusted and cannot be used" % url
  56. self.url = url
  57. BBFetchException.__init__(self, msg)
  58. self.args = (url,)
  59. class MalformedUrl(BBFetchException):
  60. """Exception raised when encountering an invalid url"""
  61. def __init__(self, url, message=''):
  62. if message:
  63. msg = message
  64. else:
  65. msg = "The URL: '%s' is invalid and cannot be interpreted" % url
  66. self.url = url
  67. BBFetchException.__init__(self, msg)
  68. self.args = (url,)
  69. class FetchError(BBFetchException):
  70. """General fetcher exception when something happens incorrectly"""
  71. def __init__(self, message, url = None):
  72. if url:
  73. msg = "Fetcher failure for URL: '%s'. %s" % (url, message)
  74. else:
  75. msg = "Fetcher failure: %s" % message
  76. self.url = url
  77. BBFetchException.__init__(self, msg)
  78. self.args = (message, url)
  79. class ChecksumError(FetchError):
  80. """Exception when mismatched checksum encountered"""
  81. def __init__(self, message, url = None, checksum = None):
  82. self.checksum = checksum
  83. FetchError.__init__(self, message, url)
  84. class NoChecksumError(FetchError):
  85. """Exception when no checksum is specified, but BB_STRICT_CHECKSUM is set"""
  86. class UnpackError(BBFetchException):
  87. """General fetcher exception when something happens incorrectly when unpacking"""
  88. def __init__(self, message, url):
  89. msg = "Unpack failure for URL: '%s'. %s" % (url, message)
  90. self.url = url
  91. BBFetchException.__init__(self, msg)
  92. self.args = (message, url)
  93. class NoMethodError(BBFetchException):
  94. """Exception raised when there is no method to obtain a supplied url or set of urls"""
  95. def __init__(self, url):
  96. msg = "Could not find a fetcher which supports the URL: '%s'" % url
  97. self.url = url
  98. BBFetchException.__init__(self, msg)
  99. self.args = (url,)
  100. class MissingParameterError(BBFetchException):
  101. """Exception raised when a fetch method is missing a critical parameter in the url"""
  102. def __init__(self, missing, url):
  103. msg = "URL: '%s' is missing the required parameter '%s'" % (url, missing)
  104. self.url = url
  105. self.missing = missing
  106. BBFetchException.__init__(self, msg)
  107. self.args = (missing, url)
  108. class ParameterError(BBFetchException):
  109. """Exception raised when a url cannot be proccessed due to invalid parameters."""
  110. def __init__(self, message, url):
  111. msg = "URL: '%s' has invalid parameters. %s" % (url, message)
  112. self.url = url
  113. BBFetchException.__init__(self, msg)
  114. self.args = (message, url)
  115. class NetworkAccess(BBFetchException):
  116. """Exception raised when network access is disabled but it is required."""
  117. def __init__(self, url, cmd):
  118. msg = "Network access disabled through BB_NO_NETWORK (or set indirectly due to use of BB_FETCH_PREMIRRORONLY) but access requested with command %s (for url %s)" % (cmd, url)
  119. self.url = url
  120. self.cmd = cmd
  121. BBFetchException.__init__(self, msg)
  122. self.args = (url, cmd)
  123. class NonLocalMethod(Exception):
  124. def __init__(self):
  125. Exception.__init__(self)
  126. class URI(object):
  127. """
  128. A class representing a generic URI, with methods for
  129. accessing the URI components, and stringifies to the
  130. URI.
  131. It is constructed by calling it with a URI, or setting
  132. the attributes manually:
  133. uri = URI("http://example.com/")
  134. uri = URI()
  135. uri.scheme = 'http'
  136. uri.hostname = 'example.com'
  137. uri.path = '/'
  138. It has the following attributes:
  139. * scheme (read/write)
  140. * userinfo (authentication information) (read/write)
  141. * username (read/write)
  142. * password (read/write)
  143. Note, password is deprecated as of RFC 3986.
  144. * hostname (read/write)
  145. * port (read/write)
  146. * hostport (read only)
  147. "hostname:port", if both are set, otherwise just "hostname"
  148. * path (read/write)
  149. * path_quoted (read/write)
  150. A URI quoted version of path
  151. * params (dict) (read/write)
  152. * query (dict) (read/write)
  153. * relative (bool) (read only)
  154. True if this is a "relative URI", (e.g. file:foo.diff)
  155. It stringifies to the URI itself.
  156. Some notes about relative URIs: while it's specified that
  157. a URI beginning with <scheme>:// should either be directly
  158. followed by a hostname or a /, the old URI handling of the
  159. fetch2 library did not comform to this. Therefore, this URI
  160. class has some kludges to make sure that URIs are parsed in
  161. a way comforming to bitbake's current usage. This URI class
  162. supports the following:
  163. file:relative/path.diff (IETF compliant)
  164. git:relative/path.git (IETF compliant)
  165. git:///absolute/path.git (IETF compliant)
  166. file:///absolute/path.diff (IETF compliant)
  167. file://relative/path.diff (not IETF compliant)
  168. But it does not support the following:
  169. file://hostname/absolute/path.diff (would be IETF compliant)
  170. Note that the last case only applies to a list of
  171. "whitelisted" schemes (currently only file://), that requires
  172. its URIs to not have a network location.
  173. """
  174. _relative_schemes = ['file', 'git']
  175. _netloc_forbidden = ['file']
  176. def __init__(self, uri=None):
  177. self.scheme = ''
  178. self.userinfo = ''
  179. self.hostname = ''
  180. self.port = None
  181. self._path = ''
  182. self.params = {}
  183. self.query = {}
  184. self.relative = False
  185. if not uri:
  186. return
  187. # We hijack the URL parameters, since the way bitbake uses
  188. # them are not quite RFC compliant.
  189. uri, param_str = (uri.split(";", 1) + [None])[:2]
  190. urlp = urllib.parse.urlparse(uri)
  191. self.scheme = urlp.scheme
  192. reparse = 0
  193. # Coerce urlparse to make URI scheme use netloc
  194. if not self.scheme in urllib.parse.uses_netloc:
  195. urllib.parse.uses_params.append(self.scheme)
  196. reparse = 1
  197. # Make urlparse happy(/ier) by converting local resources
  198. # to RFC compliant URL format. E.g.:
  199. # file://foo.diff -> file:foo.diff
  200. if urlp.scheme in self._netloc_forbidden:
  201. uri = re.sub("(?<=:)//(?!/)", "", uri, 1)
  202. reparse = 1
  203. if reparse:
  204. urlp = urllib.parse.urlparse(uri)
  205. # Identify if the URI is relative or not
  206. if urlp.scheme in self._relative_schemes and \
  207. re.compile("^\w+:(?!//)").match(uri):
  208. self.relative = True
  209. if not self.relative:
  210. self.hostname = urlp.hostname or ''
  211. self.port = urlp.port
  212. self.userinfo += urlp.username or ''
  213. if urlp.password:
  214. self.userinfo += ':%s' % urlp.password
  215. self.path = urllib.parse.unquote(urlp.path)
  216. if param_str:
  217. self.params = self._param_str_split(param_str, ";")
  218. if urlp.query:
  219. self.query = self._param_str_split(urlp.query, "&")
  220. def __str__(self):
  221. userinfo = self.userinfo
  222. if userinfo:
  223. userinfo += '@'
  224. return "%s:%s%s%s%s%s%s" % (
  225. self.scheme,
  226. '' if self.relative else '//',
  227. userinfo,
  228. self.hostport,
  229. self.path_quoted,
  230. self._query_str(),
  231. self._param_str())
  232. def _param_str(self):
  233. return (
  234. ''.join([';', self._param_str_join(self.params, ";")])
  235. if self.params else '')
  236. def _query_str(self):
  237. return (
  238. ''.join(['?', self._param_str_join(self.query, "&")])
  239. if self.query else '')
  240. def _param_str_split(self, string, elmdelim, kvdelim="="):
  241. ret = collections.OrderedDict()
  242. for k, v in [x.split(kvdelim, 1) for x in string.split(elmdelim)]:
  243. ret[k] = v
  244. return ret
  245. def _param_str_join(self, dict_, elmdelim, kvdelim="="):
  246. return elmdelim.join([kvdelim.join([k, v]) for k, v in dict_.items()])
  247. @property
  248. def hostport(self):
  249. if not self.port:
  250. return self.hostname
  251. return "%s:%d" % (self.hostname, self.port)
  252. @property
  253. def path_quoted(self):
  254. return urllib.parse.quote(self.path)
  255. @path_quoted.setter
  256. def path_quoted(self, path):
  257. self.path = urllib.parse.unquote(path)
  258. @property
  259. def path(self):
  260. return self._path
  261. @path.setter
  262. def path(self, path):
  263. self._path = path
  264. if not path or re.compile("^/").match(path):
  265. self.relative = False
  266. else:
  267. self.relative = True
  268. @property
  269. def username(self):
  270. if self.userinfo:
  271. return (self.userinfo.split(":", 1))[0]
  272. return ''
  273. @username.setter
  274. def username(self, username):
  275. password = self.password
  276. self.userinfo = username
  277. if password:
  278. self.userinfo += ":%s" % password
  279. @property
  280. def password(self):
  281. if self.userinfo and ":" in self.userinfo:
  282. return (self.userinfo.split(":", 1))[1]
  283. return ''
  284. @password.setter
  285. def password(self, password):
  286. self.userinfo = "%s:%s" % (self.username, password)
  287. def decodeurl(url):
  288. """Decodes an URL into the tokens (scheme, network location, path,
  289. user, password, parameters).
  290. """
  291. m = re.compile('(?P<type>[^:]*)://((?P<user>[^/]+)@)?(?P<location>[^;]+)(;(?P<parm>.*))?').match(url)
  292. if not m:
  293. raise MalformedUrl(url)
  294. type = m.group('type')
  295. location = m.group('location')
  296. if not location:
  297. raise MalformedUrl(url)
  298. user = m.group('user')
  299. parm = m.group('parm')
  300. locidx = location.find('/')
  301. if locidx != -1 and type.lower() != 'file':
  302. host = location[:locidx]
  303. path = location[locidx:]
  304. elif type.lower() == 'file':
  305. host = ""
  306. path = location
  307. else:
  308. host = location
  309. path = ""
  310. if user:
  311. m = re.compile('(?P<user>[^:]+)(:?(?P<pswd>.*))').match(user)
  312. if m:
  313. user = m.group('user')
  314. pswd = m.group('pswd')
  315. else:
  316. user = ''
  317. pswd = ''
  318. p = collections.OrderedDict()
  319. if parm:
  320. for s in parm.split(';'):
  321. if s:
  322. if not '=' in s:
  323. raise MalformedUrl(url, "The URL: '%s' is invalid: parameter %s does not specify a value (missing '=')" % (url, s))
  324. s1, s2 = s.split('=')
  325. p[s1] = s2
  326. return type, host, urllib.parse.unquote(path), user, pswd, p
  327. def encodeurl(decoded):
  328. """Encodes a URL from tokens (scheme, network location, path,
  329. user, password, parameters).
  330. """
  331. type, host, path, user, pswd, p = decoded
  332. if not path:
  333. raise MissingParameterError('path', "encoded from the data %s" % str(decoded))
  334. if not type:
  335. raise MissingParameterError('type', "encoded from the data %s" % str(decoded))
  336. url = '%s://' % type
  337. if user and type != "file":
  338. url += "%s" % user
  339. if pswd:
  340. url += ":%s" % pswd
  341. url += "@"
  342. if host and type != "file":
  343. url += "%s" % host
  344. # Standardise path to ensure comparisons work
  345. while '//' in path:
  346. path = path.replace("//", "/")
  347. url += "%s" % urllib.parse.quote(path)
  348. if p:
  349. for parm in p:
  350. url += ";%s=%s" % (parm, p[parm])
  351. return url
  352. def uri_replace(ud, uri_find, uri_replace, replacements, d):
  353. if not ud.url or not uri_find or not uri_replace:
  354. logger.error("uri_replace: passed an undefined value, not replacing")
  355. return None
  356. uri_decoded = list(decodeurl(ud.url))
  357. uri_find_decoded = list(decodeurl(uri_find))
  358. uri_replace_decoded = list(decodeurl(uri_replace))
  359. logger.debug(2, "For url %s comparing %s to %s" % (uri_decoded, uri_find_decoded, uri_replace_decoded))
  360. result_decoded = ['', '', '', '', '', {}]
  361. for loc, i in enumerate(uri_find_decoded):
  362. result_decoded[loc] = uri_decoded[loc]
  363. regexp = i
  364. if loc == 0 and regexp and not regexp.endswith("$"):
  365. # Leaving the type unanchored can mean "https" matching "file" can become "files"
  366. # which is clearly undesirable.
  367. regexp += "$"
  368. if loc == 5:
  369. # Handle URL parameters
  370. if i:
  371. # Any specified URL parameters must match
  372. for k in uri_replace_decoded[loc]:
  373. if uri_decoded[loc][k] != uri_replace_decoded[loc][k]:
  374. return None
  375. # Overwrite any specified replacement parameters
  376. for k in uri_replace_decoded[loc]:
  377. for l in replacements:
  378. uri_replace_decoded[loc][k] = uri_replace_decoded[loc][k].replace(l, replacements[l])
  379. result_decoded[loc][k] = uri_replace_decoded[loc][k]
  380. elif (re.match(regexp, uri_decoded[loc])):
  381. if not uri_replace_decoded[loc]:
  382. result_decoded[loc] = ""
  383. else:
  384. for k in replacements:
  385. uri_replace_decoded[loc] = uri_replace_decoded[loc].replace(k, replacements[k])
  386. #bb.note("%s %s %s" % (regexp, uri_replace_decoded[loc], uri_decoded[loc]))
  387. result_decoded[loc] = re.sub(regexp, uri_replace_decoded[loc], uri_decoded[loc], 1)
  388. if loc == 2:
  389. # Handle path manipulations
  390. basename = None
  391. if uri_decoded[0] != uri_replace_decoded[0] and ud.mirrortarball:
  392. # If the source and destination url types differ, must be a mirrortarball mapping
  393. basename = os.path.basename(ud.mirrortarball)
  394. # Kill parameters, they make no sense for mirror tarballs
  395. uri_decoded[5] = {}
  396. elif ud.localpath and ud.method.supports_checksum(ud):
  397. basename = os.path.basename(ud.localpath)
  398. if basename and not result_decoded[loc].endswith(basename):
  399. result_decoded[loc] = os.path.join(result_decoded[loc], basename)
  400. else:
  401. return None
  402. result = encodeurl(result_decoded)
  403. if result == ud.url:
  404. return None
  405. logger.debug(2, "For url %s returning %s" % (ud.url, result))
  406. return result
  407. methods = []
  408. urldata_cache = {}
  409. saved_headrevs = {}
  410. def fetcher_init(d):
  411. """
  412. Called to initialize the fetchers once the configuration data is known.
  413. Calls before this must not hit the cache.
  414. """
  415. # When to drop SCM head revisions controlled by user policy
  416. srcrev_policy = d.getVar('BB_SRCREV_POLICY', True) or "clear"
  417. if srcrev_policy == "cache":
  418. logger.debug(1, "Keeping SRCREV cache due to cache policy of: %s", srcrev_policy)
  419. elif srcrev_policy == "clear":
  420. logger.debug(1, "Clearing SRCREV cache due to cache policy of: %s", srcrev_policy)
  421. revs = bb.persist_data.persist('BB_URI_HEADREVS', d)
  422. try:
  423. bb.fetch2.saved_headrevs = revs.items()
  424. except:
  425. pass
  426. revs.clear()
  427. else:
  428. raise FetchError("Invalid SRCREV cache policy of: %s" % srcrev_policy)
  429. _checksum_cache.init_cache(d)
  430. for m in methods:
  431. if hasattr(m, "init"):
  432. m.init(d)
  433. def fetcher_parse_save():
  434. _checksum_cache.save_extras()
  435. def fetcher_parse_done():
  436. _checksum_cache.save_merge()
  437. def fetcher_compare_revisions():
  438. """
  439. Compare the revisions in the persistant cache with current values and
  440. return true/false on whether they've changed.
  441. """
  442. data = bb.persist_data.persist('BB_URI_HEADREVS', d).items()
  443. data2 = bb.fetch2.saved_headrevs
  444. changed = False
  445. for key in data:
  446. if key not in data2 or data2[key] != data[key]:
  447. logger.debug(1, "%s changed", key)
  448. changed = True
  449. return True
  450. else:
  451. logger.debug(2, "%s did not change", key)
  452. return False
  453. def mirror_from_string(data):
  454. return [ i.split() for i in (data or "").replace('\\n','\n').split('\n') if i ]
  455. def verify_checksum(ud, d, precomputed={}):
  456. """
  457. verify the MD5 and SHA256 checksum for downloaded src
  458. Raises a FetchError if one or both of the SRC_URI checksums do not match
  459. the downloaded file, or if BB_STRICT_CHECKSUM is set and there are no
  460. checksums specified.
  461. Returns a dict of checksums that can be stored in a done stamp file and
  462. passed in as precomputed parameter in a later call to avoid re-computing
  463. the checksums from the file. This allows verifying the checksums of the
  464. file against those in the recipe each time, rather than only after
  465. downloading. See https://bugzilla.yoctoproject.org/show_bug.cgi?id=5571.
  466. """
  467. _MD5_KEY = "md5"
  468. _SHA256_KEY = "sha256"
  469. if ud.ignore_checksums or not ud.method.supports_checksum(ud):
  470. return {}
  471. if _MD5_KEY in precomputed:
  472. md5data = precomputed[_MD5_KEY]
  473. else:
  474. md5data = bb.utils.md5_file(ud.localpath)
  475. if _SHA256_KEY in precomputed:
  476. sha256data = precomputed[_SHA256_KEY]
  477. else:
  478. sha256data = bb.utils.sha256_file(ud.localpath)
  479. if ud.method.recommends_checksum(ud) and not ud.md5_expected and not ud.sha256_expected:
  480. # If strict checking enabled and neither sum defined, raise error
  481. strict = d.getVar("BB_STRICT_CHECKSUM", True) or "0"
  482. if strict == "1":
  483. logger.error('No checksum specified for %s, please add at least one to the recipe:\n'
  484. 'SRC_URI[%s] = "%s"\nSRC_URI[%s] = "%s"' %
  485. (ud.localpath, ud.md5_name, md5data,
  486. ud.sha256_name, sha256data))
  487. raise NoChecksumError('Missing SRC_URI checksum', ud.url)
  488. # Log missing sums so user can more easily add them
  489. logger.warning('Missing md5 SRC_URI checksum for %s, consider adding to the recipe:\n'
  490. 'SRC_URI[%s] = "%s"',
  491. ud.localpath, ud.md5_name, md5data)
  492. logger.warning('Missing sha256 SRC_URI checksum for %s, consider adding to the recipe:\n'
  493. 'SRC_URI[%s] = "%s"',
  494. ud.localpath, ud.sha256_name, sha256data)
  495. # We want to alert the user if a checksum is defined in the recipe but
  496. # it does not match.
  497. msg = ""
  498. mismatch = False
  499. if ud.md5_expected and ud.md5_expected != md5data:
  500. msg = msg + "\nFile: '%s' has %s checksum %s when %s was expected" % (ud.localpath, 'md5', md5data, ud.md5_expected)
  501. mismatch = True;
  502. if ud.sha256_expected and ud.sha256_expected != sha256data:
  503. msg = msg + "\nFile: '%s' has %s checksum %s when %s was expected" % (ud.localpath, 'sha256', sha256data, ud.sha256_expected)
  504. mismatch = True;
  505. if mismatch:
  506. msg = msg + '\nIf this change is expected (e.g. you have upgraded to a new version without updating the checksums) then you can use these lines within the recipe:\nSRC_URI[%s] = "%s"\nSRC_URI[%s] = "%s"\nOtherwise you should retry the download and/or check with upstream to determine if the file has become corrupted or otherwise unexpectedly modified.\n' % (ud.md5_name, md5data, ud.sha256_name, sha256data)
  507. if len(msg):
  508. raise ChecksumError('Checksum mismatch!%s' % msg, ud.url, md5data)
  509. return {
  510. _MD5_KEY: md5data,
  511. _SHA256_KEY: sha256data
  512. }
  513. def verify_donestamp(ud, d, origud=None):
  514. """
  515. Check whether the done stamp file has the right checksums (if the fetch
  516. method supports them). If it doesn't, delete the done stamp and force
  517. a re-download.
  518. Returns True, if the donestamp exists and is valid, False otherwise. When
  519. returning False, any existing done stamps are removed.
  520. """
  521. if not ud.needdonestamp:
  522. return True
  523. if not os.path.exists(ud.donestamp):
  524. return False
  525. if (not ud.method.supports_checksum(ud) or
  526. (origud and not origud.method.supports_checksum(origud))):
  527. # done stamp exists, checksums not supported; assume the local file is
  528. # current
  529. return True
  530. if not os.path.exists(ud.localpath):
  531. # done stamp exists, but the downloaded file does not; the done stamp
  532. # must be incorrect, re-trigger the download
  533. bb.utils.remove(ud.donestamp)
  534. return False
  535. precomputed_checksums = {}
  536. # Only re-use the precomputed checksums if the donestamp is newer than the
  537. # file. Do not rely on the mtime of directories, though. If ud.localpath is
  538. # a directory, there will probably not be any checksums anyway.
  539. if (os.path.isdir(ud.localpath) or
  540. os.path.getmtime(ud.localpath) < os.path.getmtime(ud.donestamp)):
  541. try:
  542. with open(ud.donestamp, "rb") as cachefile:
  543. pickled = pickle.Unpickler(cachefile)
  544. precomputed_checksums.update(pickled.load())
  545. except Exception as e:
  546. # Avoid the warnings on the upgrade path from emtpy done stamp
  547. # files to those containing the checksums.
  548. if not isinstance(e, EOFError):
  549. # Ignore errors, they aren't fatal
  550. logger.warning("Couldn't load checksums from donestamp %s: %s "
  551. "(msg: %s)" % (ud.donestamp, type(e).__name__,
  552. str(e)))
  553. try:
  554. checksums = verify_checksum(ud, d, precomputed_checksums)
  555. # If the cache file did not have the checksums, compute and store them
  556. # as an upgrade path from the previous done stamp file format.
  557. if checksums != precomputed_checksums:
  558. with open(ud.donestamp, "wb") as cachefile:
  559. p = pickle.Pickler(cachefile, pickle.HIGHEST_PROTOCOL)
  560. p.dump(checksums)
  561. return True
  562. except ChecksumError as e:
  563. # Checksums failed to verify, trigger re-download and remove the
  564. # incorrect stamp file.
  565. logger.warning("Checksum mismatch for local file %s\n"
  566. "Cleaning and trying again." % ud.localpath)
  567. if os.path.exists(ud.localpath):
  568. rename_bad_checksum(ud, e.checksum)
  569. bb.utils.remove(ud.donestamp)
  570. return False
  571. def update_stamp(ud, d):
  572. """
  573. donestamp is file stamp indicating the whole fetching is done
  574. this function update the stamp after verifying the checksum
  575. """
  576. if not ud.needdonestamp:
  577. return
  578. if os.path.exists(ud.donestamp):
  579. # Touch the done stamp file to show active use of the download
  580. try:
  581. os.utime(ud.donestamp, None)
  582. except:
  583. # Errors aren't fatal here
  584. pass
  585. else:
  586. try:
  587. checksums = verify_checksum(ud, d)
  588. # Store the checksums for later re-verification against the recipe
  589. with open(ud.donestamp, "wb") as cachefile:
  590. p = pickle.Pickler(cachefile, pickle.HIGHEST_PROTOCOL)
  591. p.dump(checksums)
  592. except ChecksumError as e:
  593. # Checksums failed to verify, trigger re-download and remove the
  594. # incorrect stamp file.
  595. logger.warning("Checksum mismatch for local file %s\n"
  596. "Cleaning and trying again." % ud.localpath)
  597. if os.path.exists(ud.localpath):
  598. rename_bad_checksum(ud, e.checksum)
  599. bb.utils.remove(ud.donestamp)
  600. raise
  601. def subprocess_setup():
  602. # Python installs a SIGPIPE handler by default. This is usually not what
  603. # non-Python subprocesses expect.
  604. # SIGPIPE errors are known issues with gzip/bash
  605. signal.signal(signal.SIGPIPE, signal.SIG_DFL)
  606. def get_autorev(d):
  607. # only not cache src rev in autorev case
  608. if d.getVar('BB_SRCREV_POLICY', True) != "cache":
  609. d.setVar('BB_DONT_CACHE', '1')
  610. return "AUTOINC"
  611. def get_srcrev(d, method_name='sortable_revision'):
  612. """
  613. Return the revsion string, usually for use in the version string (PV) of the current package
  614. Most packages usually only have one SCM so we just pass on the call.
  615. In the multi SCM case, we build a value based on SRCREV_FORMAT which must
  616. have been set.
  617. The idea here is that we put the string "AUTOINC+" into return value if the revisions are not
  618. incremental, other code is then responsible for turning that into an increasing value (if needed)
  619. A method_name can be supplied to retrieve an alternatively formatted revision from a fetcher, if
  620. that fetcher provides a method with the given name and the same signature as sortable_revision.
  621. """
  622. scms = []
  623. fetcher = Fetch(d.getVar('SRC_URI', True).split(), d)
  624. urldata = fetcher.ud
  625. for u in urldata:
  626. if urldata[u].method.supports_srcrev():
  627. scms.append(u)
  628. if len(scms) == 0:
  629. raise FetchError("SRCREV was used yet no valid SCM was found in SRC_URI")
  630. if len(scms) == 1 and len(urldata[scms[0]].names) == 1:
  631. autoinc, rev = getattr(urldata[scms[0]].method, method_name)(urldata[scms[0]], d, urldata[scms[0]].names[0])
  632. if len(rev) > 10:
  633. rev = rev[:10]
  634. if autoinc:
  635. return "AUTOINC+" + rev
  636. return rev
  637. #
  638. # Mutiple SCMs are in SRC_URI so we resort to SRCREV_FORMAT
  639. #
  640. format = d.getVar('SRCREV_FORMAT', True)
  641. if not format:
  642. raise FetchError("The SRCREV_FORMAT variable must be set when multiple SCMs are used.")
  643. seenautoinc = False
  644. for scm in scms:
  645. ud = urldata[scm]
  646. for name in ud.names:
  647. autoinc, rev = getattr(ud.method, method_name)(ud, d, name)
  648. seenautoinc = seenautoinc or autoinc
  649. if len(rev) > 10:
  650. rev = rev[:10]
  651. format = format.replace(name, rev)
  652. if seenautoinc:
  653. format = "AUTOINC+" + format
  654. return format
  655. def localpath(url, d):
  656. fetcher = bb.fetch2.Fetch([url], d)
  657. return fetcher.localpath(url)
  658. def runfetchcmd(cmd, d, quiet=False, cleanup=None):
  659. """
  660. Run cmd returning the command output
  661. Raise an error if interrupted or cmd fails
  662. Optionally echo command output to stdout
  663. Optionally remove the files/directories listed in cleanup upon failure
  664. """
  665. # Need to export PATH as binary could be in metadata paths
  666. # rather than host provided
  667. # Also include some other variables.
  668. # FIXME: Should really include all export varaiables?
  669. exportvars = ['HOME', 'PATH',
  670. 'HTTP_PROXY', 'http_proxy',
  671. 'HTTPS_PROXY', 'https_proxy',
  672. 'FTP_PROXY', 'ftp_proxy',
  673. 'FTPS_PROXY', 'ftps_proxy',
  674. 'NO_PROXY', 'no_proxy',
  675. 'ALL_PROXY', 'all_proxy',
  676. 'GIT_PROXY_COMMAND',
  677. 'GIT_SSL_CAINFO',
  678. 'GIT_SMART_HTTP',
  679. 'SSH_AUTH_SOCK', 'SSH_AGENT_PID',
  680. 'SOCKS5_USER', 'SOCKS5_PASSWD',
  681. 'DBUS_SESSION_BUS_ADDRESS']
  682. if not cleanup:
  683. cleanup = []
  684. origenv = d.getVar("BB_ORIGENV", False)
  685. for var in exportvars:
  686. val = d.getVar(var, True) or (origenv and origenv.getVar(var, True))
  687. if val:
  688. cmd = 'export ' + var + '=\"%s\"; %s' % (val, cmd)
  689. logger.debug(1, "Running %s", cmd)
  690. success = False
  691. error_message = ""
  692. try:
  693. (output, errors) = bb.process.run(cmd, shell=True, stderr=subprocess.PIPE)
  694. success = True
  695. except bb.process.NotFoundError as e:
  696. error_message = "Fetch command %s" % (e.command)
  697. except bb.process.ExecutionError as e:
  698. if e.stdout:
  699. output = "output:\n%s\n%s" % (e.stdout, e.stderr)
  700. elif e.stderr:
  701. output = "output:\n%s" % e.stderr
  702. else:
  703. output = "no output"
  704. error_message = "Fetch command failed with exit code %s, %s" % (e.exitcode, output)
  705. except bb.process.CmdError as e:
  706. error_message = "Fetch command %s could not be run:\n%s" % (e.command, e.msg)
  707. if not success:
  708. for f in cleanup:
  709. try:
  710. bb.utils.remove(f, True)
  711. except OSError:
  712. pass
  713. raise FetchError(error_message)
  714. return output
  715. def check_network_access(d, info = "", url = None):
  716. """
  717. log remote network access, and error if BB_NO_NETWORK is set
  718. """
  719. if d.getVar("BB_NO_NETWORK", True) == "1":
  720. raise NetworkAccess(url, info)
  721. else:
  722. logger.debug(1, "Fetcher accessed the network with the command %s" % info)
  723. def build_mirroruris(origud, mirrors, ld):
  724. uris = []
  725. uds = []
  726. replacements = {}
  727. replacements["TYPE"] = origud.type
  728. replacements["HOST"] = origud.host
  729. replacements["PATH"] = origud.path
  730. replacements["BASENAME"] = origud.path.split("/")[-1]
  731. replacements["MIRRORNAME"] = origud.host.replace(':','.') + origud.path.replace('/', '.').replace('*', '.')
  732. def adduri(ud, uris, uds, mirrors):
  733. for line in mirrors:
  734. try:
  735. (find, replace) = line
  736. except ValueError:
  737. continue
  738. newuri = uri_replace(ud, find, replace, replacements, ld)
  739. if not newuri or newuri in uris or newuri == origud.url:
  740. continue
  741. if not trusted_network(ld, newuri):
  742. logger.debug(1, "Mirror %s not in the list of trusted networks, skipping" % (newuri))
  743. continue
  744. # Create a local copy of the mirrors minus the current line
  745. # this will prevent us from recursively processing the same line
  746. # as well as indirect recursion A -> B -> C -> A
  747. localmirrors = list(mirrors)
  748. localmirrors.remove(line)
  749. try:
  750. newud = FetchData(newuri, ld)
  751. newud.setup_localpath(ld)
  752. except bb.fetch2.BBFetchException as e:
  753. logger.debug(1, "Mirror fetch failure for url %s (original url: %s)" % (newuri, origud.url))
  754. logger.debug(1, str(e))
  755. try:
  756. # setup_localpath of file:// urls may fail, we should still see
  757. # if mirrors of the url exist
  758. adduri(newud, uris, uds, localmirrors)
  759. except UnboundLocalError:
  760. pass
  761. continue
  762. uris.append(newuri)
  763. uds.append(newud)
  764. adduri(newud, uris, uds, localmirrors)
  765. adduri(origud, uris, uds, mirrors)
  766. return uris, uds
  767. def rename_bad_checksum(ud, suffix):
  768. """
  769. Renames files to have suffix from parameter
  770. """
  771. if ud.localpath is None:
  772. return
  773. new_localpath = "%s_bad-checksum_%s" % (ud.localpath, suffix)
  774. bb.warn("Renaming %s to %s" % (ud.localpath, new_localpath))
  775. bb.utils.movefile(ud.localpath, new_localpath)
  776. def try_mirror_url(fetch, origud, ud, ld, check = False):
  777. # Return of None or a value means we're finished
  778. # False means try another url
  779. if ud.lockfile and ud.lockfile != origud.lockfile:
  780. lf = bb.utils.lockfile(ud.lockfile)
  781. try:
  782. if check:
  783. found = ud.method.checkstatus(fetch, ud, ld)
  784. if found:
  785. return found
  786. return False
  787. os.chdir(ld.getVar("DL_DIR", True))
  788. if not verify_donestamp(ud, ld, origud) or ud.method.need_update(ud, ld):
  789. ud.method.download(ud, ld)
  790. if hasattr(ud.method,"build_mirror_data"):
  791. ud.method.build_mirror_data(ud, ld)
  792. if not ud.localpath or not os.path.exists(ud.localpath):
  793. return False
  794. if ud.localpath == origud.localpath:
  795. return ud.localpath
  796. # We may be obtaining a mirror tarball which needs further processing by the real fetcher
  797. # If that tarball is a local file:// we need to provide a symlink to it
  798. dldir = ld.getVar("DL_DIR", True)
  799. if origud.mirrortarball and os.path.basename(ud.localpath) == os.path.basename(origud.mirrortarball) \
  800. and os.path.basename(ud.localpath) != os.path.basename(origud.localpath):
  801. # Create donestamp in old format to avoid triggering a re-download
  802. if ud.donestamp:
  803. bb.utils.mkdirhier(os.path.dirname(ud.donestamp))
  804. open(ud.donestamp, 'w').close()
  805. dest = os.path.join(dldir, os.path.basename(ud.localpath))
  806. if not os.path.exists(dest):
  807. os.symlink(ud.localpath, dest)
  808. if not verify_donestamp(origud, ld) or origud.method.need_update(origud, ld):
  809. origud.method.download(origud, ld)
  810. if hasattr(origud.method,"build_mirror_data"):
  811. origud.method.build_mirror_data(origud, ld)
  812. return origud.localpath
  813. # Otherwise the result is a local file:// and we symlink to it
  814. if not os.path.exists(origud.localpath):
  815. if os.path.islink(origud.localpath):
  816. # Broken symbolic link
  817. os.unlink(origud.localpath)
  818. os.symlink(ud.localpath, origud.localpath)
  819. update_stamp(origud, ld)
  820. return ud.localpath
  821. except bb.fetch2.NetworkAccess:
  822. raise
  823. except bb.fetch2.BBFetchException as e:
  824. if isinstance(e, ChecksumError):
  825. logger.warning("Mirror checksum failure for url %s (original url: %s)\nCleaning and trying again." % (ud.url, origud.url))
  826. logger.warning(str(e))
  827. if os.path.exists(ud.localpath):
  828. rename_bad_checksum(ud, e.checksum)
  829. elif isinstance(e, NoChecksumError):
  830. raise
  831. else:
  832. logger.debug(1, "Mirror fetch failure for url %s (original url: %s)" % (ud.url, origud.url))
  833. logger.debug(1, str(e))
  834. try:
  835. ud.method.clean(ud, ld)
  836. except UnboundLocalError:
  837. pass
  838. return False
  839. finally:
  840. if ud.lockfile and ud.lockfile != origud.lockfile:
  841. bb.utils.unlockfile(lf)
  842. def try_mirrors(fetch, d, origud, mirrors, check = False):
  843. """
  844. Try to use a mirrored version of the sources.
  845. This method will be automatically called before the fetchers go.
  846. d Is a bb.data instance
  847. uri is the original uri we're trying to download
  848. mirrors is the list of mirrors we're going to try
  849. """
  850. ld = d.createCopy()
  851. uris, uds = build_mirroruris(origud, mirrors, ld)
  852. for index, uri in enumerate(uris):
  853. ret = try_mirror_url(fetch, origud, uds[index], ld, check)
  854. if ret != False:
  855. return ret
  856. return None
  857. def trusted_network(d, url):
  858. """
  859. Use a trusted url during download if networking is enabled and
  860. BB_ALLOWED_NETWORKS is set globally or for a specific recipe.
  861. Note: modifies SRC_URI & mirrors.
  862. """
  863. if d.getVar('BB_NO_NETWORK', True) == "1":
  864. return True
  865. pkgname = d.expand(d.getVar('PN', False))
  866. trusted_hosts = d.getVarFlag('BB_ALLOWED_NETWORKS', pkgname, False)
  867. if not trusted_hosts:
  868. trusted_hosts = d.getVar('BB_ALLOWED_NETWORKS', True)
  869. # Not enabled.
  870. if not trusted_hosts:
  871. return True
  872. scheme, network, path, user, passwd, param = decodeurl(url)
  873. if not network:
  874. return True
  875. network = network.split(':')[0]
  876. network = network.lower()
  877. for host in trusted_hosts.split(" "):
  878. host = host.lower()
  879. if host.startswith("*.") and ("." + network).endswith(host[1:]):
  880. return True
  881. if host == network:
  882. return True
  883. return False
  884. def srcrev_internal_helper(ud, d, name):
  885. """
  886. Return:
  887. a) a source revision if specified
  888. b) latest revision if SRCREV="AUTOINC"
  889. c) None if not specified
  890. """
  891. srcrev = None
  892. pn = d.getVar("PN", True)
  893. attempts = []
  894. if name != '' and pn:
  895. attempts.append("SRCREV_%s_pn-%s" % (name, pn))
  896. if name != '':
  897. attempts.append("SRCREV_%s" % name)
  898. if pn:
  899. attempts.append("SRCREV_pn-%s" % pn)
  900. attempts.append("SRCREV")
  901. for a in attempts:
  902. srcrev = d.getVar(a, True)
  903. if srcrev and srcrev != "INVALID":
  904. break
  905. if 'rev' in ud.parm and 'tag' in ud.parm:
  906. raise FetchError("Please specify a ;rev= parameter or a ;tag= parameter in the url %s but not both." % (ud.url))
  907. if 'rev' in ud.parm or 'tag' in ud.parm:
  908. if 'rev' in ud.parm:
  909. parmrev = ud.parm['rev']
  910. else:
  911. parmrev = ud.parm['tag']
  912. if srcrev == "INVALID" or not srcrev:
  913. return parmrev
  914. if srcrev != parmrev:
  915. raise FetchError("Conflicting revisions (%s from SRCREV and %s from the url) found, please spcify one valid value" % (srcrev, parmrev))
  916. return parmrev
  917. if srcrev == "INVALID" or not srcrev:
  918. raise FetchError("Please set a valid SRCREV for url %s (possible key names are %s, or use a ;rev=X URL parameter)" % (str(attempts), ud.url), ud.url)
  919. if srcrev == "AUTOINC":
  920. srcrev = ud.method.latest_revision(ud, d, name)
  921. return srcrev
  922. def get_checksum_file_list(d):
  923. """ Get a list of files checksum in SRC_URI
  924. Returns the resolved local paths of all local file entries in
  925. SRC_URI as a space-separated string
  926. """
  927. fetch = Fetch([], d, cache = False, localonly = True)
  928. dl_dir = d.getVar('DL_DIR', True)
  929. filelist = []
  930. for u in fetch.urls:
  931. ud = fetch.ud[u]
  932. if ud and isinstance(ud.method, local.Local):
  933. paths = ud.method.localpaths(ud, d)
  934. for f in paths:
  935. pth = ud.decodedurl
  936. if '*' in pth:
  937. f = os.path.join(os.path.abspath(f), pth)
  938. if f.startswith(dl_dir):
  939. # The local fetcher's behaviour is to return a path under DL_DIR if it couldn't find the file anywhere else
  940. if os.path.exists(f):
  941. bb.warn("Getting checksum for %s SRC_URI entry %s: file not found except in DL_DIR" % (d.getVar('PN', True), os.path.basename(f)))
  942. else:
  943. bb.warn("Unable to get checksum for %s SRC_URI entry %s: file could not be found" % (d.getVar('PN', True), os.path.basename(f)))
  944. filelist.append(f + ":" + str(os.path.exists(f)))
  945. return " ".join(filelist)
  946. def get_file_checksums(filelist, pn):
  947. """Get a list of the checksums for a list of local files
  948. Returns the checksums for a list of local files, caching the results as
  949. it proceeds
  950. """
  951. return _checksum_cache.get_checksums(filelist, pn)
  952. class FetchData(object):
  953. """
  954. A class which represents the fetcher state for a given URI.
  955. """
  956. def __init__(self, url, d, localonly = False):
  957. # localpath is the location of a downloaded result. If not set, the file is local.
  958. self.donestamp = None
  959. self.needdonestamp = True
  960. self.localfile = ""
  961. self.localpath = None
  962. self.lockfile = None
  963. self.mirrortarball = None
  964. self.basename = None
  965. self.basepath = None
  966. (self.type, self.host, self.path, self.user, self.pswd, self.parm) = decodeurl(data.expand(url, d))
  967. self.date = self.getSRCDate(d)
  968. self.url = url
  969. if not self.user and "user" in self.parm:
  970. self.user = self.parm["user"]
  971. if not self.pswd and "pswd" in self.parm:
  972. self.pswd = self.parm["pswd"]
  973. self.setup = False
  974. if "name" in self.parm:
  975. self.md5_name = "%s.md5sum" % self.parm["name"]
  976. self.sha256_name = "%s.sha256sum" % self.parm["name"]
  977. else:
  978. self.md5_name = "md5sum"
  979. self.sha256_name = "sha256sum"
  980. if self.md5_name in self.parm:
  981. self.md5_expected = self.parm[self.md5_name]
  982. elif self.type not in ["http", "https", "ftp", "ftps", "sftp"]:
  983. self.md5_expected = None
  984. else:
  985. self.md5_expected = d.getVarFlag("SRC_URI", self.md5_name, True)
  986. if self.sha256_name in self.parm:
  987. self.sha256_expected = self.parm[self.sha256_name]
  988. elif self.type not in ["http", "https", "ftp", "ftps", "sftp"]:
  989. self.sha256_expected = None
  990. else:
  991. self.sha256_expected = d.getVarFlag("SRC_URI", self.sha256_name, True)
  992. self.ignore_checksums = False
  993. self.names = self.parm.get("name",'default').split(',')
  994. self.method = None
  995. for m in methods:
  996. if m.supports(self, d):
  997. self.method = m
  998. break
  999. if not self.method:
  1000. raise NoMethodError(url)
  1001. if localonly and not isinstance(self.method, local.Local):
  1002. raise NonLocalMethod()
  1003. if self.parm.get("proto", None) and "protocol" not in self.parm:
  1004. logger.warning('Consider updating %s recipe to use "protocol" not "proto" in SRC_URI.', d.getVar('PN', True))
  1005. self.parm["protocol"] = self.parm.get("proto", None)
  1006. if hasattr(self.method, "urldata_init"):
  1007. self.method.urldata_init(self, d)
  1008. if "localpath" in self.parm:
  1009. # if user sets localpath for file, use it instead.
  1010. self.localpath = self.parm["localpath"]
  1011. self.basename = os.path.basename(self.localpath)
  1012. elif self.localfile:
  1013. self.localpath = self.method.localpath(self, d)
  1014. dldir = d.getVar("DL_DIR", True)
  1015. if not self.needdonestamp:
  1016. return
  1017. # Note: .done and .lock files should always be in DL_DIR whereas localpath may not be.
  1018. if self.localpath and self.localpath.startswith(dldir):
  1019. basepath = self.localpath
  1020. elif self.localpath:
  1021. basepath = dldir + os.sep + os.path.basename(self.localpath)
  1022. elif self.basepath or self.basename:
  1023. basepath = dldir + os.sep + (self.basepath or self.basename)
  1024. else:
  1025. bb.fatal("Can't determine lock path for url %s" % url)
  1026. self.donestamp = basepath + '.done'
  1027. self.lockfile = basepath + '.lock'
  1028. def setup_revisons(self, d):
  1029. self.revisions = {}
  1030. for name in self.names:
  1031. self.revisions[name] = srcrev_internal_helper(self, d, name)
  1032. # add compatibility code for non name specified case
  1033. if len(self.names) == 1:
  1034. self.revision = self.revisions[self.names[0]]
  1035. def setup_localpath(self, d):
  1036. if not self.localpath:
  1037. self.localpath = self.method.localpath(self, d)
  1038. def getSRCDate(self, d):
  1039. """
  1040. Return the SRC Date for the component
  1041. d the bb.data module
  1042. """
  1043. if "srcdate" in self.parm:
  1044. return self.parm['srcdate']
  1045. pn = d.getVar("PN", True)
  1046. if pn:
  1047. return d.getVar("SRCDATE_%s" % pn, True) or d.getVar("SRCDATE", True) or d.getVar("DATE", True)
  1048. return d.getVar("SRCDATE", True) or d.getVar("DATE", True)
  1049. class FetchMethod(object):
  1050. """Base class for 'fetch'ing data"""
  1051. def __init__(self, urls=None):
  1052. self.urls = []
  1053. def supports(self, urldata, d):
  1054. """
  1055. Check to see if this fetch class supports a given url.
  1056. """
  1057. return 0
  1058. def localpath(self, urldata, d):
  1059. """
  1060. Return the local filename of a given url assuming a successful fetch.
  1061. Can also setup variables in urldata for use in go (saving code duplication
  1062. and duplicate code execution)
  1063. """
  1064. return os.path.join(data.getVar("DL_DIR", d, True), urldata.localfile)
  1065. def supports_checksum(self, urldata):
  1066. """
  1067. Is localpath something that can be represented by a checksum?
  1068. """
  1069. # We cannot compute checksums for directories
  1070. if os.path.isdir(urldata.localpath) == True:
  1071. return False
  1072. if urldata.localpath.find("*") != -1:
  1073. return False
  1074. return True
  1075. def recommends_checksum(self, urldata):
  1076. """
  1077. Is the backend on where checksumming is recommended (should warnings
  1078. be displayed if there is no checksum)?
  1079. """
  1080. return False
  1081. def _strip_leading_slashes(self, relpath):
  1082. """
  1083. Remove leading slash as os.path.join can't cope
  1084. """
  1085. while os.path.isabs(relpath):
  1086. relpath = relpath[1:]
  1087. return relpath
  1088. def setUrls(self, urls):
  1089. self.__urls = urls
  1090. def getUrls(self):
  1091. return self.__urls
  1092. urls = property(getUrls, setUrls, None, "Urls property")
  1093. def need_update(self, ud, d):
  1094. """
  1095. Force a fetch, even if localpath exists?
  1096. """
  1097. if os.path.exists(ud.localpath):
  1098. return False
  1099. return True
  1100. def supports_srcrev(self):
  1101. """
  1102. The fetcher supports auto source revisions (SRCREV)
  1103. """
  1104. return False
  1105. def download(self, urldata, d):
  1106. """
  1107. Fetch urls
  1108. Assumes localpath was called first
  1109. """
  1110. raise NoMethodError(url)
  1111. def unpack(self, urldata, rootdir, data):
  1112. iterate = False
  1113. file = urldata.localpath
  1114. # Localpath can't deal with 'dir/*' entries, so it converts them to '.',
  1115. # but it must be corrected back for local files copying
  1116. if urldata.basename == '*' and file.endswith('/.'):
  1117. file = '%s/%s' % (file.rstrip('/.'), urldata.path)
  1118. try:
  1119. unpack = bb.utils.to_boolean(urldata.parm.get('unpack'), True)
  1120. except ValueError as exc:
  1121. bb.fatal("Invalid value for 'unpack' parameter for %s: %s" %
  1122. (file, urldata.parm.get('unpack')))
  1123. base, ext = os.path.splitext(file)
  1124. if ext in ['.gz', '.bz2', '.Z', '.xz', '.lz']:
  1125. efile = os.path.join(rootdir, os.path.basename(base))
  1126. else:
  1127. efile = file
  1128. cmd = None
  1129. if unpack:
  1130. if file.endswith('.tar'):
  1131. cmd = 'tar x --no-same-owner -f %s' % file
  1132. elif file.endswith('.tgz') or file.endswith('.tar.gz') or file.endswith('.tar.Z'):
  1133. cmd = 'tar xz --no-same-owner -f %s' % file
  1134. elif file.endswith('.tbz') or file.endswith('.tbz2') or file.endswith('.tar.bz2'):
  1135. cmd = 'bzip2 -dc %s | tar x --no-same-owner -f -' % file
  1136. elif file.endswith('.gz') or file.endswith('.Z') or file.endswith('.z'):
  1137. cmd = 'gzip -dc %s > %s' % (file, efile)
  1138. elif file.endswith('.bz2'):
  1139. cmd = 'bzip2 -dc %s > %s' % (file, efile)
  1140. elif file.endswith('.tar.xz'):
  1141. cmd = 'xz -dc %s | tar x --no-same-owner -f -' % file
  1142. elif file.endswith('.xz'):
  1143. cmd = 'xz -dc %s > %s' % (file, efile)
  1144. elif file.endswith('.tar.lz'):
  1145. cmd = 'lzip -dc %s | tar x --no-same-owner -f -' % file
  1146. elif file.endswith('.lz'):
  1147. cmd = 'lzip -dc %s > %s' % (file, efile)
  1148. elif file.endswith('.zip') or file.endswith('.jar'):
  1149. try:
  1150. dos = bb.utils.to_boolean(urldata.parm.get('dos'), False)
  1151. except ValueError as exc:
  1152. bb.fatal("Invalid value for 'dos' parameter for %s: %s" %
  1153. (file, urldata.parm.get('dos')))
  1154. cmd = 'unzip -q -o'
  1155. if dos:
  1156. cmd = '%s -a' % cmd
  1157. cmd = "%s '%s'" % (cmd, file)
  1158. elif file.endswith('.rpm') or file.endswith('.srpm'):
  1159. if 'extract' in urldata.parm:
  1160. unpack_file = urldata.parm.get('extract')
  1161. cmd = 'rpm2cpio.sh %s | cpio -id %s' % (file, unpack_file)
  1162. iterate = True
  1163. iterate_file = unpack_file
  1164. else:
  1165. cmd = 'rpm2cpio.sh %s | cpio -id' % (file)
  1166. elif file.endswith('.deb') or file.endswith('.ipk'):
  1167. cmd = 'ar -p %s data.tar.gz | zcat | tar --no-same-owner -xpf -' % file
  1168. elif file.endswith('.tar.7z'):
  1169. cmd = '7z x -so %s | tar xf - ' % file
  1170. elif file.endswith('.7z'):
  1171. cmd = '7za x -y %s 1>/dev/null' % file
  1172. # If 'subdir' param exists, create a dir and use it as destination for unpack cmd
  1173. if 'subdir' in urldata.parm:
  1174. unpackdir = '%s/%s' % (rootdir, urldata.parm.get('subdir'))
  1175. bb.utils.mkdirhier(unpackdir)
  1176. else:
  1177. unpackdir = rootdir
  1178. if not unpack or not cmd:
  1179. # If file == dest, then avoid any copies, as we already put the file into dest!
  1180. dest = os.path.join(unpackdir, os.path.basename(file))
  1181. if file != dest and not (os.path.exists(dest) and os.path.samefile(file, dest)):
  1182. destdir = '.'
  1183. # For file:// entries all intermediate dirs in path must be created at destination
  1184. if urldata.type == "file":
  1185. # Trailing '/' does a copying to wrong place
  1186. urlpath = urldata.path.rstrip('/')
  1187. # Want files places relative to cwd so no leading '/'
  1188. urlpath = urlpath.lstrip('/')
  1189. if urlpath.find("/") != -1:
  1190. destdir = urlpath.rsplit("/", 1)[0] + '/'
  1191. bb.utils.mkdirhier("%s/%s" % (unpackdir, destdir))
  1192. cmd = 'cp -fpPR %s %s' % (file, destdir)
  1193. if not cmd:
  1194. return
  1195. # Change to unpackdir before executing command
  1196. save_cwd = os.getcwd();
  1197. os.chdir(unpackdir)
  1198. path = data.getVar('PATH', True)
  1199. if path:
  1200. cmd = "PATH=\"%s\" %s" % (path, cmd)
  1201. bb.note("Unpacking %s to %s/" % (file, os.getcwd()))
  1202. ret = subprocess.call(cmd, preexec_fn=subprocess_setup, shell=True)
  1203. os.chdir(save_cwd)
  1204. if ret != 0:
  1205. raise UnpackError("Unpack command %s failed with return value %s" % (cmd, ret), urldata.url)
  1206. if iterate is True:
  1207. iterate_urldata = urldata
  1208. iterate_urldata.localpath = "%s/%s" % (rootdir, iterate_file)
  1209. self.unpack(urldata, rootdir, data)
  1210. return
  1211. def clean(self, urldata, d):
  1212. """
  1213. Clean any existing full or partial download
  1214. """
  1215. bb.utils.remove(urldata.localpath)
  1216. def try_premirror(self, urldata, d):
  1217. """
  1218. Should premirrors be used?
  1219. """
  1220. return True
  1221. def checkstatus(self, fetch, urldata, d):
  1222. """
  1223. Check the status of a URL
  1224. Assumes localpath was called first
  1225. """
  1226. logger.info("URL %s could not be checked for status since no method exists.", url)
  1227. return True
  1228. def latest_revision(self, ud, d, name):
  1229. """
  1230. Look in the cache for the latest revision, if not present ask the SCM.
  1231. """
  1232. if not hasattr(self, "_latest_revision"):
  1233. raise ParameterError("The fetcher for this URL does not support _latest_revision", url)
  1234. revs = bb.persist_data.persist('BB_URI_HEADREVS', d)
  1235. key = self.generate_revision_key(ud, d, name)
  1236. try:
  1237. return revs[key]
  1238. except KeyError:
  1239. revs[key] = rev = self._latest_revision(ud, d, name)
  1240. return rev
  1241. def sortable_revision(self, ud, d, name):
  1242. latest_rev = self._build_revision(ud, d, name)
  1243. return True, str(latest_rev)
  1244. def generate_revision_key(self, ud, d, name):
  1245. key = self._revision_key(ud, d, name)
  1246. return "%s-%s" % (key, d.getVar("PN", True) or "")
  1247. class Fetch(object):
  1248. def __init__(self, urls, d, cache = True, localonly = False, connection_cache = None):
  1249. if localonly and cache:
  1250. raise Exception("bb.fetch2.Fetch.__init__: cannot set cache and localonly at same time")
  1251. if len(urls) == 0:
  1252. urls = d.getVar("SRC_URI", True).split()
  1253. self.urls = urls
  1254. self.d = d
  1255. self.ud = {}
  1256. self.connection_cache = connection_cache
  1257. fn = d.getVar('FILE', True)
  1258. if cache and fn and fn in urldata_cache:
  1259. self.ud = urldata_cache[fn]
  1260. for url in urls:
  1261. if url not in self.ud:
  1262. try:
  1263. self.ud[url] = FetchData(url, d, localonly)
  1264. except NonLocalMethod:
  1265. if localonly:
  1266. self.ud[url] = None
  1267. pass
  1268. if fn and cache:
  1269. urldata_cache[fn] = self.ud
  1270. def localpath(self, url):
  1271. if url not in self.urls:
  1272. self.ud[url] = FetchData(url, self.d)
  1273. self.ud[url].setup_localpath(self.d)
  1274. return self.d.expand(self.ud[url].localpath)
  1275. def localpaths(self):
  1276. """
  1277. Return a list of the local filenames, assuming successful fetch
  1278. """
  1279. local = []
  1280. for u in self.urls:
  1281. ud = self.ud[u]
  1282. ud.setup_localpath(self.d)
  1283. local.append(ud.localpath)
  1284. return local
  1285. def download(self, urls=None):
  1286. """
  1287. Fetch all urls
  1288. """
  1289. if not urls:
  1290. urls = self.urls
  1291. network = self.d.getVar("BB_NO_NETWORK", True)
  1292. premirroronly = (self.d.getVar("BB_FETCH_PREMIRRORONLY", True) == "1")
  1293. for u in urls:
  1294. ud = self.ud[u]
  1295. ud.setup_localpath(self.d)
  1296. m = ud.method
  1297. localpath = ""
  1298. if ud.lockfile:
  1299. lf = bb.utils.lockfile(ud.lockfile)
  1300. try:
  1301. self.d.setVar("BB_NO_NETWORK", network)
  1302. if verify_donestamp(ud, self.d) and not m.need_update(ud, self.d):
  1303. localpath = ud.localpath
  1304. elif m.try_premirror(ud, self.d):
  1305. logger.debug(1, "Trying PREMIRRORS")
  1306. mirrors = mirror_from_string(self.d.getVar('PREMIRRORS', True))
  1307. localpath = try_mirrors(self, self.d, ud, mirrors, False)
  1308. if premirroronly:
  1309. self.d.setVar("BB_NO_NETWORK", "1")
  1310. os.chdir(self.d.getVar("DL_DIR", True))
  1311. firsterr = None
  1312. verified_stamp = verify_donestamp(ud, self.d)
  1313. if not localpath and (not verified_stamp or m.need_update(ud, self.d)):
  1314. try:
  1315. if not trusted_network(self.d, ud.url):
  1316. raise UntrustedUrl(ud.url)
  1317. logger.debug(1, "Trying Upstream")
  1318. m.download(ud, self.d)
  1319. if hasattr(m, "build_mirror_data"):
  1320. m.build_mirror_data(ud, self.d)
  1321. localpath = ud.localpath
  1322. # early checksum verify, so that if checksum mismatched,
  1323. # fetcher still have chance to fetch from mirror
  1324. update_stamp(ud, self.d)
  1325. except bb.fetch2.NetworkAccess:
  1326. raise
  1327. except BBFetchException as e:
  1328. if isinstance(e, ChecksumError):
  1329. logger.warning("Checksum failure encountered with download of %s - will attempt other sources if available" % u)
  1330. logger.debug(1, str(e))
  1331. if os.path.exists(ud.localpath):
  1332. rename_bad_checksum(ud, e.checksum)
  1333. elif isinstance(e, NoChecksumError):
  1334. raise
  1335. else:
  1336. logger.warning('Failed to fetch URL %s, attempting MIRRORS if available' % u)
  1337. logger.debug(1, str(e))
  1338. firsterr = e
  1339. # Remove any incomplete fetch
  1340. if not verified_stamp:
  1341. m.clean(ud, self.d)
  1342. logger.debug(1, "Trying MIRRORS")
  1343. mirrors = mirror_from_string(self.d.getVar('MIRRORS', True))
  1344. localpath = try_mirrors(self, self.d, ud, mirrors)
  1345. if not localpath or ((not os.path.exists(localpath)) and localpath.find("*") == -1):
  1346. if firsterr:
  1347. logger.error(str(firsterr))
  1348. raise FetchError("Unable to fetch URL from any source.", u)
  1349. update_stamp(ud, self.d)
  1350. except BBFetchException as e:
  1351. if isinstance(e, ChecksumError):
  1352. logger.error("Checksum failure fetching %s" % u)
  1353. raise
  1354. finally:
  1355. if ud.lockfile:
  1356. bb.utils.unlockfile(lf)
  1357. def checkstatus(self, urls=None):
  1358. """
  1359. Check all urls exist upstream
  1360. """
  1361. if not urls:
  1362. urls = self.urls
  1363. for u in urls:
  1364. ud = self.ud[u]
  1365. ud.setup_localpath(self.d)
  1366. m = ud.method
  1367. logger.debug(1, "Testing URL %s", u)
  1368. # First try checking uri, u, from PREMIRRORS
  1369. mirrors = mirror_from_string(self.d.getVar('PREMIRRORS', True))
  1370. ret = try_mirrors(self, self.d, ud, mirrors, True)
  1371. if not ret:
  1372. # Next try checking from the original uri, u
  1373. try:
  1374. ret = m.checkstatus(self, ud, self.d)
  1375. except:
  1376. # Finally, try checking uri, u, from MIRRORS
  1377. mirrors = mirror_from_string(self.d.getVar('MIRRORS', True))
  1378. ret = try_mirrors(self, self.d, ud, mirrors, True)
  1379. if not ret:
  1380. raise FetchError("URL %s doesn't work" % u, u)
  1381. def unpack(self, root, urls=None):
  1382. """
  1383. Check all urls exist upstream
  1384. """
  1385. if not urls:
  1386. urls = self.urls
  1387. for u in urls:
  1388. ud = self.ud[u]
  1389. ud.setup_localpath(self.d)
  1390. if ud.lockfile:
  1391. lf = bb.utils.lockfile(ud.lockfile)
  1392. ud.method.unpack(ud, root, self.d)
  1393. if ud.lockfile:
  1394. bb.utils.unlockfile(lf)
  1395. def clean(self, urls=None):
  1396. """
  1397. Clean files that the fetcher gets or places
  1398. """
  1399. if not urls:
  1400. urls = self.urls
  1401. for url in urls:
  1402. if url not in self.ud:
  1403. self.ud[url] = FetchData(url, d)
  1404. ud = self.ud[url]
  1405. ud.setup_localpath(self.d)
  1406. if not ud.localfile and ud.localpath is None:
  1407. continue
  1408. if ud.lockfile:
  1409. lf = bb.utils.lockfile(ud.lockfile)
  1410. ud.method.clean(ud, self.d)
  1411. if ud.donestamp:
  1412. bb.utils.remove(ud.donestamp)
  1413. if ud.lockfile:
  1414. bb.utils.unlockfile(lf)
  1415. class FetchConnectionCache(object):
  1416. """
  1417. A class which represents an container for socket connections.
  1418. """
  1419. def __init__(self):
  1420. self.cache = {}
  1421. def get_connection_name(self, host, port):
  1422. return host + ':' + str(port)
  1423. def add_connection(self, host, port, connection):
  1424. cn = self.get_connection_name(host, port)
  1425. if cn not in self.cache:
  1426. self.cache[cn] = connection
  1427. def get_connection(self, host, port):
  1428. connection = None
  1429. cn = self.get_connection_name(host, port)
  1430. if cn in self.cache:
  1431. connection = self.cache[cn]
  1432. return connection
  1433. def remove_connection(self, host, port):
  1434. cn = self.get_connection_name(host, port)
  1435. if cn in self.cache:
  1436. self.cache[cn].close()
  1437. del self.cache[cn]
  1438. def close_connections(self):
  1439. for cn in list(self.cache.keys()):
  1440. self.cache[cn].close()
  1441. del self.cache[cn]
  1442. from . import cvs
  1443. from . import git
  1444. from . import gitsm
  1445. from . import gitannex
  1446. from . import local
  1447. from . import svn
  1448. from . import wget
  1449. from . import ssh
  1450. from . import sftp
  1451. from . import perforce
  1452. from . import bzr
  1453. from . import hg
  1454. from . import osc
  1455. from . import repo
  1456. from . import clearcase
  1457. from . import npm
  1458. methods.append(local.Local())
  1459. methods.append(wget.Wget())
  1460. methods.append(svn.Svn())
  1461. methods.append(git.Git())
  1462. methods.append(gitsm.GitSM())
  1463. methods.append(gitannex.GitANNEX())
  1464. methods.append(cvs.Cvs())
  1465. methods.append(ssh.SSH())
  1466. methods.append(sftp.SFTP())
  1467. methods.append(perforce.Perforce())
  1468. methods.append(bzr.Bzr())
  1469. methods.append(hg.Hg())
  1470. methods.append(osc.Osc())
  1471. methods.append(repo.Repo())
  1472. methods.append(clearcase.ClearCase())
  1473. methods.append(npm.Npm())