upload.py 18.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# Copyright (C) 2012, Ansgar Burchardt <ansgar@debian.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

"""module to handle uploads not yet installed to the archive

This module provides classes to handle uploads not yet installed to the
A
Ansgar Burchardt 已提交
20
archive.  Central is the L{Changes} class which represents a changes file.
21 22 23 24 25
It provides methods to access the included binary and source packages.
"""

import apt_inst
import apt_pkg
26
import errno
27 28
import os
import re
A
Ansgar Burchardt 已提交
29 30 31

from daklib.gpg import SignedFile
from daklib.regexes import *
32
import daklib.packagelist
33

34
class UploadException(Exception):
35 36
    pass

37
class InvalidChangesException(UploadException):
38 39
    pass

40
class InvalidBinaryException(UploadException):
41 42
    pass

43 44 45 46
class InvalidSourceException(UploadException):
    pass

class InvalidHashException(UploadException):
47 48 49 50 51 52
    def __init__(self, filename, hash_name, expected, actual):
        self.filename = filename
        self.hash_name = hash_name
        self.expected = expected
        self.actual = actual
    def __str__(self):
53 54 55 56
        return ("Invalid {0} hash for {1}:\n"
                "According to the control file the {0} hash should be {2},\n"
                "but {1} has {3}.\n"
                "\n"
A
Ansgar Burchardt 已提交
57
                "If you did not include {1} in your upload, a different version\n"
58 59
                "might already be known to the archive software.") \
                .format(self.hash_name, self.filename, self.expected, self.actual)
60

61
class InvalidFilenameException(UploadException):
62 63 64 65 66
    def __init__(self, filename):
        self.filename = filename
    def __str__(self):
        return "Invalid filename '{0}'.".format(self.filename)

67 68 69 70 71 72
class FileDoesNotExist(UploadException):
    def __init__(self, filename):
        self.filename = filename
    def __str__(self):
        return "Refers to non-existing file '{0}'".format(self.filename)

73 74 75 76 77
class HashedFile(object):
    """file with checksums
    """
    def __init__(self, filename, size, md5sum, sha1sum, sha256sum, section=None, priority=None):
        self.filename = filename
A
Ansgar Burchardt 已提交
78 79 80 81
        """name of the file
        @type: str
        """

82
        self.size = size
A
Ansgar Burchardt 已提交
83 84 85 86
        """size in bytes
        @type: long
        """

87
        self.md5sum = md5sum
A
Ansgar Burchardt 已提交
88 89 90 91
        """MD5 hash in hexdigits
        @type: str
        """

92
        self.sha1sum = sha1sum
A
Ansgar Burchardt 已提交
93 94 95 96
        """SHA1 hash in hexdigits
        @type: str
        """

97
        self.sha256sum = sha256sum
A
Ansgar Burchardt 已提交
98 99 100 101
        """SHA256 hash in hexdigits
        @type: str
        """

102
        self.section = section
A
Ansgar Burchardt 已提交
103 104 105 106
        """section or C{None}
        @type: str or C{None}
        """

107
        self.priority = priority
A
Ansgar Burchardt 已提交
108 109 110
        """priority or C{None}
        @type: str of C{None}
        """
111

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
    @classmethod
    def from_file(cls, directory, filename, section=None, priority=None):
        """create with values for an existing file

        Create a C{HashedFile} object that refers to an already existing file.

        @type  directory: str
        @param directory: directory the file is located in

        @type  filename: str
        @param filename: filename

        @type  section: str or C{None}
        @param section: optional section as given in .changes files

        @type  priority: str or C{None}
        @param priority: optional priority as given in .changes files

        @rtype:  L{HashedFile}
        @return: C{HashedFile} object for the given file
        """
        path = os.path.join(directory, filename)
        with open(path, 'r') as fh:
135
            size = os.fstat(fh.fileno()).st_size
136 137 138
            hashes = apt_pkg.Hashes(fh)
        return cls(filename, size, hashes.md5, hashes.sha1, hashes.sha256, section, priority)

