htpdate 10.3 KB
Newer Older
amnesia's avatar
amnesia committed
1 2 3 4
#!/usr/bin/perl
#
# htpdate time poller version 0.9.3
# Copyright (C) 2005 Eddy Vervest
5
# Copyright (C) 2010-2011 Tails developers <tails@boum.org>
amnesia's avatar
amnesia committed
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
#
# 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.
# http://www.gnu.org/copyleft/gpl.html

# Proxy setting are read from environment 
# e.g. in bash for setting environment variables:
#
# export HTTP_PROXY='http://wwwproxy.xs4all.nl:8080'
#
# or set the proxy value here
#
# $ENV{HTTP_PROXY} = 'http://wwwproxy.xs4all.nl:8080';
#
# If proxy authentication is required, specify your userid and password below.

use strict;
use warnings;

use version; our $VERSION = qv('0.9.3');

use Carp;
use Cwd;
31
use Data::Dumper;
amnesia's avatar
amnesia committed
32 33
use DateTime;
use DateTime::Format::DateParse;
amnesia's avatar
amnesia committed
34
use English qw( -no_match_vars );
amnesia's avatar
amnesia committed
35
use File::Path qw(rmtree);
36
use File::Spec::Functions;
amnesia's avatar
amnesia committed
37
use File::Temp qw/tempdir/;
38 39
use Getopt::Long::Descriptive;
use List::Util qw( shuffle );
amnesia's avatar
amnesia committed
40 41
use open qw{:utf8 :std};
use POSIX qw( WIFEXITED );
amnesia's avatar
amnesia committed
42
use threads;
43
use Try::Tiny;
amnesia's avatar
amnesia committed
44 45 46

my $datecommand = '/bin/date';  # "date" command to set time
my $dateparam   = '-s';         # "date" parameter to set time
47
my $maxadjust   = 0;            # maximum time step in seconds (0 means no max.)
amnesia's avatar
amnesia committed
48 49 50
my $minadjust   = 1;            # minimum time step in seconds
my $ssl_protocol = 'TLSv1';     # will be passed to wget's --secure-protocol
my $userid      = '';           # userid for proxy servers
51 52 53 54 55 56
my $password    = '';           # password for proxy server
my (
    $debug, $useragent, $fullrequest, $log, $quiet, $set_date,
    $dns_timeout, $done_file, $res_file, $usage, $opt, $runas,
    $allowed_per_pool_failure_ratio, @pools,
);
57 58 59

sub done {
    if (defined $done_file) {
60
	$> = 0 if $runas;
61 62 63
	open my $f, '>', $done_file or
	    print STDERR "Couldn't write done file: $done_file\n";
	close $f;
64
	$> = getpwnam($runas) if $runas;
65 66 67 68
    }
}

$SIG{__DIE__} = sub {
69 70 71 72
    # Avoid the "done" file to be created by an catched exception.
    # When a eval block is being run, e.g. for exception catching, $^S is true.
    # It is false otherwise.
    done unless $^S;
73 74
    die(@_);
};
amnesia's avatar
amnesia committed
75 76 77 78 79

sub message {
    my @msg = @_;

    if ($log) {
amnesia's avatar
amnesia committed
80
        open my $h, '>>', $log or die "Cannot open log file $log: $!";
amnesia's avatar
amnesia committed
81 82 83 84 85 86 87 88 89 90 91 92
        print $h "@msg\n";
        close $h;
    }
    else {
        print "@msg\n" unless $quiet;
    }
}

sub debug {
    message(@_) if $debug;
}

93 94 95
sub error {
    debug(@_);
    croak @_;
amnesia's avatar
amnesia committed
96
}
amnesia's avatar
amnesia committed
97 98 99

sub parseCommandLine () {
    # specify valid switches
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
    ($opt, $usage) = describe_options(
        'htpdate %o',
        [ 'debug|d', "debug", { default => 0 } ],
        [ 'help', "print usage message and exit" ],
        [ 'quiet|q', "quiet", { default => 0 } ],
        [ 'user|u:s', "userid to run as" ],
        [ 'dont_set_date|x', "do not set the time (only show)", { default => 0 } ],
        [ 'user_agent|a:s', "http user agent to use", { default => "htpdate/$VERSION" } ],
        [ 'fullrequest|f', "request the full page and referenced resources rather than only its header", { default => 0 } ],
        [ 'log_file|l:s', "log to this file rather than to STDOUT" ],
        [ 'dns_timeout|t:i', "DNS timeout for wget" ],
        [ 'done_file|D:s', "create this file after quitting in any way" ],
        [ 'success_file|T:s', "create this file after setting time successfully" ],
        [ 'pal_pool=s@', "distrusted hostnames" ],
        [ 'neutral_pool=s@', "neutral hostnames" ],
        [ 'foe_pool=s@', "distrusted hostnames" ],
        [ 'allowed_per_pool_failure_ratio:f', "ratio (0.0-1.0) of allowed per-pool failure", { default => 1.0 } ],
    );

    usage() if $opt->help;
    usage() unless $opt->pal_pool && $opt->neutral_pool && $opt->foe_pool;

    $runas       = $opt->user if $opt->user;
    $>           = getpwnam($runas) if $runas;
    $useragent   = $opt->user_agent;
    $debug       = $opt->debug;
    $fullrequest = $opt->fullrequest;
    $log         = $opt->log_file if $opt->log_file;
    $quiet       = $opt->quiet;
    $set_date    = ! $opt->dont_set_date;
    $dns_timeout = $opt->dns_timeout;
    $done_file   = $opt->done_file if $opt->done_file;
    $res_file    = $opt->success_file if $opt->success_file;
    $allowed_per_pool_failure_ratio = $opt->allowed_per_pool_failure_ratio;
    @pools = map {
        [
            map {
                $_ = 'https://'.$_ unless $_ =~ /^http/i;
            } split(/,/, join(',', @{$_}))
        ]
    } ($opt->pal_pool, $opt->neutral_pool, $opt->foe_pool);
amnesia's avatar
amnesia committed
141 142 143
}

