htpdate 10 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 69 70 71
    }
}

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

sub message {
    my @msg = @_;

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

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

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

sub parseCommandLine () {
    # specify valid switches
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
    ($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
140 141 142
}

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

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

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

    my $newestdt;

    foreach my $file (@files) {
        next if -l $file || -d _;
        my $date;
amnesia's avatar
amnesia committed
158
        open(my $file_h, '<', $file) or die "Can not read file $file: $!";
amnesia's avatar
amnesia committed
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
        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;
}

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
=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
231

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

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

237 238 239 240 241 242
    my @wget_options = (
        '-U', $useragent, '--quiet', '--no-cache',
        '-e', 'robots=off',
        '--secure-protocol', $ssl_protocol,
        '--directory-prefix', $tmpdir,
    );
243
    push @wget_options, ('--dns-timeout', $dns_timeout) if defined $dns_timeout;
amnesia's avatar
amnesia committed
244
    if ($fullrequest) {
245 246 247 248 249 250 251 252 253 254
        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
255 256
    }

257
    my @cmdline = ('wget', @wget_options, $url);
amnesia's avatar
amnesia committed
258 259 260

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

amnesia's avatar
amnesia committed
271 272
    rmtree($tmpdir);

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

276 277
    my $diff = $newest_epoch - $local;
    my $took = $local - $before;
278

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

281
    return $diff;
amnesia's avatar
amnesia committed
282 283 284
}

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

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

289 290
    my $local = DateTime->now->epoch();
    my $absdiff = abs($diff);
amnesia's avatar
amnesia committed
291

amnesia's avatar
amnesia committed
292
    debug("Median diff: $diff second(s)");
amnesia's avatar
amnesia committed
293

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

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