1 # Copyright 2010-2013 Gentoo Foundation
2 # Distributed under the terms of the GNU General Public License v2
4 from __future__ import print_function
18 from urllib.parse import urlparse, urlunparse
20 from urlparse import urlparse, urlunparse
23 portage.proxy.lazyimport.lazyimport(globals(),
24 'portage.package.ebuild.config:check_config_instance,config',
25 'portage.package.ebuild.doebuild:doebuild_environment,' + \
27 'portage.package.ebuild.prepare_build_dirs:prepare_build_dirs',
30 from portage import OrderedDict, os, selinux, shutil, _encodings, \
31 _shell_quote, _unicode_encode
32 from portage.checksum import (hashfunc_map, perform_md5, verify_all,
33 _filter_unaccelarated_hashes, _hash_filter, _apply_hash_filter)
34 from portage.const import BASH_BINARY, CUSTOM_MIRRORS_FILE, \
36 from portage.data import portage_gid, portage_uid, secpass, userpriv_groups
37 from portage.exception import FileNotFound, OperationNotPermitted, \
38 PortageException, TryAgain
39 from portage.localization import _
40 from portage.locks import lockfile, unlockfile
41 from portage.output import colorize, EOutput
42 from portage.util import apply_recursive_permissions, \
43 apply_secpass_permissions, ensure_dirs, grabdict, shlex_split, \
44 varexpand, writemsg, writemsg_level, writemsg_stdout
45 from portage.process import spawn
47 _userpriv_spawn_kwargs = (
50 ("groups", userpriv_groups),
54 def _hide_url_passwd(url):
55 return re.sub(r'//(.+):.+@(.+)', r'//\1:*password*@\2', url)
57 def _spawn_fetch(settings, args, **kwargs):
59 Spawn a process with appropriate settings for fetching, including
60 userfetch and selinux support.
63 global _userpriv_spawn_kwargs
65 # Redirect all output to stdout since some fetchers like
66 # wget pollute stderr (if portage detects a problem then it
67 # can send it's own message to stderr).
68 if "fd_pipes" not in kwargs:
70 kwargs["fd_pipes"] = {
71 0 : portage._get_stdin().fileno(),
72 1 : sys.__stdout__.fileno(),
73 2 : sys.__stdout__.fileno(),
76 if "userfetch" in settings.features and \
77 os.getuid() == 0 and portage_gid and portage_uid and \
78 hasattr(os, "setgroups"):
79 kwargs.update(_userpriv_spawn_kwargs)
83 if settings.selinux_enabled():
84 spawn_func = selinux.spawn_wrapper(spawn_func,
85 settings["PORTAGE_FETCH_T"])
87 # bash is an allowed entrypoint, while most binaries are not
88 if args[0] != BASH_BINARY:
89 args = [BASH_BINARY, "-c", "exec \"$@\"", args[0]] + args
91 # Ensure that EBUILD_PHASE is set to fetch, so that config.environ()
92 # does not filter the calling environment (which may contain needed
93 # proxy variables, as in bug #315421).
94 phase_backup = settings.get('EBUILD_PHASE')
95 settings['EBUILD_PHASE'] = 'fetch'
97 rval = spawn_func(args, env=settings.environ(), **kwargs)
99 if phase_backup is None:
100 settings.pop('EBUILD_PHASE', None)
102 settings['EBUILD_PHASE'] = phase_backup
106 _userpriv_test_write_file_cache = {}
107 _userpriv_test_write_cmd_script = ">> %(file_path)s 2>/dev/null ; rval=$? ; " + \
108 "rm -f %(file_path)s ; exit $rval"
110 def _userpriv_test_write_file(settings, file_path):
112 Drop privileges and try to open a file for writing. The file may or
113 may not exist, and the parent directory is assumed to exist. The file
114 is removed before returning.
116 @param settings: A config instance which is passed to _spawn_fetch()
117 @param file_path: A file path to open and write.
118 @return: True if write succeeds, False otherwise.
121 global _userpriv_test_write_file_cache, _userpriv_test_write_cmd_script
122 rval = _userpriv_test_write_file_cache.get(file_path)
126 args = [BASH_BINARY, "-c", _userpriv_test_write_cmd_script % \
127 {"file_path" : _shell_quote(file_path)}]
129 returncode = _spawn_fetch(settings, args)
131 rval = returncode == os.EX_OK
132 _userpriv_test_write_file_cache[file_path] = rval
135 def _checksum_failure_temp_file(distdir, basename):
137 First try to find a duplicate temp file with the same checksum and return
138 that filename if available. Otherwise, use mkstemp to create a new unique
139 filename._checksum_failure_.$RANDOM, rename the given file, and return the
140 new filename. In any case, filename will be renamed or removed before this
141 function returns a temp filename.
144 filename = os.path.join(distdir, basename)
145 size = os.stat(filename).st_size
147 tempfile_re = re.compile(re.escape(basename) + r'\._checksum_failure_\..*')
148 for temp_filename in os.listdir(distdir):
149 if not tempfile_re.match(temp_filename):
151 temp_filename = os.path.join(distdir, temp_filename)
153 if size != os.stat(temp_filename).st_size:
158 temp_checksum = perform_md5(temp_filename)
160 # Apparently the temp file disappeared. Let it go.
163 checksum = perform_md5(filename)
164 if checksum == temp_checksum:
168 fd, temp_filename = \
169 tempfile.mkstemp("", basename + "._checksum_failure_.", distdir)
171 os.rename(filename, temp_filename)
174 def _check_digests(filename, digests, show_errors=1):
176 Check digests and display a message if an error occurs.
177 @return True if all digests match, False otherwise.
179 verified_ok, reason = verify_all(filename, digests)
182 writemsg(_("!!! Previously fetched"
183 " file: '%s'\n") % filename, noiselevel=-1)
184 writemsg(_("!!! Reason: %s\n") % reason[0],
186 writemsg(_("!!! Got: %s\n"
187 "!!! Expected: %s\n") % \
188 (reason[1], reason[2]), noiselevel=-1)
192 def _check_distfile(filename, digests, eout, show_errors=1, hash_filter=None):
194 @return a tuple of (match, stat_obj) where match is True if filename
195 matches all given digests (if any) and stat_obj is a stat result, or
196 None if the file does not exist.
200 size = digests.get("size")
201 if size is not None and len(digests) == 1:
205 st = os.stat(filename)
208 if size is not None and size != st.st_size:
212 eout.ebegin(_("%s size ;-)") % os.path.basename(filename))
214 elif st.st_size == 0:
215 # Zero-byte distfiles are always invalid.
218 digests = _filter_unaccelarated_hashes(digests)
219 if hash_filter is not None:
220 digests = _apply_hash_filter(digests, hash_filter)
221 if _check_digests(filename, digests, show_errors=show_errors):
222 eout.ebegin("%s %s ;-)" % (os.path.basename(filename),
223 " ".join(sorted(digests))))
229 _fetch_resume_size_re = re.compile('(^[\d]+)([KMGTPEZY]?$)')
244 def _get_checksum_failure_max_tries(settings, default=5):
246 Get the maximum number of failed download attempts.
248 Generally, downloading the same file repeatedly from
249 every single available mirror is a waste of bandwidth
250 and time, so there needs to be a cap.
252 key = 'PORTAGE_FETCH_CHECKSUM_TRY_MIRRORS'
255 v = int(settings.get(key, default))
256 except (ValueError, OverflowError):
257 writemsg(_("!!! Variable %s contains "
258 "non-integer value: '%s'\n")
259 % (key, settings[key]),
261 writemsg(_("!!! Using %s default value: %s\n")
266 writemsg(_("!!! Variable %s contains "
267 "value less than 1: '%s'\n")
270 writemsg(_("!!! Using %s default value: %s\n")
277 def _get_fetch_resume_size(settings, default='350K'):
278 key = 'PORTAGE_FETCH_RESUME_MIN_SIZE'
279 v = settings.get(key)
281 v = "".join(v.split())
283 # If it's empty, silently use the default.
285 match = _fetch_resume_size_re.match(v)
287 match.group(2).upper() not in _size_suffix_map):
288 writemsg(_("!!! Variable %s contains an "
289 "unrecognized format: '%s'\n")
290 % (key, settings[key]),
292 writemsg(_("!!! Using %s default value: %s\n")
298 match = _fetch_resume_size_re.match(v)
299 v = int(match.group(1)) * \
300 2 ** _size_suffix_map[match.group(2).upper()]
304 def _get_file_uri_tuples(uris):
305 """Return a list of (filename, URI) tuples."""
307 # Check for 'items' attribute since OrderedDict is not a dict.
308 if hasattr(uris, 'items'):
309 for filename, uri_set in uris.items():
311 file_uri_tuples.append((filename, uri))
313 file_uri_tuples.append((filename, None))
316 if urlparse(uri).scheme:
317 file_uri_tuples.append(
318 (os.path.basename(uri), uri))
320 file_uri_tuples.append(
321 (os.path.basename(uri), None))
322 return file_uri_tuples
325 def _expand_mirror(uri, custom_mirrors=(), third_party_mirrors=()):
327 Replace the 'mirror://' scheme and netloc in the URI.
329 Returns an iterable listing expanded (group, URI) tuples,
330 where the group is either 'custom' or 'third-party'.
332 parsed = urlparse(uri)
333 mirror = parsed.netloc
336 # Try user-defined mirrors first
337 if mirror in custom_mirrors:
338 for cmirr in custom_mirrors[mirror]:
339 m_uri = urlparse(cmirr)
340 yield ('custom', urlunparse((
341 m_uri.scheme, m_uri.netloc, path) +
344 # now try the official mirrors
345 if mirror in third_party_mirrors:
347 for locmirr in third_party_mirrors[mirror]:
348 m_uri = urlparse(locmirr)
349 uris.append(urlunparse((
350 m_uri.scheme, m_uri.netloc, path) +
354 yield ('third-party', uri)
356 if (not custom_mirrors.get(mirror, []) and
357 not third_party_mirrors.get(mirror, [])):
359 _("No known mirror by the name: %s\n")
362 writemsg(_("Invalid mirror definition in SRC_URI:\n"),
364 writemsg(" %s\n" % uri, noiselevel=-1)
367 def _get_uris(uris, settings, custom_mirrors=(), locations=()):
368 restrict = settings.get("PORTAGE_RESTRICT", "").split()
369 restrict_fetch = "fetch" in restrict
370 restrict_mirror = "mirror" in restrict or "nomirror" in restrict
372 "force-mirror" in settings.features and
375 third_party_mirrors = settings.thirdpartymirrors()
376 third_party_mirror_uris = {}
377 filedict = OrderedDict()
379 for filename, uri in _get_file_uri_tuples(uris=uris):
380 if filename not in filedict:
381 filedict[filename] = [
382 os.path.join(location, 'distfiles', filename)
383 for location in locations]
386 if uri.startswith('mirror://'):
387 expanded_uris = _expand_mirror(
388 uri=uri, custom_mirrors=custom_mirrors,
389 third_party_mirrors=third_party_mirrors)
390 filedict[filename].extend(
391 uri for _, uri in expanded_uris)
392 third_party_mirror_uris.setdefault(filename, []).extend(
393 uri for group, uri in expanded_uris
394 if group == 'third-party')
396 if restrict_fetch or force_mirror:
397 # Only fetch from specific mirrors is allowed.
399 primaryuris = primaryuri_dict.get(filename)
400 if primaryuris is None:
402 primaryuri_dict[filename] = primaryuris
403 primaryuris.append(uri)
405 # Order primaryuri_dict values to match that in SRC_URI.
406 for uris in primaryuri_dict.values():
409 # Prefer third_party_mirrors over normal mirrors in cases when
410 # the file does not yet exist on the normal mirrors.
411 for filename, uris in third_party_mirror_uris.items():
412 primaryuri_dict.setdefault(filename, []).extend(uris)
414 # Now merge primaryuri values into filedict (includes mirrors
415 # explicitly referenced in SRC_URI).
416 if "primaryuri" in restrict:
417 for filename, uris in filedict.items():
418 filedict[filename] = primaryuri_dict.get(filename, []) + uris
420 for filename in filedict:
421 filedict[filename] += primaryuri_dict.get(filename, [])
423 return filedict, primaryuri_dict
426 def fetch(myuris, mysettings, listonly=0, fetchonly=0,
427 locks_in_subdir=".locks", use_locks=1, try_mirrors=1, digests=None,
428 allow_missing_digests=True):
429 "fetch files. Will use digest file if available."
434 features = mysettings.features
435 restrict = mysettings.get("PORTAGE_RESTRICT","").split()
437 userfetch = secpass >= 2 and "userfetch" in features
438 userpriv = secpass >= 2 and "userpriv" in features
440 # 'nomirror' is bad/negative logic. You Restrict mirroring, not no-mirroring.
441 restrict_mirror = "mirror" in restrict or "nomirror" in restrict
443 if ("mirror" in features) and ("lmirror" not in features):
444 # lmirror should allow you to bypass mirror restrictions.
445 # XXX: This is not a good thing, and is temporary at best.
446 print(_(">>> \"mirror\" mode desired and \"mirror\" restriction found; skipping fetch."))
449 checksum_failure_max_tries = _get_checksum_failure_max_tries(
451 fetch_resume_size = _get_fetch_resume_size(settings=mysettings)
453 # Behave like the package has RESTRICT="primaryuri" after a
454 # couple of checksum failures, to increase the probablility
455 # of success before checksum_failure_max_tries is reached.
456 checksum_failure_primaryuri = 2
458 # In the background parallel-fetch process, it's safe to skip checksum
459 # verification of pre-existing files in $DISTDIR that have the correct
460 # file size. The parent process will verify their checksums prior to
463 parallel_fetchonly = "PORTAGE_PARALLEL_FETCHONLY" in mysettings
464 if parallel_fetchonly:
467 check_config_instance(mysettings)
469 custommirrors = grabdict(os.path.join(mysettings["PORTAGE_CONFIGROOT"],
470 CUSTOM_MIRRORS_FILE), recursive=1)
474 if listonly or ("distlocks" not in features):
478 if "skiprocheck" in features:
481 if not os.access(mysettings["DISTDIR"],os.W_OK) and fetch_to_ro:
483 writemsg(colorize("BAD",
484 _("!!! For fetching to a read-only filesystem, "
485 "locking should be turned off.\n")), noiselevel=-1)
486 writemsg(_("!!! This can be done by adding -distlocks to "
487 "FEATURES in /etc/portage/make.conf\n"), noiselevel=-1)
490 # local mirrors are always added
491 if "local" in custommirrors:
492 mymirrors += custommirrors["local"]
495 # We don't add any mirrors.
499 mymirrors += [x.rstrip("/") for x in mysettings["GENTOO_MIRRORS"].split() if x]
501 hash_filter = _hash_filter(mysettings.get("PORTAGE_CHECKSUM_FILTER", ""))
502 if hash_filter.transparent:
504 skip_manifest = mysettings.get("EBUILD_SKIP_MANIFEST") == "1"
506 allow_missing_digests = True
507 pkgdir = mysettings.get("O")
508 if digests is None and not (pkgdir is None or skip_manifest):
509 mydigests = mysettings.repositories.get_repo_for_location(
510 os.path.dirname(os.path.dirname(pkgdir))).load_manifest(
511 pkgdir, mysettings["DISTDIR"]).getTypeDigests("DIST")
512 elif digests is None or skip_manifest:
513 # no digests because fetch was not called for a specific package
518 ro_distdirs = [x for x in \
519 shlex_split(mysettings.get("PORTAGE_RO_DISTDIRS", "")) \
523 for x in range(len(mymirrors)-1,-1,-1):
524 if mymirrors[x] and mymirrors[x][0]=='/':
525 fsmirrors += [mymirrors[x]]
528 restrict_fetch = "fetch" in restrict
529 custom_local_mirrors = custommirrors.get("local", [])
531 # With fetch restriction, a normal uri may only be fetched from
532 # custom local mirrors (if available). A mirror:// uri may also
533 # be fetched from specific mirrors (effectively overriding fetch
534 # restriction, but only for specific mirrors).
535 locations = custom_local_mirrors
537 locations = mymirrors
539 filedict, primaryuri_dict = _get_uris(
540 uris=myuris, settings=mysettings,
541 custom_mirrors=custommirrors, locations=locations)
548 if can_fetch and not fetch_to_ro:
549 global _userpriv_test_write_file_cache
553 dir_gid = portage_gid
554 if "FAKED_MODE" in mysettings:
555 # When inside fakeroot, directories with portage's gid appear
556 # to have root's gid. Therefore, use root's gid instead of
557 # portage's gid to avoid spurrious permissions adjustments
558 # when inside fakeroot.
563 for x in distdir_dirs:
564 mydir = os.path.join(mysettings["DISTDIR"], x)
565 write_test_file = os.path.join(
566 mydir, ".__portage_test_write__")
573 if st is not None and stat.S_ISDIR(st.st_mode):
574 if not (userfetch or userpriv):
576 if _userpriv_test_write_file(mysettings, write_test_file):
579 _userpriv_test_write_file_cache.pop(write_test_file, None)
580 if ensure_dirs(mydir, gid=dir_gid, mode=dirmode, mask=modemask):
582 # The directory has just been created
583 # and therefore it must be empty.
585 writemsg(_("Adjusting permissions recursively: '%s'\n") % mydir,
588 raise # bail out on the first error that occurs during recursion
589 if not apply_recursive_permissions(mydir,
590 gid=dir_gid, dirmode=dirmode, dirmask=modemask,
591 filemode=filemode, filemask=modemask, onerror=onerror):
592 raise OperationNotPermitted(
593 _("Failed to apply recursive permissions for the portage group."))
594 except PortageException as e:
595 if not os.path.isdir(mysettings["DISTDIR"]):
596 writemsg("!!! %s\n" % str(e), noiselevel=-1)
597 writemsg(_("!!! Directory Not Found: DISTDIR='%s'\n") % mysettings["DISTDIR"], noiselevel=-1)
598 writemsg(_("!!! Fetching will fail!\n"), noiselevel=-1)
601 not fetch_to_ro and \
602 not os.access(mysettings["DISTDIR"], os.W_OK):
603 writemsg(_("!!! No write access to '%s'\n") % mysettings["DISTDIR"],
607 distdir_writable = can_fetch and not fetch_to_ro
609 restrict_fetch_msg = False
611 for myfile in filedict:
615 1 partially downloaded
616 2 completely downloaded
620 orig_digests = mydigests.get(myfile, {})
622 if not (allow_missing_digests or listonly):
623 verifiable_hash_types = set(orig_digests).intersection(hashfunc_map)
624 verifiable_hash_types.discard("size")
625 if not verifiable_hash_types:
626 expected = set(hashfunc_map)
627 expected.discard("size")
628 expected = " ".join(sorted(expected))
629 got = set(orig_digests)
631 got = " ".join(sorted(got))
632 reason = (_("Insufficient data for checksum verification"),
634 writemsg(_("!!! Fetched file: %s VERIFY FAILED!\n") % myfile,
636 writemsg(_("!!! Reason: %s\n") % reason[0],
638 writemsg(_("!!! Got: %s\n!!! Expected: %s\n") % \
639 (reason[1], reason[2]), noiselevel=-1)
642 failed_files.add(myfile)
647 size = orig_digests.get("size")
649 # Zero-byte distfiles are always invalid, so discard their digests.
650 del mydigests[myfile]
653 pruned_digests = orig_digests
654 if parallel_fetchonly:
657 pruned_digests["size"] = size
659 myfile_path = os.path.join(mysettings["DISTDIR"], myfile)
661 has_space_superuser = True
664 writemsg_stdout("\n", noiselevel=-1)
666 # check if there is enough space in DISTDIR to completely store myfile
667 # overestimate the filesize so we aren't bitten by FS overhead
669 if size is not None and hasattr(os, "statvfs"):
671 vfs_stat = os.statvfs(mysettings["DISTDIR"])
673 writemsg_level("!!! statvfs('%s'): %s\n" %
674 (mysettings["DISTDIR"], e),
675 noiselevel=-1, level=logging.ERROR)
678 if vfs_stat is not None:
680 mysize = os.stat(myfile_path).st_size
682 if e.errno not in (errno.ENOENT, errno.ESTALE):
686 if (size - mysize + vfs_stat.f_bsize) >= \
687 (vfs_stat.f_bsize * vfs_stat.f_bavail):
689 if (size - mysize + vfs_stat.f_bsize) >= \
690 (vfs_stat.f_bsize * vfs_stat.f_bfree):
691 has_space_superuser = False
693 if not has_space_superuser:
700 if distdir_writable and use_locks:
704 lock_kwargs["flags"] = os.O_NONBLOCK
707 file_lock = lockfile(myfile_path,
708 wantnewlockfile=1, **lock_kwargs)
710 writemsg(_(">>> File '%s' is already locked by "
711 "another fetcher. Continuing...\n") % myfile,
718 eout.quiet = mysettings.get("PORTAGE_QUIET") == "1"
719 match, mystat = _check_distfile(
720 myfile_path, pruned_digests, eout, hash_filter=hash_filter)
722 # Skip permission adjustment for symlinks, since we don't
723 # want to modify anything outside of the primary DISTDIR,
724 # and symlinks typically point to PORTAGE_RO_DISTDIRS.
725 if distdir_writable and not os.path.islink(myfile_path):
727 apply_secpass_permissions(myfile_path,
728 gid=portage_gid, mode=0o664, mask=0o2,
730 except PortageException as e:
731 if not os.access(myfile_path, os.R_OK):
732 writemsg(_("!!! Failed to adjust permissions:"
733 " %s\n") % str(e), noiselevel=-1)
737 if distdir_writable and mystat is None:
738 # Remove broken symlinks if necessary.
740 os.unlink(myfile_path)
744 if mystat is not None:
745 if stat.S_ISDIR(mystat.st_mode):
747 _("!!! Unable to fetch file since "
748 "a directory is in the way: \n"
749 "!!! %s\n") % myfile_path,
750 level=logging.ERROR, noiselevel=-1)
753 if mystat.st_size == 0:
756 os.unlink(myfile_path)
759 elif distdir_writable:
760 if mystat.st_size < fetch_resume_size and \
761 mystat.st_size < size:
762 # If the file already exists and the size does not
763 # match the existing digests, it may be that the
764 # user is attempting to update the digest. In this
765 # case, the digestgen() function will advise the
766 # user to use `ebuild --force foo.ebuild manifest`
767 # in order to force the old digests to be replaced.
768 # Since the user may want to keep this file, rename
769 # it instead of deleting it.
770 writemsg(_(">>> Renaming distfile with size "
771 "%d (smaller than " "PORTAGE_FETCH_RESU"
772 "ME_MIN_SIZE)\n") % mystat.st_size)
774 _checksum_failure_temp_file(
775 mysettings["DISTDIR"], myfile)
776 writemsg_stdout(_("Refetching... "
777 "File renamed to '%s'\n\n") % \
778 temp_filename, noiselevel=-1)
779 elif mystat.st_size >= size:
781 _checksum_failure_temp_file(
782 mysettings["DISTDIR"], myfile)
783 writemsg_stdout(_("Refetching... "
784 "File renamed to '%s'\n\n") % \
785 temp_filename, noiselevel=-1)
787 if distdir_writable and ro_distdirs:
789 for x in ro_distdirs:
790 filename = os.path.join(x, myfile)
791 match, mystat = _check_distfile(
792 filename, pruned_digests, eout, hash_filter=hash_filter)
794 readonly_file = filename
796 if readonly_file is not None:
798 os.unlink(myfile_path)
800 if e.errno not in (errno.ENOENT, errno.ESTALE):
803 os.symlink(readonly_file, myfile_path)
806 # this message is shown only after we know that
807 # the file is not already fetched
809 writemsg(_("!!! Insufficient space to store %s in %s\n") % \
810 (myfile, mysettings["DISTDIR"]), noiselevel=-1)
812 if has_space_superuser:
813 writemsg(_("!!! Insufficient privileges to use "
814 "remaining space.\n"), noiselevel=-1)
816 writemsg(_("!!! You may set FEATURES=\"-userfetch\""
817 " in /etc/portage/make.conf in order to fetch with\n"
818 "!!! superuser privileges.\n"), noiselevel=-1)
820 if fsmirrors and not os.path.exists(myfile_path) and has_space:
821 for mydir in fsmirrors:
822 mirror_file = os.path.join(mydir, myfile)
824 shutil.copyfile(mirror_file, myfile_path)
825 writemsg(_("Local mirror has file: %s\n") % myfile)
827 except (IOError, OSError) as e:
828 if e.errno not in (errno.ENOENT, errno.ESTALE):
833 mystat = os.stat(myfile_path)
835 if e.errno not in (errno.ENOENT, errno.ESTALE):
839 # Skip permission adjustment for symlinks, since we don't
840 # want to modify anything outside of the primary DISTDIR,
841 # and symlinks typically point to PORTAGE_RO_DISTDIRS.
842 if not os.path.islink(myfile_path):
844 apply_secpass_permissions(myfile_path,
845 gid=portage_gid, mode=0o664, mask=0o2,
847 except PortageException as e:
848 if not os.access(myfile_path, os.R_OK):
849 writemsg(_("!!! Failed to adjust permissions:"
850 " %s\n") % (e,), noiselevel=-1)
852 # If the file is empty then it's obviously invalid. Remove
853 # the empty file and try to download if possible.
854 if mystat.st_size == 0:
857 os.unlink(myfile_path)
858 except EnvironmentError:
860 elif myfile not in mydigests:
861 # We don't have a digest, but the file exists. We must
862 # assume that it is fully downloaded.
865 if mystat.st_size < mydigests[myfile]["size"] and \
867 fetched = 1 # Try to resume this download.
868 elif parallel_fetchonly and \
869 mystat.st_size == mydigests[myfile]["size"]:
872 mysettings.get("PORTAGE_QUIET") == "1"
874 "%s size ;-)" % (myfile, ))
878 digests = _filter_unaccelarated_hashes(mydigests[myfile])
879 if hash_filter is not None:
880 digests = _apply_hash_filter(digests, hash_filter)
881 verified_ok, reason = verify_all(myfile_path, digests)
883 writemsg(_("!!! Previously fetched"
884 " file: '%s'\n") % myfile, noiselevel=-1)
885 writemsg(_("!!! Reason: %s\n") % reason[0],
887 writemsg(_("!!! Got: %s\n"
888 "!!! Expected: %s\n") % \
889 (reason[1], reason[2]), noiselevel=-1)
890 if reason[0] == _("Insufficient data for checksum verification"):
894 _checksum_failure_temp_file(
895 mysettings["DISTDIR"], myfile)
896 writemsg_stdout(_("Refetching... "
897 "File renamed to '%s'\n\n") % \
898 temp_filename, noiselevel=-1)
902 mysettings.get("PORTAGE_QUIET", None) == "1"
904 digests = list(digests)
907 "%s %s ;-)" % (myfile, " ".join(digests)))
909 continue # fetch any remaining files
911 # Create a reversed list since that is optimal for list.pop().
912 uri_list = filedict[myfile][:]
914 checksum_failure_count = 0
915 tried_locations = set()
918 # Eliminate duplicates here in case we've switched to
919 # "primaryuri" mode on the fly due to a checksum failure.
920 if loc in tried_locations:
922 tried_locations.add(loc)
924 writemsg_stdout(loc+" ", noiselevel=-1)
926 # allow different fetchcommands per protocol
927 protocol = loc[0:loc.find("://")]
929 global_config_path = GLOBAL_CONFIG_PATH
930 if portage.const.EPREFIX:
931 global_config_path = os.path.join(portage.const.EPREFIX,
932 GLOBAL_CONFIG_PATH.lstrip(os.sep))
934 missing_file_param = False
935 fetchcommand_var = "FETCHCOMMAND_" + protocol.upper()
936 fetchcommand = mysettings.get(fetchcommand_var)
937 if fetchcommand is None:
938 fetchcommand_var = "FETCHCOMMAND"
939 fetchcommand = mysettings.get(fetchcommand_var)
940 if fetchcommand is None:
942 _("!!! %s is unset. It should "
943 "have been defined in\n!!! %s/make.globals.\n") \
944 % (fetchcommand_var, global_config_path),
945 level=logging.ERROR, noiselevel=-1)
947 if "${FILE}" not in fetchcommand:
949 _("!!! %s does not contain the required ${FILE}"
950 " parameter.\n") % fetchcommand_var,
951 level=logging.ERROR, noiselevel=-1)
952 missing_file_param = True
954 resumecommand_var = "RESUMECOMMAND_" + protocol.upper()
955 resumecommand = mysettings.get(resumecommand_var)
956 if resumecommand is None:
957 resumecommand_var = "RESUMECOMMAND"
958 resumecommand = mysettings.get(resumecommand_var)
959 if resumecommand is None:
961 _("!!! %s is unset. It should "
962 "have been defined in\n!!! %s/make.globals.\n") \
963 % (resumecommand_var, global_config_path),
964 level=logging.ERROR, noiselevel=-1)
966 if "${FILE}" not in resumecommand:
968 _("!!! %s does not contain the required ${FILE}"
969 " parameter.\n") % resumecommand_var,
970 level=logging.ERROR, noiselevel=-1)
971 missing_file_param = True
973 if missing_file_param:
975 _("!!! Refer to the make.conf(5) man page for "
976 "information about how to\n!!! correctly specify "
977 "FETCHCOMMAND and RESUMECOMMAND.\n"),
978 level=logging.ERROR, noiselevel=-1)
979 if myfile != os.path.basename(loc):
985 mysize = os.stat(myfile_path).st_size
987 if e.errno not in (errno.ENOENT, errno.ESTALE):
993 writemsg(_("!!! File %s isn't fetched but unable to get it.\n") % myfile,
995 elif size is None or size > mysize:
996 writemsg(_("!!! File %s isn't fully fetched, but unable to complete it\n") % myfile,
999 writemsg(_("!!! File %s is incorrect size, "
1000 "but unable to retry.\n") % myfile, noiselevel=-1)
1005 if fetched != 2 and has_space:
1006 #we either need to resume or start the download
1009 mystat = os.stat(myfile_path)
1010 except OSError as e:
1011 if e.errno not in (errno.ENOENT, errno.ESTALE):
1016 if mystat.st_size < fetch_resume_size:
1017 writemsg(_(">>> Deleting distfile with size "
1018 "%d (smaller than " "PORTAGE_FETCH_RESU"
1019 "ME_MIN_SIZE)\n") % mystat.st_size)
1021 os.unlink(myfile_path)
1022 except OSError as e:
1024 (errno.ENOENT, errno.ESTALE):
1030 writemsg(_(">>> Resuming download...\n"))
1031 locfetch=resumecommand
1032 command_var = resumecommand_var
1035 locfetch=fetchcommand
1036 command_var = fetchcommand_var
1037 writemsg_stdout(_(">>> Downloading '%s'\n") % \
1038 _hide_url_passwd(loc))
1044 for k in ("DISTDIR", "PORTAGE_SSH_OPTS"):
1046 variables[k] = mysettings[k]
1050 myfetch = shlex_split(locfetch)
1051 myfetch = [varexpand(x, mydict=variables) for x in myfetch]
1055 myret = _spawn_fetch(mysettings, myfetch)
1059 apply_secpass_permissions(myfile_path,
1060 gid=portage_gid, mode=0o664, mask=0o2)
1061 except FileNotFound:
1063 except PortageException as e:
1064 if not os.access(myfile_path, os.R_OK):
1065 writemsg(_("!!! Failed to adjust permissions:"
1066 " %s\n") % str(e), noiselevel=-1)
1069 # If the file is empty then it's obviously invalid. Don't
1070 # trust the return value from the fetcher. Remove the
1071 # empty file and try to download again.
1073 if os.stat(myfile_path).st_size == 0:
1074 os.unlink(myfile_path)
1077 except EnvironmentError:
1080 if mydigests is not None and myfile in mydigests:
1082 mystat = os.stat(myfile_path)
1083 except OSError as e:
1084 if e.errno not in (errno.ENOENT, errno.ESTALE):
1090 if stat.S_ISDIR(mystat.st_mode):
1091 # This can happen if FETCHCOMMAND erroneously
1092 # contains wget's -P option where it should
1095 _("!!! The command specified in the "
1096 "%s variable appears to have\n!!! "
1097 "created a directory instead of a "
1098 "normal file.\n") % command_var,
1099 level=logging.ERROR, noiselevel=-1)
1101 _("!!! Refer to the make.conf(5) "
1102 "man page for information about how "
1103 "to\n!!! correctly specify "
1104 "FETCHCOMMAND and RESUMECOMMAND.\n"),
1105 level=logging.ERROR, noiselevel=-1)
1108 # no exception? file exists. let digestcheck() report
1109 # an appropriately for size or checksum errors
1111 # If the fetcher reported success and the file is
1112 # too small, it's probably because the digest is
1113 # bad (upstream changed the distfile). In this
1114 # case we don't want to attempt to resume. Show a
1115 # digest verification failure to that the user gets
1116 # a clue about what just happened.
1117 if myret != os.EX_OK and \
1118 mystat.st_size < mydigests[myfile]["size"]:
1119 # Fetch failed... Try the next one... Kill 404 files though.
1120 if (mystat[stat.ST_SIZE]<100000) and (len(myfile)>4) and not ((myfile[-5:]==".html") or (myfile[-4:]==".htm")):
1121 html404=re.compile("<title>.*(not found|404).*</title>",re.I|re.M)
1123 _unicode_encode(myfile_path,
1124 encoding=_encodings['fs'], errors='strict'),
1125 mode='r', encoding=_encodings['content'], errors='replace'
1127 if html404.search(f.read()):
1129 os.unlink(mysettings["DISTDIR"]+"/"+myfile)
1130 writemsg(_(">>> Deleting invalid distfile. (Improper 404 redirect from server.)\n"))
1133 except (IOError, OSError):
1138 # File is the correct size--check the checksums for the fetched
1139 # file NOW, for those users who don't have a stable/continuous
1140 # net connection. This way we have a chance to try to download
1141 # from another mirror...
1142 digests = _filter_unaccelarated_hashes(mydigests[myfile])
1143 if hash_filter is not None:
1144 digests = _apply_hash_filter(digests, hash_filter)
1145 verified_ok, reason = verify_all(myfile_path, digests)
1147 writemsg(_("!!! Fetched file: %s VERIFY FAILED!\n") % myfile,
1149 writemsg(_("!!! Reason: %s\n") % reason[0],
1151 writemsg(_("!!! Got: %s\n!!! Expected: %s\n") % \
1152 (reason[1], reason[2]), noiselevel=-1)
1153 if reason[0] == _("Insufficient data for checksum verification"):
1156 _checksum_failure_temp_file(
1157 mysettings["DISTDIR"], myfile)
1158 writemsg_stdout(_("Refetching... "
1159 "File renamed to '%s'\n\n") % \
1160 temp_filename, noiselevel=-1)
1162 checksum_failure_count += 1
1163 if checksum_failure_count == \
1164 checksum_failure_primaryuri:
1165 # Switch to "primaryuri" mode in order
1166 # to increase the probablility of
1169 primaryuri_dict.get(myfile)
1172 reversed(primaryuris))
1173 if checksum_failure_count >= \
1174 checksum_failure_max_tries:
1178 eout.quiet = mysettings.get("PORTAGE_QUIET", None) == "1"
1180 eout.ebegin("%s %s ;-)" % \
1181 (myfile, " ".join(sorted(digests))))
1189 elif mydigests!=None:
1190 writemsg(_("No digest file available and download failed.\n\n"),
1193 if use_locks and file_lock:
1194 unlockfile(file_lock)
1198 writemsg_stdout("\n", noiselevel=-1)
1200 if restrict_fetch and not restrict_fetch_msg:
1201 restrict_fetch_msg = True
1202 msg = _("\n!!! %s/%s"
1203 " has fetch restriction turned on.\n"
1204 "!!! This probably means that this "
1205 "ebuild's files must be downloaded\n"
1206 "!!! manually. See the comments in"
1207 " the ebuild for more information.\n\n") % \
1208 (mysettings["CATEGORY"], mysettings["PF"])
1210 level=logging.ERROR, noiselevel=-1)
1211 elif restrict_fetch:
1215 elif not filedict[myfile]:
1216 writemsg(_("Warning: No mirrors available for file"
1217 " '%s'\n") % (myfile), noiselevel=-1)
1219 writemsg(_("!!! Couldn't download '%s'. Aborting.\n") % myfile,
1223 failed_files.add(myfile)
1226 failed_files.add(myfile)