htpdate 9.91 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);
amnesia's avatar
amnesia committed
36
use File::Temp qw/tempdir/;
37 38
use Getopt::Long::Descriptive;
use List::Util qw( shuffle );
amnesia's avatar
amnesia committed
39 40
use open qw{:utf8 :std};
use POSIX qw( WIFEXITED );
amnesia's avatar
amnesia committed
41
use threads;
42
use Try::Tiny;
amnesia's avatar
amnesia committed
43 44 45

my $datecommand = '/bin/date';  # "date" command to set time
my $dateparam   = '-s';         # "date" parameter to set time
46
my $maxadjust   = 0;            # maximum time step in seconds (0 means no max.)
amnesia's avatar
amnesia committed
47 48 49
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
50 51 52 53 54 55
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,
);
56 57 58

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

$SIG{__DIE__} = sub {
    done;
    die(@_);
};
amnesia's avatar
amnesia committed
71 72 73 74 75

sub message {
    my @msg = @_;

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

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

89 90 91
sub error {
    debug(@_);
    croak @_;
amnesia's avatar
amnesia committed
92
}
amnesia's avatar
amnesia committed
93 94 95

sub parseCommandLine () {
    # specify valid switches
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
    ($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);

    debug("Pools:\n", Dumper(\@pools));
amnesia's avatar
amnesia committed
139 140 141
}

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

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

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

    my $newestdt;

    foreach my $file (@files) {
        next if -l $file || -d _;
        my $date;
amnesia's avatar
amnesia committed
157
        open(my $file_h, '<', $file) or die "Can not read file $file: $!";
amnesia's avatar
amnesia committed
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
        while (my $line = <$file_h>) {
            chomp $line;
            # empty line == we leave the headers to go into the content
            last if $line eq '';
            last if ($date) = ($line =~ m/^Date:\s+(.*)$/m);
        }
        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;
}

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
=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}.

$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})
        };
        return $res if $res;
        $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,
        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
230

231 232
    defined $url or error "getUrlDateDiff must be passed an URL";
    debug("getUrlDateDiff: $url");
amnesia's avatar
amnesia committed
233

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

    my @wget_options = ( '-U', $useragent, '--quiet', '--no-cache',
                         '-e', 'robots=off', '--save-headers',
                         '--no-directories',
                         '--secure-protocol', $ssl_protocol,
                     );
241
    push @wget_options, ('--dns-timeout', $dns_timeout) if defined $dns_timeout;
242
    push @wget_options, ('--directory-prefix', $tmpdir);
amnesia's avatar
amnesia committed
243 244 245 246
    if ($fullrequest) {
        push @wget_options, ('--page-requisites', '--span-hosts');
    }

247
    my @cmdline = ('wget', @wget_options, $url);
amnesia's avatar
amnesia committed
248 249 250

    # fetch (the page and) referenced resources:
    # images, stylesheets, scripts, etc.
251
    my $before = DateTime->now->epoch();
amnesia's avatar
amnesia committed
252
    WIFEXITED(system(@cmdline)) or error "Failed to fetch content from $url: $!";
253
    my $local = DateTime->now->epoch();
amnesia's avatar
amnesia committed
254 255 256
    my $newestdt;
    eval { $newestdt = newestDateHeader($tmpdir) };
    if ($EVAL_ERROR =~ m/No downloaded files can be found/) {
amnesia's avatar
amnesia committed
257
        rmtree($tmpdir);
amnesia's avatar
amnesia committed
258
        error "No file could be downloaded from $url.";
amnesia's avatar
amnesia committed
259
    }
amnesia's avatar
amnesia committed
260

amnesia's avatar
amnesia committed
261 262
    rmtree($tmpdir);

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

266 267
    my $diff = $newest_epoch - $local;
    my $took = $local - $before;
268

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

271
    return $diff;
amnesia's avatar
amnesia committed
272 273 274
}

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

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

279 280
    my $local = DateTime->now->epoch();
    my $absdiff = abs($diff);
amnesia's avatar
amnesia committed
281

amnesia's avatar
amnesia committed
282
    debug("Median diff: $diff second(s)");
amnesia's avatar
amnesia committed
283

284
    if ( $maxadjust && $absdiff gt $maxadjust ) {
amnesia's avatar
amnesia committed
285
        message("Not setting clock as diff ($diff seconds) is too large.");
amnesia's avatar
amnesia committed
286
    }
287
    elsif ( $absdiff lt $minadjust) {
amnesia's avatar
amnesia committed
288
        message("Not setting clock as diff ($diff seconds) is too small.");
amnesia's avatar
amnesia committed
289 290
    }
    else {
amnesia's avatar
amnesia committed
291
        my $newtime = DateTime->now->epoch + $diff;
amnesia's avatar
amnesia committed
292
        message("Setting time to $newtime...");
amnesia's avatar
amnesia committed
293
        if ($set_date) {
294
            $> = 0 if $runas;
amnesia's avatar
amnesia committed
295 296
            open(my $fd, "-|", $datecommand, $dateparam, '@' . $newtime)
                or die "Cannot set run command $datecommand: $!";
amnesia's avatar
amnesia committed
297
            if ( $? != 0 ) {
amnesia's avatar
amnesia committed
298 299
                my @output = <$fd>;
                error "An error occured setting the time\n@output";
amnesia's avatar
amnesia committed
300 301
            }
            close($fd);
302
            $> = getpwnam($runas) if $runas;
amnesia's avatar
amnesia committed
303 304
        }
    }
305
    $> = 0 if $runas;
306 307 308
    open my $res_h, '>>', $res_file or die "Cannot open res file $res_file: $!";
    print $res_h "$diff\n";
    close $res_h;
309
    $> = getpwnam($runas) if $runas;
amnesia's avatar
amnesia committed
310 311
}

312
parseCommandLine();
313
message("Running htpdate.");
314
my @diffs = grep {
315 316
    defined $_
} map {
317
    my $diff = $_->{thread}->join();
318 319
    if (! defined $diff) {
        error('Aborting as one pool could not be reached');
320
    }
321
    $diff;
322 323 324
} map {
    {
        url    => $_,
325 326 327 328
        thread => threads->create(\&getPoolDateDiff, {
            urls => $_,
            fullrequest => $fullrequest,
        })
329
    }
330
} @pools
amnesia's avatar
amnesia committed
331
    or error "No Date header could be received.";
332 333
my @sorted_diffs = sort @diffs;
adjustDate($sorted_diffs[int(@sorted_diffs / 2)]);
334
done;