#!/usr/bin/perl -wT

# F*EX CGI for download
#
# Author: Ulli Horlacher <framstag@rus.uni-stuttgart.de>
#

BEGIN { ($ENV{PERLINIT}||'') =~ /(.+)/s and eval $1 }

# use utf8;
use Fcntl 		qw(:DEFAULT :flock :seek);
use Cwd			qw(abs_path getcwd);
use File::Basename;
use IO::Handle;
use Encode;

# add fex lib
($FEXLIB) = $ENV{FEXLIB} =~ /(.+)/;
die "$0: no $FEXLIB\n" unless -d $FEXLIB;

our $error = 'F*EX download ERROR';
our $head = "$ENV{SERVER_NAME} F*EX download";
# import from fex.pp
our ($spooldir,$tmpdir,@logdir,$skeydir,$dkeydir,$akeydir,$durl);
our ($bs,$fop_auth,$timeout,$keep_default,$nowarning,$imgtype,$userlog);
our ($limited_download,$admin,$akey,$adlm,$amdl,$vp,$arx,$archive_sharing);
our (@file_link_dirs);
our ($MB,$RA);

local $from = '';
local $to = '';
local $file = '';
local $qs = $ENV{QUERY_STRING}||'';

# load common code, local config : $HOME/lib/fex.ph
require "$FEXLIB/fex.pp" or die "$0: cannot load $FEXLIB/fex.pp - $!\n";

&redirect_stderr;

my $RM = $ENV{REQUEST_METHOD};

my $maccess = ''; # modify access right

if (@download_hosts and not ipin($RA,@download_hosts)) {
  http_die(
    "Downloads from your host ($RA) are not allowed.",
    "Contacter $ENV{SERVER_ADMIN} pour des détails supplémentaires."
  );
}

&check_maint;

# # call localized fop if available
# if ($0 !~ m{/locale/.*/fop} and my $lang = $ENV{HTTP_ACCEPT_LANGUAGE}) {
#   if ($lang =~ /^de/ and $0 =~ m{(.*)/cgi-bin/fop}) {
#     my $fop = "$1/locale/deutsch/cgi-bin/fop";
#     exec $fop if -x $fop;
#   }
# }

my $log = 'fop.log';

my $http_client = $ENV{HTTP_USER_AGENT} || '';

$file = $ENV{PATH_INFO} || '';
http_die('no file name') unless $file;
$file =~ s:%3F:/?/:g; # escape '?' for URL-decoding
$file =~ s:%([\dA-F]{2}):unpack("a",pack("H2",$1)):ge;
$file =~ s:/\?/:%3F:g; # deescape '?'
$file =~ s:/\.:/_:g;
$file =~ s:^/+::;
$file = untaint($file);

if ($file !~ m:./.:) {
  http_header('403 Forbidden');
  exit;
}

# secure mode with HTTP authorization?
if ($fop_auth) {
  @http_auth = ();
  if (($ENV{HTTP_AUTHORIZATION}||'') =~ /Basic\s+(\S+)/) {
    @http_auth = split(':',decode_b64($1));
  }
  if (@http_auth != 2) {
    &require_auth;
  }
  &check_auth($file,@http_auth);
}

# download-URI-scheme for share archive request (with version)
if ($file =~ m:SHARE/(.+?)/(.+?)/(.+?)/(\w+)/((.+)_($vp\.($arx)))$: or
    $file =~ m:(.+?)/SHARE/(.+?)/(.+?)/(\w+)/((.+)_($vp\.($arx)))$: or
    $file =~ m:(.+?)/(.+?)/(.+?)/(\w+)/((.+)_($vp\.($arx)))$:)
{
  my $owner   = $1;
  my $share   = $2;
  my $suser   = $3;
  my $key     = $4;
  my $file    = $5;
  my $archive = $6;
  my $avt     = $7;
  
#  die "$::file\n[$share] [$suser]";
  unless ($owner =~ /\w/ and $share =~ /\w/ and $suser =~ /\w/) {
    http_die("illegal request");
  }
  checkaddress($owner) or http_die("$owner is not a legal email address");
  checkaddress($suser) or http_die("$suser is not a legal email address");
  my $ic = '[/|<>]';
  $share   =~ /($ic)/ and http_die("$share contains illegal character $1");
  $archive =~ /($ic)/ and http_die("$archive contains illegal character $1");
  $owner .= '@'.$mdomain if $mdomain and $owner !~ /@/;
  $suser .= '@'.$mdomain if $mdomain and $suser !~ /@/;
  
  my $sdir = "$owner/SHARE/$share";
  my $filed = "$sdir/archives/$archive/$avt";
  my $sharing = readlink("$owner/\@ARCHIVE_SHARING")||'';
  if ($sharing =~ /no/i or not $archive_sharing and $sharing !~ /yes/i)
  { http_die("archive sharing n\'est pas autorisé") }
  
  if ($owner eq $suser) {
    $maccess = 'owner';
  } else {
    $maccess = readlink_("$sdir/users/$suser/access");
  }
  
  if (0) {
    # old code!
    my $id = readline1("$owner/@") or
      http_die("unknown owner user $owner");
    if ($key ne md5_hex("$fichier:$id") and
      $key ne md5_hex("$fichier:".md5_hex($id)))
    { 
      # http_die("wrong share access key for owner $suser") 
      nvt_print(
        'HTTP/1.0 426 Upgrade Required - Client too old',
        "Content-Type: text/plain",
        "X-Share-Archive: $filed",
        '',
        "Client too old, you must upgrade"
      );
      exit;
    }
  }
  
  my $akey = '';
  $akey = $1 if ($ENV{HTTP_COOKIE}||'') =~ /akey=(\w+)/;
# http_die("akey=$akey");
  if ($akey and readlink_("$akeydir/$akey") =~ m:/\Q$owner\E$: ) {
    # owner authentificated
  } else {
    $akey = ''
  }

  if ($owner eq $suser and $akey) {
    # $owner authorized
  } else {
    my $pkey = readline1("$sdir/users/$suser/pkey") or
      http_die("unknown user $suser or no PKEY on share $share");
    if ($key ne md5_hex("$fichier:$pkey")) {
      http_die("wrong share access key for $suser");
    }
  }

  if ($RM eq 'HEAD') {
    my $size = -s "$filed/upload" || -s "$filed/data" || 0;
    my $fileid = readlink("$filed/id");
    my $dkey = readlink("$filed/dkey");
    nvt_print(
      'HTTP/1.1 200 OK',
      "Content-Length: $size",
      "X-Share-Archive: $filed",
    );
    if ($fileid) {
      nvt_print("X-File-ID: $fileid");
    }
    if ($dkey and -l "$dkeydir/$dkey") {
      nvt_print("X-Location: $durl/$dkey/$file");
    }
    nvt_print('');
    &reexec;
  }

  $::owner   = $owner;
  $::to      = $owner;
  $::from    = $owner;
  $::suser   = $suser;
  $::share   = $share;
  $::archive = "$archive:$avt";
  $::file    = "$sdir/archives/$archive/$avt";
}

# download-URI-scheme for share archive request (generic)
elsif ($file =~ m:(.+?)/SHARE/(.+?)/(.+?)/(\w+)/(.+): or
       $file =~ m:(.+?)/(.+?)/(.+?)/(\w+)/(.+):)
{
  my $owner   = $1;
  my $share   = $2;
  my $suser   = $3;
  my $key     = $4;
  my $archive = $5;
  unless ($owner =~ /\w/ and $share =~ /\w/ and $suser =~ /\w/) {
    http_die("illegal request");
  }
  $owner .= '@'.$mdomain if $mdomain and $owner !~ /@/;
  $suser .= '@'.$mdomain if $mdomain and $suser !~ /@/;
  my $vt = my $avt = '';
  if ($qs =~ /ARCHIVE=([\w.+-]+)\/([\w.%+-]+)/) {
    $archive = $1;
    $vt = $2;
    $avt = $1.'_'.$2;
  }
  my $sdir = "$owner/SHARE/$share";
  my @archives;
  foreach (glob "$sdir/archives/*/*/data") {
    push @archives,$1 if m:(.*/\Q$archive\E/$vp\.($arx))/:;
  }
  unless (@archives) {
    http_header('404 Fichier introuvable');
    print html_header($head),
          "<h3>archive $archive not found</h3>\n",
          "</body></html>\n";
    exit;
  }

  if ($owner eq $suser) {
    my $id = readline1("$owner/@") or
      http_die("unknown owner user $owner");
    if ($key ne md5_hex("$archive:$id") and
        $key ne md5_hex("$avt:$id") and
        $key ne md5_hex("$archive:".md5_hex($id)))
    { http_die("wrong share access key [$archive]") }
    my $sharing = readlink("$owner/\@ARCHIVE_SHARING")||'';
    if ($sharing =~ /no/i or not $archive_sharing and $sharing !~ /yes/i)
    { http_die("archive sharing n\'est pas autorisé") }
    $maccess = 'owner';
  } else {
    my $pkey = readline1("$sdir/users/$suser/pkey") or
      http_die("unknown share user $suser");
    if ($key ne md5_hex("$archive:$pkey") and
        $key ne md5_hex("$avt:$pkey"))
    { http_die("wrong share access key [$archive]") }
    $maccess = readlink_("$sdir/users/$suser/access");
  }

  $::owner   = $owner;
  $::to      = $owner;
  $::from    = $owner;
  $::suser   = $suser;
  $::share   = $share;
  if ($vt) {
    $::file  = "$owner/SHARE/$share/archives/$archive/$vt";
  } else {
    $::file  = $archives[-1];
  }
  $::archive = $archive.':'.basename($::file);
  # $qs = '';
}

