__init__.py 67 KB

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