139 140 141 142 143
    def check(self, directory):
        """Validate hashes

        Check if size and hashes match the expected value.

A
Ansgar Burchardt 已提交
144 145
        @type  directory: str
        @param directory: directory the file is located in
146

A
Ansgar Burchardt 已提交
147
        @raise InvalidHashException: hash mismatch
148 149 150
        """
        path = os.path.join(directory, self.filename)

151 152 153 154 155 156 157 158 159
        try:
            with open(path) as fh:
                size = os.fstat(fh.fileno()).st_size
                hashes = apt_pkg.Hashes(fh)
        except IOError as e:
            if e.errno == errno.ENOENT:
                raise FileDoesNotExist(self.filename)
            raise

160 161 162
        if size != self.size:
            raise InvalidHashException(self.filename, 'size', self.size, size)

163 164
        if hashes.md5 != self.md5sum:
            raise InvalidHashException(self.filename, 'md5sum', self.md5sum, hashes.md5)
165

166 167
        if hashes.sha1 != self.sha1sum:
            raise InvalidHashException(self.filename, 'sha1sum', self.sha1sum, hashes.sha1)
168

169 170
        if hashes.sha256 != self.sha256sum:
            raise InvalidHashException(self.filename, 'sha256sum', self.sha256sum, hashes.sha256)
171 172 173 174

def parse_file_list(control, has_priority_and_section):
    """Parse Files and Checksums-* fields

A
Ansgar Burchardt 已提交
175 176 177 178 179 180
    @type  control: dict-like
    @param control: control file to take fields from

    @type  has_priority_and_section: bool
    @param has_priority_and_section: Files field include section and priority
                                     (as in .changes)
181

A
Ansgar Burchardt 已提交
182
    @raise InvalidChangesException: missing fields or other grave errors
183

A
Ansgar Burchardt 已提交
184 185
    @rtype:  dict
    @return: dict mapping filenames to L{daklib.upload.HashedFile} objects
186 187 188
    """
    entries = {}

189
    for line in control.get("Files", "").split('\n'):
190 191 192 193 194 195 196 197 198 199 200 201
        if len(line) == 0:
            continue

        if has_priority_and_section:
            (md5sum, size, section, priority, filename) = line.split()
            entry = dict(md5sum=md5sum, size=long(size), section=section, priority=priority, filename=filename)
        else:
            (md5sum, size, filename) = line.split()
            entry = dict(md5sum=md5sum, size=long(size), filename=filename)

        entries[filename] = entry

202
    for line in control.get("Checksums-Sha1", "").split('\n'):
203 204 205 206
        if len(line) == 0:
            continue
        (sha1sum, size, filename) = line.split()
        entry = entries.get(filename, None)
207 208
        if entry is None:
            raise InvalidChangesException('{0} is listed in Checksums-Sha1, but not in Files.'.format(filename))
209
        if entry is not None and entry.get('size', None) != long(size):
210 211 212
            raise InvalidChangesException('Size for {0} in Files and Checksum-Sha1 fields differ.'.format(filename))
        entry['sha1sum'] = sha1sum

213
    for line in control.get("Checksums-Sha256", "").split('\n'):
214 215 216 217
        if len(line) == 0:
            continue
        (sha256sum, size, filename) = line.split()
        entry = entries.get(filename, None)
218 219
        if entry is None:
            raise InvalidChangesException('{0} is listed in Checksums-Sha256, but not in Files.'.format(filename))
220
        if entry is not None and entry.get('size', None) != long(size):
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
            raise InvalidChangesException('Size for {0} in Files and Checksum-Sha256 fields differ.'.format(filename))
        entry['sha256sum'] = sha256sum

    files = {}
    for entry in entries.itervalues():
        filename = entry['filename']
        if 'size' not in entry:
            raise InvalidChangesException('No size for {0}.'.format(filename))
        if 'md5sum' not in entry:
            raise InvalidChangesException('No md5sum for {0}.'.format(filename))
        if 'sha1sum' not in entry:
            raise InvalidChangesException('No sha1sum for {0}.'.format(filename))
        if 'sha256sum' not in entry:
            raise InvalidChangesException('No sha256sum for {0}.'.format(filename))
        if not re_file_safe.match(filename):
            raise InvalidChangesException("{0}: References file with unsafe filename {1}.".format(self.filename, filename))
        f = files[filename] = HashedFile(**entry)

    return files

