summaryrefslogtreecommitdiffstats
path: root/extensions/Push/lib/Connector/TCL.pm
blob: b2fb818fdbccf0648f18294086e670f088b0e178 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# 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::Extension::Push::Connector::TCL;

use strict;
use warnings;

use base 'Bugzilla::Extension::Push::Connector::Base';

use Bugzilla::Constants;
use Bugzilla::Extension::Push::Constants;
use Bugzilla::Extension::Push::Serialise;
use Bugzilla::Extension::Push::Util;
use Bugzilla::User;

use Digest::MD5 qw(md5_hex);

sub options {
    return (
        {
            name     => 'tcl_user',
            label    => 'Bugzilla TCL User',
            type     => 'string',
            default  => 'tcl@bugzilla.tld',
            required => 1,
            validate => sub {
                Bugzilla::User->new({ name => $_[0] })
                    || die "Invalid Bugzilla user ($_[0])\n";
            },
        },
        {
            name     => 'sftp_host',
            label    => 'SFTP Host',
            type     => 'string',
            default  => '',
            required => 1,
        },
        {
            name     => 'sftp_port',
            label    => 'SFTP Port',
            type     => 'string',
            default  => '22',
            required => 1,
            validate => sub {
                $_[0] =~ /\D/ && die "SFTP Port must be an integer\n";
            },
        },
        {
            name     => 'sftp_user',
            label    => 'SFTP Username',
            type     => 'string',
            default  => '',
            required => 1,
        },
        {
            name     => 'sftp_pass',
            label    => 'SFTP Password',
            type     => 'password',
            default  => '',
            required => 1,
        },
        {
            name     => 'sftp_remote_path',
            label    => 'SFTP Remote Path',
            type     => 'string',
            default  => '',
            required => 0,
        },
    );
}

my $_instance;

sub init {
    my ($self) = @_;
    $_instance = $self;
}

sub load_config {
    my ($self) = @_;
    $self->SUPER::load_config(@_);
}

sub should_send {
    my ($self, $message) = @_;

    my $data = $message->payload_decoded;
    my $bug_data = $self->_get_bug_data($data)
        || return 0;

    # sanity check user
    $self->{tcl_user} ||= Bugzilla::User->new({ name => $self->config->{tcl_user} });
    if (!$self->{tcl_user} || !$self->{tcl_user}->is_enabled) {
        return 0;
    }

    # only send bugs created by the tcl user
    unless ($bug_data->{reporter}->{id} == $self->{tcl_user}->id) {
        return 0;
    }

    # don't push changes made by the tcl user
    if ($data->{event}->{user}->{id} == $self->{tcl_user}->id) {
        return 0;
    }

    # send comments
    if ($data->{event}->{routing_key} eq 'comment.create') {
        return 0 if $data->{comment}->{is_private};
        return 1;
    }

    # send status and resolution updates
    foreach my $change (@{ $data->{event}->{changes} }) {
        return 1 if $change->{field} eq 'bug_status' || $change->{field} eq 'resolution';
    }

    # and nothing else
    return 0;
}