# download-URI-scheme /$dkey/$file ?
elsif ($file =~ m:^(\w+)/[^/]+$:) {
  $dkey = $1;
  if ($link = readlink("$dkeydir/$dkey")) {
    if ($link eq '/dev/null') {
      http_die("/$file has been withdrawn");
    }
    $link =~ s:^\.\./:: or http_die("internal error on dkey for $link");
    $file = untaint($link);
    if ($file =~ m:(.+?)/(.+?)/:) {
      $to   = $1;
      $from = $2;
    }
  } else {
    http_die("no such file /$file");
  }
  if (not $fop_auth and my $dlpw = readlink("$dkeydir/$dkey/dlpw")) {
    @http_auth = ();
    if (($ENV{HTTP_AUTHORIZATION}||'') =~ /Basic\s+(\S+)/) {
      @http_auth = split(':',decode_b64($1));
    }
    readlink("$dkeydir/$dkey") =~ m:/(.+?)/:;
    my $id = readline1("$1/@")||'';
    if (@http_auth != 2 or not length($http_auth[1]) or
        $http_auth[1] ne $dlpw and $http_auth[1] ne $id)
    {
      http_header(
        '401 Authorization Required',
        "WWW-Authenticate: Basic realm=\"$ENV{PATH_INFO}\"",
        'Content-Length: 0',
      );
      # control back to fexsrv for further HTTP handling
      &reexec;
    }
  }
}
# download-URI-scheme /$to/$from/$file
elsif ($file =~ m:.+/.+/.+:) {
  $file =~ s/\?.*//;

  # add domain to addresses if necessary
  if ($file =~ s:(.+?)/(.+?)/(.+):$3:) {
    $to   = lc $1;
    $from = lc $2;
    if ($to eq '+') {
      $prefetch = $to = $from;
    } elsif ($to eq '.') {
      $to = $from;
    } else {
      $to =~ s/[:,].*//;
    }
    $to   .= '@'.$hostname if $to   eq 'anonymous';
    $from .= '@'.$hostname if $from eq 'anonymous';
    $to   .= '@'.$mdomain if $mdomain and -d "$to\@$mdomain";
    $from .= '@'.$mdomain if $mdomain and -d "$from\@$mdomain";
    $file = "$to/$from/$file";
  }

  if ($RM eq 'GET' and -s "$from/\@ALLOWED_RECIPIENTS") {
    http_die("$from is a restricted user");
  }
  
  my $id = '';
  $id = $1 if $qs =~ /\bID=(\S+)/i;
  if (not($id and check_authID($from,$id))) {
    http_die("need auth-ID");
  }
}

if ($file and $to and $from) {
  # afex!
  if ($from =~ s/^(anonymous).*/$1/) {
    if (@anonymous_upload and ipin($RA,@anonymous_upload) or $dkey) {
      $anonymous = $from;
    } else {
      http_header('403 Forbidden');
      print html_header($head),
        "Your ip $RA has no permission to request the URI $ENV{REQUEST_URI}\n",
        "</body></html>\n";
      exit;
    }
  }
}

$filed = $file;
$data = "$filed/data";

# open $file,$file; print Digest::MD5->new->addfile($file)->hexdigest;

unless ($to) {
  http_die("internal error: unknown recipient");
}

unless ($from) {
  http_die("internal error: unknown sender");
}

&check_status($from);

checkaddress($to);
$to = untaint($to);
$foplog = "$to/.log/fop";
mkdir("$to/.log");
foplog('REQUEST');

# server based ip restrictions
if (@download_hosts and not ipin($RA,@download_hosts)) {
  http_die(
    "Downloads from your host ($RA) are not allowed.",
    "Contacter $ENV{SERVER_ADMIN} pour des détails supplémentaires."
  );
}

# user based ip restrictions
unless (check_rhosts("$to/\@DOWNLOAD_HOSTS")) {
  http_die("You are not allowed to download from IP $RA");
}

# file based ip restrictions
unless (check_rhosts("$file/restrictions")) {
  my $ipe = lc(ipe($RA));
  http_die("Download of files from external user $from is restricted "
          ."to internal hosts. Your IP $ipe n\'est pas autorisé.");
}

if ($qs =~ s/(^|&)DELETE//i) {
  if ($from eq $to and not $share) {
    my $id = '';
    $id = $1 if $qs =~ /\bID=(\S+)/i;
    if (not($id and check_authID($from,$id))) {
      http_die("need auth-ID");
    }
  }
  if (unlink $data) {
    foplog('DELETE');
    $filename = filename($file);
    if (open my $log,'>',"$file/error") {
      printf {$log} "%s a été effacé par %s le %s\n",
                    $filename,$RA,isodate(time);
      close $log;
    }
    foreach my $logdir (@logdir) {
      my $msg = sprintf "%s [%s_%s] %s %s deleted\n",
                isodate(time),$$,$ENV{REQUESTCOUNT},$RA,encode_Q($file);
      if (open $log,'>>',"$logdir/$log") {
        print {$log} $msg;
        close $log;
      }
    }
    if ($share and $archive) {
      rmrf($file);
      rmdir(dirname($file));
      faslog("$owner/SHARE/$share","$suser deleted $archive");
    }
    http_header('200 OK',"X-File: $file");
    print html_header($head),
          "<h3>$filename effacé</h3>\n",
          "</body></html>\n";
    exit;
  } else {
    http_die("no such file");
  }
  exit;
}

