Frontend.pm 31 KB
Newer Older
intrigeri's avatar
intrigeri committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
=head1 NAME

Tails::IUK::Frontend - lead Tails user through the process of upgrading the system, if needed

=cut

package Tails::IUK::Frontend;

use 5.10.1;
use strictures 2;

use autodie qw(:all);
use Carp;
use Carp::Assert;
use Carp::Assert::More;
use English qw{-no_match_vars};
use Env;
use Function::Parameters;
use IPC::Run;
20
use List::Util qw(reduce);
21
22
23
use Locale::Messages qw{bind_textdomain_codeset
                        bind_textdomain_filter
                        turn_utf_8_on};
intrigeri's avatar
intrigeri committed
24
use Path::Tiny;
25
use POSIX;
intrigeri's avatar
intrigeri committed
26
use String::Errf qw{errf};
27
use Tails::Download::HTTPS;
intrigeri's avatar
intrigeri committed
28
use Tails::RunningSystem;
intrigeri's avatar
Sort    
intrigeri committed
29
use Tails::IUK::DownloadProgress;
intrigeri's avatar
intrigeri committed
30
31
32
33
34
use Tails::IUK::UpgradeDescriptionFile;
use Tails::IUK::Utils qw{space_available_in};
use Tails::MirrorPool;
use Try::Tiny;
use Types::Path::Tiny qw{AbsDir AbsFile};
35
use Types::Standard qw(ArrayRef Bool CodeRef Defined HashRef InstanceOf Int Maybe Str Object);
intrigeri's avatar
intrigeri committed
36

37
38
39
40
41
BEGIN {
    bind_textdomain_filter 'tails', \&turn_utf_8_on;
    bind_textdomain_codeset 'tails', 'utf-8';
}

intrigeri's avatar
intrigeri committed
42
43
44
45
46
no Moo::sification;
use Moo;
use MooX::HandlesVia;

with 'Tails::Role::HasEncoding';
tous's avatar
tous committed
47
with 'Tails::IUK::Role::FormatByte';
intrigeri's avatar
intrigeri committed
48
49
50

use namespace::clean;

51
52
53
54
# Must be after namespace::clean, so that we can use "around" for the "__"
# function.
use Locale::TextDomain 'tails';

intrigeri's avatar
intrigeri committed
55
56
use MooX::Options;

57
58
59
60
61
62
63
64
65
66
67
# Workaround the fact MooX::Options is incompatible with Locale::TextDomain
# (it needs a __ method, which it injects via MooX::Locale::Passthrough,
# but that does not go well when Locale::TextDomain is loaded).
around __ => sub {
    my $orig = shift;
    # if called as a class or object method,
    # let's ignore the second argument ($self)
    shift if ref $_[0] or $_[0] eq __PACKAGE__;
    my $msgid = shift;
    Locale::TextDomain::__($msgid);
};
intrigeri's avatar
intrigeri committed
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

=head1 ATTRIBUTES

=cut

option "override_$_" => (
    is        => 'lazy',
    isa       => Str,
    format    => 's',
    predicate => 1,
) for (qw{baseurl build_target trusted_gnupg_homedir});

option override_initial_install_os_release_file =>
    is        => 'lazy',
    isa       => AbsFile,
    coerce    => AbsFile->coercion,
    format    => 's',
    predicate => 1;

option override_os_release_file =>
    is        => 'lazy',
    isa       => AbsFile,
    coerce    => AbsFile->coercion,
    format    => 's',
    predicate => 1;

option "override_$_" => (
    isa        => AbsDir,
    is         => 'ro',
    lazy_build => 1,
    coerce     => AbsDir->coercion,
    format     => 's',
    predicate  => 1,
) for (qw{dev_dir liveos_mountpoint proc_dir run_dir});

option batch =>
    is  => 'lazy',
    isa => Bool;

option 'override_started_from_device_installed_with_tails_installer' =>
    is            => 'lazy',
    isa           => Str,
    format        => 's',
    predicate     => 1,
    documentation => q{Internal, for test suite only};

has 'running_system' =>
    is      => 'lazy',
    isa     => InstanceOf['Tails::RunningSystem'],
    handles => [
        qw{upgrade_description_file_url upgrade_description_sig_url},
        qw{product_name initial_install_version build_target channel}
    ];

has 'free_space' =>
    is            => 'lazy',
    isa           => Int,
    documentation => q{Free space (in bytes) on the system partition};

option 'override_free_space' =>
    is            => 'lazy',
    isa           => Int,
    format        => 'i',
    predicate     => 1,
    documentation => q{Internal, for test suite only};


