Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 156 additions & 0 deletions Bugzilla/Attachment/Zip.pm
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# This Source Code Form is "Incompatible With Secondary Licenses", as
# defined by the Mozilla Public License, v. 2.0.

package Bugzilla::Attachment::Zip;

use 5.10.1;
use strict;
use warnings;

use Bugzilla::Attachment;
use Bugzilla::Error;
use Bugzilla::Util qw(datetime_from);

use Encode qw(encode);
use IO::Compress::Zip qw($ZipError);
use List::Util qw(sum0);

# Most filesystems cap one file name at 255 bytes.
use constant MAX_NAME_BYTES => 255;

# Returns the attachments of $bug the current user may download as a ZIP:
# those get_attachments_by_bug lets them see, minus obsolete and deleted
# ones. The caller must already have checked that the user can see $bug
# (Bugzilla::Bug->check does).
sub attachments_for_bug {
my ($class, $bug) = @_;
my $user = Bugzilla->user;
my $attachments
= Bugzilla::Attachment->get_attachments_by_bug($bug, {exclude_obsolete => 1});

# get_attachments_by_bug checks privacy and obsolescence on the ids and then
# loads the rows in a second query, so check both again on the rows as
# loaded, as the bug page does.
return [
grep {
$_->datasize
&& !$_->isobsolete
&& (!$_->isprivate || $user->is_insider || $_->attacher->id == $user->id)
} @$attachments
];
}

# Throws a user error unless there is something to download and its total
# size is within the attachment_zip_max_size param (in kilobytes). Runs on
# datasize alone, so no attachment data is fetched from storage for a
# request that will be refused.
sub check_size {
my ($class, $attachments) = @_;
@$attachments || ThrowUserError('attachment_zip_empty');

$class->_check_limit(sum0(map { $_->datasize } @$attachments));
return;
}

# Throws a user error if $total_size bytes is over the attachment_zip_max_size
# param (in kilobytes).
sub _check_limit {
my ($class, $total_size) = @_;
my $max_size = Bugzilla->params->{attachment_zip_max_size} * 1024;
if ($total_size > $max_size) {
ThrowUserError('attachment_zip_too_large',
{total_size => $total_size, max_size => $max_size});
}
return;
}

# Returns the bytes of a ZIP file holding $attachments. Each member is named
# "<attach_id>-<filename>", so two attachments with the same filename do not
# overwrite each other when the archive is extracted.
#
# check_size works from datasize, which can differ from the bytes in storage
# (it counts characters for pasted text), so the bytes actually read are
# held to the same limit here.
sub build {
my ($class, $attachments) = @_;
my $read_size = 0;
my $output = '';
my $zip;

foreach my $attachment (@$attachments) {

# Read through the storage, not $attachment->data, which would keep every
# attachment's data cached in memory alongside the ZIP until the request
# ends. Database and filesystem storage return undef for data that has
# gone since the attachment was loaded, such as one deleted meanwhile.
my $data = $attachment->current_storage->get_data;
if (!defined $data) {
ThrowCodeError('attachment_zip_missing_data', {attach_id => $attachment->id});
}

$class->_check_limit($read_size += length $data);

# Efs marks the name as UTF-8 but does not encode it, so encode it here.
my %member = (
Name => encode('UTF-8', $class->member_name($attachment)),
Time => datetime_from($attachment->attached)->epoch,
Efs => 1,
);

# IO::Compress::Zip takes the first member's header from new() and each
# later one from newStream().
my $ok
= $zip
? $zip->newStream(%member)
: ($zip = IO::Compress::Zip->new(\$output, %member));

$ok && $zip->print($data)
or ThrowCodeError('attachment_zip_failed', {zip_error => $ZipError});
}
$zip && $zip->close()
or ThrowCodeError('attachment_zip_failed', {zip_error => $ZipError});

return \$output;
}