class Changes(object):
    """Representation of a .changes file
    """
    def __init__(self, directory, filename, keyrings, require_signature=True):
        if not re_file_safe.match(filename):
            raise InvalidChangesException('{0}: unsafe filename'.format(filename))
A
Ansgar Burchardt 已提交
247

248
        self.directory = directory
A
Ansgar Burchardt 已提交
249 250 251 252
        """directory the .changes is located in
        @type: str
        """

253
        self.filename = filename
A
Ansgar Burchardt 已提交
254 255 256 257
        """name of the .changes file
        @type: str
        """

258 259 260
        data = open(self.path).read()
        self._signed_file = SignedFile(data, keyrings, require_signature)
        self.changes = apt_pkg.TagSection(self._signed_file.contents)
A
Ansgar Burchardt 已提交
261 262 263 264
        """dict to access fields of the .changes file
        @type: dict-like
        """

265 266 267 268 269 270 271 272
        self._binaries = None
        self._source = None
        self._files = None
        self._keyrings = keyrings
        self._require_signature = require_signature

    @property
    def path(self):
A
Ansgar Burchardt 已提交
273 274 275
        """path to the .changes file
        @type: str
        """
276 277 278 279
        return os.path.join(self.directory, self.filename)

    @property
    def primary_fingerprint(self):
A
Ansgar Burchardt 已提交
280 281 282
        """fingerprint of the key used for signing the .changes file
        @type: str
        """
283 284 285 286
        return self._signed_file.primary_fingerprint

    @property
    def valid_signature(self):
A
Ansgar Burchardt 已提交
287 288 289
        """C{True} if the .changes has a valid signature
        @type: bool
        """
290 291
        return self._signed_file.valid

292 293 294 295 296 297 298 299
    @property
    def signature_timestamp(self):
        return self._signed_file.signature_timestamp

    @property
    def contents_sha1(self):
        return self._signed_file.contents_sha1

300 301
    @property
    def architectures(self):
A
Ansgar Burchardt 已提交
302 303 304
        """list of architectures included in the upload
        @type: list of str
        """
305
        return self.changes.get('Architecture', '').split()
306 307 308

    @property
    def distributions(self):
A
Ansgar Burchardt 已提交
309 310 311
        """list of target distributions for the upload
        @type: list of str
        """
312 313 314 315
        return self.changes['Distribution'].split()

    @property
    def source(self):
A
Ansgar Burchardt 已提交
316 317 318
        """included source or C{None}
        @type: L{daklib.upload.Source} or C{None}
        """
319 320 321 322 323 324 325 326 327
        if self._source is None:
            source_files = []
            for f in self.files.itervalues():
                if re_file_dsc.match(f.filename) or re_file_source.match(f.filename):
                    source_files.append(f)
            if len(source_files) > 0:
                self._source = Source(self.directory, source_files, self._keyrings, self._require_signature)
        return self._source

328 329 330 331 332 333 334
    @property
    def sourceful(self):
        """C{True} if the upload includes source
        @type: bool
        """
        return "source" in self.architectures

335 336 337 338 339 340 341
    @property
    def source_name(self):
        """source package name
        @type: str
        """
        return re_field_source.match(self.changes['Source']).group('package')

342 343
    @property
    def binaries(self):
A
Ansgar Burchardt 已提交
344 345 346
        """included binary packages
        @type: list of L{daklib.upload.Binary}
        """
347 348 349 350 351 352 353 354 355 356
        if self._binaries is None:
            binaries = []
            for f in self.files.itervalues():
                if re_file_binary.match(f.filename):
                    binaries.append(Binary(self.directory, f))
            self._binaries = binaries
        return self._binaries

    @property
    def byhand_files(self):