=head1 CONSTRUCTORS AND BUILDERS

=cut

method _build_batch () { 0; }

method _build_running_system () {
    my @args;
    for (qw{baseurl build_target dev_dir liveos_mountpoint},
         qw{os_release_file initial_install_os_release_file},
         qw{proc_dir run_dir}) {
        my $attribute = "override_$_";
        my $predicate = "has_$attribute";
        if ($self->$predicate) {
            push @args, ($_ => $self->$attribute)
        }
    }
    if ($self->has_override_started_from_device_installed_with_tails_installer) {
        push @args, (
            override_started_from_device_installed_with_tails_installer
                => $self->override_started_from_device_installed_with_tails_installer
        );
    }
    Tails::RunningSystem->new(@args);
}

method _build_free_space () {
    $self->has_override_free_space
        ? $self->override_free_space
        : space_available_in($self->running_system->liveos_mountpoint);
}

=head1 METHODS

=cut

method fatal (Str $msg, Str :$title, Str :$debugging_info) {
172
    say STDERR $self->encoding->encode("$title\n$msg\n$debugging_info");
intrigeri's avatar
intrigeri committed
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
    $self->dialog($msg, type => 'error', title => $title) unless $self->batch;
    croak($self->encoding->encode("$title\n$msg\n$debugging_info"));
}

method info (Str $msg) {
    say $self->encoding->encode($msg);
}

method fatal_run_cmd (Str :$error_msg, ArrayRef :$cmd, Maybe[Str] :$as = undef, Str :$error_title) {
    my @cmd       = @{$cmd};

    if (defined $as && ! $ENV{HARNESS_ACTIVE}) {
        @cmd = ('sudo', '-n', '-u', $as, @cmd);
    }

    my ($stdout, $stderr);
    my $success = 1;
    my $exit_code;
    IPC::Run::run \@cmd, '>', \$stdout, '2>', \$stderr or $success = 0;
    $exit_code = $?;
    $success or $self->fatal(
        errf("<b>%{error_msg}s</b>\n\n%{details}s",
             {
196
197
                 error_msg => $error_msg,
                 details   => __(
intrigeri's avatar
intrigeri committed
198
                     q{For debugging information, execute the following command: sudo tails-debugging-info}
199
                 ),
intrigeri's avatar
intrigeri committed
200
201
202
203
204
205
206
             },
         ),
        title          => $error_title,
        debugging_info => $self->encoding->decode(errf(
            "exit code: %{exit_code}i\n\n".
            "stdout:\n%{stdout}s\n\n".
            "stderr:\n%{stderr}s",
207
            { exit_code => $exit_code, stdout => $stdout, stderr => $stderr },
intrigeri's avatar
intrigeri committed
208
209
210
211
212
213
        )),
    );

    return ($stdout, $stderr, $success, $exit_code);
}

