Coverage for distro_tracker/core/utils/packages.py: 64%
287 statements
« prev ^ index » next coverage.py v6.5.0, created at 2026-11-25 22:25 +0000
« prev ^ index » next coverage.py v6.5.0, created at 2026-11-25 22:25 +0000
1# Copyright 2013-2018 The Distro Tracker Developers
2# See the COPYRIGHT file at the top-level directory of this distribution and
3# at https://deb.li/DTAuthors
4#
5# This file is part of Distro Tracker. It is subject to the license terms
6# in the LICENSE file found in the top-level directory of this
7# distribution and at https://deb.li/DTLicense. No part of Distro Tracker,
8# including this file, may be copied, modified, propagated, or distributed
9# except according to the terms contained in the LICENSE file.
10"""Utilities for processing Debian package information."""
11import os
12import re
13import shutil
14import subprocess
15import tarfile
17import apt
19import apt_pkg
21from debian import deb822
23from django.conf import settings
24from django.core.validators import URLValidator
25from django.core.exceptions import ValidationError
26from django.urls import reverse
27from django.utils.encoding import force_bytes
29from distro_tracker.core.utils.email_messages import \
30 names_and_addresses_from_string as parse_addresses
33def package_hashdir(package_name):
34 """
35 Returns the name of the hash directory used to avoid having too
36 many entries in a single directory. It's usually the first letter
37 of the package except for lib* packages where it's the first 4
38 letters.
40 :param package_name: The package name.
41 :type package_name: str
43 :returns: Name of the hash directory.
44 :rtype: str
45 """
46 if package_name is None:
47 return None
48 if package_name.startswith('lib'):
49 return package_name[0:4]
50 else:
51 return package_name[0:1]
54def package_url(package_name):
55 """
56 Returns the URL of the page dedicated to this package name.
58 :param package_name: The package name.
59 :type package_name: str or PackageName model
61 :returns: Name of the hash directory.
62 :rtype: str
63 """
64 if package_name is None:
65 return None
66 return reverse('dtracker-package-page',
67 kwargs={'package_name': str(package_name)})
70# Debian Policy 5.6.26: <url> [ " -b " <branch> ] [ " [" <path> "]" ]
71VCS_GIT_RE = re.compile(
72 r'\s*(?P<url>\S+)'
73 r'(?:\s+-b\s*(?P<branch>\S+))?'
74 r'(?:\s+\[(?P<path>[^\]]+)\])?'
75 r'\s*$'
76)
79def extract_vcs_information(stanza):
80 """
81 Extracts the VCS information from a package's Sources entry.
83 :param stanza: The ``Sources`` entry from which to extract the VCS info.
84 Maps ``Sources`` key names to values.
85 :type stanza: dict
87 :returns: VCS information regarding the package. Contains the following
88 keys: type[, browser, url, branch, path]
89 :rtype: dict
90 """
91 vcs = {}
92 for key, value in stanza.items():
93 key = key.lower()
94 if key == 'vcs-browser':
95 vcs['browser'] = value
96 elif key.startswith('vcs-'):
97 vcs['type'] = key[4:]
98 vcs['url'] = value
99 if vcs['type'] == 'git':
100 match = VCS_GIT_RE.match(value)
101 if match:
102 vcs['url'] = match.group('url')
103 for part in ('branch', 'path'):
104 if match.group(part):
105 vcs[part] = match.group(part)
106 return vcs
109def extract_dsc_file_name(stanza):
110 """
111 Extracts the name of the .dsc file from a package's Sources entry.
113 :param stanza: The ``Sources`` entry from which to extract the VCS info.
114 Maps ``Sources`` key names to values.
115 :type stanza: dict
117 """
118 for field in ('checksums-sha256', 'checksums-sha1', 'files'):
119 for entry in stanza.get(field, []):
120 if entry.get('name', '').endswith('.dsc'): 120 ↛ 119line 120 didn't jump to line 119, because the condition on line 120 was never false
121 return entry['name']
123 return None
126def extract_information_from_sources_entry(stanza):
127 """
128 Extracts information from a ``Sources`` file entry and returns it in the
129 form of a dictionary.
131 :param stanza: The raw entry's key-value pairs.
132 :type stanza: Case-insensitive dict
133 """
134 binaries = [
135 binary.strip()
136 for binary in stanza['binary'].split(',')
137 ]
138 entry = {
139 'version': stanza['version'],
140 'homepage': stanza.get('homepage', ''),
141 'priority': stanza.get('priority', ''),
142 'section': stanza.get('section', ''),
143 'architectures': stanza['architecture'].split(),
144 'binary_packages': binaries,
145 'maintainer': parse_addresses(stanza['maintainer'])[0],
146 'uploaders': parse_addresses(stanza.get('uploaders', '')),
147 'standards_version': stanza.get('standards-version', ''),
148 'vcs': extract_vcs_information(stanza),
149 'dsc_file_name': extract_dsc_file_name(stanza),
150 'directory': stanza.get('directory', ''),
151 }
153 # Validate incoming data a little bit
154 try:
155 URLValidator()(entry['homepage'])
156 except ValidationError:
157 entry['homepage'] = ''
159 return entry
162def extract_information_from_packages_entry(stanza):
163 """
164 Extracts information from a ``Packages`` file entry and returns it in the
165 form of a dictionary.
167 :param stanza: The raw entry's key-value pairs.
168 :type stanza: Case-insensitive dict
169 """
170 entry = {
171 'version': stanza['version'],
172 'short_description': stanza.get('description', '')[:300],
173 }
175 return entry
178class SourcePackageRetrieveError(Exception):
179 pass
182class AptCache(object):
183 """
184 A class for handling cached package information.
185 """
186 DEFAULT_MAX_SIZE = 1 * 1024 ** 3 # 1 GiB
187 QUILT_FORMAT = '3.0 (quilt)'
189 class AcquireProgress(apt.progress.base.AcquireProgress):
190 """
191 Instances of this class can be passed to :meth:`apt.cache.Cache.update`
192 calls.
193 It provides a way to track which files were changed and which were not
194 by an update operation.
195 """
196 def __init__(self, *args, **kwargs):
197 super(AptCache.AcquireProgress, self).__init__(*args, **kwargs)
198 self.fetched = []
199 self.hit = []
201 def done(self, item):
202 self.fetched.append(os.path.split(item.owner.destfile)[1])
204 def ims_hit(self, item):
205 self.hit.append(os.path.split(item.owner.destfile)[1])
207 def pulse(self, owner):
208 return True
210 def __init__(self):
211 # The root cache directory is a subdirectory in the
212 # DISTRO_TRACKER_CACHE_DIRECTORY
213 self.cache_root_dir = os.path.join(
214 settings.DISTRO_TRACKER_CACHE_DIRECTORY,
215 'apt-cache'
216 )
217 self.sources_list_path = os.path.join(
218 self.cache_root_dir, 'etc', 'sources.list')
219 self.conf_file_path = os.path.join(self.cache_root_dir,
220 'etc', 'apt.conf')
221 os.environ['APT_CONFIG'] = self.conf_file_path
223 self.sources = []
224 self.packages = []
225 self.cache_max_size = getattr(
226 settings, 'DISTRO_TRACKER_APT_CACHE_MAX_SIZE',
227 self.DEFAULT_MAX_SIZE)
228 #: The directory where source package files are cached
229 self.source_cache_directory = os.path.join(self.cache_root_dir,
230 'packages')
231 self._cache_size = None # Evaluate the cache size lazily
233 self.configure_cache()
235 @property
236 def cache_size(self):
237 if self._cache_size is None:
238 self._cache_size = \
239 self.get_directory_size(self.source_cache_directory)
240 return self._cache_size
242 def get_directory_size(self, directory_path):
243 """
244 Returns the total space taken by the given directory in bytes.
246 :param directory_path: The path to the directory
247 :type directory_path: string
249 :rtype: int
250 """
251 # Convert the directory path to bytes to make sure all os calls deal
252 # with bytes, not unicode objects.
253 # This way any file names with invalid utf-8 names, are correctly
254 # handled, without causing an error.
255 directory_path = force_bytes(directory_path)
256 total_size = 0
257 for dirpath, dirnames, filenames in os.walk(directory_path):
258 for file_name in filenames:
259 file_path = os.path.join(dirpath, file_name)
260 stat = os.lstat(file_path)
261 total_size += stat.st_size
263 return total_size
265 def clear_cache(self):
266 """
267 Removes all cache information. This causes the next update to retrieve
268 fresh repository files.
269 """
270 self._remove_dir(self.cache_root_dir)
271 self.configure_cache()
273 def update_sources_list(self):
274 """
275 Updates the ``sources.list`` file used to list repositories for which
276 package information should be cached.
277 """
278 from distro_tracker.core.models import Repository
280 directory = os.path.dirname(self.sources_list_path)
281 if not os.path.exists(directory):
282 os.makedirs(directory)
284 with open(self.sources_list_path, 'w') as sources_list:
285 for repository in Repository.objects.all():
286 sources_list.write(repository.sources_list_entry + '\n')
288 def update_apt_conf(self):
289 """
290 Updates the ``apt.conf`` file which gives general settings for the
291 :class:`apt.cache.Cache`.
293 In particular, this updates the list of all architectures which should
294 be considered in package updates based on architectures that the
295 repositories support.
296 """
297 from distro_tracker.core.models import Architecture
299 with open(self.conf_file_path, 'w') as conf_file:
300 conf_file.write('APT::Architectures { ')
301 for arch in Architecture.objects.all():
302 conf_file.write(f'"{arch}";')
303 conf_file.write('};\n')
304 conf_file.write('Acquire::CompressionTypes::Order:: "xz";\n')
305 path = self.cache_root_dir
306 conf_file.write(f'Dir "{path}/";\n')
307 conf_file.write('Dir::State "state/";\n')
308 conf_file.write('Dir::State::status "dpkg-status";\n')
309 conf_file.write('Dir::Etc "etc/";\n')
310 path = self.sources_list_path
311 conf_file.write(f'Dir::Etc::sourcelist "{path}";\n')
312 path = settings.DISTRO_TRACKER_TRUSTED_GPG_PARTS_DIR
313 conf_file.write(f'Dir::Etc::TrustedParts "{path}";\n')
315 # Create the corresponding .d directory that APT tries to access
316 # next to its main configuration file
317 os.makedirs(f'{self.conf_file_path}.d', exist_ok=True)
319 def configure_cache(self):
320 """
321 Configures the cache based on the most current repository information.
322 """
323 self.update_sources_list()
324 self.update_apt_conf()
325 # Clean up the configuration we might have read during "import apt"
326 for root_key in apt_pkg.config.list():
327 apt_pkg.config.clear(root_key)
328 # Load the proper configuration
329 apt_pkg.init()
330 # Ensure we have the required directories
331 for apt_dir in [apt_pkg.config.find_dir('Dir::State::lists'),
332 apt_pkg.config.find_dir('Dir::Etc::parts'),
333 apt_pkg.config.find_dir('Dir::Etc::sourceparts'),
334 apt_pkg.config.find_dir('Dir::Etc::preferencesparts'),
335 apt_pkg.config.find_dir('Dir::Cache::archives')]:
336 if not os.path.exists(apt_dir):
337 os.makedirs(apt_dir)
339 def _index_file_full_path(self, file_name):
340 """
341 Returns the absolute path for the given cached index file.
343 :param file_name: The name of the cached index file.
344 :type file_name: string
346 :rtype: string
347 """
348 return os.path.join(
349 apt_pkg.config.find_dir('Dir::State::lists'),
350 file_name
351 )
353 def _match_index_file_to_repository(self, sources_file):
354 """
355 Returns a two-tuple ``(class:`Repository <distro_tracker.core.
356 models.Repository>`, component)``. The class:`Repository
357 <distro_tracker.core.models.Repository>` instance which matches the
358 given cached ``Sources`` file and the ``component`` of the ``Source``.
360 :rtype: (:class:`Repository <distro_tracker.core.models.Repository>`,
361 string)
362 """
363 from distro_tracker.core.models import Repository
365 sources_list = apt_pkg.SourceList()
366 sources_list.read_main_list()
367 component_url = None
368 component = None
369 for entry in sources_list.list:
370 for index_file in entry.index_files:
371 if os.path.basename(sources_file) in index_file.describe:
372 base_url, component, _ = index_file.describe.split(None, 2)
373 base_url = base_url.rstrip('/')
374 component_url = base_url + '/' + component
375 break
377 components = component.split('/')
378 if len(components) >= 2:
379 component = components[1].strip()
381 for repository in Repository.objects.all():
382 if component_url in repository.component_urls:
383 return repository, component
385 def _get_all_cached_files(self):
386 """
387 Returns a list of all cached files.
388 """
389 lists_directory = apt_pkg.config.find_dir('Dir::State::lists')
390 try:
391 return [
392 os.path.join(lists_directory, file_name)
393 for file_name in os.listdir(lists_directory)
394 if os.path.isfile(os.path.join(lists_directory, file_name))
395 ]
396 except OSError:
397 # The directory structure does not exist => nothing is cached
398 return []
400 def get_cached_files(self, filter_function=None):
401 """
402 Returns cached files, optionally filtered by the given
403 ``filter_function``
405 :param filter_function: Takes a file name as the only parameter and
406 returns a :class:`bool` indicating whether it should be included
407 in the result.
408 :type filter_function: callable
410 :returns: A list of cached file names
411 :rtype: list
412 """
413 if filter_function is None: 413 ↛ 415line 413 didn't jump to line 415, because the condition on line 413 was never true
414 # Include all files if the filter function is not provided
415 def filter_function(x):
416 return True
418 return [
419 file_name
420 for file_name in self._get_all_cached_files()
421 if filter_function(file_name)
422 ]
424 def get_sources_files_for_repository(self, repository):
425 """
426 Returns all ``Sources`` files which are cached for the given
427 repository.
429 For instance, ``Sources`` files for different suites are cached
430 separately.
432 :param repository: The repository for which to return all cached
433 ``Sources`` files
434 :type repository: :class:`Repository
435 <distro_tracker.core.models.Repository>`
437 :rtype: ``iterable`` of strings
438 """
439 return self.get_cached_files(
440 lambda file_name: (
441 file_name.endswith('Sources') and
442 self._match_index_file_to_repository(
443 file_name)[0] == repository))
445 def get_packages_files_for_repository(self, repository):
446 """
447 Returns all ``Packages`` files which are cached for the given
448 repository.
450 For instance, ``Packages`` files for different suites are cached
451 separately.
453 :param repository: The repository for which to return all cached
454 ``Packages`` files
455 :type repository: :class:`Repository
456 <distro_tracker.core.models.Repository>`
458 :rtype: ``iterable`` of strings
459 """
460 return self.get_cached_files(
461 lambda file_name: (
462 file_name.endswith('Packages') and
463 self._match_index_file_to_repository(
464 file_name)[0] == repository))
466 def update_repositories(self, force_download=False):
467 """
468 Initiates a cache update.
470 :param force_download: If set to ``True`` causes the cache to be
471 cleared before starting the update, thus making sure all index
472 files are downloaded again.
474 :returns: A two-tuple ``(updated_sources, updated_packages)``. Each of
475 the tuple's members is a list of
476 (:class:`Repository <distro_tracker.core.models.Repository>`,
477 ``component``, ``file_name``) tuple representing the repository
478 which was updated, component, and the file which contains the fresh
479 information. The file is either a ``Sources`` or a ``Packages``
480 file respectively.
481 """
482 if force_download:
483 self.clear_cache()
485 self.configure_cache()
487 cache = apt.Cache(rootdir=self.cache_root_dir)
488 progress = AptCache.AcquireProgress()
489 cache.update(progress)
491 updated_sources = []
492 updated_packages = []
493 for fetched_file in progress.fetched:
494 if fetched_file.endswith('Sources'):
495 dest = updated_sources
496 elif fetched_file.endswith('Packages'):
497 dest = updated_packages
498 else:
499 continue
500 repository, component = self._match_index_file_to_repository(
501 fetched_file)
502 dest.append((
503 repository, component, self._index_file_full_path(fetched_file)
504 ))
506 return updated_sources, updated_packages
508 def _get_format(self, record):
509 """
510 Returns the Format field value of the given source package record.
511 """
512 record = deb822.Deb822(record)
513 return record['format']
515 def _extract_quilt_package_debian_tar(self, debian_tar_path, outdir):
516 """
517 Extracts the given tarball to the given output directory.
518 """
519 with tarfile.open(debian_tar_path) as archive_file:
521 def is_within_directory(directory, target):
522 abs_directory = os.path.abspath(directory)
523 abs_target = os.path.abspath(target)
525 prefix = os.path.commonprefix([abs_directory, abs_target])
527 return prefix == abs_directory
529 def safe_extract(tar, path="."):
530 for member in tar.getmembers():
531 member_path = os.path.join(path, member.name)
532 if not is_within_directory(path, member_path):
533 raise Exception("Attempted Path Traversal in Tar File")
535 tar.extractall(path)
537 safe_extract(archive_file, outdir)
539 def get_package_source_cache_directory(self, package_name):
540 """
541 Returns the path to the directory where a particular source package is
542 cached.
544 :param package_name: The name of the source package
545 :type package_name: string
547 :rtype: string
548 """
549 package_hash = (
550 package_name[0]
551 if not package_name.startswith('lib') else
552 package_name[:4]
553 )
554 return os.path.join(
555 self.source_cache_directory,
556 package_hash,
557 package_name)
559 def get_source_version_cache_directory(self, package_name, version):
560 """
561 Returns the path to the directory where a particular source package
562 version files are extracted.
564 :param package_name: The name of the source package
565 :type package_name: string
567 :param version: The version of the source package
568 :type version: string
570 :rtype: string
571 """
572 package_dir = self.get_package_source_cache_directory(package_name)
573 return os.path.join(package_dir, package_name + '-' + version)
575 def _remove_dir(self, directory_path):
576 """
577 Removes the given directory, including any subdirectories and files.
578 The method makes sure to correctly handle the situation where the
579 directory contains files with names which are invalid utf-8.
580 """
581 # Convert the directory path to bytes to make sure all os calls deal
582 # with bytes, not unicode objects.
583 # This way any file names with invalid utf-8 names, are correctly
584 # handled, without causing an error.
585 directory_path = force_bytes(directory_path)
586 if os.path.exists(directory_path):
587 shutil.rmtree(directory_path)
589 def clear_cached_sources(self):
590 """
591 Clears all cached package source files.
592 """
593 self._remove_dir(self.source_cache_directory)
594 self._cache_size = self.get_directory_size(self.source_cache_directory)
596 def _get_apt_source_records(self, source_name, version):
597 """
598 Returns a :class:`apt_pkg.SourceRecords` instance where the given
599 source package is the current working record.
600 """
601 apt.Cache(rootdir=self.cache_root_dir) # must be pre-created
602 source_records = apt_pkg.SourceRecords()
603 source_records.restart()
604 # Find the cached record matching this source package and version
605 found = False
606 while source_records.lookup(source_name):
607 if source_records.version == version:
608 found = True
609 break
611 if not found:
612 # Package version does not exist in the cache
613 raise SourcePackageRetrieveError(
614 "Could not retrieve package {pkg} version {ver}:"
615 " No such version found in the cache".format(
616 pkg=source_name, ver=version))
618 return source_records
620 def _extract_dpkg_source(self, retrieved_files, outdir):
621 """
622 Uses dpkg-source to extract the source package.
623 """
624 dsc_file_path = next(
625 file_path
626 for file_path in retrieved_files
627 if file_path.endswith('.dsc'))
628 dsc_file_path = os.path.abspath(dsc_file_path)
629 outdir = os.path.abspath(outdir)
630 subprocess.check_output(["dpkg-source", "-x", dsc_file_path, outdir],
631 stderr=subprocess.STDOUT)
633 def _apt_acquire_package(self,
634 source_records,
635 dest_dir_path,
636 debian_directory_only):
637 """
638 Using :class:`apt_pkg.Acquire`, retrieves the source files for the
639 source package described by the current source_records record.
641 :param source_records: The record describing the source package whose
642 files should be retrieved.
643 :type source_records: :class:`apt_pkg.Acquire`
645 :param dest_dir_path: The path to the directory where the downloaded
646 files should be saved.
647 :type dest_dir_path: string
649 :param debian_directory_only: A flag indicating whether only the debian
650 directory should be downloaded.
652 :returns: A list of absolute paths of all retrieved source files.
653 :rtype: list of strings
654 """
655 package_format = self._get_format(source_records.record)
656 # A reference to each AcquireFile instance must be kept
657 files = []
658 acquire = apt_pkg.Acquire(apt.progress.base.AcquireProgress())
659 for srcfile in source_records.files:
660 base = os.path.basename(srcfile.path)
661 dest_file_path = os.path.join(dest_dir_path, base)
662 if debian_directory_only and package_format == self.QUILT_FORMAT:
663 if srcfile.type != 'diff':
664 # Only retrieve the .debian.tar.* file for quilt packages
665 # when only the debian directory is wanted
666 continue
667 files.append(apt_pkg.AcquireFile(
668 acquire,
669 source_records.index.archive_uri(srcfile.path),
670 srcfile.hashes,
671 srcfile.size,
672 base,
673 destfile=dest_file_path
674 ))
676 acquire.run()
678 # Check if all items are correctly retrieved and build the list of file
679 # paths.
680 retrieved_paths = []
681 for item in acquire.items:
682 if item.status != item.STAT_DONE:
683 raise SourcePackageRetrieveError(
684 'Could not retrieve file {file}: {error}'.format(
685 file=item.destfile,
686 error=item.error_text.decode('utf-8')))
687 retrieved_paths.append(item.destfile)
689 return retrieved_paths
691 def retrieve_source(self, source_name, version,
692 debian_directory_only=False):
693 """
694 Retrieve the source package files for the given source package version.
696 :param source_name: The name of the source package
697 :type source_name: string
698 :param version: The version of the source package
699 :type version: string
700 :param debian_directory_only: Flag indicating if the method should try
701 to retrieve only the debian directory of the source package. This
702 is usually only possible when the package format is 3.0 (quilt).
703 :type debian_directory_only: Boolean
705 :returns: The path to the directory containing the extracted source
706 package files.
707 :rtype: string
708 """
709 if self.cache_size > self.cache_max_size:
710 # If the maximum allowed cache size has been exceeded,
711 # clear the cache
712 self.clear_cached_sources()
714 source_records = self._get_apt_source_records(source_name, version)
716 dest_dir_path = self.get_package_source_cache_directory(source_name)
717 if not os.path.exists(dest_dir_path): 717 ↛ 720line 717 didn't jump to line 720, because the condition on line 717 was never false
718 os.makedirs(dest_dir_path)
719 # Remember the size of the directory in the beginning
720 old_size = self.get_directory_size(dest_dir_path)
722 # Download the source files
723 retrieved_files = self._apt_acquire_package(
724 source_records, dest_dir_path, debian_directory_only)
726 # Extract the retrieved source files
727 outdir = self.get_source_version_cache_directory(source_name, version)
728 # dpkg-source expects this directory not to exist
729 self._remove_dir(outdir)
731 package_format = self._get_format(source_records.record)
732 if debian_directory_only and package_format == self.QUILT_FORMAT: 732 ↛ 734line 732 didn't jump to line 734, because the condition on line 732 was never true
733 # dpkg-source cannot extract an incomplete package
734 self._extract_quilt_package_debian_tar(retrieved_files[0], outdir)
735 else:
736 # Let dpkg-source handle the extraction in all other cases
737 self._extract_dpkg_source(retrieved_files, outdir)
739 # Update the current cache size based on the changes made by getting
740 # this source package.
741 new_size = self.get_directory_size(dest_dir_path)
742 size_delta = new_size - old_size
743 self._cache_size += size_delta
745 return outdir
748def html_package_list(packages):
749 """Return a HTML-formatted list of packages."""
750 packages_html = []
751 for package in packages:
752 if "/" in package:
753 (source_package_name, remain) = package.split("/", 1)
754 remain = "/%s" % (remain,)
755 else:
756 (source_package_name, remain) = (package, "")
757 html = '<a href="{}">{}</a>{}'.format(
758 package_url(source_package_name), source_package_name, remain)
759 packages_html.append(html)
761 return ', '.join(packages_html)