blob: 5dfe5ff36036bf8b1afc90b6c9ecfb19ba1f48fd [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001"""
2BitBake 'Fetch' implementations
3
4Classes for obtaining upstream sources for the
5BitBake build tools.
6"""
7
8# Copyright (C) 2003, 2004 Chris Larson
9# Copyright (C) 2012 Intel Corporation
10#
Brad Bishopc342db32019-05-15 21:57:59 -040011# SPDX-License-Identifier: GPL-2.0-only
Patrick Williamsc124f4f2015-09-15 14:41:29 -050012#
13# Based on functions from the base bb module, Copyright 2003 Holger Schurig
14
Patrick Williamsc124f4f2015-09-15 14:41:29 -050015import os, re
16import signal
Patrick Williamsc124f4f2015-09-15 14:41:29 -050017import logging
Patrick Williamsc0f7c042017-02-23 20:41:17 -060018import urllib.request, urllib.parse, urllib.error
19if 'git' not in urllib.parse.uses_netloc:
20 urllib.parse.uses_netloc.append('git')
21import operator
22import collections
23import subprocess
24import pickle
Brad Bishop6e60e8b2018-02-01 10:27:11 -050025import errno
Patrick Williamsc124f4f2015-09-15 14:41:29 -050026import bb.persist_data, bb.utils
27import bb.checksum
Patrick Williamsc124f4f2015-09-15 14:41:29 -050028import bb.process
Brad Bishopd7bf8c12018-02-25 22:55:05 -050029import bb.event
Patrick Williamsc124f4f2015-09-15 14:41:29 -050030
31__version__ = "2"
32_checksum_cache = bb.checksum.FileChecksumCache()
33
34logger = logging.getLogger("BitBake.Fetcher")
35
Andrew Geissler82c905d2020-04-13 13:39:40 -050036CHECKSUM_LIST = [ "md5", "sha256", "sha1", "sha384", "sha512" ]
37SHOWN_CHECKSUM_LIST = ["sha256"]
38
Patrick Williamsc124f4f2015-09-15 14:41:29 -050039class BBFetchException(Exception):
40 """Class all fetch exceptions inherit from"""
41 def __init__(self, message):
Brad Bishopd7bf8c12018-02-25 22:55:05 -050042 self.msg = message
43 Exception.__init__(self, message)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050044
45 def __str__(self):
Brad Bishopd7bf8c12018-02-25 22:55:05 -050046 return self.msg
Patrick Williamsc124f4f2015-09-15 14:41:29 -050047
48class UntrustedUrl(BBFetchException):
49 """Exception raised when encountering a host not listed in BB_ALLOWED_NETWORKS"""
50 def __init__(self, url, message=''):
51 if message:
52 msg = message
53 else:
54 msg = "The URL: '%s' is not trusted and cannot be used" % url
55 self.url = url
56 BBFetchException.__init__(self, msg)
57 self.args = (url,)
58
59class MalformedUrl(BBFetchException):
60 """Exception raised when encountering an invalid url"""
61 def __init__(self, url, message=''):
Brad Bishopd7bf8c12018-02-25 22:55:05 -050062 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,)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050069
70class FetchError(BBFetchException):
71 """General fetcher exception when something happens incorrectly"""
72 def __init__(self, message, url = None):
Brad Bishopd7bf8c12018-02-25 22:55:05 -050073 if url:
Patrick Williamsc124f4f2015-09-15 14:41:29 -050074 msg = "Fetcher failure for URL: '%s'. %s" % (url, message)
Brad Bishopd7bf8c12018-02-25 22:55:05 -050075 else:
Patrick Williamsc124f4f2015-09-15 14:41:29 -050076 msg = "Fetcher failure: %s" % message
Brad Bishopd7bf8c12018-02-25 22:55:05 -050077 self.url = url
78 BBFetchException.__init__(self, msg)
79 self.args = (message, url)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050080
81class ChecksumError(FetchError):
82 """Exception when mismatched checksum encountered"""
83 def __init__(self, message, url = None, checksum = None):
84 self.checksum = checksum
85 FetchError.__init__(self, message, url)
86
87class NoChecksumError(FetchError):
88 """Exception when no checksum is specified, but BB_STRICT_CHECKSUM is set"""
89
90class UnpackError(BBFetchException):
91 """General fetcher exception when something happens incorrectly when unpacking"""
92 def __init__(self, message, url):
Brad Bishopd7bf8c12018-02-25 22:55:05 -050093 msg = "Unpack failure for URL: '%s'. %s" % (url, message)
94 self.url = url
95 BBFetchException.__init__(self, msg)
96 self.args = (message, url)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050097
98class NoMethodError(BBFetchException):
99 """Exception raised when there is no method to obtain a supplied url or set of urls"""
100 def __init__(self, url):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500101 msg = "Could not find a fetcher which supports the URL: '%s'" % url
102 self.url = url
103 BBFetchException.__init__(self, msg)
104 self.args = (url,)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500105
106class MissingParameterError(BBFetchException):
107 """Exception raised when a fetch method is missing a critical parameter in the url"""
108 def __init__(self, missing, url):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500109 msg = "URL: '%s' is missing the required parameter '%s'" % (url, missing)
110 self.url = url
111 self.missing = missing
112 BBFetchException.__init__(self, msg)
113 self.args = (missing, url)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500114
115class ParameterError(BBFetchException):
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000116 """Exception raised when a url cannot be processed due to invalid parameters."""
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500117 def __init__(self, message, url):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500118 msg = "URL: '%s' has invalid parameters. %s" % (url, message)
119 self.url = url
120 BBFetchException.__init__(self, msg)
121 self.args = (message, url)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500122
123class NetworkAccess(BBFetchException):
124 """Exception raised when network access is disabled but it is required."""
125 def __init__(self, url, cmd):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500126 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)
127 self.url = url
128 self.cmd = cmd
129 BBFetchException.__init__(self, msg)
130 self.args = (url, cmd)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500131
132class NonLocalMethod(Exception):
133 def __init__(self):
134 Exception.__init__(self)
135
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500136class MissingChecksumEvent(bb.event.Event):
Andrew Geissler82c905d2020-04-13 13:39:40 -0500137 def __init__(self, url, **checksums):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500138 self.url = url
Andrew Geissler82c905d2020-04-13 13:39:40 -0500139 self.checksums = checksums
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500140 bb.event.Event.__init__(self)
141
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500142
143class URI(object):
144 """
145 A class representing a generic URI, with methods for
146 accessing the URI components, and stringifies to the
147 URI.
148
149 It is constructed by calling it with a URI, or setting
150 the attributes manually:
151
152 uri = URI("http://example.com/")
153
154 uri = URI()
155 uri.scheme = 'http'
156 uri.hostname = 'example.com'
157 uri.path = '/'
158
159 It has the following attributes:
160
161 * scheme (read/write)
162 * userinfo (authentication information) (read/write)
163 * username (read/write)
164 * password (read/write)
165
166 Note, password is deprecated as of RFC 3986.
167
168 * hostname (read/write)
169 * port (read/write)
170 * hostport (read only)
171 "hostname:port", if both are set, otherwise just "hostname"
172 * path (read/write)
173 * path_quoted (read/write)
174 A URI quoted version of path
175 * params (dict) (read/write)
176 * query (dict) (read/write)
177 * relative (bool) (read only)
178 True if this is a "relative URI", (e.g. file:foo.diff)
179
180 It stringifies to the URI itself.
181
182 Some notes about relative URIs: while it's specified that
183 a URI beginning with <scheme>:// should either be directly
184 followed by a hostname or a /, the old URI handling of the
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000185 fetch2 library did not conform to this. Therefore, this URI
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500186 class has some kludges to make sure that URIs are parsed in
187 a way comforming to bitbake's current usage. This URI class
188 supports the following:
189
190 file:relative/path.diff (IETF compliant)
191 git:relative/path.git (IETF compliant)
192 git:///absolute/path.git (IETF compliant)
193 file:///absolute/path.diff (IETF compliant)
194
195 file://relative/path.diff (not IETF compliant)
196
197 But it does not support the following:
198
199 file://hostname/absolute/path.diff (would be IETF compliant)
200
201 Note that the last case only applies to a list of
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000202 explicitly allowed schemes (currently only file://), that requires
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500203 its URIs to not have a network location.
204 """
205
206 _relative_schemes = ['file', 'git']
207 _netloc_forbidden = ['file']
208
209 def __init__(self, uri=None):
210 self.scheme = ''
211 self.userinfo = ''
212 self.hostname = ''
213 self.port = None
214 self._path = ''
215 self.params = {}
216 self.query = {}
217 self.relative = False
218
219 if not uri:
220 return
221
222 # We hijack the URL parameters, since the way bitbake uses
223 # them are not quite RFC compliant.
224 uri, param_str = (uri.split(";", 1) + [None])[:2]
225
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600226 urlp = urllib.parse.urlparse(uri)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500227 self.scheme = urlp.scheme
228
229 reparse = 0
230
231 # Coerce urlparse to make URI scheme use netloc
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600232 if not self.scheme in urllib.parse.uses_netloc:
233 urllib.parse.uses_params.append(self.scheme)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500234 reparse = 1
235
236 # Make urlparse happy(/ier) by converting local resources
237 # to RFC compliant URL format. E.g.:
238 # file://foo.diff -> file:foo.diff
239 if urlp.scheme in self._netloc_forbidden:
240 uri = re.sub("(?<=:)//(?!/)", "", uri, 1)
241 reparse = 1
242
243 if reparse:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600244 urlp = urllib.parse.urlparse(uri)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500245
246 # Identify if the URI is relative or not
247 if urlp.scheme in self._relative_schemes and \
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800248 re.compile(r"^\w+:(?!//)").match(uri):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500249 self.relative = True
250
251 if not self.relative:
252 self.hostname = urlp.hostname or ''
253 self.port = urlp.port
254
255 self.userinfo += urlp.username or ''
256
257 if urlp.password:
258 self.userinfo += ':%s' % urlp.password
259
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600260 self.path = urllib.parse.unquote(urlp.path)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500261
262 if param_str:
263 self.params = self._param_str_split(param_str, ";")
264 if urlp.query:
265 self.query = self._param_str_split(urlp.query, "&")
266
267 def __str__(self):
268 userinfo = self.userinfo
269 if userinfo:
270 userinfo += '@'
271
272 return "%s:%s%s%s%s%s%s" % (
273 self.scheme,
274 '' if self.relative else '//',
275 userinfo,
276 self.hostport,
277 self.path_quoted,
278 self._query_str(),
279 self._param_str())
280
281 def _param_str(self):
282 return (
283 ''.join([';', self._param_str_join(self.params, ";")])
284 if self.params else '')
285
286 def _query_str(self):
287 return (
288 ''.join(['?', self._param_str_join(self.query, "&")])
289 if self.query else '')
290
291 def _param_str_split(self, string, elmdelim, kvdelim="="):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600292 ret = collections.OrderedDict()
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600293 for k, v in [x.split(kvdelim, 1) for x in string.split(elmdelim) if x]:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500294 ret[k] = v
295 return ret
296
297 def _param_str_join(self, dict_, elmdelim, kvdelim="="):
298 return elmdelim.join([kvdelim.join([k, v]) for k, v in dict_.items()])
299
300 @property
301 def hostport(self):
302 if not self.port:
303 return self.hostname
304 return "%s:%d" % (self.hostname, self.port)
305
306 @property
307 def path_quoted(self):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600308 return urllib.parse.quote(self.path)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500309
310 @path_quoted.setter
311 def path_quoted(self, path):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600312 self.path = urllib.parse.unquote(path)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500313
314 @property
315 def path(self):
316 return self._path
317
318 @path.setter
319 def path(self, path):
320 self._path = path
321
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500322 if not path or re.compile("^/").match(path):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500323 self.relative = False
324 else:
325 self.relative = True
326
327 @property
328 def username(self):
329 if self.userinfo:
330 return (self.userinfo.split(":", 1))[0]
331 return ''
332
333 @username.setter
334 def username(self, username):
335 password = self.password
336 self.userinfo = username
337 if password:
338 self.userinfo += ":%s" % password
339
340 @property
341 def password(self):
342 if self.userinfo and ":" in self.userinfo:
343 return (self.userinfo.split(":", 1))[1]
344 return ''
345
346 @password.setter
347 def password(self, password):
348 self.userinfo = "%s:%s" % (self.username, password)
349
350def decodeurl(url):
351 """Decodes an URL into the tokens (scheme, network location, path,
352 user, password, parameters).
353 """
354
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500355 m = re.compile('(?P<type>[^:]*)://((?P<user>[^/;]+)@)?(?P<location>[^;]+)(;(?P<parm>.*))?').match(url)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500356 if not m:
357 raise MalformedUrl(url)
358
359 type = m.group('type')
360 location = m.group('location')
361 if not location:
362 raise MalformedUrl(url)
363 user = m.group('user')
364 parm = m.group('parm')
365
366 locidx = location.find('/')
367 if locidx != -1 and type.lower() != 'file':
368 host = location[:locidx]
369 path = location[locidx:]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500370 elif type.lower() == 'file':
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500371 host = ""
372 path = location
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500373 else:
374 host = location
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800375 path = "/"
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500376 if user:
377 m = re.compile('(?P<user>[^:]+)(:?(?P<pswd>.*))').match(user)
378 if m:
379 user = m.group('user')
380 pswd = m.group('pswd')
381 else:
382 user = ''
383 pswd = ''
384
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600385 p = collections.OrderedDict()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500386 if parm:
387 for s in parm.split(';'):
388 if s:
389 if not '=' in s:
390 raise MalformedUrl(url, "The URL: '%s' is invalid: parameter %s does not specify a value (missing '=')" % (url, s))
391 s1, s2 = s.split('=')
392 p[s1] = s2
393
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600394 return type, host, urllib.parse.unquote(path), user, pswd, p
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500395
396def encodeurl(decoded):
397 """Encodes a URL from tokens (scheme, network location, path,
398 user, password, parameters).
399 """
400
401 type, host, path, user, pswd, p = decoded
402
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500403 if not type:
404 raise MissingParameterError('type', "encoded from the data %s" % str(decoded))
Andrew Geissler595f6302022-01-24 19:11:47 +0000405 url = ['%s://' % type]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500406 if user and type != "file":
Andrew Geissler595f6302022-01-24 19:11:47 +0000407 url.append("%s" % user)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500408 if pswd:
Andrew Geissler595f6302022-01-24 19:11:47 +0000409 url.append(":%s" % pswd)
410 url.append("@")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500411 if host and type != "file":
Andrew Geissler595f6302022-01-24 19:11:47 +0000412 url.append("%s" % host)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500413 if path:
414 # Standardise path to ensure comparisons work
415 while '//' in path:
416 path = path.replace("//", "/")
Andrew Geissler595f6302022-01-24 19:11:47 +0000417 url.append("%s" % urllib.parse.quote(path))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500418 if p:
419 for parm in p:
Andrew Geissler595f6302022-01-24 19:11:47 +0000420 url.append(";%s=%s" % (parm, p[parm]))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500421
Andrew Geissler595f6302022-01-24 19:11:47 +0000422 return "".join(url)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500423
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500424def uri_replace(ud, uri_find, uri_replace, replacements, d, mirrortarball=None):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500425 if not ud.url or not uri_find or not uri_replace:
426 logger.error("uri_replace: passed an undefined value, not replacing")
427 return None
428 uri_decoded = list(decodeurl(ud.url))
429 uri_find_decoded = list(decodeurl(uri_find))
430 uri_replace_decoded = list(decodeurl(uri_replace))
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600431 logger.debug2("For url %s comparing %s to %s" % (uri_decoded, uri_find_decoded, uri_replace_decoded))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500432 result_decoded = ['', '', '', '', '', {}]
Andrew Geissler595f6302022-01-24 19:11:47 +0000433 # 0 - type, 1 - host, 2 - path, 3 - user, 4- pswd, 5 - params
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500434 for loc, i in enumerate(uri_find_decoded):
435 result_decoded[loc] = uri_decoded[loc]
436 regexp = i
437 if loc == 0 and regexp and not regexp.endswith("$"):
438 # Leaving the type unanchored can mean "https" matching "file" can become "files"
439 # which is clearly undesirable.
440 regexp += "$"
441 if loc == 5:
442 # Handle URL parameters
443 if i:
444 # Any specified URL parameters must match
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800445 for k in uri_find_decoded[loc]:
446 if uri_decoded[loc][k] != uri_find_decoded[loc][k]:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500447 return None
448 # Overwrite any specified replacement parameters
449 for k in uri_replace_decoded[loc]:
450 for l in replacements:
451 uri_replace_decoded[loc][k] = uri_replace_decoded[loc][k].replace(l, replacements[l])
452 result_decoded[loc][k] = uri_replace_decoded[loc][k]
Andrew Geissler595f6302022-01-24 19:11:47 +0000453 elif (loc == 3 or loc == 4) and uri_replace_decoded[loc]:
454 # User/password in the replacement is just a straight replacement
455 result_decoded[loc] = uri_replace_decoded[loc]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500456 elif (re.match(regexp, uri_decoded[loc])):
457 if not uri_replace_decoded[loc]:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500458 result_decoded[loc] = ""
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500459 else:
460 for k in replacements:
461 uri_replace_decoded[loc] = uri_replace_decoded[loc].replace(k, replacements[k])
462 #bb.note("%s %s %s" % (regexp, uri_replace_decoded[loc], uri_decoded[loc]))
Patrick Williamsd7e96312015-09-22 08:09:05 -0500463 result_decoded[loc] = re.sub(regexp, uri_replace_decoded[loc], uri_decoded[loc], 1)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500464 if loc == 2:
465 # Handle path manipulations
466 basename = None
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500467 if uri_decoded[0] != uri_replace_decoded[0] and mirrortarball:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500468 # If the source and destination url types differ, must be a mirrortarball mapping
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500469 basename = os.path.basename(mirrortarball)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500470 # Kill parameters, they make no sense for mirror tarballs
471 uri_decoded[5] = {}
472 elif ud.localpath and ud.method.supports_checksum(ud):
Andrew Geissler595f6302022-01-24 19:11:47 +0000473 basename = os.path.basename(ud.localpath)
474 if basename:
475 uri_basename = os.path.basename(uri_decoded[loc])
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000476 # Prefix with a slash as a sentinel in case
477 # result_decoded[loc] does not contain one.
478 path = "/" + result_decoded[loc]
479 if uri_basename and basename != uri_basename and path.endswith("/" + uri_basename):
480 result_decoded[loc] = path[1:-len(uri_basename)] + basename
481 elif not path.endswith("/" + basename):
482 result_decoded[loc] = os.path.join(path[1:], basename)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500483 else:
484 return None
485 result = encodeurl(result_decoded)
486 if result == ud.url:
487 return None
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600488 logger.debug2("For url %s returning %s" % (ud.url, result))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500489 return result
490
491methods = []
492urldata_cache = {}
493saved_headrevs = {}
494
495def fetcher_init(d):
496 """
497 Called to initialize the fetchers once the configuration data is known.
498 Calls before this must not hit the cache.
499 """
Andrew Geissler82c905d2020-04-13 13:39:40 -0500500
501 revs = bb.persist_data.persist('BB_URI_HEADREVS', d)
502 try:
503 # fetcher_init is called multiple times, so make sure we only save the
504 # revs the first time it is called.
505 if not bb.fetch2.saved_headrevs:
506 bb.fetch2.saved_headrevs = dict(revs)
507 except:
508 pass
509
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500510 # When to drop SCM head revisions controlled by user policy
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500511 srcrev_policy = d.getVar('BB_SRCREV_POLICY') or "clear"
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500512 if srcrev_policy == "cache":
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600513 logger.debug("Keeping SRCREV cache due to cache policy of: %s", srcrev_policy)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500514 elif srcrev_policy == "clear":
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600515 logger.debug("Clearing SRCREV cache due to cache policy of: %s", srcrev_policy)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500516 revs.clear()
517 else:
518 raise FetchError("Invalid SRCREV cache policy of: %s" % srcrev_policy)
519
520 _checksum_cache.init_cache(d)
521
522 for m in methods:
523 if hasattr(m, "init"):
524 m.init(d)
525
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500526def fetcher_parse_save():
527 _checksum_cache.save_extras()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500528
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500529def fetcher_parse_done():
530 _checksum_cache.save_merge()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500531
Brad Bishop19323692019-04-05 15:28:33 -0400532def fetcher_compare_revisions(d):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500533 """
Andrew Geissler82c905d2020-04-13 13:39:40 -0500534 Compare the revisions in the persistent cache with the saved values from
535 when bitbake was started and return true if they have changed.
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500536 """
537
Andrew Geissler82c905d2020-04-13 13:39:40 -0500538 headrevs = dict(bb.persist_data.persist('BB_URI_HEADREVS', d))
539 return headrevs != bb.fetch2.saved_headrevs
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500540
541def mirror_from_string(data):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500542 mirrors = (data or "").replace('\\n',' ').split()
543 # Split into pairs
544 if len(mirrors) % 2 != 0:
545 bb.warn('Invalid mirror data %s, should have paired members.' % data)
546 return list(zip(*[iter(mirrors)]*2))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500547
548def verify_checksum(ud, d, precomputed={}):
549 """
550 verify the MD5 and SHA256 checksum for downloaded src
551
552 Raises a FetchError if one or both of the SRC_URI checksums do not match
553 the downloaded file, or if BB_STRICT_CHECKSUM is set and there are no
554 checksums specified.
555
556 Returns a dict of checksums that can be stored in a done stamp file and
557 passed in as precomputed parameter in a later call to avoid re-computing
558 the checksums from the file. This allows verifying the checksums of the
559 file against those in the recipe each time, rather than only after
560 downloading. See https://bugzilla.yoctoproject.org/show_bug.cgi?id=5571.
561 """
562
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500563 if ud.ignore_checksums or not ud.method.supports_checksum(ud):
564 return {}
565
Andrew Geissler82c905d2020-04-13 13:39:40 -0500566 def compute_checksum_info(checksum_id):
567 checksum_name = getattr(ud, "%s_name" % checksum_id)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500568
Andrew Geissler82c905d2020-04-13 13:39:40 -0500569 if checksum_id in precomputed:
570 checksum_data = precomputed[checksum_id]
571 else:
572 checksum_data = getattr(bb.utils, "%s_file" % checksum_id)(ud.localpath)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500573
Andrew Geissler82c905d2020-04-13 13:39:40 -0500574 checksum_expected = getattr(ud, "%s_expected" % checksum_id)
575
Andrew Geissler09036742021-06-25 14:25:14 -0500576 if checksum_expected == '':
577 checksum_expected = None
578
Andrew Geissler82c905d2020-04-13 13:39:40 -0500579 return {
580 "id": checksum_id,
581 "name": checksum_name,
582 "data": checksum_data,
583 "expected": checksum_expected
584 }
585
586 checksum_infos = []
587 for checksum_id in CHECKSUM_LIST:
588 checksum_infos.append(compute_checksum_info(checksum_id))
589
590 checksum_dict = {ci["id"] : ci["data"] for ci in checksum_infos}
591 checksum_event = {"%ssum" % ci["id"] : ci["data"] for ci in checksum_infos}
592
593 for ci in checksum_infos:
594 if ci["id"] in SHOWN_CHECKSUM_LIST:
595 checksum_lines = ["SRC_URI[%s] = \"%s\"" % (ci["name"], ci["data"])]
596
597 # If no checksum has been provided
598 if ud.method.recommends_checksum(ud) and all(ci["expected"] is None for ci in checksum_infos):
599 messages = []
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500600 strict = d.getVar("BB_STRICT_CHECKSUM") or "0"
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500601
Andrew Geissler82c905d2020-04-13 13:39:40 -0500602 # If strict checking enabled and neither sum defined, raise error
603 if strict == "1":
604 messages.append("No checksum specified for '%s', please add at " \
605 "least one to the recipe:" % ud.localpath)
606 messages.extend(checksum_lines)
607 logger.error("\n".join(messages))
608 raise NoChecksumError("Missing SRC_URI checksum", ud.url)
609
610 bb.event.fire(MissingChecksumEvent(ud.url, **checksum_event), d)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500611
612 if strict == "ignore":
Andrew Geissler82c905d2020-04-13 13:39:40 -0500613 return checksum_dict
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500614
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500615 # Log missing sums so user can more easily add them
Andrew Geissler82c905d2020-04-13 13:39:40 -0500616 messages.append("Missing checksum for '%s', consider adding at " \
617 "least one to the recipe:" % ud.localpath)
618 messages.extend(checksum_lines)
619 logger.warning("\n".join(messages))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500620
621 # We want to alert the user if a checksum is defined in the recipe but
622 # it does not match.
Andrew Geissler82c905d2020-04-13 13:39:40 -0500623 messages = []
624 messages.append("Checksum mismatch!")
625 bad_checksum = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500626
Andrew Geissler82c905d2020-04-13 13:39:40 -0500627 for ci in checksum_infos:
628 if ci["expected"] and ci["expected"] != ci["data"]:
Andrew Geissler09036742021-06-25 14:25:14 -0500629 messages.append("File: '%s' has %s checksum '%s' when '%s' was " \
Andrew Geissler82c905d2020-04-13 13:39:40 -0500630 "expected" % (ud.localpath, ci["id"], ci["data"], ci["expected"]))
631 bad_checksum = ci["data"]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500632
Andrew Geissler82c905d2020-04-13 13:39:40 -0500633 if bad_checksum:
634 messages.append("If this change is expected (e.g. you have upgraded " \
635 "to a new version without updating the checksums) " \
636 "then you can use these lines within the recipe:")
637 messages.extend(checksum_lines)
638 messages.append("Otherwise you should retry the download and/or " \
639 "check with upstream to determine if the file has " \
640 "become corrupted or otherwise unexpectedly modified.")
641 raise ChecksumError("\n".join(messages), ud.url, bad_checksum)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500642
Andrew Geissler82c905d2020-04-13 13:39:40 -0500643 return checksum_dict
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500644
645def verify_donestamp(ud, d, origud=None):
646 """
647 Check whether the done stamp file has the right checksums (if the fetch
648 method supports them). If it doesn't, delete the done stamp and force
649 a re-download.
650
651 Returns True, if the donestamp exists and is valid, False otherwise. When
652 returning False, any existing done stamps are removed.
653 """
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500654 if not ud.needdonestamp or (origud and not origud.needdonestamp):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500655 return True
656
Brad Bishop316dfdd2018-06-25 12:45:53 -0400657 if not os.path.exists(ud.localpath):
658 # local path does not exist
659 if os.path.exists(ud.donestamp):
660 # done stamp exists, but the downloaded file does not; the done stamp
661 # must be incorrect, re-trigger the download
662 bb.utils.remove(ud.donestamp)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500663 return False
664
665 if (not ud.method.supports_checksum(ud) or
666 (origud and not origud.method.supports_checksum(origud))):
Brad Bishop316dfdd2018-06-25 12:45:53 -0400667 # if done stamp exists and checksums not supported; assume the local
668 # file is current
669 return os.path.exists(ud.donestamp)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500670
671 precomputed_checksums = {}
672 # Only re-use the precomputed checksums if the donestamp is newer than the
673 # file. Do not rely on the mtime of directories, though. If ud.localpath is
674 # a directory, there will probably not be any checksums anyway.
Brad Bishop316dfdd2018-06-25 12:45:53 -0400675 if os.path.exists(ud.donestamp) and (os.path.isdir(ud.localpath) or
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500676 os.path.getmtime(ud.localpath) < os.path.getmtime(ud.donestamp)):
677 try:
678 with open(ud.donestamp, "rb") as cachefile:
679 pickled = pickle.Unpickler(cachefile)
680 precomputed_checksums.update(pickled.load())
681 except Exception as e:
682 # Avoid the warnings on the upgrade path from emtpy done stamp
683 # files to those containing the checksums.
684 if not isinstance(e, EOFError):
685 # Ignore errors, they aren't fatal
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600686 logger.warning("Couldn't load checksums from donestamp %s: %s "
687 "(msg: %s)" % (ud.donestamp, type(e).__name__,
688 str(e)))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500689
690 try:
691 checksums = verify_checksum(ud, d, precomputed_checksums)
692 # If the cache file did not have the checksums, compute and store them
693 # as an upgrade path from the previous done stamp file format.
694 if checksums != precomputed_checksums:
695 with open(ud.donestamp, "wb") as cachefile:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600696 p = pickle.Pickler(cachefile, 2)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500697 p.dump(checksums)
698 return True
699 except ChecksumError as e:
700 # Checksums failed to verify, trigger re-download and remove the
701 # incorrect stamp file.
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600702 logger.warning("Checksum mismatch for local file %s\n"
703 "Cleaning and trying again." % ud.localpath)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500704 if os.path.exists(ud.localpath):
705 rename_bad_checksum(ud, e.checksum)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500706 bb.utils.remove(ud.donestamp)
707 return False
708
709
710def update_stamp(ud, d):
711 """
712 donestamp is file stamp indicating the whole fetching is done
713 this function update the stamp after verifying the checksum
714 """
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500715 if not ud.needdonestamp:
716 return
717
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500718 if os.path.exists(ud.donestamp):
719 # Touch the done stamp file to show active use of the download
720 try:
721 os.utime(ud.donestamp, None)
722 except:
723 # Errors aren't fatal here
724 pass
725 else:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500726 try:
727 checksums = verify_checksum(ud, d)
728 # Store the checksums for later re-verification against the recipe
729 with open(ud.donestamp, "wb") as cachefile:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600730 p = pickle.Pickler(cachefile, 2)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500731 p.dump(checksums)
732 except ChecksumError as e:
733 # Checksums failed to verify, trigger re-download and remove the
734 # incorrect stamp file.
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600735 logger.warning("Checksum mismatch for local file %s\n"
736 "Cleaning and trying again." % ud.localpath)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500737 if os.path.exists(ud.localpath):
738 rename_bad_checksum(ud, e.checksum)
739 bb.utils.remove(ud.donestamp)
740 raise
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500741
742def subprocess_setup():
743 # Python installs a SIGPIPE handler by default. This is usually not what
744 # non-Python subprocesses expect.
745 # SIGPIPE errors are known issues with gzip/bash
746 signal.signal(signal.SIGPIPE, signal.SIG_DFL)
747
748def get_autorev(d):
749 # only not cache src rev in autorev case
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500750 if d.getVar('BB_SRCREV_POLICY') != "cache":
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500751 d.setVar('BB_DONT_CACHE', '1')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500752 return "AUTOINC"
753
754def get_srcrev(d, method_name='sortable_revision'):
755 """
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500756 Return the revision string, usually for use in the version string (PV) of the current package
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500757 Most packages usually only have one SCM so we just pass on the call.
758 In the multi SCM case, we build a value based on SRCREV_FORMAT which must
759 have been set.
760
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500761 The idea here is that we put the string "AUTOINC+" into return value if the revisions are not
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500762 incremental, other code is then responsible for turning that into an increasing value (if needed)
763
764 A method_name can be supplied to retrieve an alternatively formatted revision from a fetcher, if
765 that fetcher provides a method with the given name and the same signature as sortable_revision.
766 """
767
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000768 d.setVar("__BBSEENSRCREV", "1")
Andrew Geissler5199d832021-09-24 16:47:35 -0500769 recursion = d.getVar("__BBINSRCREV")
770 if recursion:
771 raise FetchError("There are recursive references in fetcher variables, likely through SRC_URI")
772 d.setVar("__BBINSRCREV", True)
773
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500774 scms = []
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500775 fetcher = Fetch(d.getVar('SRC_URI').split(), d)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500776 urldata = fetcher.ud
777 for u in urldata:
778 if urldata[u].method.supports_srcrev():
779 scms.append(u)
780
Andrew Geissler595f6302022-01-24 19:11:47 +0000781 if not scms:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500782 raise FetchError("SRCREV was used yet no valid SCM was found in SRC_URI")
783
784 if len(scms) == 1 and len(urldata[scms[0]].names) == 1:
785 autoinc, rev = getattr(urldata[scms[0]].method, method_name)(urldata[scms[0]], d, urldata[scms[0]].names[0])
786 if len(rev) > 10:
787 rev = rev[:10]
Andrew Geissler5199d832021-09-24 16:47:35 -0500788 d.delVar("__BBINSRCREV")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500789 if autoinc:
790 return "AUTOINC+" + rev
791 return rev
792
793 #
794 # Mutiple SCMs are in SRC_URI so we resort to SRCREV_FORMAT
795 #
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500796 format = d.getVar('SRCREV_FORMAT')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500797 if not format:
Brad Bishop19323692019-04-05 15:28:33 -0400798 raise FetchError("The SRCREV_FORMAT variable must be set when multiple SCMs are used.\n"\
799 "The SCMs are:\n%s" % '\n'.join(scms))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500800
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600801 name_to_rev = {}
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500802 seenautoinc = False
803 for scm in scms:
804 ud = urldata[scm]
805 for name in ud.names:
806 autoinc, rev = getattr(ud.method, method_name)(ud, d, name)
807 seenautoinc = seenautoinc or autoinc
808 if len(rev) > 10:
809 rev = rev[:10]
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600810 name_to_rev[name] = rev
811 # Replace names by revisions in the SRCREV_FORMAT string. The approach used
812 # here can handle names being prefixes of other names and names appearing
813 # as substrings in revisions (in which case the name should not be
814 # expanded). The '|' regular expression operator tries matches from left to
815 # right, so we need to sort the names with the longest ones first.
816 names_descending_len = sorted(name_to_rev, key=len, reverse=True)
817 name_to_rev_re = "|".join(re.escape(name) for name in names_descending_len)
818 format = re.sub(name_to_rev_re, lambda match: name_to_rev[match.group(0)], format)
819
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500820 if seenautoinc:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500821 format = "AUTOINC+" + format
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500822
Andrew Geissler5199d832021-09-24 16:47:35 -0500823 d.delVar("__BBINSRCREV")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500824 return format
825
826def localpath(url, d):
827 fetcher = bb.fetch2.Fetch([url], d)
828 return fetcher.localpath(url)
829
Patrick Williams0ca19cc2021-08-16 14:03:13 -0500830# Need to export PATH as binary could be in metadata paths
831# rather than host provided
832# Also include some other variables.
833FETCH_EXPORT_VARS = ['HOME', 'PATH',
834 'HTTP_PROXY', 'http_proxy',
835 'HTTPS_PROXY', 'https_proxy',
836 'FTP_PROXY', 'ftp_proxy',
837 'FTPS_PROXY', 'ftps_proxy',
838 'NO_PROXY', 'no_proxy',
839 'ALL_PROXY', 'all_proxy',
840 'GIT_PROXY_COMMAND',
841 'GIT_SSH',
842 'GIT_SSL_CAINFO',
843 'GIT_SMART_HTTP',
844 'SSH_AUTH_SOCK', 'SSH_AGENT_PID',
845 'SOCKS5_USER', 'SOCKS5_PASSWD',
846 'DBUS_SESSION_BUS_ADDRESS',
847 'P4CONFIG',
848 'SSL_CERT_FILE',
Andrew Geissler5199d832021-09-24 16:47:35 -0500849 'AWS_PROFILE',
Patrick Williams0ca19cc2021-08-16 14:03:13 -0500850 'AWS_ACCESS_KEY_ID',
851 'AWS_SECRET_ACCESS_KEY',
852 'AWS_DEFAULT_REGION']
853
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000854def get_fetcher_environment(d):
855 newenv = {}
856 origenv = d.getVar("BB_ORIGENV")
857 for name in bb.fetch2.FETCH_EXPORT_VARS:
858 value = d.getVar(name)
859 if not value and origenv:
860 value = origenv.getVar(name)
861 if value:
862 newenv[name] = value
863 return newenv
864
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600865def runfetchcmd(cmd, d, quiet=False, cleanup=None, log=None, workdir=None):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500866 """
867 Run cmd returning the command output
868 Raise an error if interrupted or cmd fails
869 Optionally echo command output to stdout
870 Optionally remove the files/directories listed in cleanup upon failure
871 """
872
Patrick Williams0ca19cc2021-08-16 14:03:13 -0500873 exportvars = FETCH_EXPORT_VARS
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500874
875 if not cleanup:
876 cleanup = []
877
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800878 # If PATH contains WORKDIR which contains PV-PR which contains SRCPV we
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500879 # can end up in circular recursion here so give the option of breaking it
880 # in a data store copy.
881 try:
882 d.getVar("PV")
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800883 d.getVar("PR")
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500884 except bb.data_smart.ExpansionError:
885 d = bb.data.createCopy(d)
886 d.setVar("PV", "fetcheravoidrecurse")
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800887 d.setVar("PR", "fetcheravoidrecurse")
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500888
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600889 origenv = d.getVar("BB_ORIGENV", False)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500890 for var in exportvars:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500891 val = d.getVar(var) or (origenv and origenv.getVar(var))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500892 if val:
893 cmd = 'export ' + var + '=\"%s\"; %s' % (val, cmd)
894
Brad Bishop316dfdd2018-06-25 12:45:53 -0400895 # Disable pseudo as it may affect ssh, potentially causing it to hang.
896 cmd = 'export PSEUDO_DISABLED=1; ' + cmd
897
Brad Bishop19323692019-04-05 15:28:33 -0400898 if workdir:
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600899 logger.debug("Running '%s' in %s" % (cmd, workdir))
Brad Bishop19323692019-04-05 15:28:33 -0400900 else:
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600901 logger.debug("Running %s", cmd)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500902
903 success = False
904 error_message = ""
905
906 try:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600907 (output, errors) = bb.process.run(cmd, log=log, shell=True, stderr=subprocess.PIPE, cwd=workdir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500908 success = True
909 except bb.process.NotFoundError as e:
Andrew Geisslereff27472021-10-29 15:35:00 -0500910 error_message = "Fetch command %s not found" % (e.command)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500911 except bb.process.ExecutionError as e:
912 if e.stdout:
913 output = "output:\n%s\n%s" % (e.stdout, e.stderr)
914 elif e.stderr:
915 output = "output:\n%s" % e.stderr
916 else:
917 output = "no output"
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600918 error_message = "Fetch command %s failed with exit code %s, %s" % (e.command, e.exitcode, output)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500919 except bb.process.CmdError as e:
920 error_message = "Fetch command %s could not be run:\n%s" % (e.command, e.msg)
921 if not success:
922 for f in cleanup:
923 try:
924 bb.utils.remove(f, True)
925 except OSError:
926 pass
927
928 raise FetchError(error_message)
929
930 return output
931
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500932def check_network_access(d, info, url):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500933 """
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500934 log remote network access, and error if BB_NO_NETWORK is set or the given
935 URI is untrusted
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500936 """
Brad Bishop19323692019-04-05 15:28:33 -0400937 if bb.utils.to_boolean(d.getVar("BB_NO_NETWORK")):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500938 raise NetworkAccess(url, info)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500939 elif not trusted_network(d, url):
940 raise UntrustedUrl(url, info)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500941 else:
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600942 logger.debug("Fetcher accessed the network with the command %s" % info)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500943
944def build_mirroruris(origud, mirrors, ld):
945 uris = []
946 uds = []
947
948 replacements = {}
949 replacements["TYPE"] = origud.type
950 replacements["HOST"] = origud.host
951 replacements["PATH"] = origud.path
952 replacements["BASENAME"] = origud.path.split("/")[-1]
953 replacements["MIRRORNAME"] = origud.host.replace(':','.') + origud.path.replace('/', '.').replace('*', '.')
954
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500955 def adduri(ud, uris, uds, mirrors, tarballs):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500956 for line in mirrors:
957 try:
958 (find, replace) = line
959 except ValueError:
960 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500961
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500962 for tarball in tarballs:
963 newuri = uri_replace(ud, find, replace, replacements, ld, tarball)
964 if not newuri or newuri in uris or newuri == origud.url:
965 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500966
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500967 if not trusted_network(ld, newuri):
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600968 logger.debug("Mirror %s not in the list of trusted networks, skipping" % (newuri))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500969 continue
Patrick Williamsd7e96312015-09-22 08:09:05 -0500970
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500971 # Create a local copy of the mirrors minus the current line
972 # this will prevent us from recursively processing the same line
973 # as well as indirect recursion A -> B -> C -> A
974 localmirrors = list(mirrors)
975 localmirrors.remove(line)
976
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500977 try:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500978 newud = FetchData(newuri, ld)
979 newud.setup_localpath(ld)
980 except bb.fetch2.BBFetchException as e:
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600981 logger.debug("Mirror fetch failure for url %s (original url: %s)" % (newuri, origud.url))
982 logger.debug(str(e))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500983 try:
984 # setup_localpath of file:// urls may fail, we should still see
985 # if mirrors of the url exist
986 adduri(newud, uris, uds, localmirrors, tarballs)
987 except UnboundLocalError:
988 pass
989 continue
990 uris.append(newuri)
991 uds.append(newud)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500992
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500993 adduri(newud, uris, uds, localmirrors, tarballs)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500994
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500995 adduri(origud, uris, uds, mirrors, origud.mirrortarballs or [None])
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500996
997 return uris, uds
998
999def rename_bad_checksum(ud, suffix):
1000 """
1001 Renames files to have suffix from parameter
1002 """
1003
1004 if ud.localpath is None:
1005 return
1006
1007 new_localpath = "%s_bad-checksum_%s" % (ud.localpath, suffix)
1008 bb.warn("Renaming %s to %s" % (ud.localpath, new_localpath))
Brad Bishop79641f22019-09-10 07:20:22 -04001009 if not bb.utils.movefile(ud.localpath, new_localpath):
1010 bb.warn("Renaming %s to %s failed, grep movefile in log.do_fetch to see why" % (ud.localpath, new_localpath))
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001011
1012
1013def try_mirror_url(fetch, origud, ud, ld, check = False):
1014 # Return of None or a value means we're finished
1015 # False means try another url
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05001016
1017 if ud.lockfile and ud.lockfile != origud.lockfile:
1018 lf = bb.utils.lockfile(ud.lockfile)
1019
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001020 try:
1021 if check:
1022 found = ud.method.checkstatus(fetch, ud, ld)
1023 if found:
1024 return found
1025 return False
1026
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001027 if not verify_donestamp(ud, ld, origud) or ud.method.need_update(ud, ld):
1028 ud.method.download(ud, ld)
1029 if hasattr(ud.method,"build_mirror_data"):
1030 ud.method.build_mirror_data(ud, ld)
1031
1032 if not ud.localpath or not os.path.exists(ud.localpath):
1033 return False
1034
1035 if ud.localpath == origud.localpath:
1036 return ud.localpath
1037
1038 # We may be obtaining a mirror tarball which needs further processing by the real fetcher
1039 # If that tarball is a local file:// we need to provide a symlink to it
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001040 dldir = ld.getVar("DL_DIR")
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001041
1042 if origud.mirrortarballs and os.path.basename(ud.localpath) in origud.mirrortarballs and os.path.basename(ud.localpath) != os.path.basename(origud.localpath):
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001043 # Create donestamp in old format to avoid triggering a re-download
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05001044 if ud.donestamp:
1045 bb.utils.mkdirhier(os.path.dirname(ud.donestamp))
1046 open(ud.donestamp, 'w').close()
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001047 dest = os.path.join(dldir, os.path.basename(ud.localpath))
1048 if not os.path.exists(dest):
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001049 # In case this is executing without any file locks held (as is
1050 # the case for file:// URLs), two tasks may end up here at the
1051 # same time, in which case we do not want the second task to
1052 # fail when the link has already been created by the first task.
1053 try:
1054 os.symlink(ud.localpath, dest)
1055 except FileExistsError:
1056 pass
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001057 if not verify_donestamp(origud, ld) or origud.method.need_update(origud, ld):
1058 origud.method.download(origud, ld)
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001059 if hasattr(origud.method, "build_mirror_data"):
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001060 origud.method.build_mirror_data(origud, ld)
Patrick Williamsf1e5d692016-03-30 15:21:19 -05001061 return origud.localpath
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001062 # Otherwise the result is a local file:// and we symlink to it
Andrew Geissler09209ee2020-12-13 08:44:15 -06001063 ensure_symlink(ud.localpath, origud.localpath)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001064 update_stamp(origud, ld)
1065 return ud.localpath
1066
1067 except bb.fetch2.NetworkAccess:
1068 raise
1069
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001070 except IOError as e:
Brad Bishop19323692019-04-05 15:28:33 -04001071 if e.errno in [errno.ESTALE]:
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001072 logger.warning("Stale Error Observed %s." % ud.url)
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001073 return False
1074 raise
1075
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001076 except bb.fetch2.BBFetchException as e:
1077 if isinstance(e, ChecksumError):
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001078 logger.warning("Mirror checksum failure for url %s (original url: %s)\nCleaning and trying again." % (ud.url, origud.url))
1079 logger.warning(str(e))
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05001080 if os.path.exists(ud.localpath):
1081 rename_bad_checksum(ud, e.checksum)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001082 elif isinstance(e, NoChecksumError):
1083 raise
1084 else:
Andrew Geisslerd1e89492021-02-12 15:35:20 -06001085 logger.debug("Mirror fetch failure for url %s (original url: %s)" % (ud.url, origud.url))
1086 logger.debug(str(e))
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001087 try:
1088 ud.method.clean(ud, ld)
1089 except UnboundLocalError:
1090 pass
1091 return False
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05001092 finally:
1093 if ud.lockfile and ud.lockfile != origud.lockfile:
1094 bb.utils.unlockfile(lf)
1095
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001096
Andrew Geissler09209ee2020-12-13 08:44:15 -06001097def ensure_symlink(target, link_name):
Brad Bishop1a4b7ee2018-12-16 17:11:34 -08001098 if not os.path.exists(link_name):
1099 if os.path.islink(link_name):
1100 # Broken symbolic link
1101 os.unlink(link_name)
1102
1103 # In case this is executing without any file locks held (as is
1104 # the case for file:// URLs), two tasks may end up here at the
1105 # same time, in which case we do not want the second task to
1106 # fail when the link has already been created by the first task.
1107 try:
1108 os.symlink(target, link_name)
1109 except FileExistsError:
1110 pass
1111
1112
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001113def try_mirrors(fetch, d, origud, mirrors, check = False):
1114 """
1115 Try to use a mirrored version of the sources.
1116 This method will be automatically called before the fetchers go.
1117
1118 d Is a bb.data instance
1119 uri is the original uri we're trying to download
1120 mirrors is the list of mirrors we're going to try
1121 """
1122 ld = d.createCopy()
1123
1124 uris, uds = build_mirroruris(origud, mirrors, ld)
1125
1126 for index, uri in enumerate(uris):
1127 ret = try_mirror_url(fetch, origud, uds[index], ld, check)
Andrew Geissler82c905d2020-04-13 13:39:40 -05001128 if ret:
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001129 return ret
1130 return None
1131
1132def trusted_network(d, url):
1133 """
1134 Use a trusted url during download if networking is enabled and
1135 BB_ALLOWED_NETWORKS is set globally or for a specific recipe.
1136 Note: modifies SRC_URI & mirrors.
1137 """
Brad Bishop19323692019-04-05 15:28:33 -04001138 if bb.utils.to_boolean(d.getVar("BB_NO_NETWORK")):
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001139 return True
1140
1141 pkgname = d.expand(d.getVar('PN', False))
Brad Bishop1a4b7ee2018-12-16 17:11:34 -08001142 trusted_hosts = None
1143 if pkgname:
1144 trusted_hosts = d.getVarFlag('BB_ALLOWED_NETWORKS', pkgname, False)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001145
1146 if not trusted_hosts:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001147 trusted_hosts = d.getVar('BB_ALLOWED_NETWORKS')
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001148
1149 # Not enabled.
1150 if not trusted_hosts:
1151 return True
1152
1153 scheme, network, path, user, passwd, param = decodeurl(url)
1154
1155 if not network:
1156 return True
1157
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05001158 network = network.split(':')[0]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001159 network = network.lower()
1160
1161 for host in trusted_hosts.split(" "):
1162 host = host.lower()
1163 if host.startswith("*.") and ("." + network).endswith(host[1:]):
1164 return True
1165 if host == network:
1166 return True
1167
1168 return False
1169
1170def srcrev_internal_helper(ud, d, name):
1171 """
1172 Return:
1173 a) a source revision if specified
1174 b) latest revision if SRCREV="AUTOINC"
1175 c) None if not specified
1176 """
1177
1178 srcrev = None
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001179 pn = d.getVar("PN")
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001180 attempts = []
1181 if name != '' and pn:
Patrick Williams213cb262021-08-07 19:21:33 -05001182 attempts.append("SRCREV_%s:pn-%s" % (name, pn))
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001183 if name != '':
1184 attempts.append("SRCREV_%s" % name)
1185 if pn:
Patrick Williams213cb262021-08-07 19:21:33 -05001186 attempts.append("SRCREV:pn-%s" % pn)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001187 attempts.append("SRCREV")
1188
1189 for a in attempts:
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001190 srcrev = d.getVar(a)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001191 if srcrev and srcrev != "INVALID":
1192 break
1193
1194 if 'rev' in ud.parm and 'tag' in ud.parm:
1195 raise FetchError("Please specify a ;rev= parameter or a ;tag= parameter in the url %s but not both." % (ud.url))
1196
1197 if 'rev' in ud.parm or 'tag' in ud.parm:
1198 if 'rev' in ud.parm:
1199 parmrev = ud.parm['rev']
1200 else:
1201 parmrev = ud.parm['tag']
1202 if srcrev == "INVALID" or not srcrev:
1203 return parmrev
1204 if srcrev != parmrev:
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001205 raise FetchError("Conflicting revisions (%s from SRCREV and %s from the url) found, please specify one valid value" % (srcrev, parmrev))
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001206 return parmrev
1207
1208 if srcrev == "INVALID" or not srcrev:
1209 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)
1210 if srcrev == "AUTOINC":
1211 srcrev = ud.method.latest_revision(ud, d, name)
1212
1213 return srcrev
1214
1215def get_checksum_file_list(d):
1216 """ Get a list of files checksum in SRC_URI
1217
1218 Returns the resolved local paths of all local file entries in
1219 SRC_URI as a space-separated string
1220 """
1221 fetch = Fetch([], d, cache = False, localonly = True)
1222
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001223 dl_dir = d.getVar('DL_DIR')
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001224 filelist = []
1225 for u in fetch.urls:
1226 ud = fetch.ud[u]
1227
1228 if ud and isinstance(ud.method, local.Local):
1229 paths = ud.method.localpaths(ud, d)
1230 for f in paths:
1231 pth = ud.decodedurl
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001232 if f.startswith(dl_dir):
1233 # The local fetcher's behaviour is to return a path under DL_DIR if it couldn't find the file anywhere else
1234 if os.path.exists(f):
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001235 bb.warn("Getting checksum for %s SRC_URI entry %s: file not found except in DL_DIR" % (d.getVar('PN'), os.path.basename(f)))
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001236 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001237 bb.warn("Unable to get checksum for %s SRC_URI entry %s: file could not be found" % (d.getVar('PN'), os.path.basename(f)))
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001238 filelist.append(f + ":" + str(os.path.exists(f)))
1239
1240 return " ".join(filelist)
1241
Andrew Geissler82c905d2020-04-13 13:39:40 -05001242def get_file_checksums(filelist, pn, localdirsexclude):
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001243 """Get a list of the checksums for a list of local files
1244
1245 Returns the checksums for a list of local files, caching the results as
1246 it proceeds
1247
1248 """
Andrew Geissler82c905d2020-04-13 13:39:40 -05001249 return _checksum_cache.get_checksums(filelist, pn, localdirsexclude)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001250
1251
1252class FetchData(object):
1253 """
1254 A class which represents the fetcher state for a given URI.
1255 """
1256 def __init__(self, url, d, localonly = False):
1257 # localpath is the location of a downloaded result. If not set, the file is local.
1258 self.donestamp = None
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05001259 self.needdonestamp = True
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001260 self.localfile = ""
1261 self.localpath = None
1262 self.lockfile = None
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001263 self.mirrortarballs = []
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001264 self.basename = None
1265 self.basepath = None
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001266 (self.type, self.host, self.path, self.user, self.pswd, self.parm) = decodeurl(d.expand(url))
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001267 self.date = self.getSRCDate(d)
1268 self.url = url
1269 if not self.user and "user" in self.parm:
1270 self.user = self.parm["user"]
1271 if not self.pswd and "pswd" in self.parm:
1272 self.pswd = self.parm["pswd"]
1273 self.setup = False
1274
Andrew Geissler82c905d2020-04-13 13:39:40 -05001275 def configure_checksum(checksum_id):
1276 if "name" in self.parm:
1277 checksum_name = "%s.%ssum" % (self.parm["name"], checksum_id)
1278 else:
1279 checksum_name = "%ssum" % checksum_id
1280
1281 setattr(self, "%s_name" % checksum_id, checksum_name)
1282
1283 if checksum_name in self.parm:
1284 checksum_expected = self.parm[checksum_name]
Andrew Geissler95ac1b82021-03-31 14:34:31 -05001285 elif self.type not in ["http", "https", "ftp", "ftps", "sftp", "s3", "az"]:
Andrew Geissler82c905d2020-04-13 13:39:40 -05001286 checksum_expected = None
1287 else:
1288 checksum_expected = d.getVarFlag("SRC_URI", checksum_name)
1289
1290 setattr(self, "%s_expected" % checksum_id, checksum_expected)
1291
1292 for checksum_id in CHECKSUM_LIST:
1293 configure_checksum(checksum_id)
1294
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001295 self.ignore_checksums = False
1296
1297 self.names = self.parm.get("name",'default').split(',')
1298
1299 self.method = None
1300 for m in methods:
1301 if m.supports(self, d):
1302 self.method = m
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001303 break
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001304
1305 if not self.method:
1306 raise NoMethodError(url)
1307
1308 if localonly and not isinstance(self.method, local.Local):
1309 raise NonLocalMethod()
1310
1311 if self.parm.get("proto", None) and "protocol" not in self.parm:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001312 logger.warning('Consider updating %s recipe to use "protocol" not "proto" in SRC_URI.', d.getVar('PN'))
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001313 self.parm["protocol"] = self.parm.get("proto", None)
1314
1315 if hasattr(self.method, "urldata_init"):
1316 self.method.urldata_init(self, d)
1317
1318 if "localpath" in self.parm:
1319 # if user sets localpath for file, use it instead.
1320 self.localpath = self.parm["localpath"]
1321 self.basename = os.path.basename(self.localpath)
1322 elif self.localfile:
1323 self.localpath = self.method.localpath(self, d)
1324
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001325 dldir = d.getVar("DL_DIR")
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05001326
1327 if not self.needdonestamp:
1328 return
1329
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001330 # Note: .done and .lock files should always be in DL_DIR whereas localpath may not be.
1331 if self.localpath and self.localpath.startswith(dldir):
1332 basepath = self.localpath
1333 elif self.localpath:
1334 basepath = dldir + os.sep + os.path.basename(self.localpath)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05001335 elif self.basepath or self.basename:
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001336 basepath = dldir + os.sep + (self.basepath or self.basename)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05001337 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001338 bb.fatal("Can't determine lock path for url %s" % url)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05001339
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001340 self.donestamp = basepath + '.done'
1341 self.lockfile = basepath + '.lock'
1342
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001343 def setup_revisions(self, d):
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001344 self.revisions = {}
1345 for name in self.names:
1346 self.revisions[name] = srcrev_internal_helper(self, d, name)
1347
1348 # add compatibility code for non name specified case
1349 if len(self.names) == 1:
1350 self.revision = self.revisions[self.names[0]]
1351
1352 def setup_localpath(self, d):
1353 if not self.localpath:
1354 self.localpath = self.method.localpath(self, d)
1355
1356 def getSRCDate(self, d):
1357 """
1358 Return the SRC Date for the component
1359
1360 d the bb.data module
1361 """
1362 if "srcdate" in self.parm:
1363 return self.parm['srcdate']
1364
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001365 pn = d.getVar("PN")
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001366
1367 if pn:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001368 return d.getVar("SRCDATE_%s" % pn) or d.getVar("SRCDATE") or d.getVar("DATE")
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001369
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001370 return d.getVar("SRCDATE") or d.getVar("DATE")
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001371
1372class FetchMethod(object):
1373 """Base class for 'fetch'ing data"""
1374
1375 def __init__(self, urls=None):
1376 self.urls = []
1377
1378 def supports(self, urldata, d):
1379 """
1380 Check to see if this fetch class supports a given url.
1381 """
1382 return 0
1383
1384 def localpath(self, urldata, d):
1385 """
1386 Return the local filename of a given url assuming a successful fetch.
1387 Can also setup variables in urldata for use in go (saving code duplication
1388 and duplicate code execution)
1389 """
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001390 return os.path.join(d.getVar("DL_DIR"), urldata.localfile)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001391
1392 def supports_checksum(self, urldata):
1393 """
1394 Is localpath something that can be represented by a checksum?
1395 """
1396
1397 # We cannot compute checksums for directories
Andrew Geissler82c905d2020-04-13 13:39:40 -05001398 if os.path.isdir(urldata.localpath):
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001399 return False
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001400 return True
1401
1402 def recommends_checksum(self, urldata):
1403 """
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001404 Is the backend on where checksumming is recommended (should warnings
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001405 be displayed if there is no checksum)?
1406 """
1407 return False
1408
Andrew Geissler82c905d2020-04-13 13:39:40 -05001409 def verify_donestamp(self, ud, d):
1410 """
1411 Verify the donestamp file
1412 """
1413 return verify_donestamp(ud, d)
1414
1415 def update_donestamp(self, ud, d):
1416 """
1417 Update the donestamp file
1418 """
1419 update_stamp(ud, d)
1420
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001421 def _strip_leading_slashes(self, relpath):
1422 """
1423 Remove leading slash as os.path.join can't cope
1424 """
1425 while os.path.isabs(relpath):
1426 relpath = relpath[1:]
1427 return relpath
1428
1429 def setUrls(self, urls):
1430 self.__urls = urls
1431
1432 def getUrls(self):
1433 return self.__urls
1434
1435 urls = property(getUrls, setUrls, None, "Urls property")
1436
1437 def need_update(self, ud, d):
1438 """
1439 Force a fetch, even if localpath exists?
1440 """
1441 if os.path.exists(ud.localpath):
1442 return False
1443 return True
1444
1445 def supports_srcrev(self):
1446 """
1447 The fetcher supports auto source revisions (SRCREV)
1448 """
1449 return False
1450
1451 def download(self, urldata, d):
1452 """
1453 Fetch urls
1454 Assumes localpath was called first
1455 """
Brad Bishop19323692019-04-05 15:28:33 -04001456 raise NoMethodError(urldata.url)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001457
1458 def unpack(self, urldata, rootdir, data):
1459 iterate = False
1460 file = urldata.localpath
1461
1462 try:
1463 unpack = bb.utils.to_boolean(urldata.parm.get('unpack'), True)
1464 except ValueError as exc:
1465 bb.fatal("Invalid value for 'unpack' parameter for %s: %s" %
1466 (file, urldata.parm.get('unpack')))
1467
1468 base, ext = os.path.splitext(file)
1469 if ext in ['.gz', '.bz2', '.Z', '.xz', '.lz']:
1470 efile = os.path.join(rootdir, os.path.basename(base))
1471 else:
1472 efile = file
1473 cmd = None
1474
1475 if unpack:
Andrew Geissler595f6302022-01-24 19:11:47 +00001476 tar_cmd = 'tar --extract --no-same-owner'
1477 if 'striplevel' in urldata.parm:
1478 tar_cmd += ' --strip-components=%s' % urldata.parm['striplevel']
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001479 if file.endswith('.tar'):
Andrew Geissler595f6302022-01-24 19:11:47 +00001480 cmd = '%s -f %s' % (tar_cmd, file)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001481 elif file.endswith('.tgz') or file.endswith('.tar.gz') or file.endswith('.tar.Z'):
Andrew Geissler595f6302022-01-24 19:11:47 +00001482 cmd = '%s -z -f %s' % (tar_cmd, file)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001483 elif file.endswith('.tbz') or file.endswith('.tbz2') or file.endswith('.tar.bz2'):
Andrew Geissler595f6302022-01-24 19:11:47 +00001484 cmd = 'bzip2 -dc %s | %s -f -' % (file, tar_cmd)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001485 elif file.endswith('.gz') or file.endswith('.Z') or file.endswith('.z'):
1486 cmd = 'gzip -dc %s > %s' % (file, efile)
1487 elif file.endswith('.bz2'):
1488 cmd = 'bzip2 -dc %s > %s' % (file, efile)
Brad Bishop316dfdd2018-06-25 12:45:53 -04001489 elif file.endswith('.txz') or file.endswith('.tar.xz'):
Andrew Geissler595f6302022-01-24 19:11:47 +00001490 cmd = 'xz -dc %s | %s -f -' % (file, tar_cmd)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001491 elif file.endswith('.xz'):
1492 cmd = 'xz -dc %s > %s' % (file, efile)
1493 elif file.endswith('.tar.lz'):
Andrew Geissler595f6302022-01-24 19:11:47 +00001494 cmd = 'lzip -dc %s | %s -f -' % (file, tar_cmd)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001495 elif file.endswith('.lz'):
1496 cmd = 'lzip -dc %s > %s' % (file, efile)
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001497 elif file.endswith('.tar.7z'):
Andrew Geissler595f6302022-01-24 19:11:47 +00001498 cmd = '7z x -so %s | %s -f -' % (file, tar_cmd)
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001499 elif file.endswith('.7z'):
1500 cmd = '7za x -y %s 1>/dev/null' % file
Andrew Geissler6ce62a22020-11-30 19:58:47 -06001501 elif file.endswith('.tzst') or file.endswith('.tar.zst'):
Andrew Geissler595f6302022-01-24 19:11:47 +00001502 cmd = 'zstd --decompress --stdout %s | %s -f -' % (file, tar_cmd)
Andrew Geissler6ce62a22020-11-30 19:58:47 -06001503 elif file.endswith('.zst'):
1504 cmd = 'zstd --decompress --stdout %s > %s' % (file, efile)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001505 elif file.endswith('.zip') or file.endswith('.jar'):
1506 try:
1507 dos = bb.utils.to_boolean(urldata.parm.get('dos'), False)
1508 except ValueError as exc:
1509 bb.fatal("Invalid value for 'dos' parameter for %s: %s" %
1510 (file, urldata.parm.get('dos')))
1511 cmd = 'unzip -q -o'
1512 if dos:
1513 cmd = '%s -a' % cmd
1514 cmd = "%s '%s'" % (cmd, file)
1515 elif file.endswith('.rpm') or file.endswith('.srpm'):
1516 if 'extract' in urldata.parm:
1517 unpack_file = urldata.parm.get('extract')
1518 cmd = 'rpm2cpio.sh %s | cpio -id %s' % (file, unpack_file)
1519 iterate = True
1520 iterate_file = unpack_file
1521 else:
1522 cmd = 'rpm2cpio.sh %s | cpio -id' % (file)
1523 elif file.endswith('.deb') or file.endswith('.ipk'):
Brad Bishopa5c52ff2018-11-23 10:55:50 +13001524 output = subprocess.check_output(['ar', '-t', file], preexec_fn=subprocess_setup)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001525 datafile = None
1526 if output:
1527 for line in output.decode().splitlines():
1528 if line.startswith('data.tar.'):
1529 datafile = line
1530 break
1531 else:
1532 raise UnpackError("Unable to unpack deb/ipk package - does not contain data.tar.* file", urldata.url)
1533 else:
1534 raise UnpackError("Unable to unpack deb/ipk package - could not list contents", urldata.url)
Andrew Geissler595f6302022-01-24 19:11:47 +00001535 cmd = 'ar x %s %s && %s -p -f %s && rm %s' % (file, datafile, tar_cmd, datafile, datafile)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05001536
1537 # If 'subdir' param exists, create a dir and use it as destination for unpack cmd
1538 if 'subdir' in urldata.parm:
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001539 subdir = urldata.parm.get('subdir')
1540 if os.path.isabs(subdir):
1541 if not os.path.realpath(subdir).startswith(os.path.realpath(rootdir)):
1542 raise UnpackError("subdir argument isn't a subdirectory of unpack root %s" % rootdir, urldata.url)
1543 unpackdir = subdir
1544 else:
1545 unpackdir = os.path.join(rootdir, subdir)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05001546 bb.utils.mkdirhier(unpackdir)
1547 else:
1548 unpackdir = rootdir
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001549
1550 if not unpack or not cmd:
1551 # If file == dest, then avoid any copies, as we already put the file into dest!
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05001552 dest = os.path.join(unpackdir, os.path.basename(file))
1553 if file != dest and not (os.path.exists(dest) and os.path.samefile(file, dest)):
1554 destdir = '.'
1555 # For file:// entries all intermediate dirs in path must be created at destination
1556 if urldata.type == "file":
1557 # Trailing '/' does a copying to wrong place
1558 urlpath = urldata.path.rstrip('/')
1559 # Want files places relative to cwd so no leading '/'
1560 urlpath = urlpath.lstrip('/')
1561 if urlpath.find("/") != -1:
1562 destdir = urlpath.rsplit("/", 1)[0] + '/'
1563 bb.utils.mkdirhier("%s/%s" % (unpackdir, destdir))
Andrew Geisslerc3d88e42020-10-02 09:45:00 -05001564 cmd = 'cp -fpPRH "%s" "%s"' % (file, destdir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001565
1566 if not cmd:
1567 return
1568
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001569 path = data.getVar('PATH')
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001570 if path:
1571 cmd = "PATH=\"%s\" %s" % (path, cmd)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001572 bb.note("Unpacking %s to %s/" % (file, unpackdir))
1573 ret = subprocess.call(cmd, preexec_fn=subprocess_setup, shell=True, cwd=unpackdir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001574
1575 if ret != 0:
1576 raise UnpackError("Unpack command %s failed with return value %s" % (cmd, ret), urldata.url)
1577
1578 if iterate is True:
1579 iterate_urldata = urldata
1580 iterate_urldata.localpath = "%s/%s" % (rootdir, iterate_file)
1581 self.unpack(urldata, rootdir, data)
1582
1583 return
1584
1585 def clean(self, urldata, d):
1586 """
1587 Clean any existing full or partial download
1588 """
1589 bb.utils.remove(urldata.localpath)
1590
1591 def try_premirror(self, urldata, d):
1592 """
1593 Should premirrors be used?
1594 """
1595 return True
1596
Andrew Geissler82c905d2020-04-13 13:39:40 -05001597 def try_mirrors(self, fetch, urldata, d, mirrors, check=False):
1598 """
1599 Try to use a mirror
1600 """
1601 return bool(try_mirrors(fetch, d, urldata, mirrors, check))
1602
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001603 def checkstatus(self, fetch, urldata, d):
1604 """
1605 Check the status of a URL
1606 Assumes localpath was called first
1607 """
Brad Bishop19323692019-04-05 15:28:33 -04001608 logger.info("URL %s could not be checked for status since no method exists.", urldata.url)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001609 return True
1610
1611 def latest_revision(self, ud, d, name):
1612 """
1613 Look in the cache for the latest revision, if not present ask the SCM.
1614 """
1615 if not hasattr(self, "_latest_revision"):
Brad Bishop19323692019-04-05 15:28:33 -04001616 raise ParameterError("The fetcher for this URL does not support _latest_revision", ud.url)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001617
1618 revs = bb.persist_data.persist('BB_URI_HEADREVS', d)
1619 key = self.generate_revision_key(ud, d, name)
1620 try:
1621 return revs[key]
1622 except KeyError:
1623 revs[key] = rev = self._latest_revision(ud, d, name)
1624 return rev
1625
1626 def sortable_revision(self, ud, d, name):
1627 latest_rev = self._build_revision(ud, d, name)
1628 return True, str(latest_rev)
1629
1630 def generate_revision_key(self, ud, d, name):
Andrew Geissler82c905d2020-04-13 13:39:40 -05001631 return self._revision_key(ud, d, name)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001632
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001633 def latest_versionstring(self, ud, d):
1634 """
1635 Compute the latest release name like "x.y.x" in "x.y.x+gitHASH"
1636 by searching through the tags output of ls-remote, comparing
1637 versions and returning the highest match as a (version, revision) pair.
1638 """
1639 return ('', '')
1640
Andrew Geissler82c905d2020-04-13 13:39:40 -05001641 def done(self, ud, d):
1642 """
1643 Is the download done ?
1644 """
1645 if os.path.exists(ud.localpath):
1646 return True
Andrew Geissler82c905d2020-04-13 13:39:40 -05001647 return False
1648
Andrew Geissler4ed12e12020-06-05 18:00:41 -05001649 def implicit_urldata(self, ud, d):
1650 """
1651 Get a list of FetchData objects for any implicit URLs that will also
1652 be downloaded when we fetch the given URL.
1653 """
1654 return []
1655
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001656class Fetch(object):
1657 def __init__(self, urls, d, cache = True, localonly = False, connection_cache = None):
1658 if localonly and cache:
1659 raise Exception("bb.fetch2.Fetch.__init__: cannot set cache and localonly at same time")
1660
Andrew Geissler595f6302022-01-24 19:11:47 +00001661 if not urls:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001662 urls = d.getVar("SRC_URI").split()
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001663 self.urls = urls
1664 self.d = d
1665 self.ud = {}
1666 self.connection_cache = connection_cache
1667
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001668 fn = d.getVar('FILE')
1669 mc = d.getVar('__BBMULTICONFIG') or ""
Andrew Geissler82c905d2020-04-13 13:39:40 -05001670 key = None
1671 if cache and fn:
1672 key = mc + fn + str(id(d))
1673 if key in urldata_cache:
1674 self.ud = urldata_cache[key]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001675
1676 for url in urls:
1677 if url not in self.ud:
1678 try:
1679 self.ud[url] = FetchData(url, d, localonly)
1680 except NonLocalMethod:
1681 if localonly:
1682 self.ud[url] = None
1683 pass
1684
Andrew Geissler82c905d2020-04-13 13:39:40 -05001685 if key:
1686 urldata_cache[key] = self.ud
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001687
1688 def localpath(self, url):
1689 if url not in self.urls:
1690 self.ud[url] = FetchData(url, self.d)
1691
1692 self.ud[url].setup_localpath(self.d)
1693 return self.d.expand(self.ud[url].localpath)
1694
1695 def localpaths(self):
1696 """
1697 Return a list of the local filenames, assuming successful fetch
1698 """
1699 local = []
1700
1701 for u in self.urls:
1702 ud = self.ud[u]
1703 ud.setup_localpath(self.d)
1704 local.append(ud.localpath)
1705
1706 return local
1707
1708 def download(self, urls=None):
1709 """
1710 Fetch all urls
1711 """
1712 if not urls:
1713 urls = self.urls
1714
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001715 network = self.d.getVar("BB_NO_NETWORK")
Brad Bishop19323692019-04-05 15:28:33 -04001716 premirroronly = bb.utils.to_boolean(self.d.getVar("BB_FETCH_PREMIRRORONLY"))
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001717
1718 for u in urls:
1719 ud = self.ud[u]
1720 ud.setup_localpath(self.d)
1721 m = ud.method
Andrew Geissler82c905d2020-04-13 13:39:40 -05001722 done = False
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001723
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05001724 if ud.lockfile:
1725 lf = bb.utils.lockfile(ud.lockfile)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001726
1727 try:
1728 self.d.setVar("BB_NO_NETWORK", network)
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001729
Andrew Geissler82c905d2020-04-13 13:39:40 -05001730 if m.verify_donestamp(ud, self.d) and not m.need_update(ud, self.d):
1731 done = True
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001732 elif m.try_premirror(ud, self.d):
Andrew Geisslerd1e89492021-02-12 15:35:20 -06001733 logger.debug("Trying PREMIRRORS")
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001734 mirrors = mirror_from_string(self.d.getVar('PREMIRRORS'))
Andrew Geissler82c905d2020-04-13 13:39:40 -05001735 done = m.try_mirrors(self, ud, self.d, mirrors)
1736 if done:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001737 try:
1738 # early checksum verification so that if the checksum of the premirror
1739 # contents mismatch the fetcher can still try upstream and mirrors
Andrew Geissler82c905d2020-04-13 13:39:40 -05001740 m.update_donestamp(ud, self.d)
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001741 except ChecksumError as e:
1742 logger.warning("Checksum failure encountered with premirror download of %s - will attempt other sources." % u)
Andrew Geisslerd1e89492021-02-12 15:35:20 -06001743 logger.debug(str(e))
Andrew Geissler82c905d2020-04-13 13:39:40 -05001744 done = False
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001745
1746 if premirroronly:
1747 self.d.setVar("BB_NO_NETWORK", "1")
1748
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001749 firsterr = None
Andrew Geisslereff27472021-10-29 15:35:00 -05001750 verified_stamp = False
1751 if done:
1752 verified_stamp = m.verify_donestamp(ud, self.d)
Andrew Geissler82c905d2020-04-13 13:39:40 -05001753 if not done and (not verified_stamp or m.need_update(ud, self.d)):
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001754 try:
1755 if not trusted_network(self.d, ud.url):
1756 raise UntrustedUrl(ud.url)
Andrew Geisslerd1e89492021-02-12 15:35:20 -06001757 logger.debug("Trying Upstream")
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001758 m.download(ud, self.d)
1759 if hasattr(m, "build_mirror_data"):
1760 m.build_mirror_data(ud, self.d)
Andrew Geissler82c905d2020-04-13 13:39:40 -05001761 done = True
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001762 # early checksum verify, so that if checksum mismatched,
1763 # fetcher still have chance to fetch from mirror
Andrew Geissler82c905d2020-04-13 13:39:40 -05001764 m.update_donestamp(ud, self.d)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001765
1766 except bb.fetch2.NetworkAccess:
1767 raise
1768
1769 except BBFetchException as e:
1770 if isinstance(e, ChecksumError):
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001771 logger.warning("Checksum failure encountered with download of %s - will attempt other sources if available" % u)
Andrew Geisslerd1e89492021-02-12 15:35:20 -06001772 logger.debug(str(e))
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05001773 if os.path.exists(ud.localpath):
1774 rename_bad_checksum(ud, e.checksum)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001775 elif isinstance(e, NoChecksumError):
1776 raise
1777 else:
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001778 logger.warning('Failed to fetch URL %s, attempting MIRRORS if available' % u)
Andrew Geisslerd1e89492021-02-12 15:35:20 -06001779 logger.debug(str(e))
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001780 firsterr = e
1781 # Remove any incomplete fetch
1782 if not verified_stamp:
1783 m.clean(ud, self.d)
Andrew Geisslerd1e89492021-02-12 15:35:20 -06001784 logger.debug("Trying MIRRORS")
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001785 mirrors = mirror_from_string(self.d.getVar('MIRRORS'))
Andrew Geissler82c905d2020-04-13 13:39:40 -05001786 done = m.try_mirrors(self, ud, self.d, mirrors)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001787
Andrew Geissler82c905d2020-04-13 13:39:40 -05001788 if not done or not m.done(ud, self.d):
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001789 if firsterr:
1790 logger.error(str(firsterr))
1791 raise FetchError("Unable to fetch URL from any source.", u)
1792
Andrew Geissler82c905d2020-04-13 13:39:40 -05001793 m.update_donestamp(ud, self.d)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001794
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001795 except IOError as e:
Brad Bishop19323692019-04-05 15:28:33 -04001796 if e.errno in [errno.ESTALE]:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001797 logger.error("Stale Error Observed %s." % u)
1798 raise ChecksumError("Stale Error Detected")
1799
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001800 except BBFetchException as e:
1801 if isinstance(e, ChecksumError):
1802 logger.error("Checksum failure fetching %s" % u)
1803 raise
1804
1805 finally:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05001806 if ud.lockfile:
1807 bb.utils.unlockfile(lf)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001808
1809 def checkstatus(self, urls=None):
1810 """
Andrew Geisslereff27472021-10-29 15:35:00 -05001811 Check all URLs exist upstream.
1812
1813 Returns None if the URLs exist, raises FetchError if the check wasn't
1814 successful but there wasn't an error (such as file not found), and
1815 raises other exceptions in error cases.
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001816 """
1817
1818 if not urls:
1819 urls = self.urls
1820
1821 for u in urls:
1822 ud = self.ud[u]
1823 ud.setup_localpath(self.d)
1824 m = ud.method
Andrew Geisslerd1e89492021-02-12 15:35:20 -06001825 logger.debug("Testing URL %s", u)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001826 # First try checking uri, u, from PREMIRRORS
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001827 mirrors = mirror_from_string(self.d.getVar('PREMIRRORS'))
Andrew Geissler82c905d2020-04-13 13:39:40 -05001828 ret = m.try_mirrors(self, ud, self.d, mirrors, True)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001829 if not ret:
1830 # Next try checking from the original uri, u
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001831 ret = m.checkstatus(self, ud, self.d)
1832 if not ret:
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001833 # Finally, try checking uri, u, from MIRRORS
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001834 mirrors = mirror_from_string(self.d.getVar('MIRRORS'))
Andrew Geissler82c905d2020-04-13 13:39:40 -05001835 ret = m.try_mirrors(self, ud, self.d, mirrors, True)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001836
1837 if not ret:
1838 raise FetchError("URL %s doesn't work" % u, u)
1839
1840 def unpack(self, root, urls=None):
1841 """
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001842 Unpack urls to root
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001843 """
1844
1845 if not urls:
1846 urls = self.urls
1847
1848 for u in urls:
1849 ud = self.ud[u]
1850 ud.setup_localpath(self.d)
1851
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001852 if ud.lockfile:
1853 lf = bb.utils.lockfile(ud.lockfile)
1854
1855 ud.method.unpack(ud, root, self.d)
1856
1857 if ud.lockfile:
1858 bb.utils.unlockfile(lf)
1859
1860 def clean(self, urls=None):
1861 """
1862 Clean files that the fetcher gets or places
1863 """
1864
1865 if not urls:
1866 urls = self.urls
1867
1868 for url in urls:
1869 if url not in self.ud:
Brad Bishop19323692019-04-05 15:28:33 -04001870 self.ud[url] = FetchData(url, self.d)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001871 ud = self.ud[url]
1872 ud.setup_localpath(self.d)
1873
1874 if not ud.localfile and ud.localpath is None:
1875 continue
1876
1877 if ud.lockfile:
1878 lf = bb.utils.lockfile(ud.lockfile)
1879
1880 ud.method.clean(ud, self.d)
1881 if ud.donestamp:
1882 bb.utils.remove(ud.donestamp)
1883
1884 if ud.lockfile:
1885 bb.utils.unlockfile(lf)
1886
Andrew Geissler4ed12e12020-06-05 18:00:41 -05001887 def expanded_urldata(self, urls=None):
1888 """
1889 Get an expanded list of FetchData objects covering both the given
1890 URLS and any additional implicit URLs that are added automatically by
1891 the appropriate FetchMethod.
1892 """
1893
1894 if not urls:
1895 urls = self.urls
1896
1897 urldata = []
1898 for url in urls:
1899 ud = self.ud[url]
1900 urldata.append(ud)
1901 urldata += ud.method.implicit_urldata(ud, self.d)
1902
1903 return urldata
1904
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001905class FetchConnectionCache(object):
1906 """
1907 A class which represents an container for socket connections.
1908 """
1909 def __init__(self):
1910 self.cache = {}
1911
1912 def get_connection_name(self, host, port):
1913 return host + ':' + str(port)
1914
1915 def add_connection(self, host, port, connection):
1916 cn = self.get_connection_name(host, port)
1917
1918 if cn not in self.cache:
1919 self.cache[cn] = connection
1920
1921 def get_connection(self, host, port):
1922 connection = None
1923
1924 cn = self.get_connection_name(host, port)
1925 if cn in self.cache:
1926 connection = self.cache[cn]
1927
1928 return connection
1929
1930 def remove_connection(self, host, port):
1931 cn = self.get_connection_name(host, port)
1932 if cn in self.cache:
1933 self.cache[cn].close()
1934 del self.cache[cn]
1935
1936 def close_connections(self):
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001937 for cn in list(self.cache.keys()):
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001938 self.cache[cn].close()
1939 del self.cache[cn]
1940
1941from . import cvs
1942from . import git
1943from . import gitsm
1944from . import gitannex
1945from . import local
1946from . import svn
1947from . import wget
1948from . import ssh
1949from . import sftp
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001950from . import s3
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001951from . import perforce
1952from . import bzr
1953from . import hg
1954from . import osc
1955from . import repo
1956from . import clearcase
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05001957from . import npm
Andrew Geissler82c905d2020-04-13 13:39:40 -05001958from . import npmsw
Andrew Geissler95ac1b82021-03-31 14:34:31 -05001959from . import az
Andrew Geissler595f6302022-01-24 19:11:47 +00001960from . import crate
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001961
1962methods.append(local.Local())
1963methods.append(wget.Wget())
1964methods.append(svn.Svn())
1965methods.append(git.Git())
1966methods.append(gitsm.GitSM())
1967methods.append(gitannex.GitANNEX())
1968methods.append(cvs.Cvs())
1969methods.append(ssh.SSH())
1970methods.append(sftp.SFTP())
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001971methods.append(s3.S3())
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001972methods.append(perforce.Perforce())
1973methods.append(bzr.Bzr())
1974methods.append(hg.Hg())
1975methods.append(osc.Osc())
1976methods.append(repo.Repo())
1977methods.append(clearcase.ClearCase())
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05001978methods.append(npm.Npm())
Andrew Geissler82c905d2020-04-13 13:39:40 -05001979methods.append(npmsw.NpmShrinkWrap())
Andrew Geissler95ac1b82021-03-31 14:34:31 -05001980methods.append(az.Az())
Andrew Geissler595f6302022-01-24 19:11:47 +00001981methods.append(crate.Crate())