A
Ansgar Burchardt 已提交
357 358 359
        """included byhand files
        @type: list of L{daklib.upload.HashedFile}
        """
360 361 362 363 364 365 366 367 368 369 370 371 372
        byhand = []

        for f in self.files.itervalues():
            if re_file_dsc.match(f.filename) or re_file_source.match(f.filename) or re_file_binary.match(f.filename):
                continue
            if f.section != 'byhand' and f.section[:4] != 'raw-':
                raise InvalidChangesException("{0}: {1} looks like a byhand package, but is in section {2}".format(self.filename, f.filename, f.section))
            byhand.append(f)

        return byhand

    @property
    def binary_names(self):
A
Ansgar Burchardt 已提交
373 374 375
        """names of included binary packages
        @type: list of str
        """
376 377 378 379
        return self.changes['Binary'].split()

    @property
    def closed_bugs(self):
A
Ansgar Burchardt 已提交
380 381 382
        """bugs closed by this upload
        @type: list of str
        """
383 384 385 386
        return self.changes.get('Closes', '').split()

    @property
    def files(self):
A
Ansgar Burchardt 已提交
387 388 389
        """dict mapping filenames to L{daklib.upload.HashedFile} objects
        @type: dict
        """
390 391 392 393 394 395
        if self._files is None:
            self._files = parse_file_list(self.changes, True)
        return self._files

    @property
    def bytes(self):
A
Ansgar Burchardt 已提交
396 397 398
        """total size of files included in this upload in bytes
        @type: number
        """
399 400 401 402 403 404
        count = 0
        for f in self.files.itervalues():
            count += f.size
        return count

    def __cmp__(self, other):
A
Ansgar Burchardt 已提交
405
        """compare two changes files
406 407 408 409 410 411

        We sort by source name and version first.  If these are identical,
        we sort changes that include source before those without source (so
        that sourceful uploads get processed first), and finally fall back
        to the filename (this should really never happen).

A
Ansgar Burchardt 已提交
412 413
        @rtype:  number
        @return: n where n < 0 if self < other, n = 0 if self == other, n > 0 if self > other
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
        """
        ret = cmp(self.changes.get('Source'), other.changes.get('Source'))

        if ret == 0:
            # compare version
            ret = apt_pkg.version_compare(self.changes.get('Version', ''), other.changes.get('Version', ''))

        if ret == 0:
            # sort changes with source before changes without source
            if 'source' in self.architectures and 'source' not in other.architectures:
                ret = -1
            elif 'source' not in self.architectures and 'source' in other.architectures:
                ret = 1
            else:
                ret = 0

        if ret == 0:
            # fall back to filename
            ret = cmp(self.filename, other.filename)

        return ret

class Binary(object):
    """Representation of a binary package
    """
    def __init__(self, directory, hashed_file):
        self.hashed_file = hashed_file
A
Ansgar Burchardt 已提交
441 442 443
        """file object for the .deb
        @type: HashedFile
        """
444 445 446

        path = os.path.join(directory, hashed_file.filename)
        data = apt_inst.DebFile(path).control.extractdata("control")
A
Ansgar Burchardt 已提交
447

448
        self.control = apt_pkg.TagSection(data)
A
Ansgar Burchardt 已提交
449 450 451
        """dict to access fields in DEBIAN/control
        @type: dict-like
        """
452

453 454 455 456 457
    @classmethod
    def from_file(cls, directory, filename):
        hashed_file = HashedFile.from_file(directory, filename)
        return cls(directory, hashed_file)

458 459
    @property
    def source(self):
A
Ansgar Burchardt 已提交
460 461
        """get tuple with source package name and version
        @type: tuple of str
462 463 464 465 466 467 468 469 470 471 472 473
        """
        source = self.control.get("Source", None)
        if source is None:
            return (self.control["Package"], self.control["Version"])
        match = re_field_source.match(source)
        if not match:
            raise InvalidBinaryException('{0}: Invalid Source field.'.format(self.hashed_file.filename))
        version = match.group('version')
        if version is None:
            version = self.control['Version']
        return (match.group('package'), version)