sub usage () {
144
    print STDERR $usage->text;
amnesia's avatar
amnesia committed
145 146 147 148 149 150
    exit;
}

sub newestDateHeader {
    my ($dir) = @_;

151
    my @files = grep { ! ( $_ =~ m|/?\.{1,2}$| ) } glob("$dir/.* $dir/*");
amnesia's avatar
amnesia committed
152
    @files or error "No downloaded files can be found";
amnesia's avatar
amnesia committed
153 154 155 156 157 158

    my $newestdt;

    foreach my $file (@files) {
        next if -l $file || -d _;
        my $date;
amnesia's avatar
amnesia committed
159
        open(my $file_h, '<', $file) or die "Can not read file $file: $!";
amnesia's avatar
amnesia committed
160 161 162 163
        while (my $line = <$file_h>) {
            chomp $line;
            # empty line == we leave the headers to go into the content
            last if $line eq '';
164
            last if ($date) = ($line =~ m/^\s*Date:\s+(.*)$/m);
amnesia's avatar
amnesia committed
165 166 167 168 169 170 171 172 173 174 175 176 177 178
        }
        close $file_h;
        if (defined $date) {
            # RFC 2616 (3.3.1) says Date headers MUST be represented in GMT
            my $dt = DateTime::Format::DateParse->parse_datetime( $date, 'GMT' );
            if (! defined $newestdt || DateTime->compare($dt, $newestdt) > 0) {
                $newestdt = $dt;
            }
        }
    }

    return $newestdt;
}

179 180 181 182
=head2 random_first_with_allowed_failure_ratio

Returns the result of the first successful application of
$args->{code} on a random element of $args->{list}.
183 184
Success is tested using the $args->{is_success} predicate,
called on the value returned by $args->{code}.
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

$args->{allowed_failure_ratio} caps the maximum failure ratio before
giving up.

$args->{code} is called with two arguments: the currently (randomly
picked) considered element, and $args->{args}.

Any exceptions thrown by $args->{code} is catched.

=cut
sub random_first_with_allowed_failure_ratio {
    my $args = shift;

    my %tried;
    $tried{$_} = 0 for (@{$args->{list}});
    my $failures = 0;
    my $total = keys %tried;

    while ( $failures / $total <= $args->{allowed_failure_ratio} ) {
        my @randomized_left = shuffle grep { ! $tried{$_} } keys(%tried);
        my $picked = $randomized_left[0];
        $tried{$picked}++;
        my $res;
        try {
            $res = $args->{code}->($picked, $args->{args})
        };
211
        return $res if $args->{is_success}->($res);
212 213 214 215 216 217 218 219 220 221 222 223 224
        $failures++;
    }

    return;
}

sub getPoolDateDiff {
    my $args = shift;
    my $fullrequest = defined $args->{fullrequest} ? $args->{fullrequest} : 0;

    random_first_with_allowed_failure_ratio({
        list => $args->{urls},
        code => \&getUrlDateDiff,
225
        is_success => sub { defined shift },
226 227 228 229 230 231 232 233 234
        args => { fullrequest => $fullrequest },
        allowed_failure_ratio => $allowed_per_pool_failure_ratio,
    });
}

