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
20 from urlparse import urlparse
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 fetch(myuris, mysettings, listonly=0, fetchonly=0,
305 locks_in_subdir=".locks", use_locks=1, try_mirrors=1, digests=None,
306 allow_missing_digests=True):
307 "fetch files. Will use digest file if available."
312 features = mysettings.features
313 restrict = mysettings.get("PORTAGE_RESTRICT","").split()
315 userfetch = secpass >= 2 and "userfetch" in features
316 userpriv = secpass >= 2 and "userpriv" in features
318 # 'nomirror' is bad/negative logic. You Restrict mirroring, not no-mirroring.
319 restrict_mirror = "mirror" in restrict or "nomirror" in restrict
321 if ("mirror" in features) and ("lmirror" not in features):
322 # lmirror should allow you to bypass mirror restrictions.
323 # XXX: This is not a good thing, and is temporary at best.
324 print(_(">>> \"mirror\" mode desired and \"mirror\" restriction found; skipping fetch."))
327 checksum_failure_max_tries = _get_checksum_failure_max_tries(
329 fetch_resume_size = _get_fetch_resume_size(settings=mysettings)
331 # Behave like the package has RESTRICT="primaryuri" after a
332 # couple of checksum failures, to increase the probablility
333 # of success before checksum_failure_max_tries is reached.
334 checksum_failure_primaryuri = 2
335 thirdpartymirrors = mysettings.thirdpartymirrors()
337 # In the background parallel-fetch process, it's safe to skip checksum
338 # verification of pre-existing files in $DISTDIR that have the correct
339 # file size. The parent process will verify their checksums prior to
342 parallel_fetchonly = "PORTAGE_PARALLEL_FETCHONLY" in mysettings
343 if parallel_fetchonly:
346 check_config_instance(mysettings)
348 custommirrors = grabdict(os.path.join(mysettings["PORTAGE_CONFIGROOT"],
349 CUSTOM_MIRRORS_FILE), recursive=1)
353 if listonly or ("distlocks" not in features):
357 if "skiprocheck" in features:
360 if not os.access(mysettings["DISTDIR"],os.W_OK) and fetch_to_ro:
362 writemsg(colorize("BAD",
363 _("!!! For fetching to a read-only filesystem, "
364 "locking should be turned off.\n")), noiselevel=-1)
365 writemsg(_("!!! This can be done by adding -distlocks to "
366 "FEATURES in /etc/portage/make.conf\n"), noiselevel=-1)
369 # local mirrors are always added
370 if "local" in custommirrors:
371 mymirrors += custommirrors["local"]
374 # We don't add any mirrors.
378 mymirrors += [x.rstrip("/") for x in mysettings["GENTOO_MIRRORS"].split() if x]
380 hash_filter = _hash_filter(mysettings.get("PORTAGE_CHECKSUM_FILTER", ""))
381 if hash_filter.transparent:
383 skip_manifest = mysettings.get("EBUILD_SKIP_MANIFEST") == "1"
385 allow_missing_digests = True
386 pkgdir = mysettings.get("O")
387 if digests is None and not (pkgdir is None or skip_manifest):
388 mydigests = mysettings.repositories.get_repo_for_location(
389 os.path.dirname(os.path.dirname(pkgdir))).load_manifest(
390 pkgdir, mysettings["DISTDIR"]).getTypeDigests("DIST")
391 elif digests is None or skip_manifest:
392 # no digests because fetch was not called for a specific package
397 ro_distdirs = [x for x in \
398 shlex_split(mysettings.get("PORTAGE_RO_DISTDIRS", "")) \
402 for x in range(len(mymirrors)-1,-1,-1):
403 if mymirrors[x] and mymirrors[x][0]=='/':
404 fsmirrors += [mymirrors[x]]
407 restrict_fetch = "fetch" in restrict
408 force_mirror = "force-mirror" in features and not restrict_mirror
409 custom_local_mirrors = custommirrors.get("local", [])
411 # With fetch restriction, a normal uri may only be fetched from
412 # custom local mirrors (if available). A mirror:// uri may also
413 # be fetched from specific mirrors (effectively overriding fetch
414 # restriction, but only for specific mirrors).
415 locations = custom_local_mirrors
417 locations = mymirrors
420 # Check for 'items' attribute since OrderedDict is not a dict.
421 if hasattr(myuris, 'items'):
422 for myfile, uri_set in myuris.items():
423 for myuri in uri_set:
424 file_uri_tuples.append((myfile, myuri))
426 file_uri_tuples.append((myfile, None))
429 if urlparse(myuri).scheme:
430 file_uri_tuples.append((os.path.basename(myuri), myuri))
432 file_uri_tuples.append((os.path.basename(myuri), None))
434 filedict = OrderedDict()
436 thirdpartymirror_uris = {}
437 for myfile, myuri in file_uri_tuples:
438 if myfile not in filedict:
440 for y in range(0,len(locations)):
441 filedict[myfile].append(locations[y]+"/distfiles/"+myfile)
444 if myuri[:9]=="mirror://":
445 eidx = myuri.find("/", 9)
447 mirrorname = myuri[9:eidx]
448 path = myuri[eidx+1:]
450 # Try user-defined mirrors first
451 if mirrorname in custommirrors:
452 for cmirr in custommirrors[mirrorname]:
453 filedict[myfile].append(
454 cmirr.rstrip("/") + "/" + path)
456 # now try the official mirrors
457 if mirrorname in thirdpartymirrors:
458 uris = [locmirr.rstrip("/") + "/" + path \
459 for locmirr in thirdpartymirrors[mirrorname]]
461 filedict[myfile].extend(uris)
462 thirdpartymirror_uris.setdefault(myfile, []).extend(uris)
464 if not filedict[myfile]:
465 writemsg(_("No known mirror by the name: %s\n") % (mirrorname))
467 writemsg(_("Invalid mirror definition in SRC_URI:\n"), noiselevel=-1)
468 writemsg(" %s\n" % (myuri), noiselevel=-1)
470 if restrict_fetch or force_mirror:
471 # Only fetch from specific mirrors is allowed.
473 primaryuris = primaryuri_dict.get(myfile)
474 if primaryuris is None:
476 primaryuri_dict[myfile] = primaryuris
477 primaryuris.append(myuri)
479 # Order primaryuri_dict values to match that in SRC_URI.
480 for uris in primaryuri_dict.values():
483 # Prefer thirdpartymirrors over normal mirrors in cases when
484 # the file does not yet exist on the normal mirrors.
485 for myfile, uris in thirdpartymirror_uris.items():
486 primaryuri_dict.setdefault(myfile, []).extend(uris)
488 # Now merge primaryuri values into filedict (includes mirrors
489 # explicitly referenced in SRC_URI).
490 if "primaryuri" in restrict:
491 for myfile, uris in filedict.items():
492 filedict[myfile] = primaryuri_dict.get(myfile, []) + uris
494 for myfile in filedict:
495 filedict[myfile] += primaryuri_dict.get(myfile, [])
502 if can_fetch and not fetch_to_ro:
503 global _userpriv_test_write_file_cache
507 dir_gid = portage_gid
508 if "FAKED_MODE" in mysettings:
509 # When inside fakeroot, directories with portage's gid appear
510 # to have root's gid. Therefore, use root's gid instead of
511 # portage's gid to avoid spurrious permissions adjustments
512 # when inside fakeroot.
517 for x in distdir_dirs:
518 mydir = os.path.join(mysettings["DISTDIR"], x)
519 write_test_file = os.path.join(
520 mydir, ".__portage_test_write__")
527 if st is not None and stat.S_ISDIR(st.st_mode):
528 if not (userfetch or userpriv):
530 if _userpriv_test_write_file(mysettings, write_test_file):
533 _userpriv_test_write_file_cache.pop(write_test_file, None)
534 if ensure_dirs(mydir, gid=dir_gid, mode=dirmode, mask=modemask):
536 # The directory has just been created
537 # and therefore it must be empty.
539 writemsg(_("Adjusting permissions recursively: '%s'\n") % mydir,
542 raise # bail out on the first error that occurs during recursion
543 if not apply_recursive_permissions(mydir,
544 gid=dir_gid, dirmode=dirmode, dirmask=modemask,
545 filemode=filemode, filemask=modemask, onerror=onerror):
546 raise OperationNotPermitted(
547 _("Failed to apply recursive permissions for the portage group."))
548 except PortageException as e:
549 if not os.path.isdir(mysettings["DISTDIR"]):
550 writemsg("!!! %s\n" % str(e), noiselevel=-1)
551 writemsg(_("!!! Directory Not Found: DISTDIR='%s'\n") % mysettings["DISTDIR"], noiselevel=-1)
552 writemsg(_("!!! Fetching will fail!\n"), noiselevel=-1)
555 not fetch_to_ro and \
556 not os.access(mysettings["DISTDIR"], os.W_OK):
557 writemsg(_("!!! No write access to '%s'\n") % mysettings["DISTDIR"],
561 distdir_writable = can_fetch and not fetch_to_ro
563 restrict_fetch_msg = False
565 for myfile in filedict:
569 1 partially downloaded
570 2 completely downloaded
574 orig_digests = mydigests.get(myfile, {})
576 if not (allow_missing_digests or listonly):
577 verifiable_hash_types = set(orig_digests).intersection(hashfunc_map)
578 verifiable_hash_types.discard("size")
579 if not verifiable_hash_types:
580 expected = set(hashfunc_map)
581 expected.discard("size")
582 expected = " ".join(sorted(expected))
583 got = set(orig_digests)
585 got = " ".join(sorted(got))
586 reason = (_("Insufficient data for checksum verification"),
588 writemsg(_("!!! Fetched file: %s VERIFY FAILED!\n") % myfile,
590 writemsg(_("!!! Reason: %s\n") % reason[0],
592 writemsg(_("!!! Got: %s\n!!! Expected: %s\n") % \
593 (reason[1], reason[2]), noiselevel=-1)
596 failed_files.add(myfile)
601 size = orig_digests.get("size")
603 # Zero-byte distfiles are always invalid, so discard their digests.
604 del mydigests[myfile]
607 pruned_digests = orig_digests
608 if parallel_fetchonly:
611 pruned_digests["size"] = size
613 myfile_path = os.path.join(mysettings["DISTDIR"], myfile)
615 has_space_superuser = True
618 writemsg_stdout("\n", noiselevel=-1)
620 # check if there is enough space in DISTDIR to completely store myfile
621 # overestimate the filesize so we aren't bitten by FS overhead
623 if size is not None and hasattr(os, "statvfs"):
625 vfs_stat = os.statvfs(mysettings["DISTDIR"])
627 writemsg_level("!!! statvfs('%s'): %s\n" %
628 (mysettings["DISTDIR"], e),
629 noiselevel=-1, level=logging.ERROR)
632 if vfs_stat is not None:
634 mysize = os.stat(myfile_path).st_size
636 if e.errno not in (errno.ENOENT, errno.ESTALE):
640 if (size - mysize + vfs_stat.f_bsize) >= \
641 (vfs_stat.f_bsize * vfs_stat.f_bavail):
643 if (size - mysize + vfs_stat.f_bsize) >= \
644 (vfs_stat.f_bsize * vfs_stat.f_bfree):
645 has_space_superuser = False
647 if not has_space_superuser:
654 if distdir_writable and use_locks:
658 lock_kwargs["flags"] = os.O_NONBLOCK
661 file_lock = lockfile(myfile_path,
662 wantnewlockfile=1, **lock_kwargs)
664 writemsg(_(">>> File '%s' is already locked by "
665 "another fetcher. Continuing...\n") % myfile,
672 eout.quiet = mysettings.get("PORTAGE_QUIET") == "1"
673 match, mystat = _check_distfile(
674 myfile_path, pruned_digests, eout, hash_filter=hash_filter)
676 # Skip permission adjustment for symlinks, since we don't
677 # want to modify anything outside of the primary DISTDIR,
678 # and symlinks typically point to PORTAGE_RO_DISTDIRS.
679 if distdir_writable and not os.path.islink(myfile_path):
681 apply_secpass_permissions(myfile_path,
682 gid=portage_gid, mode=0o664, mask=0o2,
684 except PortageException as e:
685 if not os.access(myfile_path, os.R_OK):
686 writemsg(_("!!! Failed to adjust permissions:"
687 " %s\n") % str(e), noiselevel=-1)
691 if distdir_writable and mystat is None:
692 # Remove broken symlinks if necessary.
694 os.unlink(myfile_path)
698 if mystat is not None:
699 if stat.S_ISDIR(mystat.st_mode):
701 _("!!! Unable to fetch file since "
702 "a directory is in the way: \n"
703 "!!! %s\n") % myfile_path,
704 level=logging.ERROR, noiselevel=-1)
707 if mystat.st_size == 0:
710 os.unlink(myfile_path)
713 elif distdir_writable:
714 if mystat.st_size < fetch_resume_size and \
715 mystat.st_size < size:
716 # If the file already exists and the size does not
717 # match the existing digests, it may be that the
718 # user is attempting to update the digest. In this
719 # case, the digestgen() function will advise the
720 # user to use `ebuild --force foo.ebuild manifest`
721 # in order to force the old digests to be replaced.
722 # Since the user may want to keep this file, rename
723 # it instead of deleting it.
724 writemsg(_(">>> Renaming distfile with size "
725 "%d (smaller than " "PORTAGE_FETCH_RESU"
726 "ME_MIN_SIZE)\n") % mystat.st_size)
728 _checksum_failure_temp_file(
729 mysettings["DISTDIR"], myfile)
730 writemsg_stdout(_("Refetching... "
731 "File renamed to '%s'\n\n") % \
732 temp_filename, noiselevel=-1)
733 elif mystat.st_size >= size:
735 _checksum_failure_temp_file(
736 mysettings["DISTDIR"], myfile)
737 writemsg_stdout(_("Refetching... "
738 "File renamed to '%s'\n\n") % \
739 temp_filename, noiselevel=-1)
741 if distdir_writable and ro_distdirs:
743 for x in ro_distdirs:
744 filename = os.path.join(x, myfile)
745 match, mystat = _check_distfile(
746 filename, pruned_digests, eout, hash_filter=hash_filter)
748 readonly_file = filename
750 if readonly_file is not None:
752 os.unlink(myfile_path)
754 if e.errno not in (errno.ENOENT, errno.ESTALE):
757 os.symlink(readonly_file, myfile_path)
760 # this message is shown only after we know that
761 # the file is not already fetched
763 writemsg(_("!!! Insufficient space to store %s in %s\n") % \
764 (myfile, mysettings["DISTDIR"]), noiselevel=-1)
766 if has_space_superuser:
767 writemsg(_("!!! Insufficient privileges to use "
768 "remaining space.\n"), noiselevel=-1)
770 writemsg(_("!!! You may set FEATURES=\"-userfetch\""
771 " in /etc/portage/make.conf in order to fetch with\n"
772 "!!! superuser privileges.\n"), noiselevel=-1)
774 if fsmirrors and not os.path.exists(myfile_path) and has_space:
775 for mydir in fsmirrors:
776 mirror_file = os.path.join(mydir, myfile)
778 shutil.copyfile(mirror_file, myfile_path)
779 writemsg(_("Local mirror has file: %s\n") % myfile)
781 except (IOError, OSError) as e:
782 if e.errno not in (errno.ENOENT, errno.ESTALE):
787 mystat = os.stat(myfile_path)
789 if e.errno not in (errno.ENOENT, errno.ESTALE):
793 # Skip permission adjustment for symlinks, since we don't
794 # want to modify anything outside of the primary DISTDIR,
795 # and symlinks typically point to PORTAGE_RO_DISTDIRS.
796 if not os.path.islink(myfile_path):
798 apply_secpass_permissions(myfile_path,
799 gid=portage_gid, mode=0o664, mask=0o2,
801 except PortageException as e:
802 if not os.access(myfile_path, os.R_OK):
803 writemsg(_("!!! Failed to adjust permissions:"
804 " %s\n") % (e,), noiselevel=-1)
806 # If the file is empty then it's obviously invalid. Remove
807 # the empty file and try to download if possible.
808 if mystat.st_size == 0:
811 os.unlink(myfile_path)
812 except EnvironmentError:
814 elif myfile not in mydigests:
815 # We don't have a digest, but the file exists. We must
816 # assume that it is fully downloaded.
819 if mystat.st_size < mydigests[myfile]["size"] and \
821 fetched = 1 # Try to resume this download.
822 elif parallel_fetchonly and \
823 mystat.st_size == mydigests[myfile]["size"]:
826 mysettings.get("PORTAGE_QUIET") == "1"
828 "%s size ;-)" % (myfile, ))
832 digests = _filter_unaccelarated_hashes(mydigests[myfile])
833 if hash_filter is not None:
834 digests = _apply_hash_filter(digests, hash_filter)
835 verified_ok, reason = verify_all(myfile_path, digests)
837 writemsg(_("!!! Previously fetched"
838 " file: '%s'\n") % myfile, noiselevel=-1)
839 writemsg(_("!!! Reason: %s\n") % reason[0],
841 writemsg(_("!!! Got: %s\n"
842 "!!! Expected: %s\n") % \
843 (reason[1], reason[2]), noiselevel=-1)
844 if reason[0] == _("Insufficient data for checksum verification"):
848 _checksum_failure_temp_file(
849 mysettings["DISTDIR"], myfile)
850 writemsg_stdout(_("Refetching... "
851 "File renamed to '%s'\n\n") % \
852 temp_filename, noiselevel=-1)
856 mysettings.get("PORTAGE_QUIET", None) == "1"
858 digests = list(digests)
861 "%s %s ;-)" % (myfile, " ".join(digests)))
863 continue # fetch any remaining files
865 # Create a reversed list since that is optimal for list.pop().
866 uri_list = filedict[myfile][:]
868 checksum_failure_count = 0
869 tried_locations = set()
872 # Eliminate duplicates here in case we've switched to
873 # "primaryuri" mode on the fly due to a checksum failure.
874 if loc in tried_locations:
876 tried_locations.add(loc)
878 writemsg_stdout(loc+" ", noiselevel=-1)
880 # allow different fetchcommands per protocol
881 protocol = loc[0:loc.find("://")]
883 global_config_path = GLOBAL_CONFIG_PATH
884 if portage.const.EPREFIX:
885 global_config_path = os.path.join(portage.const.EPREFIX,
886 GLOBAL_CONFIG_PATH.lstrip(os.sep))
888 missing_file_param = False
889 fetchcommand_var = "FETCHCOMMAND_" + protocol.upper()
890 fetchcommand = mysettings.get(fetchcommand_var)
891 if fetchcommand is None:
892 fetchcommand_var = "FETCHCOMMAND"
893 fetchcommand = mysettings.get(fetchcommand_var)
894 if fetchcommand is None:
896 _("!!! %s is unset. It should "
897 "have been defined in\n!!! %s/make.globals.\n") \
898 % (fetchcommand_var, global_config_path),
899 level=logging.ERROR, noiselevel=-1)
901 if "${FILE}" not in fetchcommand:
903 _("!!! %s does not contain the required ${FILE}"
904 " parameter.\n") % fetchcommand_var,
905 level=logging.ERROR, noiselevel=-1)
906 missing_file_param = True
908 resumecommand_var = "RESUMECOMMAND_" + protocol.upper()
909 resumecommand = mysettings.get(resumecommand_var)
910 if resumecommand is None:
911 resumecommand_var = "RESUMECOMMAND"
912 resumecommand = mysettings.get(resumecommand_var)
913 if resumecommand is None:
915 _("!!! %s is unset. It should "
916 "have been defined in\n!!! %s/make.globals.\n") \
917 % (resumecommand_var, global_config_path),
918 level=logging.ERROR, noiselevel=-1)
920 if "${FILE}" not in resumecommand:
922 _("!!! %s does not contain the required ${FILE}"
923 " parameter.\n") % resumecommand_var,
924 level=logging.ERROR, noiselevel=-1)
925 missing_file_param = True
927 if missing_file_param:
929 _("!!! Refer to the make.conf(5) man page for "
930 "information about how to\n!!! correctly specify "
931 "FETCHCOMMAND and RESUMECOMMAND.\n"),
932 level=logging.ERROR, noiselevel=-1)
933 if myfile != os.path.basename(loc):
939 mysize = os.stat(myfile_path).st_size
941 if e.errno not in (errno.ENOENT, errno.ESTALE):
947 writemsg(_("!!! File %s isn't fetched but unable to get it.\n") % myfile,
949 elif size is None or size > mysize:
950 writemsg(_("!!! File %s isn't fully fetched, but unable to complete it\n") % myfile,
953 writemsg(_("!!! File %s is incorrect size, "
954 "but unable to retry.\n") % myfile, noiselevel=-1)
959 if fetched != 2 and has_space:
960 #we either need to resume or start the download
963 mystat = os.stat(myfile_path)
965 if e.errno not in (errno.ENOENT, errno.ESTALE):
970 if mystat.st_size < fetch_resume_size:
971 writemsg(_(">>> Deleting distfile with size "
972 "%d (smaller than " "PORTAGE_FETCH_RESU"
973 "ME_MIN_SIZE)\n") % mystat.st_size)
975 os.unlink(myfile_path)
978 (errno.ENOENT, errno.ESTALE):
984 writemsg(_(">>> Resuming download...\n"))
985 locfetch=resumecommand
986 command_var = resumecommand_var
989 locfetch=fetchcommand
990 command_var = fetchcommand_var
991 writemsg_stdout(_(">>> Downloading '%s'\n") % \
992 _hide_url_passwd(loc))
998 for k in ("DISTDIR", "PORTAGE_SSH_OPTS"):
1000 variables[k] = mysettings[k]
1004 myfetch = shlex_split(locfetch)
1005 myfetch = [varexpand(x, mydict=variables) for x in myfetch]
1009 myret = _spawn_fetch(mysettings, myfetch)
1013 apply_secpass_permissions(myfile_path,
1014 gid=portage_gid, mode=0o664, mask=0o2)
1015 except FileNotFound:
1017 except PortageException as e:
1018 if not os.access(myfile_path, os.R_OK):
1019 writemsg(_("!!! Failed to adjust permissions:"
1020 " %s\n") % str(e), noiselevel=-1)
1023 # If the file is empty then it's obviously invalid. Don't
1024 # trust the return value from the fetcher. Remove the
1025 # empty file and try to download again.
1027 if os.stat(myfile_path).st_size == 0:
1028 os.unlink(myfile_path)
1031 except EnvironmentError:
1034 if mydigests is not None and myfile in mydigests:
1036 mystat = os.stat(myfile_path)
1037 except OSError as e:
1038 if e.errno not in (errno.ENOENT, errno.ESTALE):
1044 if stat.S_ISDIR(mystat.st_mode):
1045 # This can happen if FETCHCOMMAND erroneously
1046 # contains wget's -P option where it should
1049 _("!!! The command specified in the "
1050 "%s variable appears to have\n!!! "
1051 "created a directory instead of a "
1052 "normal file.\n") % command_var,
1053 level=logging.ERROR, noiselevel=-1)
1055 _("!!! Refer to the make.conf(5) "
1056 "man page for information about how "
1057 "to\n!!! correctly specify "
1058 "FETCHCOMMAND and RESUMECOMMAND.\n"),
1059 level=logging.ERROR, noiselevel=-1)
1062 # no exception? file exists. let digestcheck() report
1063 # an appropriately for size or checksum errors
1065 # If the fetcher reported success and the file is
1066 # too small, it's probably because the digest is
1067 # bad (upstream changed the distfile). In this
1068 # case we don't want to attempt to resume. Show a
1069 # digest verification failure to that the user gets
1070 # a clue about what just happened.
1071 if myret != os.EX_OK and \
1072 mystat.st_size < mydigests[myfile]["size"]:
1073 # Fetch failed... Try the next one... Kill 404 files though.
1074 if (mystat[stat.ST_SIZE]<100000) and (len(myfile)>4) and not ((myfile[-5:]==".html") or (myfile[-4:]==".htm")):
1075 html404=re.compile("<title>.*(not found|404).*</title>",re.I|re.M)
1077 _unicode_encode(myfile_path,
1078 encoding=_encodings['fs'], errors='strict'),
1079 mode='r', encoding=_encodings['content'], errors='replace'
1081 if html404.search(f.read()):
1083 os.unlink(mysettings["DISTDIR"]+"/"+myfile)
1084 writemsg(_(">>> Deleting invalid distfile. (Improper 404 redirect from server.)\n"))
1087 except (IOError, OSError):
1092 # File is the correct size--check the checksums for the fetched
1093 # file NOW, for those users who don't have a stable/continuous
1094 # net connection. This way we have a chance to try to download
1095 # from another mirror...
1096 digests = _filter_unaccelarated_hashes(mydigests[myfile])
1097 if hash_filter is not None:
1098 digests = _apply_hash_filter(digests, hash_filter)
1099 verified_ok, reason = verify_all(myfile_path, digests)
1101 writemsg(_("!!! Fetched file: %s VERIFY FAILED!\n") % myfile,
1103 writemsg(_("!!! Reason: %s\n") % reason[0],
1105 writemsg(_("!!! Got: %s\n!!! Expected: %s\n") % \
1106 (reason[1], reason[2]), noiselevel=-1)
1107 if reason[0] == _("Insufficient data for checksum verification"):
1110 _checksum_failure_temp_file(
1111 mysettings["DISTDIR"], myfile)
1112 writemsg_stdout(_("Refetching... "
1113 "File renamed to '%s'\n\n") % \
1114 temp_filename, noiselevel=-1)
1116 checksum_failure_count += 1
1117 if checksum_failure_count == \
1118 checksum_failure_primaryuri:
1119 # Switch to "primaryuri" mode in order
1120 # to increase the probablility of
1123 primaryuri_dict.get(myfile)
1126 reversed(primaryuris))
1127 if checksum_failure_count >= \
1128 checksum_failure_max_tries:
1132 eout.quiet = mysettings.get("PORTAGE_QUIET", None) == "1"
1134 eout.ebegin("%s %s ;-)" % \
1135 (myfile, " ".join(sorted(digests))))
1143 elif mydigests!=None:
1144 writemsg(_("No digest file available and download failed.\n\n"),
1147 if use_locks and file_lock:
1148 unlockfile(file_lock)
1152 writemsg_stdout("\n", noiselevel=-1)
1154 if restrict_fetch and not restrict_fetch_msg:
1155 restrict_fetch_msg = True
1156 msg = _("\n!!! %s/%s"
1157 " has fetch restriction turned on.\n"
1158 "!!! This probably means that this "
1159 "ebuild's files must be downloaded\n"
1160 "!!! manually. See the comments in"
1161 " the ebuild for more information.\n\n") % \
1162 (mysettings["CATEGORY"], mysettings["PF"])
1164 level=logging.ERROR, noiselevel=-1)
1165 elif restrict_fetch:
1169 elif not filedict[myfile]:
1170 writemsg(_("Warning: No mirrors available for file"
1171 " '%s'\n") % (myfile), noiselevel=-1)
1173 writemsg(_("!!! Couldn't download '%s'. Aborting.\n") % myfile,
1177 failed_files.add(myfile)
1180 failed_files.add(myfile)