474 475 476 477
    @property
    def name(self):
        return self.control['Package']

478 479
    @property
    def type(self):
A
Ansgar Burchardt 已提交
480 481
        """package type ('deb' or 'udeb')
        @type: str
482 483 484 485 486 487 488 489
        """
        match = re_file_binary.match(self.hashed_file.filename)
        if not match:
            raise InvalidBinaryException('{0}: Does not match re_file_binary'.format(self.hashed_file.filename))
        return match.group('type')

    @property
    def component(self):
A
Ansgar Burchardt 已提交
490 491 492
        """component name
        @type: str
        """
493 494 495 496 497 498 499 500 501 502
        fields = self.control['Section'].split('/')
        if len(fields) > 1:
            return fields[0]
        return "main"

class Source(object):
    """Representation of a source package
    """
    def __init__(self, directory, hashed_files, keyrings, require_signature=True):
        self.hashed_files = hashed_files
A
Ansgar Burchardt 已提交
503 504 505 506
        """list of source files (including the .dsc itself)
        @type: list of L{HashedFile}
        """

507 508 509 510 511 512 513
        self._dsc_file = None
        for f in hashed_files:
            if re_file_dsc.match(f.filename):
                if self._dsc_file is not None:
                    raise InvalidSourceException("Multiple .dsc found ({0} and {1})".format(self._dsc_file.filename, f.filename))
                else:
                    self._dsc_file = f
514 515 516 517

        # make sure the hash for the dsc is valid before we use it
        self._dsc_file.check(directory)

518 519 520 521
        dsc_file_path = os.path.join(directory, self._dsc_file.filename)
        data = open(dsc_file_path, 'r').read()
        self._signed_file = SignedFile(data, keyrings, require_signature)
        self.dsc = apt_pkg.TagSection(self._signed_file.contents)
A
Ansgar Burchardt 已提交
522 523 524 525
        """dict to access fields in the .dsc file
        @type: dict-like
        """

526 527 528 529 530
        self.package_list = daklib.packagelist.PackageList(self.dsc)
        """Information about packages built by the source.
        @type: daklib.packagelist.PackageList
        """

531 532
        self._files = None

533 534 535 536 537
    @classmethod
    def from_file(cls, directory, filename, keyrings, require_signature=True):
        hashed_file = HashedFile.from_file(directory, filename)
        return cls(directory, [hashed_file], keyrings, require_signature)

538 539
    @property
    def files(self):
A
Ansgar Burchardt 已提交
540 541 542 543 544 545
        """dict mapping filenames to L{HashedFile} objects for additional source files

        This list does not include the .dsc itself.

        @type: dict
        """
546 547 548 549 550 551
        if self._files is None:
            self._files = parse_file_list(self.dsc, False)
        return self._files

    @property
    def primary_fingerprint(self):
A
Ansgar Burchardt 已提交
552 553 554
        """fingerprint of the key used to sign the .dsc
        @type: str
        """
555 556 557 558
        return self._signed_file.primary_fingerprint

    @property
    def valid_signature(self):
A
Ansgar Burchardt 已提交
559 560 561
        """C{True} if the .dsc has a valid signature
        @type: bool
        """
562 563 564 565
        return self._signed_file.valid

    @property
    def component(self):
A
Ansgar Burchardt 已提交
566 567 568 569 570 571
        """guessed component name

        Might be wrong. Don't rely on this.

        @type: str
        """
572 573 574 575 576 577
        if 'Section' not in self.dsc:
            return 'main'
        fields = self.dsc['Section'].split('/')
        if len(fields) > 1:
            return fields[0]
        return "main"
578 579 580 581 582 583 584

    @property
    def filename(self):
        """filename of .dsc file
        @type: str
        """
        return self._dsc_file.filename