sub send {
    my ($self, $message) = @_;
    my $logger = Bugzilla->push_ext->logger;
    my $config = $self->config;

    require XML::Simple;
    require Net::SFTP;

    $self->{tcl_user} ||= Bugzilla::User->new({ name => $self->config->{tcl_user} });
    if (!$self->{tcl_user}) {
        return (PUSH_RESULT_TRANSIENT, "Invalid bugzilla-user (" . $self->config->{tcl_user} . ")");
    }

    # load the bug
    my $data = $message->payload_decoded;
    my $bug_data = $self->_get_bug_data($data);

    # build payload
    my %xml = (
        Mozilla_ID => $bug_data->{id},
        When       => $data->{event}->{time},
        Who        => $data->{event}->{user}->{login},
        Status     => $bug_data->{status}->{name},
        Resolution => $bug_data->{resolution},
    );
    if ($data->{event}->{routing_key} eq 'comment.create') {
        $xml{Comment} = $data->{comment}->{body};
    }

    # convert to xml
    my $xml = XML::Simple::XMLout(
        \%xml,
        NoAttr => 1,
        RootName => 'sync',
        XMLDecl => 1,
    );

    # generate md5
    my $md5 = md5_hex($xml);

    # build filename
    my ($sec, $min, $hour, $day, $mon, $year) = localtime(time);
    my $change_set = $data->{event}->{change_set};
    $change_set =~ s/\.//g;
    my $filename = sprintf(
        '%04s%02d%02d%02d%02d%02d%s',
        $year + 1900,
        $mon + 1,
        $day,
        $hour,
        $min,
        $sec,
        $change_set,
    );

    # create temp files;
    my $temp_dir = File::Temp::Directory->new();
    my $local_dir = $temp_dir->dirname;
    _write_file("$local_dir/$filename.sync", $xml);
    _write_file("$local_dir/$filename.sync.check", $md5);
    _write_file("$local_dir/$filename.done", '');

    my $remote_dir = $self->config->{sftp_remote_path} eq ''
        ? ''
        : $self->config->{sftp_remote_path} . '/';

    # send files via sftp
    $logger->debug("Connecting to " . $self->config->{sftp_host} . ":" . $self->config->{sftp_port});
    my $sftp = Net::SFTP->new(
        $self->config->{sftp_host},
        ssh_args => {
            port => $self->config->{sftp_port},
        },
        user => $self->config->{sftp_user},
        password => $self->config->{sftp_pass},
    );

    $logger->debug("Uploading $local_dir/$filename.sync");
    $sftp->put("$local_dir/$filename.sync", "$remote_dir$filename.sync")
        or return (PUSH_RESULT_ERROR, "Failed to upload $local_dir/$filename.sync");

    $logger->debug("Uploading $local_dir/$filename.sync.check");
    $sftp->put("$local_dir/$filename.sync.check", "$remote_dir$filename.sync.check")
        or return (PUSH_RESULT_ERROR, "Failed to upload $local_dir/$filename.sync.check");

    $logger->debug("Uploading $local_dir/$filename.done");
    $sftp->put("$local_dir/$filename.done", "$remote_dir$filename.done")
        or return (PUSH_RESULT_ERROR, "Failed to upload $local_dir/$filename.done");

    # success
    return (PUSH_RESULT_OK, "uploaded $filename.sync");
}

sub _get_bug_data {
    my ($self, $data) = @_;
    my $target = $data->{event}->{target};
    if ($target eq 'bug') {
        return $data->{bug};
    } elsif (exists $data->{$target}->{bug}) {
        return $data->{$target}->{bug};
    } else {
        return;
    }
}

sub _write_file {
    my ($filename, $content) = @_;
    open(my $fh, ">$filename") or die "Failed to write to $filename: $!\n";
    print $fh $content;
    close($fh) or die "Failed to write to $filename: $!\n";
}

1;

# File::Temp->newdir() requires a newer version of File::Temp than we have on
# production, so here's a small inline package which performs the same task.

package File::Temp::Directory;

use strict;
use warnings;

use File::Temp;
use File::Path qw(rmtree);
use File::Spec;

my @chars;

sub new {
    my ($class) = @_;
    my $self = {};
    bless($self, $class);

    @chars = qw/ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
                 a b c d e f g h i j k l m n o p q r s t u v w x y z
                 0 1 2 3 4 5 6 7 8 9 _
               /;

    $self->{TEMPLATE} = File::Spec->catdir(File::Spec->tmpdir, 'X' x 10);
    $self->{DIRNAME} = $self->_mktemp();
    return $self;
}

sub _mktemp {
    my ($self) = @_;
    my $path = $self->_random_name();
    while(1) {
        if (mkdir($path, 0700)) {
            # in case of odd umask
            chmod(0700, $path);
            return $path;
        } else {
            # abort with error if the reason for failure was anything except eexist
            die "Could not create directory $path: $!\n" unless ($!{EEXIST});
            # loop round for another try
        }
        $path = $self->_random_name();
    }

    return $path;
}

sub _random_name {
    my ($self) = @_;
    my $path = $self->{TEMPLATE};
    $path =~ s/X/$chars[int(rand(@chars))]/ge;
    return $path;
}

sub dirname {
    my ($self) = @_;
    return $self->{DIRNAME};
}

sub DESTROY {
    my ($self) = @_;
    local($., $@, $!, $^E, $?);
    if (-d $self->{DIRNAME}) {
        # Some versions of rmtree will abort if you attempt to remove the
        # directory you are sitting in. We protect that and turn it into a
        # warning. We do this because this occurs during object destruction and
        # so can not be caught by the user.
        eval { rmtree($self->{DIRNAME}, 0, 0); };
        warn $@ if ($@ && $^W);
    }
}

1;