# request with ?query-parameter ?
if ($qs and not $share) {

  http_die("\"$1\" n\'est pas autorisé dansURL") if $qs =~ /([<>\'\"])/;

  $qs =~ s/^share=.*//;

  # subuser with skey?
  if ($qs =~ s/&*SKEY=([\w:]+)//i) {
    $skey = $1;
    # encrypted skey?
    if ($skey =~ s/^MD5H:(.+)/$1/) {
      # lookup real skey
      foreach my $s (glob "$skeydir/*") {
        $s =~ s:.*/::;
        if ($skey eq md5_hex($s.$ENV{SID})) {
          $skey = $s;
          last;
        }
      }
    }
    if (open $skey,'<',"$skeydir/$skey") {
      $from = $to = '';
      while (<$skey>) {
        $from = lc($1) if /^from=(.+)/;
        $to   = lc($1) if /^to=(.+)/;
      }
      close $skey;
      if ($from and $to) {
        $file =~ s:.*/:$to/$from/:;
      } else {
        http_die("INTERNAL ERROR: missing data in $skeydir/$skey");
      }
    } else {
      debuglog("SKEY=$skey");
      http_die("wrong SKEY authentication");
    }
  }

  # group member with gkey?
  if ($qs =~ s/&*GKEY=([\w:]+)//i) {
    $gkey = $1;
    # encrypted gkey?
    if ($gkey =~ s/^MD5H:(.+)/$1/) {
      # lookup real gkey
      foreach my $g (glob "$gkeydir/*") {
        $g =~ s:.*/::;
        if ($gkey eq md5_hex($g.$ENV{SID})) {
          $gkey = $g;
          last;
        }
      }
    }
    if (open $gkey,'<',"$gkeydir/$gkey") {
      $from = $to = '';
      while (<$gkey>) {
        $from  = lc($1) if /^from=(.+)/;
        $group = lc($1) if /^to=\@(.+)/;
      }
      close $gkey;
      if ($from and $group and open $group,'<',"$from/\@GROUP/$group") {
        while (<$group>) {
          s/#.*//;
          s/\s//g;
          if (/(.+):/) {
            my $to = $1;
            $file =~ s:.*/:$to/$from/:;
            last;
          }
        }
        close $group;
      } else {
        http_die("INTERNAL ERROR: missing data in $gkeydir/$gkey");
      }
    } else {
      debuglog("GKEY=$gkey");
      http_die("wrong GKEY authentication");
    }
  }

  # onetime user with okey?
  if ($qs =~ s/OKEY=(\w+)//i) {
    $okey = $1;
    if ($from = readlink("$to/\@OKEY/$okey")) {
      $from = untaint($from);
      $file =~ s:.*/:$to/$from/:;
    } else {
      debuglog("OKEY=$okey");
      http_die("unknown OKEY");
    }
  }

  # check for ID in query
  elsif ($qs =~ s/\&*\bID=([^&]+)//i) {
    $id = $1;
    $fop_auth = 0;

    if ($id eq 'PUBLIC') {
      http_header('403 Forbidden');
      exit;
    }

    if ($file =~ m:^(.+)/(.+)/(.+):) {
      $to   = $1;
      $from = $2;
      $from =~ s/\s//g;
      if ($to eq '.') {
        $to = $from;
      } else {
        $to   =~ s/,+/,/g;
        $to   =~ s/\s//g;
      }
      if ($mdomain and $from ne 'anonymous') {
        $to   .= '@'.$mdomain if $to   !~ /@/;
        $from .= '@'.$mdomain if $from !~ /@/;
      }
      $to   = lc $to;
      $from = lc $from;
    } else {
      http_die("unknown file query format");
    }

    # public or anonymous recipient? (needs no auth-ID for sender)
    if ($anonymous or 
        $id eq 'PUBLIC' and
        @public_recipients and grep /^\Q$to\E$/i,@public_recipients)
    {
      $dkey ||= $id; # needed for later check
    } else {
      unless (-f "$from/@") { http_die("unknown user $from") }
      unless ($id)          { http_die("no auth-ID") }
      unless (check_authID($from,$id)) {
#       debuglog("real id=$rid, id sent by user=$id");
        http_die("wrong auth-ID");
      }
    }

    # set akey link for HTTP sessions
    # (need original id for consistent non-moving akey)
    if (-f "$from/@") { $akey = genakey($from) }

    my %to;
    COLLECTTO: foreach my $to (split(',',$to)) {
      if ($to !~ /.@./ and open my $AB,'<',"$from/\@ADDRESS_BOOK") {
        while (<$AB>) {
          s/\s*#.*//;
          s/^\s+//;
          next unless $_;
          if (/^\s*([\S]+)\s+([\S]+)/) {
            my ($alias,$address) = ($1,$2);
            if ($to =~ /^\Q$alias\E$/i) {
              foreach my $to (split(",",$address)) {
                $to .= '@'.$mdomain if $mdomain and $to !~ /@/;
                $to{$to} = lc $to; # ignore dupes
              }
              next COLLECTTO;
            }
          }
        }
      } elsif ($to =~ /^\@(.+)/) {
        my $group = "$from/\@GROUP/$1";
        if (not -l $group and open $group) {
          while (<$group>) {
            s/#.*//;
            s/\s//g;
            if (/(.+\@[w.-]+):.+/) {
              $to{$1} = lc $1; # ignore dupes
            }
          }
          close $group;
        }
      } else {
        $to .= '@'.$mdomain if $mdomain and $to !~ /.@./;
        $to{$to} = lc $to; # ignore dupes
      }
    }
    foreach $to (keys %to) {
      # if (-e "$to/\@CAPTIVE") { http_die("$to is CAPTIVE") }
      unless (-d $to or checkaddress($to)) {
        http_die("$to is not a legal email address");
      }
    }

  }

  if ($qs =~ /\&?KEEP=(\d+)/i) {
    $keep = $1;
    $filename = filename($file);
    check_captive($file);
    if  (-f $data) {
      unlink "$file/keep";
      if (symlink $keep,"$file/keep") {
        http_header('200 OK');
        print html_header($head),
              "<h3>set keep=$keep for $filename</h3>\n",
              "</body></html>\n";
      } else {
        http_header('599 internal error');
        print html_header($head),
              "<h3>$filename - $!</h3>\n",
              "</body></html>\n";
      }
    } else {
      http_header('404 Fichier introuvable');
      print html_header($head),
            "<h3>$filename not found</h3>\n",
            "</body></html>\n";
    }
    exit;
  } elsif ($qs =~ s/\&?KEEP//i) {
    check_captive($file);
    $autodelete = 'NO';
  }

  if ($qs =~ s/\&?FILEID=(\w+)//i) { $fileid = $1 }

  if ($qs =~ s/\&?IGNOREWARNING//i) { $ignorewarning = 1 }

  if ($qs =~ /^LIST(META)?$/) {
    http_header('200 OK','Content-Type: text/plain');
    print "$file :\n";
    chdir $file and exec qw'l -T l -f d';
    exit;
  }

  # copy file to yourself
  if ($qs eq 'COPY') {
    unless (-f "$file/data") {
      http_die("Fichier introuvable.");
    }
    ($to,$from,$file) = split('/',$file);
    unless ("$to/@") {
      # http_header('403 Forbidden');
      # print html_header($head),
      #  "You have no permission to copy a file.\n",
      #  "</body></html>\n";
      http_die("You have no permission to copy a file.");
    }
    if (-s "$to/\@ALLOWED_RECIPIENTS") {
      http_die("You are a restricted user.");
    }
    if (-e "$to/$to/$file/data") {
      # http_header('409 File Exists');
      # print html_header($head),
      #   "Le fichier $file exite déjà dans votre spool sortant.\n",
      #   "</body></html>\n";
      http_die("Le fichier $file exite déjà dans votre spool sortant.");
    }
    mkdirp("$to/$to/$file");
    link "$to/$from/$file/data","$to/$to/$file/data"
      or http_die("cannot link to $to/$to/$file/data - $!\n");
    my $fkey = copy("$to/$from/$file/filename","$to/$to/$file/filename");
    open my $notify,'>',"$to/$to/$file/notify";
    close $notify;
    my $dkey = randstring(8);
    unlink "$to/$to/$file/dkey","$dkeydir/$dkey";
    symlink "../$to/$to/$file","$dkeydir/$dkey";
    symlink $dkey,"$to/$to/$file/dkey";
    http_header('200 OK',"Location: $durl/$dkey/$fkey");
    print html_header($head),
      "File $file copied to yourself.\n",
      "</body></html>\n";
    exit;
  }

  # wipe out!? (for anonymous upload)
  if ($qs =~ s/(^|&)PURGE//i) {
    $filename = filename($file);
    if (@anonymous_upload and ipin($RA,@anonymous_upload)) {
      unlink "$dkeydir/$dkey" if $dkey;
      if (rmrf($file)) {
        foreach my $logdir (@logdir) {
          my $msg = sprintf "%s [%s_%s] %s %s purged\n",
                    isodate(time),$$,$ENV{REQUESTCOUNT},$RA,encode_Q($file);
          if (open $log,'>>',"$logdir/$log") {
            print {$log} $msg;
            close $log;
          }
        }
        http_header('200 OK',"X-File: $file");
        print html_header($head),
          "<h3>$filename purged</h3>\n",
          "</body></html>\n";
      } else {
        http_die("no such file");
      }
    } else {
      http_die("you are not allowed to purge $filename");
    }
    exit;
  }

  # request for taille du fichier?
  if ($qs eq '?') {
    sendsize($file);
    # control back to fexsrv for further HTTP handling
    &reexec;
  }

  # reject unknown URL parameters
  if ($qs and $qs !~ /\b(DOWNLOAD|EXTRACT|SHOW|PREVIEW|INDEX|LISTARCHIVE|vkey)|^!/) {
    http_die("unknown query format $qs");
  }

}

unless ($id and check_authID($from,$id) or $dkey or $anonymous or $share) {
  http_die("wrong parameter $file");
}

if ($from and $file eq "$from/$from/ADDRESS_BOOK") {
  if (open my $AB,'<',"$from/\@ADDRESS_BOOK") {
    my $ab = '';
    while (<$AB>) {
      s/^\s+//;
      s/\s+$//;
      s/[\r\n]//g;
      $ab .= $_."\r\n";
    }
    close $AB;
    nvt_print(
      'HTTP/1.1 200 OK',
      'Content-Length: ' . length($ab),
      'Content-Type: text/plain',
      ''
    );
    print $ab;
  } else {
    nvt_print(
      'HTTP/1.1 404 No address book found',
      'Content-Length: 0',
      ''
    );
  }
  # control back to fexsrv for further HTTP handling
  &reexec;
}

if ($from and $file eq "$from/$from/CONFIG") {
  my $config = '';
  if (open my $CF,'<',"$from/\@CONFIG") {
    while (<$CF>) {
      s/^\s+//;
      s/\s+$//;
      s/[\r\n]//g;
      $config .= $_."\r\n";
    }
    close $CF;
  } else {
    $config =
      "## user configuration defaults\r\n".
      "#\r\n".
      "## keep (days)\r\n".
      "# keep=10\r\n".
      "#\r\n".
      "## xxx keep (days)\r\n".
      "# keep_xxx=1\r\n".
      "#\r\n".
      "## autodelete (yes,no,delay)\r\n".
      "# autodelete=delay\r\n".
      "";
  }

  nvt_print(
    'HTTP/1.1 200 OK',
    'Content-Length: ' . length($config),
    'Content-Type: text/plain',
    ''
  );
  print $config;
  # control back to fexsrv for further HTTP handling
  &reexec;
}

if (-f $data) {
  # already downloaded (or accessed)?
  my $accessed;
  my $mhdl = lc(readlink("$to/\@MULTIHOST_DOWNLOAD")||'');
  if ($limited_download and $limited_download !~ /^n/i
      and $from ne $to			# fex to yourself is ok!
      and $from !~ /^_?fexmail/		# fexmail is ok!
      and $to !~ /^_?fexmail/		# fexmail is ok!
      and $to !~ /^anonymous/		# anonymous fex is ok!
      and $to !~ /$amdl/		# allowed multi download recipients
      and $mhdl ne 'yes'                # recipient multihost download option
      and $file !~ /\/STDFEX$/		# xx is ok!
      and $file !~ /\/SHARE\//		# sharing is ok!
      and (slurp("$file/comment")||'') !~ /!\*!/ # multi download allow flag
      and (open $file,'<',"$filed/download" and $accessed = 'downloaded' or
           open $file,'<',"$filed/view"     and $accessed = 'viewed' or
           open $file,'<',"$filed/access"   and $accessed = 'accessed'))
  {
#      and $http_client !~ /$adlm/	# allowed download managers
    my $d1 = <$file> || ''; # first download
    chomp $d1;
    close $file;
    if ($RA) {
      # allow downloads from same ip
      $d1 = '' if $d1 =~ /^[\d\s:-]+\Q$RA/;
      # allow downloads from sender ip
      $d1 = '' if (readlink("$file/ip")||'') eq $RA;
      # allow downloads from same hostname (with different ips)
      if ($d1 =~ /^[\d-]+ [\d:]+ ([\w.:]+)/) {
        my $da = $1;
        my ($dh,$rh);
        $dh = $1 if `host $da 2>/dev/null` =~ / pointer (.+)/;
        $rh = $1 if `host $RA 2>/dev/null` =~ / pointer (.+)/;
        $d1 = '' if $dh and $rh and $dh eq $rh;
      }
    }
    if ($d1 and $d1 =~ /^([\d-]+ [\d:]+) ([\w.:]+)/) {
      # $file = filename($file);
      http_die("$file has already been $accessed by $2 at $1");
    }
  }
} elsif (-l $data) {
  # $file =~ s:.*/::;
  http_die("<code>$file</code> has been withdrawn");
} elsif (my $err = readline1("$file/error")) {
  fdlog($log,$file,0,0);
  http_die($err);
} elsif (not -f "$file/data" and $_ = readline1("$file/download")) {
  # fallback because of bug in old fex_cleanup
  fdlog($log,$file,0,0);
  my $err = $_;
  if (/^([\d-]+ [\d:]+) (\S+)/) {
    $err = sprintf "%s has been autodeleted after download from %s at %s\n",
                   filename($file),$2,$1;
  }
  http_die($err);
} else {
  fdlog($log,$file,0,0);
  if ($file =~ /^anonymous.*afex_\d+\.tar$/) {
    # should be extra handled...
  }
  http_die("no such file $file");
}

if (lstat "$filed/protected" and $http_client !~ /^(fex|wget)/i) {
  my $vkey = '';
  $qs =~ /vkey=(\w+)/ and $vkey = $1;
  if ($vkey ne $dkey) {
    my $uri = $ENV{REQUEST_URI};
    $uri =~ s/\?.*//;
    http_header('200 Ok');
    print html_header($head);
    pq(qq(
      '<h1>Download is protected</h1>'
      '<form action="$uri" method="get">'
      'Download key:'
      '<input type="text" name="vkey" size="10">'
      '<input type="submit" value="soumettre">'
      '</form>'
      '</body></html>'
    ));
    exit;
  }
}

$alist = "$filed/alist";

if ($filed =~ /\.(zip|7z)$/i and -s $alist and -s $data and $qs) {

  if ($qs =~ /EXTRACT=(\d+):(.+)/ and $1) {
    my $size = $1;
    my $file = $2;

    $file =~ s/%([\dA-F]{2})/unpack("a",pack("H2",$1))/ge;

    close STDERR;
    if ($filed =~ /\.zip$/i) {
      open $data,'-|',qw'unzip -p',$data,shellquote($file)
        or http_die("cannot unzip $filed - $!\n");
    }
    if ($filed =~ /\.7z$/i) {
      open $data,'-|',qw'7z e -so',$data,$file
        or http_die("cannot unzip $filed - $!\n");
    }
    my $x;
    if (read($data,$x,$bs)) {
      nvt_print('HTTP/1.1 200 OK');
      nvt_print("Content-Length: $size") if $size >= 0;
      if ($file =~ /\.($imgtype)$/i) {
        nvt_print("Content-Type: image/$1");
      } elsif ($file =~ /\.(pdf)$/i) {
        nvt_print("Content-Type: application/$1");
      } elsif ($file =~ /\.txt$/i) {
        nvt_print("Content-Type: text/plain");
      } else {
        nvt_print("Content-Type: application/binary");
        nvt_print("Content-Disposition: attachment; filename=\"$file\"");
      }
      nvt_print("Connection: close",'');
      print $x;
      print $x while read($data,$x,$bs);
      close $data;
    } else {
      http_die("$file not found in $filed");
    }
    fdlog($log,"$filed:$file",$size,-s $data);
    my $view = "$filed/view";
    if (open $view,'>>',$view) {
      printf {$view} "%s %s %s\n",isodate(time),$RA,$file;
      close $view;
    }
    exit;
  }

  if ($qs =~ /SHOW=(\d+)/ and $1) {
    my $i = $1;
    my $rnd = $i;
    my $archive = basename($filed);
    my ($file,$zf,$dkey,$fname,$uri,$browse,$counter);
    my ($previous,$next,$first,$last,$random,$index,$gallery,$previousa,$nexta);
    my ($extract,$style,$src,$nav,$z7l);
    my @images = ();

    open $alist,'<',$alist or http_die("cannot open $alist - $!\n");
    while (<$alist>) {
      $z7l //= /^ *Date +Time +Size +Name/;
      if ($z7l) {
        if (/^[\d-]+ [\d:]+ +(\d+) (.+\.($imgtype))$/i) {
          push @images,"$1:$2";
        }
      } elsif ($filed =~ /\.zip$/i) {
        if (/^ *(\d+) +[\d-]+ [\d:]+ +(.+\.($imgtype))$/i) {
          push @images,"$1:$2";
        }
      }
    }
    close $alist;
    unless (@images) {
      http_die("no images in archive $archive");
    }
    $file = $images[$i-1];
    unless (defined($file)) {
      http_die("no image #$i in archive $archive");
    }
    $file =~ s/^\d+://;
    $fname = htmlencode($file);
#    unless ($share) {
#      if (($ENV{HTTP_COOKIE}||'') =~ /dkey=(\w+)/) {
#        $dkey = $1;
#        if (readlink_("$filed/dkey") ne $dkey) {
#          http_die("wrong DKEY\n");
#        }
#      } else {
#        http_die("no DKEY\n");
#      }
#    }
    
    close STDERR;
    if ($filed =~ /\.zip$/i) {
      open $data,'-|',qw'unzip -p',$data,shellquote($file)
        or http_die("cannot unzip $filed - $!\n");
    }
    if ($filed =~ /\.7z$/i) {
      open $data,'-|',qw'7z e -so',$data,$file
        or http_die("cannot unzip $filed - $!\n");
    }
    local $/;
    $zf = <$data>;
    if (not defined($zf) or length($zf)<1) {
      http_die("$fname not found in $filed")
    }
    close $data;
    if ($share) {
      $uri = $ENV{REQUEST_URI};
      $uri =~ s/\?.*//;
    } else {
      $dkey = readlink_("$filed/dkey") or http_die("no DKEY\n");
      $uri = "/fop/$dkey/$archive";
    }
    $archive =~ s/\.(zip|7z)$//i;
    if ($#images) { $rnd = int(rand($#images+1))+1 while $rnd == $i }
    $first  = sprintf('<a href="%s?SHOW=%d"><button>first</button></a>',$uri,1);
    $last   = sprintf('<a href="%s?SHOW=%d"><button>last</button></a>',$uri,$#images+1);
    $random = sprintf('<a href="%s?SHOW=%d"><button>random</button></a>',$uri,$rnd);
    $index  = sprintf('<a href="%s?INDEX"><button>index</button></a>',$uri);
    if (-f "$filed/preview/1.jpg") {
      $gallery = sprintf('<a href="%s?PREVIEW"><button id="gallery">gallery</button></a>',$uri);
    } else {
      $gallery = '';
    }
    $counter = sprintf('(%d/%d)',$i,$#images+1);
    if ($i>1) {
      $previous =  sprintf('<a href="%s?SHOW=%d"><button id="previous">previous</button></a>',$uri,$i-1);
      $previousa = sprintf('<a href="%s?SHOW=%d"><button><h1>&larr;</h1></button></a>',$uri,$i-1);
    } else {
      $previous = 'previous';
      $previousa = '<h1>&nbsp;</h1>';
    }
    if (defined($images[$i])) {
      $next  =  sprintf('<a href="%s?SHOW=%d"><button id="next">next</button></a>',$uri,$i+1);
      $nexta = sprintf('<a href="%s?SHOW=%d"><button><h1>&rarr;</h1></button></a>',$uri,$i+1);
    } else {
      $next  = 'next';
      $nexta = '<h1>&nbsp;</h1>';
    }
    if (scalar(@images) == 1) {
      $first  = 'first';
      $last   = 'last';
      $random = 'random';
    }
    if ($share) {
      $extract = sprintf('%s?EXTRACT=%s',$uri,$images[$i-1]);
    } else {
      $extract = sprintf('/fop/%s/%s?EXTRACT=%s',$dkey,urlencode(basename($file)),$images[$i-1]);
    }
#   $style = 'max-height:800px;height:auto;width:auto;';
#   $style = 'max-width:80vw;max-height:80vh';
    $style = 'max-width:calc(100vw - 8em);max-height:calc(100vh - 10em)';
    $src = "data:image/jpeg;base64,".encode_b64($zf);
    $nav = join(' &nbsp; 'x3,$first,$previous,$next,$last,$random,$index,$gallery,$counter);
    http_header('200 OK');
    pq(qq(
      '<html>'
      '<HEAD>'
      '<meta name="viewport" content="width=device-width, initial-scale=1" />'
      '<TITLE>$fname</TITLE>'
      '</HEAD>'
      '<body>'
      '<script>'
      'document.onkeydown = function(e) {'
      '  switch (e.keyCode) {'
      '    case  8:'
      '    case 37:'
      '      document.getElementById("previous").click();'
      '      break;'
      '    case 32:'
      '    case 39:'
      '      document.getElementById("next").click();'
      '      break;'
      '    case 38:'
      '      document.getElementById("gallery").click();'
      '      break;'
      '  }'
      '};'
      '</script>'
      '<center>'
      '$nav'
      '<p>'
      '<table border=0><tr>'
      '<td>$previousa'
      '<td><a href="$extract"><img style="$style" src="$src"></a>'
      '<td>$nexta'
      '</tr></table>'
      '<h1>$archive : <a href="$extract">$fname</a></h1>'
      '$nav'
      '</center>'
      '</body>'
      '</html>'
    ));

    fdlog($log,"$filed:$file",length($zf),-s $data);
    my $view = "$filed/view";
    if (open $view,'>>',$view) {
      printf {$view} "%s %s %s\n",isodate(time),$RA,$file;
      close $view;
    }
    exit;
  }

  # no more longer used, because PREVIEW delivers index.html with b64 images
  if ($qs =~ /PREVIEW=(\d+)/ and $1) {
    my $preview = "$filed/preview/$1.jpg"; # WRONG! May be gif or png!
    if (my $size = -s $preview and open $preview,$preview) {
      nvt_print(
        'HTTP/1.1 200 OK',
        "Content-Length: $size",
        'Content-Type: image/jpg',
        ''
      );
      my $x;
      print $x while read($preview,$x,$bs);
    } else {
      nvt_print(
        'HTTP/1.1 404 Fichier introuvable',
        'Content-Length: 0',
        ''
      );
    }
    &reexec;
  }

  if ($qs =~ /PREVIEW$/) {
    chdir "$filed/preview" or http_die("$filed/preview - $!");
    my $preview = "index.html";
    if (open $preview,$preview) {
      http_header(
        '200 OK',
        'Content-Type: text/html',
      );
      while (<$preview>) {
        if (/<a href=".*?SHOW=(\d+)">/) {
          my @pimg = glob "$1.*";
          if (@pimg and -f $pimg[0]) {
            my $image = slurp($pimg[0]);
            my $src = "data:image/jpeg;base64,".encode_b64($image);
            s/img src=".*"/img src="$src"/;
          }
        }
        print;
      }
    } else {
      nvt_print(
        'HTTP/1.0 404 Fichier introuvable',
        'Content-Length: 0',
        ''
      );
    }
    exit;
  }

}

if (-s $alist and -s $data and $qs !~ /DOWNLOAD/) {
  my $webbrowser =
    'Mozilla|Firefox|AppleWebKit|Gecko|Chrome|Safari|Opera|MSIE|w3m|Lynx';
  my $uri = $ENV{REQUEST_URI};
  my $rdkey = '   ';
  my $listarchive = $qs eq 'LISTARCHIVE';
  my @images = ();
  my $access = "$filed/access";

  if ($qs !~ /^INDEX/) {
    $rdkey = $1 if ($ENV{HTTP_HEADER}||'') =~ m{\nReferer:.*/fop/(.+)/};
  }

  if (($http_client =~ /$webbrowser/ and
       $http_client !~ /Thunderbird/ and
       $uri !~ /$rdkey/
       or $qs eq '!' or $listarchive)
      and open $alist,'<',$alist)
  {

    if ($limited_download !~ /^n/i and -s $access and
        $filed =~ m:(.+?@.+?)/(.+?@.+?)/:)
    {
      my $to = $1;
      my $from = $2;
      if ($from ne $to and
          $from !~ /^_?fexmail/ and
          $to !~ /^_?fexmail/ and
          $to !~ /^anonymous/ and
          lc(readlink("$to/\@MULTIHOST_DOWNLOAD")||'') ne 'yes' and
          (slurp("$file/comment")||'') !~ /!\*!/ and
          ($ENV{HTTP_COOKIE}||'') !~ /dkey=$dkey/)
      {
        foreach my $a (qw'dowload view access') {
          local $_ = slurp("filed/$a")||'';
          if (/^([\d-]+ [\d:]+) ([\w.:]+)/ and $2 ne $RA) {
            http_die("$file has already been ${a}ed by $2 at $1");
          }
        }
      }
    }

    my $size = int((-s $data||0)/$MB+0.5)||'<1';
    my $comment = htmlquote(slurp("$filed/comment")||'');
    $comment =~ s/^!.+?!\s*//;
    $comment =~ s/^NOMAIL//;
    $comment =~ s/\n/ /g;
    $comment =~ s/\s+$//g;
    $uri =~ s/\?.*//;
    if ($listarchive) {
      http_header('200 OK');
      print "<html><body>\n";
    } elsif ($filed =~ m:(.+?)/SHARE/(.+?)/archives/(.+)/(.+):) {
      my $owner = $1;
      my $share = $2;
      my $archive = $3;
      my $vt = $4;
      my $file = $3.'_'.$4;
      my $uploader = readlink("$filed/uploader")||$owner;
      my $fas= "/fas?owner=$owner?share=$share";
      my $referer = $ENV{HTTP_REFERER}||'';
      my $mr = '';
      my $ma = (readlink("$filed/keep")||$keep_default)*60*60*24;
      if ($referer =~ /(user=.*pkey=\w+)/) {
        $fas .= "?$1"
      } elsif ($referer =~ m:/fas/.+/(.+@.+)/(\w+)$:) {
        $fas .= "?user=$1?pkey=$2"
      }
      if (0 and $maccess =~ /owner|manage/) {
        my $formparam =
          'method="post" accept-charset="UTF-8" enctype="multipart/form-data"';
        $comment = qqq(qq(
          '<form action="$fas?modify=commentaire:$archive:$vt" $formparam>'
          '<input type="text"   name="comment" value="$comment" size="80">'
          '<input type="submit" value="save">'
          '</form>'
        ));
      }
      if ($comment =~ /\S/) {
        $comment = "<tr><td><b>commentaire:</b><td><b>$comment</b></tr>";
      } else {
        $comment = '';
      }
      my @archives = glob(dirname($filed).'/*_*/data');
      if (@archives and $archives[-1] eq "$filed/data") {
        $mr = ' (most recent)';
      }
      $dkey ||= readlink("$filed/dkey");
      if ($dkey) {
        http_header(
          '200 OK',
          "Set-Cookie: dkey=$dkey; Max-Age=$ma; Path=/fop/$dkey",
        );
      } else {
        http_header('200 OK');
      }
      my $suri = $uri;
      $suri =~ s:/fop:/fas:;
      $suri =~ s:/SHARE/([^/]+/[^/]+).*:/$1:;
      print html_header($file,"<a href=\"$uri?DOWNLOAD=$file\">Download: $file</a>");
      pq(qq(
        '<h3>$filed</h3>'
        '<table>'
        '<tr><td><b>archive:</b><td><b><a href="$uri">$file</a></b>$mr</tr>'
        '<tr><td><b>size:</b><td><b>$size MB</b></tr>'
        '<tr><td><b>share:</b><td><b><a href="$suri">$share<a></b></tr>'
        '<tr><td><b>owner:</b><td><b>$owner</b></tr>'
        '<tr><td><b>uploader:</b><td><b>$uploader</b></tr>'
        '$comment'
        '</table>'
        '<p>'
      ));
      if ($akey and readlink_("$akeydir/$akey") =~ m:/\Q$owner\E$: ) {
        pq(qq(
          '[<a href="$fas?show=archive:$share:$archive">show all versions</a>]'
          '[<a href="$fas?show=share:$share:archives">show share</a>]'
          '<p>'
        ));
      }
    } elsif ($filed =~ m:(.+?)/(.+?)/(.+):) {
      # regular fop
      my $to = $1;
      my $from = $2;
      my $file = $3;
      my $dkey = readlink_("$filed/dkey");
      my $ma = (readlink("$filed/keep")||$keep_default)*60*60*24;
      my $uri = $ENV{REQUEST_URI};
      
      $uri =~ s/\?.*//;
      http_header(
        '200 OK',
        "Set-Cookie: dkey=$dkey; Max-Age=$ma; Path=/fop/$dkey"
      );
      print html_header($file,"<a href=\"$uri?DOWNLOAD=$file\">Download: $file</a>");
#      print "<pre>Set-Cookie: dkey=$dkey; Max-Age=$ma; Path=$uri</pre>\n"
      pq(qq(
        '<table>'
        '<!-- fichier: $file -->'
        '<tr><td><b>File:</b><td><b><a href=\"$uri\">$file</a></b></tr>'
        '<!-- size: $size MB -->'
        '<tr><td><b>Size:</b><td><b>$size MB</b></tr>'
        '<!-- expéditeur: $from -->'
        '<tr><td><b>Sender:</b><td><b>$from</b></tr>'
        '<!-- destinataire: $to -->'
        '<tr><td><b>Recipient:</b><td><b>$to</b></tr>'
      ));
      if ($comment =~ /\S/) {
        pq(qq(
        '<!-- commentaire: $comment -->'
        '<tr><td><b>commentaire:</b><td><b>$comment</b></tr>'
        ));
      }
      print "</table>\n";
    } else {
      http_die("INTERNAL ERROR: file=$filed ?!");
    }
    my $list = '';
    my $z7l;
    my $zl;
    if ($filed =~ /\.zip$/i) {
      $zl = 1;
    }
    if ($filed =~ /\.7z$/i and `7z l $filed/data 2>/dev/null` =~ /\nSolid = -/) {
      $zl = 1;
    }
    while (<$alist>) {
      s/&/&amp;/g;
      s/</&lt;/g;
      $z7l //= /^ *Date +Time +Size +Name/;
#      unless ($listarchive or m:/$: or $filed =~ m:/SHARE/: and $filed !~ m:/test/:) {
      unless ($listarchive) {
        next if m:/$:;
        if ($zl) {
          if ($z7l) {
            unless (/\d \d+ files(, \d+ folders)?$/) {
              s/^(\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d +(\d+) )(.+)/$1<a href="$uri?EXTRACT=$2:$3">$3<\/a>/;
            }
          } else {
            s/ (\d\d)-(\d\d)-(\d\d\d\d) / $3-$1-$2 /;
            s/^(\s*(\d+)\s+[\d-]+ \d\d:\d\d   )(.+)/$1<a href="$uri?EXTRACT=$2:$3">$3<\/a>/;
          }
          if (/>(.+\.($imgtype))</i) {
            push @images,$1;
            if (1 or $qs =~ /^INDEX/) {
              my $i = $#images+1;
              s/EXTRACT=.*?\"/SHOW=$i\"/;
              s/\n/ ($i)\n/;
            }
          }
        }
        # rename file so that a webbrowser can save its name
        if (/\?EXTRACT=(.+?)\"/) {
          my $x = $1;
          $x =~ s|.*[:/]||;
          if ($x =~ /\.($imgtype|txt|pdf)$/i) {
            s/[^\/]+\?/$x?/;
            my $archive = $filed;
            if ($archive =~ m:/SHARE/:) {
              $archive =~ s:.*?/archives/::;
            } else {
              $archive =~ s:.*/::;
            }
            s/EXTRACT=/ARCHIVE=$archive&EXTRACT=/;
          }
        }
      }
      $list .= $_;
    }

    if (open $access,'>>',$access) {
      printf {$access} "%s %s\n",isodate(time),$RA;
      close $access;
    }

    if (scalar(@images)>1 and -f "$filed/preview/1.jpg") {
      pq(qq(
        '<h3>Archive content <a href="$uri?PREVIEW">[preview images]</a>:</h3>'
        '<pre>'
        '$list'
        '</pre>'
        '<a href="$uri?PREVIEW"><button>preview images</button></a>'
      ));
    } else {
      pq(qq(
        '<h3>Archive content:</h3>'
        '<pre>'
        '$list'
        '</pre>'
      ));
    }
    print "</body></html>\n";
    exit;
  }
}

# set time mark for this access
if ($file =~ m:(.+?)/:) {
  my $user = $1;
  my $time = untaint(time);
  utime $time,$time,$user;
}

my $seek = 0;
my $stop = 0;

# reget or range?
if ($range = $ENV{HTTP_RANGE}) {
  debuglog("Range: $range");
  $seek = $1 if $range =~ /^bytes=(\d+)-/i;
  $stop = $1 if $range =~ /^bytes=\d*-(\d+)/i;
}

if (not $autodelete or $autodelete ne 'NO') {
  $autodelete = readlink("$file/autodelete")||'YES';
}
$autodelete = 'NO' if $file =~ m:/SHARE/: and not $dkey;

$sb = sendfile($file,$seek,$stop);
shutdown(STDOUT,2);

debuglog(sprintf("%s %s %d %d %d",
         isodate(time),$file,$sb||0,$seek,(-s $data)||0));
# debuglog(sprintf("%s+%s == %s",$sb,$seek,(-s $data)||0));

if ($sb+$seek == (-s $data)||0) {

  # note successful download
  $download = "$file/download";
  if (open $download,'>>',$download) {
    printf {$download} "%s %s\n",isodate(time),$RA;
    close $download;
  }
  foplog('READ');
  if ($file =~ m:(.+)/SHARE/(_)/archives/(.+?)/(.+):) {
    $owner = $1;
    $share = $2;
    $archive = "$3:$4";
    $suser = '.';
  }
  if ($share and $archive) {
    faslog("$owner/SHARE/$share","$suser downloaded $archive");
  }

  # delete file after grace period
  if (uc($autodelete) eq 'YES') {
    $grace_time = 60 unless defined $grace_time;
    for (;;) {
      my $utime = (stat $data)[8] || 0;
      my $dtime = (stat $download)[8] || 0;
      exit if $utime > $dtime;
      last if time > $dtime+$grace_time;
      sleep 10;
    }
    unlink $data;
    my $error = "$file/error";
    if (open $error,'>',$error) {
      printf {$error} "%s has been autodeleted after download from %s at %s\n",
                      filename($file),$RA,isodate(time);
      close $error;
    }
  }

}

exit;


sub sendfile {
  my ($file,$seek,$stop) = @_;
  my ($filename,$size,$total_size,$fileid,$md5sum,$filetype,$streaming);
  my ($data,$download,$upload,$header,$buf,$range,$s,$b,$t0);
  my $type = '';

  $seek ||= 0;
  
  # swap to and from for special senders, see fup storage swap!
  $file =~ s:^(_?anonymous_.*)/(anonymous.*)/:$2/$1/:;
  $file =~ s:^(_?fexmail_.*)/(fexmail.*)/:$2/$1/:;

  $data     = $file.'/data';
  $download = $file.'/download';
  $header   = $file.'/header';

  # fallback defaults, should be set later with better values
  $filename = filename($file);
  $total_size = -s $data || 0;

  # file link?
  if (-l $data) {
    # prefetch? (fexsync, etc)
    if (readlink($data) eq 'upload') {
      if (open $data,'<',$data and flock($data,LOCK_EX|LOCK_NB)) {
        $file =~ m:(.+)/.+/(.+):;
        http_die("$1 has stopped uploading $2");
      }
      close $data;
      $total_size = readlink("$file/size");
      unless (defined $total_size) {
        # taille du fichier is unknown on streaming upload
        $total_size = -1;
        $streaming = 1;
      }
      $upload = "$file/upload";
    } else {
      unless (-f $data and -r $data) {
        http_die("<code>$file</code> has been withdrawn");
      }
      $data = abs_path($data);
      my $fok;
      foreach (@file_link_dirs) {
        my $dir = abs_path($_);
        $fok = $data if $data =~ /^\Q$dir\//;
      }
      unless ($fok) {
        http_die("no permission to download <code>$file</code>");
      }
    }
  } else {
    unless (-f $data and -r $data) {
      http_die("<code>$file</code> has gone");
    }
  }

  if ($RM eq 'GET') {
    debuglog("Exp: FROM=\"$from\"","Exp: TO=\"$to\"");
    open $data,'<',$data or http_die("cannot read <code>$file</code>");
    flock($data,LOCK_EX|LOCK_NB) unless $upload;

    # security check: must be regular file after abs_path()
    if (-l $data and not $upload) {
      http_die("no permission to download <code>$file</code>");
    }
    # HTTP Range download suckers are already rejected by fexsrv
#    unless ($range = $ENV{HTTP_RANGE}) {
      # download lock
      open $download,'>>',$download or die "$download - $!\n";
      if ($file =~ m:(.+?)/(.+?)/: and $1 ne $2) {
        # only one concurrent download is allowed if sender <> recipient
        flock($download,LOCK_EX|LOCK_NB) or
          http_die("$file locked: a download is already in progress");
      }
#    }
    $size = $total_size - $seek - ($stop ? $total_size-$stop-1 : 0);
  } elsif ($RM eq 'HEAD') {
    # $size = -s $data || 0;
    $size = readlink("$file/size") || -1; # no size symlink ==> streaming upload
  } else {
    http_die("unknown HTTP request method $RM");
  }

  # read MIME entity header (what the upload client said)
  if (open $header,'<',$header) {
    while (<$header>) {
      if (/^Content-Type: (.+)/i) {
        $type = $1;
        last;
      }
    }
    close $header;
    $type =~ s/\s//g;
  }

  $fileid = readlink_("$file/id");
  $md5sum = readlink_("$file/md5sum");

  # determine own MIME entity header for download
  my $mime = $file;
  $mime =~ s:/.*:/\@MIME:;
  my $mt = $ENV{FEXHOME}.'/etc/mime.types';
  if (($type =~ /x-mime/i or -e $mime) and open $mt,'<',$mt) {
    $type = '';
    MIMETYPES: while (<$mt>) {
      chomp;
      s/#.*//;
      s/^\s+//;
      my ($mt,@ft) = split;
      foreach my $ft (@ft) {
        if ($filename =~ /\.\Q$ft\E$/i) {
          $type = $mt;
          last MIMETYPES;
        }
      }
    }
    close $mt;
    unless ($type) {
      if (`file $file/data` =~ /script|text/) {
        $type = 'text/plain';
      }
    }
  }
  # reset to default MIME type
  $type ||= 'application/octet-stream';

  # HTML n\'est pas autorisé for security reasons! (embedded javascript, etc)
  $type =~ s/html/plain/i;

  debuglog("download with $http_client");

  if ($seek or $stop) {
    if ($size < 0) {
      http_header('416 Requested Range Not Satisfiable');
      exit;
    }
    if ($stop) {
      $range = sprintf("bytes %s-%s/%s",$seek,$stop,$total_size);
    } else {
      $range = sprintf("bytes %s-%s/%s",$seek,$total_size-1,$total_size);
    }
    # RFC 7233 "Responses to a Range Request"
    nvt_print(
      'HTTP/1.1 206 Partial Content',
      "Content-Length: $size",
      "Content-Range: $range",
      "Content-Type: $type",
    );
    if ($http_client !~ /MSIE/) {
      nvt_print("Cache-Control: no-cache");
      if ($type eq 'application/octet-stream') {
        nvt_print("Content-Disposition: attachment; filename=\"$filename\"");
      }
    }
    nvt_print('');
  } else {
    # another stupid IE bug-workaround
    # http://drupal.org/node/163445
    # http://support.microsoft.com/kb/323308
    if ($http_client =~ /MSIE/ and not $nowarning) {
      # $type = 'application/x-msdownload';
      if ($ignorewarning) {
        $type .= "; filename=$filename";
        nvt_print(
          'HTTP/1.1 200 OK',
          "Content-Length: $size",
          "Content-Type: $type",
#         "Pragma: no-cache",
#         "Cache-Control: no-store",
          "Content-Disposition: attachment; filename=\"$filename\"",
          "Connection: close",
        );
#        nvt_print('','HTTP/1.1 200 OK',"Content-Length: $size","Content-Type: $type"); exit;
        nvt_print($_) foreach(@extra_header);
      } else {
        http_header('200 OK');
        print html_header($head);
        pq(qq(
          '<h2>Internet Explorer warning</h2>'
          'Utiliser Microsoft Internet Explorer pour le téléchargement'
          'entraînera probablement des problèmes, parce qu\'il n\'est pas compatible avec Internet (RFC 2616).'
          '<p>'
          'Nous recommandons <a href="http://firefox.com">Firefox</a>'
          '<p>'
          'Si vous souhaitez vraiment continuer avec Internet Explorer, alors'
          '<a href="$ENV{REQUEST_URL}?IGNOREWARNING">'
          'cliquez ici avec le bouton droit de la souris et sélectionner "save as"'
          '</a>'
          '<p>'
          'See also <a href="/FAQ/user.html">F*EX user FAQ</a>.'
          '</body></html>'
        ));
        &reexec;
      }
    } else {
      nvt_print('HTTP/1.1 200 OK');
      nvt_print("Content-Length: $size") if $size >= 0;
      nvt_print(
        "Content-Type: $type",
        "Cache-Control: no-cache",
        "Connection: close",
      );
      if ($type eq 'application/octet-stream') {
        nvt_print(qq'Content-Disposition: attachment; filename="$filename"');
      }
      nvt_print($_) foreach(@extra_header);
    }

    nvt_print("X-Size: $total_size");
    nvt_print("X-File-ID: $fileid") if $fileid;
    nvt_print("X-MD5: $md5sum")     if $md5sum;
    # if ((`file "$file/data" 2>/dev/null` || '') =~ m{.*/data:\s(.+)}) {
    #  nvt_print("X-File-Type: $1");
    # }
    if ($dkey = $dkey||readlink("$file/dkey")) {
      my $ma = (readlink("$file/keep")||$keep_default)*60*60*24;
      my $uri = $ENV{REQUEST_URI};
      $uri =~ s/\?.*//;
      nvt_print("Set-Cookie: dkey=$dkey; Max-Age=$ma; Path=$uri");
    }
    # nvt_print("X-RM: $RM");
    nvt_print('');
  }

  if ($RM eq 'HEAD') {
    # control back to fexsrv for further HTTP handling
    &reexec;
  }

  if ($RM eq 'GET') {

    if (@throttle) {
      my $to = $file;
      $to =~ s:/.*::;
      foreach (@throttle) {
        if (/(.+):(\d+)$/) {
          my $throttle = $1;
          my $limit = $2;
          # throttle ip address?
          if ($throttle =~ /^[\d.-]+$/) {
            if (ipin($RA,$throttle)) {
              $bwl = $limit;
              last;
            }
          }
          # throttle email address?
          else {
            # allow wildcard *, but not regexps
            $throttle =~ quotemeta $throttle;
            $throttle =~ s/\*/.*/g;
            if ($to =~ /$throttle$/) {
              $bwl = $limit;
              last;
            }
          }
        }
      }
    }

    if (-l $data) {
      # my $wait = "$file/wait";
      # open $wait,'>',$wait and close $wait;
    }

    seek $data,$seek,0 if $seek;

    $t0 = time;
    $s = $b = 0;

    local $SIG{ABRT} =
    local $SIG{HUP} =
    local $SIG{INT} =
    local $SIG{PIPE} =
    local $SIG{QUIT} =
    local $SIG{TERM} =
      sub {
        fdlog($log,$file,$s,$size);
        sigexit(@_);
      };

    local $SIG{ALRM} =
      sub {
        fdlog($log,$file,$s,$size);
        debuglog('TIMEOUT');
        exit 99;
      };

    while ($s < $size or $streaming) {
      # sysread/syswrite because of speed
      if ($b = sysread($data,$buf,$bs)) {
        # last chunk for HTTP Range?
        if ($stop and $s+$b > $size) {
          $b = $size-$s;
          $buf = substr($buf,0,$b)
        }
        $s += $b;
        alarm($timeout*10);
        syswrite STDOUT,$buf or last; # client still alive?
        if ($bwl) {
          alarm(0);
          sleep 1 while $s/(time-$t0||1)/1024 > $bwl;
        }
      } else {
        if ($upload) {
          # uploader no more at work?
          if (flock($data,LOCK_EX|LOCK_NB)) {
            # read last chunks of upload
            while ($b = sysread($data,$buf,$bs)) {
              $s += $b;
              alarm($timeout*10);
              syswrite STDOUT,$buf or last;
            }
            last;
          } else {
            sleep 1;
          }
        } else {
          last;
        }
      }
    }

    close $data;
    alarm(0);

    fdlog($log,$file,$s,$size);
  }
  close $download;

  return $s;
}


sub sendsize {
  my ($path) = @_;
  my ($file,$upload,$to,$from,$dkey);
  my $size = 0;
  local $_;

  $path =~ s:^/::;
  ($to,$from,$file) = split('/',$path);
  $to =~ s/,.*//;
  $to   = lc $to;
  $from = lc $from;

  # swap to and from for special senders, see fup storage swap!
  ($from,$to) = ($to,$from) if $from =~ /^(fexmail|anonymous)/;

  $to   .= '@'.$hostname if $to   eq 'anonymous';
  $from .= '@'.$hostname if $from eq 'anonymous';

  $to   .= '@'.$mdomain if -d "$to\@$mdomain";
  $from .= '@'.$mdomain if -d "$from\@$mdomain";

  $file =~ s/%([A-F0-9]{2})/chr(hex($1))/ge;
  $file = urlencode($file);

  if ($to eq '*' and $fileid) {
    foreach my $fd (glob "*/$from/$file") {
      if (-f "$fd/data"
          and -l "$fd/id" and readlink("$fd/id") eq $fileid
          and $dkey = readlink("$fd/dkey")) {
        $to = $fd;
        $to =~ s:/.*::;
        last;
      }
    }
  } elsif ($to !~ /@/ and open my $AB,'<',"$from/\@ADDRESS_BOOK") {
    while (<$AB>) {
      s/\s*#.*//;
      $_ = lc $_;
      my ($alias,$address) = split;
      if ($address) {
        $address =~ s/,.*//;
        $address .= '@'.$mdomain if $mdomain and $address !~ /@/;
        if ($to eq $alias) {
          $to = $address;
          last;
        }
      }
    }
    close $AB;
  }

  if (-f "$filed/data") {
    $dkey = readlink("$filed/dkey");
    $fkey = slurp("$filed/filename")||$file;
  } elsif ($prefetch) {
    mkdirp($filed);
    $dkey = randstring(8);
    symlink "../$filed","$dkeydir/$dkey";
    symlink $dkey,"$filed/dkey";
    $fkey = $file;
  }

  $upload = -s "$filed/upload" || -s "$filed/data" || 0;
  $size = readlink("$filed/size") || 0;
  $fileid = readlink("$filed/id") || '';

#  if ($size and not $prefetch and not -f "$filed/data") {
#    http_die("<code>$file</code> has gone");
#  }

  if ($RM eq 'HEAD' and my $cl = $ENV{CONTENT_LENGTH}) {
    # check sender quota
    my ($quota,$du) = check_sender_quota($from,$filed);
    if ($quota and $du+$cl/$MB > $quota) {
      http_die("vous avez dépassé votre quota");
    }
    # check recipient quota
    # (should check all recipients, but fexsend queries only the first one!)
    ($quota,$du) = check_recipient_quota($to,$filed);
    if ($quota and $du+$cl/$MB > $quota) {
      http_die("$to ne peut pas recevoir de fichiers: quota dépassé");
    }
  }

  nvt_print('HTTP/1.1 200 OK');
  nvt_print("Server: fexsrv");
  nvt_print("Content-Length: $upload");
  nvt_print("X-Original-Recipient: $to");
  if ($dkey and not -s "$from/\@ALLOWED_RECIPIENTS") {
    nvt_print("X-DKEY: $dkey");
    if ($fkey) {
      foreach my $durl (@durl) {
        if ($durl =~ /^$ENV{PROTO}/i) {
          if (my $xkey = readlink("$filed/xkey")) {
            # xkey downloads are handled directly by fexsrv
            # xkey downloads are only one time possible
            my $x = "$durl//$xkey";
            $x =~ s:/fop::;
            nvt_print("X-Location: $x");
          }
          nvt_print("X-Location: $durl/$dkey/$fkey");
        }
      }
    }
  }
  nvt_print("X-Size: $size");
  nvt_print("X-File-ID: $fileid") if $fileid;
  nvt_print("X-Features: $ENV{FEATURES}");
  nvt_print('');
}


sub check_rhosts {
  my $ipr = shift;
  my @hosts;
  local $_;

  if (open $ipr,'<',$ipr) {
    while (<$ipr>) {
      chomp;
      s/#.*//;
      s/\s//g;
      if ($_ eq '@LOCAL_RHOSTS') {
        push @hosts,@local_rhosts if @local_rhosts;
      } elsif (/\w/) {
        push @hosts,$_;
      }
    }
    close $ipr;
    if (@hosts and not ipin($RA,@hosts)) {
      return 0;
    }
  }
  return 1;
}


sub require_auth {
  http_header(
    '401 Authorization Required',
    'WWW-Authenticate: Basic realm="'.$ENV{SERVER_NAME}.' F*EX download"',
    'Content-Length: 0',
  );
  # control back to fexsrv for further HTTP handling
  &reexec;
}


sub check_auth {
  my ($path,$user,$auth) = @_;
  my ($to,$from,$file,$dkey);
  my ($id,$idf);
  my ($subuser,$subid);
  my $auth_ok = 0;
  local $_;

  if ($path =~ m:(.+)/(.+)/(.+):) {
    ($to,$from,$file) = ($1,$2,$3);
  } elsif ($path =~ m:(.+)/(.+):) {
    ($dkey,$file) = ($1,$2);
    $path = readlink("$dkeydir/$dkey") or http_die('no such file');
    (undef,$to,$from,$file) = split('/',$path);
  } else {
    http_die("wrong URL format for download");
  }

  $to   .= '@'.$mdomain if $mdomain and $to   !~ /@/;
  $from .= '@'.$mdomain if $mdomain and $from !~ /@/;

  $to   = lc $to;
  $from = lc $from;

  # auth user match to in download URL?
  if ($to ne $user and "$to\@$mdomain" ne $user and $to ne "$user@$mdomain") {
    debuglog("mismatch: to=$to, auth user=$user");
    &require_auth;
  }

  # check for real user
  if (open $idf,'<',"$to/@") {
    $id = getline($idf);
    close $idf;
    unless ($id and $id eq $auth) {
      debuglog("$user mismatch: id=$id, auth=$auth");
      &require_auth;
    }
  }
  # check for sub user
  elsif (open $idf,'<',"$from/\@SUBUSER") {
    while (<$idf>) {
      chomp;
      s/#.*//;
      ($subuser,$subid) = split ':';
      if ($subid and $subid eq $auth
          and ($user eq $subuser
               or $subuser eq '*@*'
               or $subuser =~ /^\*\@(.+)/ and $user =~ /\@\Q$1\E$/i
               or $subuser =~ /(.+)\@\*$/ and $user =~ /^\Q$1\E\@/i)) {
        $auth_ok = 1;
        last;
      }
    }
    close $idf;
    unless ($auth_ok) {
      debuglog("no matching $user in $from/\@SUBUSER");
      &require_auth;
    }
  } else {
    debuglog("no $to/@ and no $from/@");
    &require_auth;
  }

}


sub check_captive {
  my $to = shift;
  $to =~ s:/.*::;
  $to .= '@'.$mdomain if $mdomain and -d "$to\@$mdomain";
  if (-e "$to/\@CAPTIVE") {
    http_die("$to is CAPTIVE - no URL parameters allowed");
  }
}


sub foplog {
  my $access = shift;
#  use Scalar::Util qw(tainted);
#  my $xx = "$foplog is tainted\n" if tainted($foplog);
  if ($userlog and $RM eq 'GET' and $dkey and $foplog =~ /(.+)/) {
    my $foplog = $1;
    if (open $foplog,'>>',$foplog) {
#      printf {$foplog} $xx if xx;
      printf {$foplog} "%s %s %s %s \"%s\"\n",
        isodate(time),$RA,$access,$filed,$http_client;
      close $foplog;
    }
  }
}

sub sigexit {
  my ($sig) = @_;
  my $msg;

  $msg = @_ ? "@_" : '???';
  $msg =~ s/\n/ /g;
  $msg =~ s/\s+$//;

  errorlog("$file caught SIGNAL $msg");

  # sigpipe means: client has terminated
  # this event will be handled further by sendfile(), do not terminate here
  if ($sig eq 'PIPE') {
    debuglog("SIGNAL $msg");
  } else {
    $SIG{__DIE__} = '';
    if ($sig eq 'DIE') {
      shift;
      die "$msg\n";
    } else {
      die "SIGNAL $msg\n";
    }
  }
}
