Initial commit
authorAlex Bligh <alex@alex.org.uk>
Thu, 9 Aug 2012 20:16:32 +0000 (21:16 +0100)
committerAlex Bligh <alex@alex.org.uk>
Thu, 9 Aug 2012 20:16:32 +0000 (21:16 +0100)
LICENCE [new file with mode: 0644]
README [new file with mode: 0644]
ambdownload.php [new file with mode: 0644]
download.pl [new file with mode: 0755]
http.conf.example [new file with mode: 0644]

diff --git a/LICENCE b/LICENCE
new file mode 100644 (file)
index 0000000..474d125
--- /dev/null
+++ b/LICENCE
@@ -0,0 +1,7 @@
+Copyright (c) 2012 Alex Bligh
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/README b/README
new file mode 100644 (file)
index 0000000..f35f6d8
--- /dev/null
+++ b/README
@@ -0,0 +1,92 @@
+Download Server
+===============
+
+(c) 2012 Alex Bligh - Provided under the MIT Licence. See LICENCE file.
+
+This download server provides reliable logged downloads over http. It is
+intended to be used where:
+
+A. A website (such as a Wordpress website) wants to offer a downlaod facility
+   and record the downloads made. Let's call this the 'source website'.
+
+B. The download should come from a different website (possibly because the
+   source website is https and large downloads over http are resource
+   consumptive). Let's call this the 'download web site'.
+
+C. It is imperative that the download must be tracked by authenticated
+   username, and by time and success.
+
+The strategy used is as follows:
+
+1. The source website contains a link to a download page, which appears
+   to be on the source website, but in fact is redirect page.
+
+2. The redirect page redirects to a dynamically constructed URL on
+   on the download site. That URL is a URL for a CGI script with the
+   following parameters:
+
+     a) the file to be downloaded (or the name of a symlink to
+        such a file).
+
+     b) the id of the user against whom the download is to be logged.
+
+     c) the UNIX time (since epoch)
+
+     d) a hash of the above plus a shared secret
+
+3. The download script checks the parameters, checks the time is
+   within a few seconds, and checks the hash value. If these match, it
+   serves the file, logging start, success and errors. The purpose of the
+   time check is so that the URL can't realistically be distributed to
+   others. The hash prevents tampering with the parameters.
+
+
+INSTALLATION
+============
+
+httpd.conf.example contains an example httpd.conf for the downloads server
+
+download.pl contains the script to go in the download directory on the
+download server, and should be marked executable. In this example that
+would be
+  /var/www/server.example.com/download/download.pl
+
+ambdownload.php is a Wordpress plugin which will can be installed in the
+plugins directory in Wordpress, e.g. in
+  wp-content/plugins/ambdownload/ambdownload.php
+This allows setting of a custom meta on a page to turn it into a download
+page. For instance, if you wished to make a page redirect to download
+'myfile', set a custom meta key for that page named 'download_file'
+to the value 'myfile'. You will need to enable this module once you have
+installed it.
+
+Note, to avoid having to muck around with Wordpress, myfile could be a symlink,
+and the script will correctly name the downloaded file as per the target of the
+symlink.
+
+Running download.pl with two parameters, e.g.
+   /var/www/server.example.com/download/download.pl 'myname@example.com' 'myfile'
+will print out the URL to use to download 'myfile', logged as
+'myname@example.com'
+
+Your files to be downloaded should be put in
+  /var/www/server.example.com/download/
+These may be symlinks. The apache configuration will prevent them from being
+downloaded directly.
+
+Ensure both servers have a file
+  /etc/apache2/download.secret
+with some random textual data in. 32 random ASCII characters should be fine.
+You can change this whenever you want, provided it's changed on both servers
+simultaneously.
+
+Logging will take place to
+  /var/log/download.log
+Ensure this file is created by you, and owned by the user running cgi scripts.
+Usually this will do
+  # >/var/log/download.log
+  # chown www-data:www-data /var/log/download.log
+
+You will need to do your own log rotation.
+
+
diff --git a/ambdownload.php b/ambdownload.php
new file mode 100644 (file)
index 0000000..c32d715
--- /dev/null
@@ -0,0 +1,43 @@
+<?php\r
+/*\r
+Plugin Name: ambdownload\r
+Plugin URI: http://blog.alex.org.uk/\r
+Description: Redirect a given page to a download URL\r
+Version: 2.2\r
+Author: Alex Bligh\r
+Author URI: http://blog.alex.org.uk\r
+*/\r
+\r
+class ambdownload\r
+{\r
+       function getDownloadLink($user, $file="default")\r
+       {\r
+               $time = time();\r
+               $secret = rtrim(file_get_contents("/etc/apache2/download.secret"));\r
+               $id = $user;\r
+               $hash = hash("sha256",$time.":".$id.":".$file.":".$secret);\r
+               $link = "http://server.example.com/download?";\r
+               return $link.sprintf("id=%s&file=%s&time=%s&hash=%s",urlencode($id),urlencode($file),$time,$hash);\r
+       }\r
+\r
+       function downloadRedirect()\r
+       {       \r
+               global $post;\r
+               if ((is_single() || is_singular() || is_page()))\r
+               {\r
+                       $download_file = get_post_meta($post->ID, 'download_file', true);  \r
+                       if ($download_file) {  \r
+                               global $current_user;\r
+                               get_currentuserinfo();\r
+                               wp_redirect(ambdownload::getDownloadLink($current_user->user_email, $download_file));\r
+                               exit;\r
+                       }\r
+               }\r
+       }\r
+}\r
+\r
+\r
+add_action( 'template_redirect', array('ambdownload', 'downloadRedirect'), 1, 2);\r
+\r
+\r
+\r
diff --git a/download.pl b/download.pl
new file mode 100755 (executable)
index 0000000..af11039
--- /dev/null
@@ -0,0 +1,155 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+use POSIX qw(strftime);
+use URI::Escape;
+use File::Copy qw( copy );
+use File::Basename;
+use Digest::SHA qw(sha256_hex sha1);
+use MIME::Base64;
+use File::Spec;
+use CGI;
+use HTML::Entities;
+use IO::Handle;
+
+my $log;
+my $transaction="unknown";
+
+my $logfile = "/var/log/download.log";
+my $datadir = "/var/www/server.example.com/public_html/download/";
+my $secretfile="/etc/apache2/download.secret";
+my $secret;
+my $sentheader = 0;
+my $maxdrift = 60;
+
+sub lprintf
+{
+    if (defined($log))
+    {
+       my $now = strftime "%a, %d %b %Y %T %z", localtime;
+       print $log "$now: [$$][$transaction]: ";
+       printf $log @_;
+    }
+}
+
+sub closelog
+{
+    close $log if defined($log);
+    $log = undef;
+}
+
+sub openlog
+{
+    closelog;
+    open ($log, '>>', $logfile) || die ("Cannot open logfile $logfile: $!");
+    $log->autoflush;
+}
+
+sub qdie
+{
+    my $err = shift @_;
+    lprintf "ERROR: $err\n";
+    if (!$sentheader)
+    {
+       my $error = encode_entities( $err );
+       print "Status: 404 Not Found\n";
+       print "Content-type: text/html\n\n";
+       print "<html><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>$error</p><hr><address>Download Server</address>";
+       print "</body></html>\n";
+    }
+    closelog;
+    die $err;
+}
+
+sub caughtsignal
+{
+    my $signame = shift;
+    qdie ("Received SIG$signame");
+}
+    
+sub sendfile {
+    my $file = shift @_;
+    my $name = basename($file);
+
+    open my $fh, '<:raw', $file
+        or qdie "Cannot open '$file': $!";
+
+    $sentheader = 1;
+    print CGI::header(
+        -type => 'application/octet-stream',
+        -attachment => $name,
+       );
+
+    binmode STDOUT, ':raw';
+
+    unless (copy $fh => \*STDOUT, 8192)
+    {
+       qdie "Cannot write to STDOUT";
+    }
+
+    close $fh
+        or qdie "Cannot close '$file': $!";
+
+    return;
+}
+
+sub gethash
+{
+    return sha256_hex(shift @_);
+}
+
+sub decodeparams
+{
+    my $query = CGI::url(-absolute=>1);
+    my $clienttime = CGI::url_param('time');
+    my $clientid = CGI::url_param('id');
+    my $clienthash = CGI::url_param('hash');
+    my $clientfile = CGI::url_param('file');
+    $clientfile = "default" unless(defined($clientfile));
+    qdie ("Bad parameters") unless (defined($clienttime) && defined($clientid) && defined($clienthash) && ($clienttime=~/^[0-9]+$/));
+    my $drift = time()-$clienttime;
+    qdie ("Client time has drifted - we have ".time()) if (($drift < -$maxdrift) || ($drift > $maxdrift));
+    qdie ("Bad ID") unless ($clientid=~/^[-+._\@a-zA-Z0-9]+$/);
+    qdie ("Bad filename") unless ($clientfile=~/^[-+._a-zA-Z0-9]+$/);
+    qdie ("Bad filename") if ($clientfile=~/^\./);
+
+    my $hash = gethash($clienttime.":".$clientid.":".$clientfile.":".$secret);
+    qdie ("Bad hash") unless ($hash eq $clienthash);
+    my $fn = $datadir.$clientfile;
+    $fn = File::Spec->rel2abs( readlink($fn) ) if (-l $fn);
+    qdie ("File not found") unless ( -f $fn);
+    $clientfile = basename ($fn);
+    $transaction=$hash." ".$clientfile." ".$clientid;
+    return $fn;
+}
+
+open (my $sfh, "<", $secretfile) || qdie("Can't open secret file $secretfile: $!");
+chomp($secret=join("",<$sfh>));
+close ($sfh);
+
+if (!defined($ENV{DOCUMENT_ROOT}) && !defined($ENV{SERVER_NAME}))
+{
+    die ("Bad parameters") unless ($#ARGV == 1);
+    my $t = time();
+    printf "id=%s&file=%s&time=%s&hash=%s",uri_escape($ARGV[0]),uri_escape($ARGV[1]),$t,gethash($t.":".$ARGV[0].":".$ARGV[1].":".$secret)."\n";
+    exit(0);
+}
+else
+{
+    openlog;
+    my $file = decodeparams;
+    lprintf("STARTING\n");
+    $SIG{INT} = \&caughtsignal;
+    $SIG{QUIT} = \&caughtsignal;
+    $SIG{PIPE} = \&caughtsignal;
+    $SIG{HUP} = \&caughtsignal;
+    $SIG{KILL} = \&caughtsignal;
+    $SIG{TERM} = \&caughtsignal;
+    sendfile($file);
+    lprintf("SUCCESS\n");
+    closelog;
+
+    exit(0);
+}
diff --git a/http.conf.example b/http.conf.example
new file mode 100644 (file)
index 0000000..8570008
--- /dev/null
@@ -0,0 +1,12 @@
+<VirtualHost 192.200.0.1:80>
+  DocumentRoot /var/www/server.example.com/public_html
+  ServerName server.example.com
+  AddHandler cgi-script .pl
+  <Directory "/var/www/server.example.com/public_html/download">
+    Options +ExecCGI
+    Options -Indexes
+    RewriteEngine on
+    RewriteCond %{REQUEST_FILENAME} !download\.pl$
+    RewriteRule ^(.*)$ /download/download.pl
+   </Directory>
+</VirtualHost>