tous's avatar
tous committed
214
method init_zenity_progress_dialog_text ((InstanceOf['Tails::IUK::DownloadProgress']) $download_progress) {
215
216
217
218
    # Zenity doesn't resize the width of the progress
    # dialog if a text is bigger than the initial text.
    # So let's give to the progress dialog initial text
    # a value that avoids zenity break download_progress->info
intrigeri's avatar
intrigeri committed
219
    # into a new line.
220

tous's avatar
tous committed
221

222
223
224
225
226
227
228
    my $time_left_str = reduce {length $a > length $b ? $a : $b} map {
        my $time_key  = $_;
        my $max_time  = $time_key eq 'hour' ? 23 : 59;
        map {
            $download_progress->time_duration->{$time_key}->($_)
        }1 .. $max_time;
    } qw{second minute hour day};
tous's avatar
tous committed
229
230
    $time_left_str =  $time_left_str . ' ' . $time_left_str;

231
232
    my $byte_unit = reduce {length $a > length $b ? $a : $b} map {
        $self->format_bytes(1024**$_)}0 .. 3;
tous's avatar
tous committed
233
234
235
236
237
238
239
240
241
242
243
    $byte_unit =~ s/\d+//;

    my $big_str       = '000000' . $byte_unit;
    my $init_text     = $download_progress->info;
    my $size_left_str = $self->format_bytes($download_progress->last_byte_downloaded);
    my $unknow_str    = $download_progress->estimated_end_time;

    $init_text =~ s/\Q$unknow_str\E/$time_left_str/;
    $init_text =~ s/\Q$size_left_str\E/$big_str/;
    $init_text =~ s/\(0.+\//($big_str\//;

intrigeri's avatar
intrigeri committed
244
245
    $init_text = $download_progress->info
        if length ($download_progress->info) > length($init_text);
246
247
248
249

    return $init_text;
}

intrigeri's avatar
intrigeri committed
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
method dialog (Str $question, Str :$type = 'question', Str :$title,
               Maybe[Str] :$ok_label = undef, Maybe[Str] :$cancel_label = undef) {
    if ($type ne 'question' && $type ne 'info') {
        assert_undefined($ok_label);
    }
    if ($type ne 'question') {
        assert_undefined($cancel_label);
    }
    my @cmd  = ('zenity', "--$type", '--ellipsize', '--text', $question);
    my $info = $question;
    if (defined $title) {
        $info = "$title\n$info";
        push @cmd, ('--title', $title);
    }
    if (defined $ok_label) {
        $info = "$info: $ok_label";
        push @cmd, ('--ok-label', $ok_label);
    }
    if (defined $cancel_label) {
        $info = "$info / $cancel_label";
        push @cmd, ('--cancel-label', $cancel_label);
    }
    $self->info($info);
    return 1 if $self->batch;
    system(@cmd);
    ${^CHILD_ERROR_NATIVE} == 0;
}

method upgrader_run_dir () {
    $self->running_system->run_dir->child('tails-upgrader');
}

method checked_upgrades_file () {
    $self->upgrader_run_dir->child('checked_upgrades');
}

286
method refresh_signing_key () {
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
    my ($error_msg, $new_key_content);
    $error_msg =
        __(
            q{<b>An error occured while updating the signing key.</b>\n\n}.
            q{<b>This prevents determining whether an upgrade is available from our website.</b>\n\n}.
            q{Check your network connection, and restart Tails to try upgrading again.\n\n}.
            q{If the problem persists, go to file:///usr/share/doc/tails/website/doc/upgrade/error/check.en.html},
        );
    try {
        $new_key_content = Tails::Download::HTTPS->new(
            max_download_size => 128 * 2**10,
            )->get_url(
                $self->running_system->baseurl . '/tails-signing-minimal.key'
            );
    } catch {
        $self->fatal(
            $error_msg,
            title => __(q{Error while downloading the signing key}),
            debugging_info => $self->encoding->decode($_),
        );
    };
308
309
310
311
312
313
314
    my ($stdout, $stderr, $exit_code);
    my $success = 1;
    IPC::Run::run ['gpg', '--import'],
          '<', \$new_key_content, '>', \$stdout, '2>', \$stderr
          or $success = 0;
    $exit_code = $?;
    $success or $self->fatal(
315
        $error_msg,
316
        title => __(q{Error while updating the signing key}),
317
318
319
320
321
322
323
324
325
        debugging_info => $self->encoding->decode(errf(
            "exit code: %{exit_code}i\n\n".
            "stdout:\n%{stdout}s\n\n".
            "stderr:\n%{stderr}s",
            { exit_code => $exit_code, stdout => $stdout, stderr => $stderr }
        )),
    );
}

intrigeri's avatar
intrigeri committed
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
method get_upgrade_description () {
    my @args;
    for (qw{baseurl build_target os_release_file initial_install_os_release_file}) {
        my $attribute = "override_$_";
        my $predicate = "has_$attribute";
        if ($self->$predicate) {
            my $arg = "--$attribute";
            push @args, ($arg, $self->$attribute);
        }
    }
    if ($self->has_override_trusted_gnupg_homedir) {
        push @args, (
            '--trusted_gnupg_homedir', $self->override_trusted_gnupg_homedir
        );
    }
    my ($stdout, $stderr, $success, $exit_code) = $self->fatal_run_cmd(
        cmd         => [ 'tails-iuk-get-upgrade-description-file', @args ],
343
344
        error_title => __(q{Error while checking for upgrades}),
        error_msg   => __(
intrigeri's avatar
intrigeri committed
345
346
347
            "<b>Could not determine whether an upgrade is available from our website.</b>\n\n".
            "Check your network connection, and restart Tails to try upgrading again.\n\n".
            "If the problem persists, go to file:///usr/share/doc/tails/website/doc/upgrade/error/check.en.html",
348
    ));
intrigeri's avatar
intrigeri committed
349
350
351
352
353
354
355
356
357
358

    return ($stdout, $stderr, $success, $exit_code);
}

method no_incremental_explanation (Str $no_incremental_reason) {
    assert_defined($no_incremental_reason);

    my $explanation;

    if ($no_incremental_reason eq 'no-incremental-upgrade-path') {
359
        $explanation = __(
intrigeri's avatar
intrigeri committed
360
361
362
363
364
            q{no automatic upgrade is available from our website }.
            q{for this version}
        );
    }
    elsif ($no_incremental_reason eq 'not-installed-with-tails-installer') {
365
        $explanation = __(
intrigeri's avatar
intrigeri committed
366
367
368
369
            q{your device was not created using a USB image or Tails Installer}
        );
    }
    elsif ($no_incremental_reason eq 'non-writable-device') {
370
        $explanation = __(
intrigeri's avatar
intrigeri committed
371
372
373
374
            q{Tails was started from a DVD or a read-only device}
        );
    }
    elsif ($no_incremental_reason eq 'not-enough-free-space') {
375
        $explanation = __(
intrigeri's avatar
intrigeri committed
376
377
378
379
            q{there is not enough free space on the Tails system partition}
        );
    }
    elsif ($no_incremental_reason eq 'not-enough-free-memory') {
380
        $explanation = __(
intrigeri's avatar
intrigeri committed
381
382
383
384
            q{not enough memory is available on this system}
        );
    }
    else {
385
        say STDERR __x(
386
387
                q{No explanation available for reason '{reason}'.},
                reason => $no_incremental_reason,
388
        );
intrigeri's avatar
intrigeri committed
389
390
391
392
393
394
395
        $explanation = $no_incremental_reason;
    }

    return "$explanation";
}

method run () {
396
    $self->refresh_signing_key;
intrigeri's avatar
intrigeri committed
397
398
    my ($upgrade_description_text) = $self->get_upgrade_description;
    my $upgrade_description = Tails::IUK::UpgradeDescriptionFile->new_from_text(
399
400
        text            => $upgrade_description_text,
        product_version => $self->running_system->product_version,
intrigeri's avatar
intrigeri committed
401
402
403
404
405
406
    );
    assert_isa($upgrade_description, 'Tails::IUK::UpgradeDescriptionFile');

    $self->checked_upgrades_file->touch;

    unless ($upgrade_description->contains_upgrade_path) {
407
        $self->info(__("The system is up-to-date"));
intrigeri's avatar
intrigeri committed
408
409
410
        exit(0);
    }

411
    $self->info(__(
intrigeri's avatar
intrigeri committed
412
        'This version of Tails is outdated, and may have security issues.'
413
    ));
intrigeri's avatar
intrigeri committed
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
441
    my ($upgrade_path, $upgrade_type, $no_incremental_reason);

    if ($self->running_system->started_from_writable_device) {
        if ($self->running_system->started_from_device_installed_with_tails_installer) {
            $upgrade_description->contains_incremental_upgrade_path or
                $no_incremental_reason = 'no-incremental-upgrade-path';
        }
        else {
            $no_incremental_reason = 'not-installed-with-tails-installer';
        }
    }
    else {
        $no_incremental_reason = 'non-writable-device';
    }

    if (! defined($no_incremental_reason)) {
        my $incremental_upgrade_path = $upgrade_description->incremental_upgrade_path;
        my $free_memory             = $self->running_system->free_memory;
        my $memory_needed           = memory_needed($incremental_upgrade_path);
        if ($free_memory >= $memory_needed) {
            my $free_space   = $self->free_space;
            my $space_needed = space_needed($incremental_upgrade_path);
            if ($free_space >= $space_needed) {
                $upgrade_path = $incremental_upgrade_path;
                $upgrade_type = 'incremental';
            }
            else {
                $no_incremental_reason = 'not-enough-free-space';
442
                $self->info(__x(
443
444
445
446
                    "The available incremental upgrade requires ".
                    "{space_needed} ".
                    "of free space on Tails system partition, ".
                    " but only {free_space} is available.",
intrigeri's avatar
intrigeri committed
447
448
                    space_needed => $self->format_bytes($space_needed),
                    free_space   => $self->format_bytes($free_space),
449
                ));
intrigeri's avatar
intrigeri committed
450
451
452
453
            }
        }
        else {
            $no_incremental_reason = 'not-enough-free-memory';
454
            $self->info(__x(
455
456
457
                "The available incremental upgrade requires ".
                "{memory_needed} of free memory, but only ".
                "{free_memory} is available.",
intrigeri's avatar
intrigeri committed
458
459
                memory_needed => $self->format_bytes($memory_needed),
                free_memory   => $self->format_bytes($free_memory),
460
            ));
intrigeri's avatar
intrigeri committed
461
462
463
464
465
466
467
468
469
470
471
472
        }
    }

    # incremental upgrade is not available or possible,
    # let's see if we can do a full upgrade
    if (! defined($upgrade_path)) {
        if ($upgrade_description->contains_full_upgrade_path) {
            $upgrade_path = $upgrade_description->full_upgrade_path;
            $upgrade_type = 'full';
        }
        else {
            $self->fatal(
473
                __(
intrigeri's avatar
intrigeri committed
474
475
                    "An incremental upgrade is available, but no full upgrade is.\n".
                    "This should not happen. Please report a bug."
476
477
                ),
                title => __(
intrigeri's avatar
intrigeri committed
478
                    q{Error while detecting available upgrades}
479
                ),
intrigeri's avatar
intrigeri committed
480
481
482
483
484
485
            );
        }
    }

    if ($upgrade_type eq 'incremental') {
        exit(0) unless($self->dialog(
486
            __x(
487
488
489
490
491
492
493
494
495
                "<b>You should upgrade to {name} {version}.</b>\n\n".
                "For more information about this new version, go to {details_url}\n\n".
                "We recommend you close all other applications during the upgrade.\n".
                "Downloading the upgrade might take a long time, from several minutes to a few hours.\n\n".
                 "Download size: {size}\n\n".
                 "Do you want to upgrade now?",
                details_url => $upgrade_path->{'details-url'},
                name        => $upgrade_description->product_name,
                version     => $upgrade_path->{version},
tous's avatar
tous committed
496
                size        => $self->format_bytes(
intrigeri's avatar
intrigeri committed
497
498
                    $upgrade_path->{'total-size'}
                ),
intrigeri's avatar
intrigeri committed
499
            ),
500
501
502
            title        => __(q{Upgrade available}),
            ok_label     => __(q{Upgrade now}),
            cancel_label => __(q{Upgrade later}),
intrigeri's avatar
intrigeri committed
503
504
505
506
507
            ));
        $self->do_incremental_upgrade($upgrade_path);
    }
    else {
        exit(0) unless($self->dialog(
508
            __x(
509
510
511
512
                "<b>You should do a manual upgrade to {name} {version}.</b>\n\n".
                "For more information about this new version, go to {details_url}\n\n".
                "It is not possible to automatically upgrade ".
                "your device to this new version: {explanation}.\n\n".
513
514
515
516
517
518
                "To learn how to do a manual upgrade, go to {manual_upgrade_url}",
                details_url        => $upgrade_path->{'details-url'},
                name               => $upgrade_description->product_name,
                version            => $upgrade_path->{version},
                explanation        => $self->no_incremental_explanation($no_incremental_reason),
                manual_upgrade_url => 'https://tails.boum.org/doc/upgrade/#manual',
519
520
            ),
            title => __(q{New version available}),
intrigeri's avatar
intrigeri committed
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
            type  => 'info',
        ));
        $self->do_full_upgrade($upgrade_path);
    }
}

fun target_files (HashRef $upgrade_path, AbsDir $destdir) {
    my @target_files;
    foreach my $target_file (@{$upgrade_path->{'target-files'}}) {
        my $basename    = path($target_file->{url})->basename;
        my $output_file = path($destdir, $basename);
        push @target_files,
            {
                %{$target_file},
                output_file => $output_file,
            };
    }

    return @target_files;
}

=head2 memory_needed

Returns the amount of free RAM, in bytes, needed to download and install
the incremental upgrade described in the upgrade path passed
as argument.

=cut
fun memory_needed (HashRef $upgrade_path) {
    # We need:
    #  - The size of the target file, because tails-iuk-get-target-file
    #    will download in a temporary directory stored in the root filesystem's
    #    union upper branch, that is in a tmpfs, that is in memory.
    #  - Enough memory to run the tails-iuk-get-target-file process.
    #  - Enough memory to run the tails-install-iuk process.
    #  - Some margin, e.g. for the squashfs kernel module to decompress
    #    the IUK when we copy its content to the system partition.
    my $get_target_file_process_memory = 60 * 1024 * 1024;
    my $install_iuk_process_memory = 90 * 1024 * 1024;
    my $margin = 64 * 1024 * 1024;

    $upgrade_path->{'total-size'}
        + $get_target_file_process_memory
        + $install_iuk_process_memory
        + $margin;
}

=head2 space_needed

Returns the amount of free space, in bytes, needed on the system
partition to download and install the incremental upgrade described in
the upgrade path passed as argument.

=cut
fun space_needed (HashRef $upgrade_path) {
    # At this point, we only know the size of the target file,
    # which is an IUK, i.e. a (compressed) SquashFS, whose content
    # will be copied to the system partition: vmlinuz, initrd; EFI,
    # isolinux, and utils directories; SquashFS diff.
    #
    # So the question basically boils down to: how well is the IUK
    # compressed?
    #
    # In practice, in most cases the total size of the IUK content is
    # dominated by the size of the SquashFS diff and the initrd, which
    # are already heavily compressed and won't be compressed further
    # in the IUK. So in most cases, we only need to leave room for
    # a tiny bit of margin, hence a $space_factor not much bigger
    # than 1 should do the job.
    #
    # Still, let's give ourselves a bit of margin, in the form or an
    # additional constant, just in case, for whatever reason, we ever
    # generate an IUK whose content is mostly uncompressed data,
    # and our $space_factor is not sufficient in itself.
    my $space_factor = 1.2;
    my $space_margin = 64 * 1024;
    $space_factor * $upgrade_path->{'total-size'} + $space_margin;
}

method get_target_files (HashRef $upgrade_path, CodeRef $url_transform, AbsDir $destdir) {
601
602
    my $title = __("Downloading upgrade");
    my $info = __x(
603
604
605
        "Downloading the upgrade to {name} {version}...",
        name    => $self->product_name,
        version => $upgrade_path->{version},
606
    );
intrigeri's avatar
intrigeri committed
607
608
609
610
611
    $self->info($info);

    foreach my $target_file (target_files($upgrade_path, $destdir)) {
        my @cmd = (
            'tails-iuk-get-target-file',
612
613
614
615
616
617
            '--uri',          $url_transform->($target_file->{url}),
            '--fallback_uri', $target_file->{url},
            '--hash_type',    'sha256',
            '--hash_value',   $target_file->{sha256},
            '--size',         $target_file->{size},
            '--output_file',  $target_file->{output_file},
intrigeri's avatar
intrigeri committed
618
619
620
621
622
623
624
625
626
627
628
629
        );
        if (! $ENV{HARNESS_ACTIVE}) {
            @cmd = ('sudo', '-n', '-u', 'tails-iuk-get-target-file', @cmd);
        }
        my ($exit_code, $stderr);
        my $success = 1;

        if ($self->batch) {
            IPC::Run::run \@cmd, '2>', \$stderr or $success = 0;
            $exit_code = $?;
        }
        else {
630
            my ($download_h, $zenity_h, $download_out, $zenity_in);
631
            my ($bytes_downloaded, $percent_complete);
632
            my $download_progress =
633
                Tails::IUK::DownloadProgress->new(size => $target_file->{size});
634
            $info = $self->init_zenity_progress_dialog_text($download_progress);
intrigeri's avatar
Lint    
intrigeri committed
635
636
637
638
639
640
641
            $download_h =  IPC::Run::start \@cmd,
                \undef, \$download_out, '2>', \$stderr;
            $zenity_h = IPC::Run::start
                [
                    qw{zenity --progress --percentage=0 --auto-close},
                    '--title', $title, '--text', $info
                ],
642
                \$zenity_in;
643
644
            try {
                while ($zenity_h->pumpable && $download_h->pumpable ) {
tous's avatar
tous committed
645
646
647
648
                    # Zenity reads data from standard input line by line.
                    # If a line is prefixed with # the text is updated with the text on that line.
                    # If a line contains only a number, the percentage is updated with that number.

649
                    ### Get download progress percentage
650
                    $download_h->pump_nb;
651
                    next unless $download_out;
652
653

                    ### Update the progress dialog bar percentage
654
655
                    $zenity_in = $download_out;
                    $zenity_h->pump_nb;
tous's avatar
tous committed
656

657
658
                    ### Update the progress dialog text

659
                    ($percent_complete) = split /\n/, $download_out;
660

tous's avatar
tous committed
661
                    # Convert percentage to total number of bytes downloaded
662
                    $bytes_downloaded = ($percent_complete/100) * $download_progress->size;
tous's avatar
tous committed
663
                    # Clear $download_out to avoid old output in the next iteration
664
                    $download_out = undef;
665

666
                    next unless $download_progress->update($bytes_downloaded);
667
668

                    # Send up-to-date progress dialog text to zenity
669
                    $zenity_in = $download_progress->info;
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
                    $zenity_h->pump_nb;
                }
            }
            catch {
                $stderr = $_;
            }
            finally {
                $zenity_h->kill_kill;
                if ($zenity_h->result) {
                    $self->cancel_download;
                    kill TERM => -getpgrp();
                }
                else {
                    $success =  $download_h->finish;
                    $exit_code = $download_h->result;
                }
intrigeri's avatar
intrigeri committed
686
            };
intrigeri's avatar
intrigeri committed
687
688
        }
        $success or $self->fatal(
689
            errf("<b>%{error_msg}s</b>\n\n%{details}s",
intrigeri's avatar
intrigeri committed
690
                 {
691
692
693
694
695
696
697
698
                     error_msg => __(
                         q{<b>The upgrade could not be downloaded.</b>\n\n}.
                         q{Check your network connection, and restart }.
                         q{Tails to try upgrading again.\n\n}.
                         q{If the problem persists, go to }.
                         q{file:///usr/share/doc/tails/website/doc/upgrade/error/download.en.html}
                     ),
                     details   => __(
intrigeri's avatar
intrigeri committed
699
                         q{For debugging information, execute the following command: sudo tails-debugging-info}
700
                     ),
intrigeri's avatar
intrigeri committed
701
                 }
702
703
            ),
            title => __(q{Error while downloading the upgrade}),
intrigeri's avatar
intrigeri committed
704
705
706
707
708
709
710
711
            debugging_info => $self->encoding->decode(errf(
                "exit code: %{exit_code}i\n\n".
                "stderr:\n%{stderr}s",
                { exit_code => $exit_code, stderr => $stderr }
            )),
        );

        -e $target_file->{output_file} or $self->fatal(
712
            __x(
713
714
715
716
                q{Output file '{output_file}' does not exist, but }.
                q{tails-iuk-get-target-file did not complain. }.
                q{Please report a bug.},
                output_file => $target_file->{output_file},
717
718
            ),
            title => __(q{Error while downloading the upgrade}),
intrigeri's avatar
intrigeri committed
719
720
721
722
723
724
725
726
727
        );
    }
}

method do_incremental_upgrade (HashRef $upgrade_path) {
    my ($stdout, $stderr, $success, $exit_code);

    my ($target_files_tempdir) = $self->fatal_run_cmd(
        cmd       => ['tails-iuk-mktemp-get-target-file'],
728
        error_title => __(
intrigeri's avatar
intrigeri committed
729
            q{Error while creating temporary downloading directory}
730
731
        ),
        error_msg => __(
intrigeri's avatar
intrigeri committed
732
            "Failed to create temporary download directory"
733
        ),
intrigeri's avatar
intrigeri committed
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
        as        => 'tails-iuk-get-target-file',
    );
    chomp $target_files_tempdir;

    my $url_transform = sub {
        my $url = shift;

        try {
            $url = Tails::MirrorPool->new(
                # hack: piggy-back on the logic we have in T::RunningSystem
                # for handling the default value and override_baseurl
                baseurl         => $self->running_system->baseurl,
                ($ENV{HARNESS_ACTIVE}
                     ? (fallback_prefix => 'https://127.0.0.1:'
                                           . $ENV{TAILS_FALLBACK_DL_URL_PORT}
                                           . '/tails')
                     : ()
                ),
            )->transformURL($url);
        } catch {
            $self->fatal(
755
                __(
intrigeri's avatar
intrigeri committed
756
757
                    "<b>Could not choose a download server.</b>\n\n".
                    "This should not happen. Please report a bug.",
758
759
                ),
                title => __(q{Error while choosing a download server}),
intrigeri's avatar
intrigeri committed
760
761
762
763
764
765
766
767
768
769
770
771
                debugging_info => $self->encoding->decode($_),
            );
        };

        return $url;
    };

    $self->get_target_files(
        $upgrade_path, $url_transform, path($target_files_tempdir)
    );

    $self->dialog(
772
        __(
intrigeri's avatar
intrigeri committed
773
            "The upgrade was successfully downloaded.\n\n".
774
            "The network connection will be disabled when applying the upgrade.\n\n".
intrigeri's avatar
intrigeri committed
775
            "Please save your work and close all other applications."
776
        ),
intrigeri's avatar
intrigeri committed
777
        type     => 'info',
778
779
        title    => __(q{Upgrade successfully downloaded}),
        ok_label => __(q{Apply upgrade}),
intrigeri's avatar
intrigeri committed
780
781
782
783
784
    );

    $self->install_iuk($upgrade_path, path($target_files_tempdir));

    $self->dialog(
785
        __(
intrigeri's avatar
intrigeri committed
786
787
788
789
            "<b>Your Tails device was successfully upgraded.</b>\n\n".
            "Some security features were temporarily disabled.\n".
            "You should restart Tails on the new version as soon as possible.\n\n".
            "Do you want to restart now?"
790
791
792
793
        ),
        title        => __(q{Restart Tails}),
        ok_label     => __(q{Restart now}),
        cancel_label => __(q{Restart later}),
intrigeri's avatar
intrigeri committed
794
795
796
797
798
799
800
801
802
    ) && $self->restart_system;

    exit(0);
}

method restart_system () {
    $self->info("Restarting the system");
    $self->fatal_run_cmd(
        cmd       => ['/sbin/reboot'],
803
804
        error_title => __(q{Error while restarting the system}),
        error_msg => __(q{Failed to restart the system}),
intrigeri's avatar
intrigeri committed
805
806
807
808
809
810
811
812
813
814
815
816
        as        => 'root',
    ) unless $ENV{HARNESS_ACTIVE};
}

method do_full_upgrade (HashRef $upgrade_path) {
    exit(0);
}

method shutdown_network () {
    $self->info("Shutting down network connection");
    $self->fatal_run_cmd(
        cmd       => ['tails-shutdown-network'],
817
818
        error_title => __(q{Error while shutting down the network}),
        error_msg => __(q{Failed to shutdown network}),
intrigeri's avatar
intrigeri committed
819
820
821
822
        as        => 'root',
    ) unless $ENV{HARNESS_ACTIVE};
}

823
824
method cancel_download () {
    $self->info("Cancelling the upgrade download");
intrigeri's avatar
Lint    
intrigeri committed
825

tous's avatar
tous committed
826
    $self->fatal_run_cmd(
intrigeri's avatar
Lint    
intrigeri committed
827
        cmd         => ['tails-iuk-cancel-download'],
828
829
        error_title => __(q{Error while cancelling the upgrade download}),
        error_msg   => __(q{Failed to cancel the upgrade download}),
intrigeri's avatar
Lint    
intrigeri committed
830
        as          => 'root',
831
    ) unless $ENV{HARNESS_ACTIVE};
832
833
}

intrigeri's avatar
intrigeri committed
834
method install_iuk (HashRef $upgrade_path, AbsDir $target_files_tempdir) {
835
836
    my $title = __("Upgrading the system");
    my $info = __(
intrigeri's avatar
intrigeri committed
837
        "<b>Your Tails device is being upgraded...</b>\n\n".
sajolida's avatar
sajolida committed
838
        "For security reasons, the network connection is now disabled."
839
    );
intrigeri's avatar
intrigeri committed
840
    $self->info($info);
841
    my $zenity_h;
intrigeri's avatar
Lint.    
intrigeri committed
842
843
844
845
846
847
    $zenity_h = IPC::Run::start
        [qw{tail -f /dev/null}],
        '|',
        [qw{zenity --progress --pulsate --no-cancel --auto-close},
         '--title', $title, '--text', $info]
        unless $self->batch;
intrigeri's avatar
intrigeri committed
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
    $self->shutdown_network;

    my @target_files = target_files($upgrade_path, $target_files_tempdir);
    assert(@target_files == 1);

    my @args;
    push @args, (
        '--override_liveos_mountpoint', $self->override_liveos_mountpoint
    ) if $self->has_override_liveos_mountpoint;

    my @cmd = ('tails-install-iuk', @args, $target_files[0]->{output_file});
    if (! $ENV{HARNESS_ACTIVE}) {
        @cmd = ('sudo', '-n', '-u', 'tails-install-iuk', @cmd);
    }

863
    my ($exit_code, $stdout, $stderr);
intrigeri's avatar
intrigeri committed
864
865
866
867
868
869
870
    my $success = 1;

    IPC::Run::run \@cmd, '>', \$stdout, '2>', \$stderr or $success = 0;
    $exit_code = $?;
    $zenity_h->kill_kill unless $self->batch;

    $success or $self->fatal(
871
        $self->encoding->decode(errf("<b>%{error_msg}s</b>\n\n%{details}s",
intrigeri's avatar
intrigeri committed
872
             {
873
                 error_msg => __(
intrigeri's avatar
intrigeri committed
874
875
876
                     q{<b>An error occured while installing the upgrade.</b>\n\n}.
                     q{Your Tails device needs to be repaired and might be unable to restart.\n\n}.
                     q{Please follow the instructions at }.
877
878
879
                     q{file:///usr/share/doc/tails/website/doc/upgrade/error/install.en.html}
                 ),
                 details   => __(
intrigeri's avatar
intrigeri committed
880
                     q{For debugging information, execute the following command: sudo tails-debugging-info}
881
                 ),
intrigeri's avatar
intrigeri committed
882
             },
883
        )),
884
        title => __(q{Error while installing the upgrade}),
intrigeri's avatar
intrigeri committed
885
886
887
888
889
890
891
892
893
894
895
        debugging_info => $self->encoding->decode(errf(
            "exit code: %{exit_code}i\n\n".
            "stdout:\n%{stdout}s\n\n".
            "stderr:\n%{stderr}s",
            { exit_code => $exit_code, stdout => $stdout, stderr => $stderr }
        )),
    );
}

no Moo;
1;