# The name of $attachment inside the ZIP. Path separators and drive letters
# become "_", so no name can make an extractor write outside its target
# directory, and so do control characters and the other characters Windows
# does not allow in a file name. Trailing periods and spaces, which Windows
# drops or refuses, are removed. Names too long for a filesystem lose the end
# of their stem, keeping the extension.
sub member_name {
my ($class, $attachment) = @_;
my $filename = $attachment->filename // '';
$filename =~ s/[\x00-\x1f\x7f<>:"\/\\|?*]/_/g;
$filename =~ s/[. ]+$//;
$filename = 'attachment' if $filename eq '';

my ($stem, $extension)
= ($attachment->id . '-' . $filename) =~ /^(.*?)((?:\.[^.]{1,16})?)$/s;
chop $stem while length(encode('UTF-8', $stem . $extension)) > MAX_NAME_BYTES;

# Cutting the stem short can leave a period or space at the end again.
(my $name = $stem . $extension) =~ s/[. ]+$//;
return $name;
}

1;

__END__

=head1 NAME

Bugzilla::Attachment::Zip - Download all of a bug's attachments as a ZIP

=head1 SYNOPSIS

my $bug = Bugzilla::Bug->check({id => $bug_id});
my $attachments = Bugzilla::Attachment::Zip->attachments_for_bug($bug);
Bugzilla::Attachment::Zip->check_size($attachments);
my $zip_ref = Bugzilla::Attachment::Zip->build($attachments);

6 changes: 6 additions & 0 deletions Bugzilla/Config/Attachment.pm
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ sub get_param_list {
default => '1000',
checker => \&check_maxattachmentsize
},
{
name => 'attachment_zip_max_size',
type => 't',
default => '51200',
checker => \&check_numeric
},
{
name => 'attachment_storage',
type => 's',
Expand Down
35 changes: 35 additions & 0 deletions attachment.cgi
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ use Bugzilla::Bug;
use Bugzilla::Field;
use Bugzilla::Attachment;
use Bugzilla::Attachment::PatchReader;
use Bugzilla::Attachment::Zip;
use Bugzilla::Token;
use Bugzilla::Keyword;
use Bugzilla::Hook;
Expand Down Expand Up @@ -92,6 +93,12 @@ elsif ($action eq "diff") {
elsif ($action eq "viewall") {
viewall();
}
elsif ($action eq "zip") {

# Building a ZIP of every attachment is costly, so anonymous users may not.
Bugzilla->login(LOGIN_REQUIRED);
zip_all();
}
elsif ($action eq "enter") {
Bugzilla->login(LOGIN_REQUIRED);
enter();
Expand Down Expand Up @@ -496,6 +503,34 @@ sub viewall {
|| ThrowTemplateError($template->error());
}

# Download every attachment of a bug the user can access, except obsolete
# ones, as a single ZIP file. The ZIP is served as a download, never inline,
# so it does not need the attachment_base host.
sub zip_all {
my $bug = Bugzilla::Bug->check({id => scalar $cgi->param('bugid'), cache => 1});

my $attachments = Bugzilla::Attachment::Zip->attachments_for_bug($bug);
Bugzilla::Attachment::Zip->check_size($attachments);
my $zip_ref = Bugzilla::Attachment::Zip->build($attachments);
Comment thread
dklawren marked this conversation as resolved.
Resolved

foreach my $attachment (@$attachments) {
Bugzilla->log_user_request($bug->id, $attachment->id, 'attachment-get');
}

# A ZIP is binary: send no charset, as view() does.
$cgi->charset('');
my $filename = 'bug-' . $bug->id . '-attachments.zip';
print $cgi->header(
-type => 'application/zip',
-content_disposition => qq{attachment; filename="$filename"},
-content_length => length($$zip_ref),
-Cache_Control => 'no-store, private',
-X_Content_Type_Options => 'nosniff',
);
disable_utf8();
print $$zip_ref;
}

# Display a form for entering a new attachment.
sub enter {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
# obsolete_attachments: count of obsolete attachment objects
# external_attachments: count of non-obsolete external attachments
# external_attachments_total: count of all external attachments (incl. obsolete)
# downloadable_attachments: count of active attachments with data, i.e. the
# ones the "Download All (ZIP)" button gets
# attachment_hide_types: hash of content types hidden behind "Show External"
#%]

Expand Down Expand Up @@ -105,6 +107,11 @@
<button type="button" role="none" id="attachments-add-btn" class="secondary">Attach New File</button>
</a>
[% END %]
[% IF user.id && downloadable_attachments %]
[%# A plain button, not a form: this template sits inside #changeform. %]
<button type="button" id="attachments-zip-btn" class="secondary"
data-href="[% basepath FILTER none %]attachment.cgi?bugid=[% bug.id FILTER uri %]&amp;action=zip">Download All (ZIP)</button>
[% END %]
[% IF external_attachments_total %]
<button type="button" id="attachments-external-btn" class="secondary">Show External</button>
[% END %]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@
# External" button is still rendered (and the rows remain reachable) when
# every external attachment happens to be obsolete.
external_attachments_total = 0;
# downloadable_attachments matches what attachment.cgi?action=zip serves:
# active attachments whose data has not been deleted.
downloadable_attachments = 0;

attachment_hide_types = {};
IF Param('attachment_hide_content_types');
Expand All @@ -74,6 +77,9 @@
obsolete_attachments = obsolete_attachments + 1;
ELSE;
active_attachments = active_attachments + 1;
IF attachment.datasize;
downloadable_attachments = downloadable_attachments + 1;
END;
IF is_external;
external_attachments = external_attachments + 1;
END;
Expand Down Expand Up @@ -1442,6 +1448,7 @@
obsolete_attachments = obsolete_attachments
external_attachments = external_attachments
external_attachments_total = external_attachments_total
downloadable_attachments = downloadable_attachments
attachment_hide_types = attachment_hide_types
%]
[% END %]
Expand Down
5 changes: 5 additions & 0 deletions extensions/BugModal/web/bug_modal.js
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,11 @@ $(function() {
updateAttachmentRows();
}

$('#attachments-zip-btn').click(function(event) {
event.preventDefault();
window.location.href = this.dataset.href;
});

// top btn
$('#top-btn')
.click(function(event) {
Expand Down
Loading