sub getUrlDateDiff {
    my $url = shift;
    my $args = shift;
    my $fullrequest = $args->{fullrequest};
amnesia's avatar
amnesia committed
235

236 237
    defined $url or error "getUrlDateDiff must be passed an URL";
    debug("getUrlDateDiff: $url");
amnesia's avatar
amnesia committed
238

239
    my $tmpdir = tempdir("XXXXXXXXXX", TMPDIR => 1);
amnesia's avatar
amnesia committed
240

241 242 243 244 245 246
    my @wget_options = (
        '-U', $useragent, '--quiet', '--no-cache',
        '-e', 'robots=off',
        '--secure-protocol', $ssl_protocol,
        '--directory-prefix', $tmpdir,
    );
247
    push @wget_options, ('--dns-timeout', $dns_timeout) if defined $dns_timeout;
amnesia's avatar
amnesia committed
248
    if ($fullrequest) {
249 250 251 252 253 254 255 256 257 258
        push @wget_options, (
            '--no-directories', '--page-requisites', '--span-hosts',
            '--save-headers',
        );
    }
    else {
        push @wget_options, (
            '--spider', '--server-response',
            '--output-file', catfile($tmpdir, 'headers'),
        );
amnesia's avatar
amnesia committed
259 260
    }

261
    my @cmdline = ('wget', @wget_options, $url);
amnesia's avatar
amnesia committed
262 263 264

    # fetch (the page and) referenced resources:
    # images, stylesheets, scripts, etc.
265
    my $before = DateTime->now->epoch();
amnesia's avatar
amnesia committed
266
    WIFEXITED(system(@cmdline)) or error "Failed to fetch content from $url: $!";
267
    my $local = DateTime->now->epoch();
amnesia's avatar
amnesia committed
268 269 270
    my $newestdt;
    eval { $newestdt = newestDateHeader($tmpdir) };
    if ($EVAL_ERROR =~ m/No downloaded files can be found/) {
amnesia's avatar
amnesia committed
271
        rmtree($tmpdir);
amnesia's avatar
amnesia committed
272
        error "No file could be downloaded from $url.";
amnesia's avatar
amnesia committed
273
    }
amnesia's avatar
amnesia committed
274

amnesia's avatar
amnesia committed
275 276
    rmtree($tmpdir);

amnesia's avatar
amnesia committed
277
    defined $newestdt or error "Could not get any Date header";
278
    my $newest_epoch = $newestdt->epoch();
amnesia's avatar
amnesia committed
279

280 281
    my $diff = $newest_epoch - $local;
    my $took = $local - $before;
282

amnesia's avatar
amnesia committed
283
    debug("$url (took ${took}s) => diff = $diff second(s)");
amnesia's avatar
amnesia committed
284

285
    return $diff;
amnesia's avatar
amnesia committed
286 287 288
}

sub adjustDate {
289
    my ($diff) = @_;
amnesia's avatar
amnesia committed
290

291
    defined $diff or error "adjustDate was passed an undefined diff";
amnesia's avatar
amnesia committed
292

293 294
    my $local = DateTime->now->epoch();
    my $absdiff = abs($diff);
amnesia's avatar
amnesia committed
295

amnesia's avatar
amnesia committed
296
    debug("Median diff: $diff second(s)");
amnesia's avatar
amnesia committed
297

298
    if ( $maxadjust && $absdiff gt $maxadjust ) {
amnesia's avatar
amnesia committed
299
        message("Not setting clock as diff ($diff seconds) is too large.");
amnesia's avatar
amnesia committed
300
    }
301
    elsif ( $absdiff lt $minadjust) {
amnesia's avatar
amnesia committed
302
        message("Not setting clock as diff ($diff seconds) is too small.");
amnesia's avatar
amnesia committed
303 304
    }
    else {
amnesia's avatar
amnesia committed
305
        my $newtime = DateTime->now->epoch + $diff;
amnesia's avatar
amnesia committed
306
        message("Setting time to $newtime...");
amnesia's avatar
amnesia committed
307
        if ($set_date) {
308
            $> = 0 if $runas;
amnesia's avatar
amnesia committed
309 310
            open(my $fd, "-|", $datecommand, $dateparam, '@' . $newtime)
                or die "Cannot set run command $datecommand: $!";
amnesia's avatar
amnesia committed
311
            if ( $? != 0 ) {
amnesia's avatar
amnesia committed
312 313
                my @output = <$fd>;
                error "An error occured setting the time\n@output";
amnesia's avatar
amnesia committed
314 315
            }
            close($fd);
316
            $> = getpwnam($runas) if $runas;
amnesia's avatar
amnesia committed
317 318
        }
    }
319
    $> = 0 if $runas;
320 321 322
    open my $res_h, '>>', $res_file or die "Cannot open res file $res_file: $!";
    print $res_h "$diff\n";
    close $res_h;
323
    $> = getpwnam($runas) if $runas;
amnesia's avatar
amnesia committed
324 325
}

326
parseCommandLine();
327
message("Running htpdate.");
328
my @diffs = grep {
329 330
    defined $_
} map {
331
    my $diff = $_->join();
332 333
    if (! defined $diff) {
        error('Aborting as one pool could not be reached');
334
    }
335
    $diff;
336
} map {
337 338 339 340
    threads->create(\&getPoolDateDiff, {
        urls => $_,
        fullrequest => $fullrequest,
    })
341
} @pools
amnesia's avatar
amnesia committed
342
    or error "No Date header could be received.";
343 344
my @sorted_diffs = sort @diffs;
adjustDate($sorted_diffs[int(@sorted_diffs / 2)]);
345
done;