#!/usr/bin/perl -wT

# shared LAN clipboard server
#
# Author: Ulli Horlacher <framstag@rus.uni-stuttgart.de>
#
# Licence: Perl Artistic

# 2023-07-10 initial version
# 2024-08-19 added simple upload locking
# 2024-11-21 added support for LCB users
# 2025-09-23 various bugfixes
# 2025-09-24 added MD5 check for get,delete,fex
# 2025-10-02 various bugfixes and SIGCHLD workarounds
# 2025-10-03 no more require of fex.pp, no eval(<DATA>)
# 2025-10-24 added support for restricted domains and restricted hosts
# 2025-10-31 fixed bug write access to foreign clipboards for restricted domains or hosts
# 2025-11-06 added support for restricted users
# 2025-11-08 added support for allowed domains

BEGIN {
  $| = 1;
  our ($FEXLIB,$FEXHOME,$LCBHOME,$lcbdir,$spooldir,$debug);
  $FEXLIB  = $1 if ($ENV{FEXLIB}||'')  =~ /(.+)/;
  $FEXHOME = $1 if ($ENV{FEXHOME}||'') =~ /(.+)/;
  $ENV{LC_ALL}   = 'en_US.utf8';
  $ENV{IFS}      = " \t\n";
  $ENV{BASH_ENV} = '';
  if ($FEXHOME) {
    $ENV{PATH} = "$FEXHOME/bin:/usr/local/bin:/bin:/sbin";
    $spooldir  = "$FEXHOME/spool";
    $lcbdir    = "$FEXHOME/spool/LCB";
  } else {
    # do NOT use abs_path($0)!
    $LCBHOME   = '/opt/lcb';
    $LCBHOME   = $1 if $0 =~ m:(.+)/.+/.+:;
    $ENV{PATH} = "$LCBHOME/bin:/usr/local/bin:/bin:/sbin";
    $lcbdir    = "$LCBHOME/spool";
    $lcbdir   .= '/LCB' if -d "$lcbdir/LCB";
  }

  # web error handler
  $SIG{__DIE__} = $SIG{__WARN__} = sub {
    my @d = localtime time;
    my $time = sprintf('%d-%02d-%02d %02d:%02d:%02d',
               $d[5]+1900,$d[4]+1,$d[3],$d[2],$d[1],$d[0]);
    my $log = $lcbdir ? "$lcbdir/lcb_error.log" : "/tmp/lcb_error.log";
    $_ = join("\n",@_);
    debug($_) if exists &debug;
    if (open $log,'>>',$log) {
      print {$log} "[$time]\n$_\n";
      close $log;
    }
    if ($RM and $RM eq 'POST') {
      eval {
        my $x;
        local $SIG{ALRM} = sub { die };
        alarm(3);
        while (read(STDIN,$x,65536)) { alarm(3) }
        alarm(0);
      };
    }
    chomp;
    s/&/&amp;/g;
    s/</&lt;/g;
    my $html = join("\n",
      "<html><body>",
      "<h1>INTERNAL ERROR in $0</h1>",
      "<pre>\n$_\n</pre>\n<p>",
      "$time",
      "</body></html>\n"
    );
    my $length = length($html);
    local $SIG{ALRM} = sub { exit 99 };
    alarm(3);
    print join("\r\n",
      "HTTP/1.0 200 INTERNAL ERROR",
      "Content-Type: text/html",
      "Content-Length: $length",
      "X-Error: $_",
      "");
    print $html;
    if ($clip0 and -e $clip0) {
      my $clip00 = $clip0.'0';
      system qw'rm -rf',$clip00;
      rename $clip0,$clip00;
    }
    sleep 1;
    close STDOUT;
    exit 99;
  };
}

use Encode;
use Socket;
use IO::Handle;
use Sys::Hostname;
use File::Basename;
use Time::HiRes qw(gettimeofday);
use Digest::MD5	qw(md5_hex);
# use Cwd qw(abs_path);

# import from fex.pp or lcb.cf
our @lcb_allowed_hosts = ();
our @lcb_forbidden_hosts = ();
our @lcb_allowed_domains = ();
our @lcb_allowed_fex_domains = ();
our @lcb_restricted_domains = ();
our @lcb_restricted_hosts = ();
our @lcb_restricted_users = ();
our ($servername,$lcb_expire,$lcb_url,$lcb_fex_aips);
our ($bs,$timeout,$charset,$RA,$RH,$HTTP_HEADER);

my $cf;
my $N = "\r\n";

if ($FEXLIB) {
  $cf = "$FEXLIB/lcb.cf";
  if (-f $cf) { require $cf or die "$0: cannot load $cf - $!\n" }
}

$cf = "/opt/lcb/etc/lcb.cf";
if (-f $cf) { require $cf or die "$0: cannot load $cf - $!\n" }

# untaint ENV
foreach my $v (keys %ENV) {
  ($ENV{$v}) = ($ENV{$v} =~ /(.*)/s) if defined $ENV{$v};
}

if ($FEXLIB) {
  $RA = $ENV{REMOTE_ADDR};
  $RH = $ENV{REMOTE_HOST};
} else {
  ### standalone server code
  my $prg = basename($0);
  my $req = getaline() or die "$prg: no request\n";
  if ($req =~ m:^(GET|PUT) (/lcb(/\S+)?) SDTP:) {
    # port 80 (only) PUT/GET via bash
    $ENV{REQUEST_METHOD} = $1;
    $ENV{REQUEST_URI} = $2;
    $ENV{PATH_INFO} = $3||'';
    $ENV{PROTO} = $ENV{SDTP} = 'sdtp';
    $SIG{__DIE__} = $SIG{__WARN__} = 'DEFAULT';
  } elsif ($req =~ m:^([A-Z]+) (/lcb(/\S*)?) HTTP:) {
    $ENV{REQUEST_METHOD} = $1;
    $ENV{REQUEST_URI} = $2;
    $ENV{PATH_INFO} = $3||'';
    $ENV{PROTO} = 'http';
  } elsif ($req =~ m:^([A-Z]+) / HTTP:) {
    nvt_print(
      "HTTP/1.0 302 Found",
      "Server: lcb",
      "Location: /lcb",
      'Content-Length: 0',
      ''
    );
    exit;
  } else {
    $SIG{__DIE__} = $SIG{__WARN__} = 'DEFAULT';
    die "$prg: no lcb HTTP or SDTP request ($req)\n";
  }

  $ENV{QUERY_STRING} = '';
  $ENV{QUERY_STRING} = $1 if $ENV{PATH_INFO} =~ s/\?(.+)//;
  $ENV{SERVER_NAME}  = $servername;
  $ENV{SERVER_ADMIN} = $admin;

  my $sa = getpeername(STDIN) or die "no network stream on STDIN\n";
  if (sockaddr_family($sa) == AF_INET) {
    ($ENV{REMOTE_PORT},$iaddr) = sockaddr_in($sa);
    $RA = inet_ntoa($iaddr);
    $RH = gethostbyaddr($iaddr,AF_INET)||'';
    ($ENV{PORT}) = sockaddr_in(getsockname(STDIN));
  } elsif (sockaddr_family($sa) == AF_INET6) {
    $^W = 0; eval 'use Socket6'; $^W = 1;
    die "$@" if $@;
    http_error(503) if $@;
    ($ENV{REMOTE_PORT},$iaddr) = unpack_sockaddr_in6($sa);
    $RA = inet_ntop(AF_INET6,$iaddr);
    $RH = gethostbyaddr($iaddr,AF_INET6)||'';
    ($ENV{PORT}) = unpack_sockaddr_in6(getsockname(STDIN));
  } else {
    die "unknown IP version\n";
  }

  $RA =~ s/^::ffff:// if $RA =~ /\./;

  my $header = $req."\n";
  while (defined($_ = getaline())) {
    last if /^\s*$/;
    if (/^(\S+):\s+(.+)/) {
      my $ht = uc($1);
      my $hd = $2;
      $ht =~ s/-/_/g;
      $ENV{"HTTP_$ht"} = $hd;
      $ENV{$ht} = $hd if $ht eq 'CONTENT_LENGTH';
    }
    $header .= $_."\n";
  }
  $ENV{HTTP_HEADER} = $header;
}

our $error = 'LCB ERROR';
our $head = "$ENV{SERVER_NAME} LAN clipboard";
our ($clip0);
our $RM = $ENV{REQUEST_METHOD};

my $n = 1;
my $ds = 60*60*24;
my $RB = 0; # read POST bytes
my ($clipd,$query,$delete,$modpub,$fex,$upload,$menu,$in,$clog);
my $http_client = $ENV{HTTP_USER_AGENT} || '';
my $html = ($http_client !~ /^(curl|Wget|yy-|lcb-)/);
my $clip = $ENV{PATH_INFO} || '';
my $lcbsrv = ($FEXLIB ? 'fexsrv/' : '') . basename($0);
my $fexsend = searchpath('fexsend');
my $SDTP = $ENV{SDTP}; # port 80 (only) PUT/GET via bash
my $cookies = '';
my $footer = '';
my $user = '';
my $lcb_user = '';
my $allowed = '';
my $restricted = '';
my $restricted_user = '';
my $restricted_domain = '';
my $restricted_host = '';
my $md5 = 0;
my $debuglog;
my $log = 'lcb.log';
my $cbcc = '\w_@.+-';
my $cbchars = 'a..z A..Z 0..9 . _ @ + -';

$RA = untaint($RA);
$RH = $1 if $RH !~ /\w\.\w/ and qhost($RA) =~ /pointer (\S+\.\w+)\.$/;

$lcb_expire ||= 3;
$timeout ||= 10;
$charset ||= 'UTF-8';

if ($FEXLIB) {
  $lcb_url = 'https://'.($servername||$hostname).'/lcb';
  $footer = join("\n",
    '<p><hr><p>',
    "$ENV{HTTP_HOST}<p>",
    qq'<address><a href="mailto:$admin">$admin</a></address>',
    "</BODY></HTML>",
    '');
} else {
  my $port = $ENV{PORT};
  if ($port == 443 or $port == 80) {
    $lcb_url = "$ENV{PROTO}://$servername/lcb";
  } else {
    $lcb_url = "$ENV{PROTO}://$servername:$port/lcb";
  }
  $lcb_url =~ s/^sdtp/http/;
  $footer = join("\n",
    '<p><hr><p>',
    "$servername<p>",
    qq'<address><a href="mailto:$admin">$admin</a></address>',
    "</BODY></HTML>",
    '');
}

unless (-d $lcbdir) {
  mkdir $lcbdir or lcb_die("cannot mkdir $lcbdir - $!\n");
}
unless (-w $lcbdir) {
  lcb_die("no write access for $lcbdir\n");
}
chdir $lcbdir or lcb_die("$lcbdir - $!");

if ($debug) {
  my $isodate = isodate(time);
  mkdir '.debug';
  $debuglog = sprintf("$lcbdir/.debug/%d%06d.%s",gettimeofday(),$RM);
  open $debuglog,'>',$debuglog;
  print {$debuglog} "CONNECT:$ENV{PORT} $isodate $RA $RH\n";
  print {$debuglog} $ENV{HTTP_HEADER};
  print {$debuglog} "\n";
}
  
&check_maint;

if (@lcb_forbidden_hosts and ipin($RA,@lcb_forbidden_hosts)) {
  lcb_die(
    "Access from your host ($RA) is not allowed.",
    "Contact $ENV{SERVER_ADMIN} for details."
  );
}

# allow local ips
if (open my $ip,'-|',qw'ip a') {
  while (<$ip>) {
    push @lcb_allowed_hosts,$1 if /inet6? (\S+?)\//;
  }
  close $ip;
}

&lcb_login  if $clip =~ /lcb\.login/;
&lcb_logout if $clip =~ /lcb\.logout/;

$cookies = $ENV{HTTP_COOKIE}||'';
$cookies =~ s/;/ /g;
if ($cookies =~ /\blcb_user=(\S+)/) {
  $user = $1;
  $lcb_user = is_lcb_user($user);
  $restricted_user = restricted_user($user);
}
if (my $x = $ENV{HTTP_X_USER}) {
  $user ||= $x;
  $lcb_user ||= is_lcb_user($x);
  $restricted_user ||= restricted_user($x);
}
  
# allow authentificated F*EX ips (created by fup, deleted by fex_cleanup)
if ($FEXLIB and @lcb_allowed_fex_domains) {
  foreach (glob "$spooldir/.aips/*") {
    if (my $a = readlink $_) {
      my $ip = basename($_);
      $a =~ s/.*@//;
      if (grep { $a =~ /\b$_$/} @lcb_allowed_fex_domains) {
        push @lcb_allowed_hosts,$ip;
      }
    }
  }
}

$clog = "$lcbdir/.cleanup";

$clip =~ s:^/lcb/:/:;
$clip =~ s!/(\d):MD5=([a-f\d]{32})/!/$1/! and $md5 = $2;
$clip =~ s:/(\d)/:/: and $clip .= ":$1";
$clip =~ s:^/+::;
$clip =~ s:^\./*:_:;
$clip =~ s/^-/_/;
$clip =~ s/^(PUBLIC_[$cbcc]+):([Uu])$/$1/ and $upload = $2;

$md5 ||= $1 if $ENV{QUERY_STRING} =~ /MD5=(\w+)/;

$allowed = $lcb_user||ipin($RA,@lcb_allowed_hosts)||allowed_domain($RA);
$restricted_domain = restricted_domain($RA); # DNS name must match
$restricted_host   = restricted_host($RA);
$restricted = $restricted_domain||$restricted_host||$restricted_user;

if ($clip eq '::') { &list }

$clip =~ s/:+$//;

if ($clip =~ /^_($|:)/ and $FEXLIB) {
  if ($RH) {
    my $x = '';
    if ($RH =~ /\.(.+\.[a-z]+)$/) {
      $x = $1;
    } else {
      $x = $RH;
    }
    $clip =~ s/^_/$x/ if $x;
  } else {
    lcb_die(qq'cannot use clipboard "_" on $servername');
  }
}
  
if ($RM eq 'HEAD' or $RM eq 'GET') {
  $allowed = check_download_allowed($clip);
}

if ($RM eq 'HEAD') {
  clipinfo($clip);
  exit;
}

if ($RM eq 'GET') {
  if ($clip =~ s/:(q)$//i) {
    $query = $1;
    $clip =~ s/:(\d)$// and $in = $1;
    $clip ||= '_';
  } elsif ($clip =~ s/:(d)$//i) {
    $delete = $1;
    $clip =~ s/:(\d)$// and $in = $1;
  } elsif ($clip =~ s/:(c):(\S+)$//) {
    $copy = $1;
    $nclip = $2;
    $nclip =~ s/[^$cbcc]/_/g;
  } elsif ($clip =~ s/:(u)$//i) {
    $upload = $1;
  } elsif ($clip =~ s/:(p)$//i) {
    $modpub = $1;
  } elsif ($clip =~ s/:(f)$//) {
    $fex = $1;
    $in = 1;
    $clip =~ s/:(\d)$// and $in = $1;
  }
  if ($clip =~ s/:(\d)$//) {
    $n = $1;
    $clip ||= '_';
  }
}

if ($clip =~ s/^([$cbcc]+)\/$/$1/) {
  if ($allowed or $restricted or $clip =~ /^PUBLIC_/) {
    $menu = $clip;
  } else {
    lcb_die(
      "Menu function not available for your host ($RA)",
      "Contact $ENV{SERVER_ADMIN} for details."
    );
  }
}
$clip =~ s/[^$cbcc]/_/g;
if ($clip =~ /[^$cbcc]/) {
  lcb_die("Illegal clipboard name \"$clip\"");
}
if ($nclip and $nclip =~ /^(\d)$|^(lcb|yy)/i) {
  lcb_die("Clipboard name \"$nclip\" is reserved");
}

$clip  = untaint($clip);
$nclip = untaint($nclip) if $nclip;
$clipd = "$lcbdir/$clip";
$clip0 = $clipd.'/0';

if ($modpub or $fex) {
  unless ($allowed or $restricted) {
    lcb_die(
      "Special function from your host ($RA) is not allowed.",
      "Contact $ENV{SERVER_ADMIN} for details."
    );
#  my $x = ipin($RA,@lcb_allowed_hosts); lcb_die("[$x]");
  }
}

if ($modpub) { &modpub }
if ($fex)    { &fex }

if (not $clip and $ENV{HTTP_X_USER}) {
  nvt_print(
    'HTTP/1.0 200 OK',
    "Server: $lcbsrv",
    'Content-Type: text/plain',
    '',
    "$lcb_url",
    '',
    'paste usage: lcbget CLIPBOARD',
    'copy usage:  lcbput CLIPBOARD < FILE',
    'copy usage:  ... | lcbput CLIPBOARD',
  );
  exit;
}

if ($RM eq 'GET') {
  &start($user) if $clip eq '';
  &bash		if $clip eq 'lcb.bash';
  &windows  	if $clip eq 'lcb.windows';
  &zip      	if $clip eq 'lcb.zip';
  &login    	if $clip eq 'lcb.login';
  &paste    	if $clip eq 'lcb.paste';
  &yy       	if $clip =~ /^yy\.(pl|sh)$|^yy$/;
  &cleanup;
  unless (-f "$clip/1/data") { lcb_die("Clipboard $clip does not exist") }
  &lcblog;
  &query    if $query;
  &del      if $delete;
  &clipcopy if $copy;
  &upload   if $upload;
  &menu	    if $menu;
  &get;
} elsif ($RM eq 'PUT') {
  &put;
} elsif ($RM eq 'POST') {
  &post;
} else {
  lcb_die("illegal request methode $RM");
}

lcb_die("clip = [$clip]");

exit;


sub clipinfo {
  my $clip = shift;
  my $clipd = $lcbdir;
  my @X = qw'File Type MD5 Args User Upload-IP';
  local $_;
  
  if ($clip =~ /(.+):(\d)$/) {
    $clipd .= "/$1/$2";
    unless (-f "$clipd/data") {
      lcb_die("$clip does not exist");
    }
  } else {
    lcb_die("unknown clip $clip");
  }
  
  nvt_print(
    'HTTP/1.0 200 OK',
    "Server: $lcbsrv",
  );
  
  foreach my $x (@X) {
    if ($_ = readline1("$clipd/$x")) {
      print "X-$x: $_\n"
    }
  }
}


sub get {
  my $clipn = "$clipd/$n";
  my $data = "$clipn/data";
  my $dip = 'Download-IP';
  my $size = -s $data;
  my $ct = 'application/binary';
  my (@X);
  local $_;
  
  unless ($size) {
    lcb_die("Clipboard item $clip:$n does not exist");
  }

  if ($md5 and $md5 ne readline1("$clipn/MD5")||'') {
    lcb_die("MD5 does not match, try BACK and RELOAD");
  }
  
  chdir $clipn     or lcb_die("cannot chdir $clipn - $!\n");
  open $data,$data or lcb_die("cannot open $data - $!\n");

  if ($ENV{PROTO} =~ /http/) {
    nvt_print('HTTP/1.0 200 OK');
    nvt_print("Server: $lcbsrv");
    nvt_print('Content-Length: '.$size);

    push @X,sprintf("X-Date: %s",isomtime($data));
    foreach my $a (glob "[A-Z]*") {
      my $ad = readline1($a);
      push @X,"X-$a: $ad";
      if ($a eq 'Type' and local $_=$ad) {
        if (/text/i)		{ $ct = 'text/plain' }
        if (/\bTIF/)		{ $ct = 'image/tiff' }
        if (/\b(PNG|JPEG|GIF)/)	{ $ct = 'image/'.lc($1) }
        if (/\b(PDF)/)		{ $ct = 'application/'.lc($1) }
      }
    }
    nvt_print("Content-Type: $ct");
    nvt_print(@X);
    nvt_print('');
  }

  $_ = (readline1($dip)||'') and $_ .= ' ';
  if (open $dip,'>',$dip) {
    print {$dip} $_,$RA,"\n";
    close $dip;
  }

  print while read($data,$_,$bs);
  close $data;

  exit;
}


sub menu {
  my $access = 'allow public access';
  local $_;

  unless (-f "$clipd/1/data") {
    lcb_die("Clipboard $clip does not exist");
  }

  $access = 'dis'.$access if $clip =~ /^public_/i;

  nvt_print(
    'HTTP/1.0 200 OK',
    "Server: $lcbsrv",
    "Content-Type: text/html",
    ''
  );
  print join("\n",
    "<HTML>",
    "<HEAD><TITLE>LAN clipboard</TITLE></HEAD>".
    "<BODY>",
    qq'<h1><a href="/lcb">LCB</a> clipboard <a href="/lcb/$clip">$clip</a></h1>',
    "<ul>",
    qq'<p><li><a href="/lcb/$clip:q">version history</a> (with fex function)',
    qq'<p><li><a href="/lcb/$clip:u">text paste</a> (upload)',
    qq'<p><li><a href="/lcb/$clip:U">file paste</a> (upload)',
    qq'<p><li><a href="/lcb/$clip:p"><button>$access</button></a>',
    '</ul>',
    '');
  if (my @CB = known_cb($user)) {
    print "Known clipboards: <code>\n";
    foreach my $cb (@CB) {
      print qq'<a href="/lcb/$cb/">$cb</a>\n';
    }
    print "</code>\n";
  }
  print $footer;

  exit;
}


sub fex {
  my $ct = $html ? 'html' : 'plain';
  my $location = '';
  my ($zip,$name);
  my $js_scroll =
    "<script>".
    "function scroll() { window.scrollTo(0,document.body.scrollHeight) }".
    "</script>\n";
  my $scroll = "<script>scroll()</script>";
  local $_;

  unless ($FEXLIB) {
    lcb_die("lcb server runs in standalone mode, no fex service available");
  }
  
  unless ($allowed or $restricted) {
    lcb_die(
      "fex not available for your host ($RA)",
      "Contact $ENV{SERVER_ADMIN} for details."
    );
  }

  chdir "$clip/$in" or lcb_die("$clip/$in - $!");
  if ($md5 and $md5 ne readline1("MD5")||'') {
    lcb_die("MD5 does not match, try BACK and RELOAD");
  }
  $_ = slurp('Type')||'';
  if (/tar archive/) {
    if ($clip =~ /(.+)\.tar$/i) {
      $zip = "$1.zip";
    } else {
      $zip = "$clip.zip";
    }
    system qw'rm -rf _' if lstat '_';
    mkdir '_' or lcb_die("$clip/$in/_ - $!");
    chdir '_' or lcb_die("$clip/$in/_ - $!");
  } else {
    $name = $clip;
    $name =~ s/(\.pdf)?$/.pdf/ if /PDF document/;
    $name =~ s/(\.png)?$/.png/ if /PNG image data/;
    $name =~ s/(\.gif)?$/.gif/ if /GIF image data/;
    $name =~ s/(\.jpg)?$/.jpg/ if /JPEG image data/;
    $name =~ s/(\.mp4)?$/.mp4/ if /MP4/;
    $name =~ s/(\.zip)?$/.zip/ if /Zip archive/;
    $name =~ s/(\.7z)?$/.7z/   if /7-zip archive/;
  }
  nvt_print(
    "HTTP/1.0 200 OK",
    "Server: $lcbsrv",
    "Content-Type: text/$ct",
    ''
  );
  if ($zip) {
    if ($html) {
      print "<html><body>\n";
      print $js_scroll;
      print "<pre>\n";
      print "Extracting";
    }
    open my $tar,'-|',qw'tar xvf ../data' or exit;
    while (<$tar>) {
      print '.' if $html;
    }
    close $tar;
    print "\n\n" if $html;
    open $fexsend,"$fexsend -0 -A $zip ./ . |" or exit;
    while (<$fexsend>) {
      next if m:/ :;
      if (/^Location: (\S+)/) {
        $location = $1;
        print qq'Location: <a href="$location">$location</a>\n' if $html;
      } else {
        s/ \Q(stored 0%)//;
        print htmlencode($_) if $html;
      }
      print $scroll if $html;
    }
  } else {
    if ($html) {
      print "<html><body>\n";
      print "<pre>\n";
    }
    open $fexsend,"$fexsend -M -= $name data . |" or exit;
    while (<$fexsend>) {
      if (/^Location: (\S+)/) {
        $location = $1;
        print qq'Location: <a href="$location">$location</a>\n' if $html;
      } else {
        print htmlencode($_) if $html;
      }
    }
  }
  if ($html) {
    print "</pre></body></body>\n";
  } else {
    print $location,"\n";
  }
  exit;
}


sub modpub {
  my $nclip;
  if ($clip =~ /^public_(.+)/i) {
    $nclip = $1;
  } else {
    $nclip = 'public_'.$clip;
  }
  lstat $clip  or  lcb_die("Clipboard $clip does not exist");
  lstat $nclip and lcb_die("Clipboards $clip and $nclip exist both");
  rename $clip,$nclip or lcb_die("Cannot create $nclip - $!");
  if ($html) {
    nvt_print(
      "HTTP/1.0 302 Found",
      "Server: $lcbsrv",
      "Location: /lcb/$nclip/",
      'Content-Length: 0',
      ''
    );
  } else {
    nvt_print(
      "HTTP/1.0 200 OK",
      "Server: $lcbsrv",
      "Content-Type: text/plain",
      ''
    );
    print "$lcb_url/$nclip/\n";
  }
  exit;
}


sub list {
  my $ct = $html ? 'html' : 'plain';
  local $_;
  
  my $list = sub {
    my $cb = shift;
    if ($html) {
      print qq'<li><a href="/lcb/$cb/">$cb</a><br>\n';
    } else {
      print $cb,"\n";
    }
  };

  if ($ENV{PROTO} =~ /http/) {
    my @ah = grep { $_ !~ /^127\.|^::1$|^fe80:/ } @lcb_allowed_hosts;
    nvt_print(
      'HTTP/1.0 200 OK',
      "Server: $lcbsrv",
      "Content-Type: text/$ct",
    );
    nvt_print("X-Allowed-Hosts: @ah") if @ah;
    nvt_print("X-Allowed-Domains: @lcb_allowed_domains") if @lcb_allowed_domains;
    nvt_print("X-Restricted-Domain: $restricted_domain") if $restricted_domain;
    nvt_print('');
    if ($html) {
      print "<html><body>\n";
      print "<h3>known clipboards</h3>\n";
      print "<ul>\n";
    }
  }

  if (ipin($RA,@lcb_allowed_hosts) or allowed_domain($RA)) {
    foreach my $cb (glob "*") {
      my $access = slurp("$cb/access.log")||'';
      &$list($cb) if $access =~ / \Q$RA\E /;
    }
  } elsif ($lcb_user) {
    foreach my $cb (known_cb($lcb_user)) {
      &$list($cb);
    }
  } elsif ($restricted) {
    foreach my $r (glob "*/restricted") {
      my $rr = readline1($r);
      if ($rr eq $restricted_domain or $rr eq $restricted_host or $rr eq $restricted_user) {
        &$list(dirname($r));
      }
    }
  } else {
    print "no LCB_USER\n";
  }

  if ($html) {
    print "</ul>\n";
    print "</body></html>\n";
  }
  exit;
}


sub known_cb {
  my $user = shift or return;
  my %CB = ();
  local $_;

  $user =~ /\S@\S+:\S/ or $user = '---';
  
  $CB{_} = 1 if -f "_/1/data";
  
  foreach my $a (glob "*/access.log") {
    if (open $a,$a) {
      while (<$a>) {
        if (/ \Q$RA\E /i or / \Q$user\E /i) {
          my $cb = dirname($a);
          $CB{$cb} = 1 if -f "$cb/1/data";
          last;
        }
      }
      close $a;
    }
  }

  return asort(keys %CB);
}


sub cleanup {
  my $expire = $lcb_expire*$ds;
  my $hs = 60*60;
  my $now = time();
  my $isodate = isodate($now);
  my @d = localtime($now);
  my $today = sprintf('%d%02d%02d',$d[5]+1900,$d[4]+1,$d[3]);
  my $remove = sub {
    system qw'rm -rf',$cbd;
    if (open $clog,'>>',$clog) {
      print {$clog} "$isodate $cbd deleted\n";
      close $clog;
    }
  };
  local $cbd;
  local $_;

  chdir $lcbdir or return;
#  return if (mtime($clog)||0)+$hs > $now;
#  system 'touch',$clog;

  foreach (glob '*') {
    next if /^lcb/i;
    next if -l;
    next unless -d;
    $cbd = untaint($_);
    if (-f "$cbd/access.log") {
      unless (-f "$cbd/0/data" or -f "$cbd/1/data") { 
        # empty clipboard
        &$remove;
        next;
      }
      if ($cbd =~ /(\d\d\d\d)[_-](\d\d)[_-](\d\d)/) {
        if ($today > "$1$2$3") { &$remove }
      } else {
        next if (mtime("$cbd/0/data")||0)+$hs > $now;
        if ($mt = mtime("$cbd/access.log")) {
          if ($now > $mt+$expire) { &$remove }
        }
      }
    }
    unless (my @x=glob "$cbd/[01]/data") {
      &$remove;
      next;
    }
  }
  
  if (my @d = glob '.debug/*') {
    my $dt = time-$ds;
    foreach my $d (@d) {
      unlink untaint($d) if mtime($d) < $dt;
    }
  }
}


sub start {
  my $user = shift;
  my $ua = ($allowed or $restricted);
  local $_;

  if ($SDTP) { http_error(400) }

  $user =~ s/:.*// if $user;
  
#  my $users = 'LAN';
#  $users .= ' and F*EX' if $FEXHOME; # via $FEXHOME/spool/.aips/
#  $users .= ' users';

  nvt_print(
    'HTTP/1.0 200 OK',
    "Server: $lcbsrv",
    'Content-Type: text/html',
    '');
  print join("\n",
    "<HTML>",
    "<HEAD><TITLE>LAN clipboard</TITLE></HEAD>".
    "<BODY>",
    '<h1>LCB : LAN ClipBoard</h1>',
    "<ul>",
    "<p><li>LCB offers clipboards for copy&paste STDIN/STDOUT (pipe),",
    "       files and directories with other LAN users or yourself on other hosts.",
    "<p><li>LCB clipboards are unlimited in number or size.",
    "<p><li>LCB clipboards have names consisting of characters <code>$cbchars</code><br>",
    "       e.g.: <code>data_2023</code>",
    "<p><li>LCB clipboard items are automatically versioned (1-9), default is item 1.<br>",
    "<p><li>LCB clipboard items have a MD5 checksum for verification.",
    "<p><li>LCB clipboards will be deleted $lcb_expire days after last access.<br>",
    "       Exception: your clipboard name contains an ISO date YYYY-MM-DD, which will be the expiration date.<br>",
    "       e.g.: <code>setup_2023-08-31</code>",
    "<p><li>LCB needs no authorization, but access is limited to LAN users and",
    "       you have to know the clipboard name.<br>",
    "       Exceptions:",
    "       <ul>",
    "       <li>A clipboard with a <code>public_</code> prefix can be read from everywhere,<br>",
    "           e.g.: <code>public_data</code><br>",
    "       <li>A clipboard with a <code>PUBLIC_</code> prefix can be read+written from everywhere,<br>",
    "           e.g.: <code>PUBLIC_data</code><br>",
    "       <li>The admin can add LCB users identified by <code>EMAIL:TOKEN</code> which have access from everywhere.",
    "       <li>The admin can add domains or hosts which have restricted access (to their own clipboards).",
    "       </ul>",
    '<p><li>LCB can be accessed by UNIX <a href="/lcb/yy">CLI client yy</a> or <a href="/lcb/lcb.bash">bash functions</a>.',
    "<p><li>LCB access (limited functions) is also possible with a webbrowser or any HTTP client (like curl or wget).",
    '');
  if ($FEXLIB and $lcb_fex_aips) {
    print qq'<p><li>If you <a href="/fup">use F*EX</a>, then your local IP is also allowed to use LCB.\n';
  }
  if ($FEXHOME and -f "$FEXHOME/htdocs/fex-vs-lcb.html") {
    print qq'<p><li><a href="/fex-vs-lcb.html">LCB / F*EX comparison</a>\n';
  }
  print qq'<p><li><a href="https://fex.belwue.de/fstools/shell-clipboards.html">shell clipboards comparison</a>';
  print qq'<p><li><a href="/lcb/lcb.paste"><button>Webbrowser upload (paste)</button></a>\n';
  print "</ul>\n";
  print "<p><hr><p>\n";
  print "$ENV{SERVER_NAME}:$ENV{PORT}\n";
  print "</BODY></HTML>\n";
  exit;
}


sub paste {
  my $ua = ($allowed or $restricted);
  my $u = '';
  my $m = '';
  $m = $1 if $cookies =~ /login=([$cbcc]+)/;
  $user ||= '';
  nvt_print(
    'HTTP/1.0 200 OK',
    "Server: $lcbsrv",
    'Content-Type: text/html',
    '');
  print qq'<h1><a href="/lcb">LAN clipboard</a> Webbrowser upload</h1>\n';
  if ($user) {
    $u = $user;
    $u =~ s/:.*//;
    print "<ul>\n";
    print "<li>You are logged in as $u<br>\n";
    if (my @CB = known_cb($user)) {
      print "<li>Known clipboards: <code>\n";
      foreach my $cb (@CB) {
        print qq'<a href="/lcb/$cb/">$cb</a>\n';
      }
      print "</code><br>\n";
    }
    print qq'<li><a href="/lcb/lcb.logout"><button>logout</button></a>\n';
  } elsif (-f "_/1/data") {
    print qq'<li><a href="/lcb/_/:q">Default clipboard</a>\n';
  }
  print qq'</ul>\n';
  if ($ua) {
    print join("\n",
      qq'<p><hr><p>',
      qq'<ul>',
      qq'<form action="/lcb" method="post" accept-charset="UTF-8" enctype="multipart/form-data">',
      $user ?
      qq'  <input type="hidden" name="user" value="$user">':
      qq'  Your email address: <input type="text" size="80" name="user" value="$m"><p>',
      qq'  Clipboard name:',
      qq'  <input type="text" size="16" name="clipboard" value="$u" title="allowed characters: $cbchars">',
      qq'  (required!)<p>',
      qq'  <li>Paste your text here:<br>',
      qq'  <textarea name="data" cols="100" rows="20"></textarea><br>',
      qq'  <input type="submit" value="submit">',
      qq'  <p>',
      qq'  <li>or select a file: <input type="file" name="file" size="80">',
      qq'  and <input type="submit" value="upload">',
      qq'</form>',
      qq'<li>or <a href="$ENV{REQUEST_URI}"><button>reset</button></a>',
      qq'</ul>',
      '');
  } else {
    print "<h3>No upload allowed for your ip $RA</h3>\n";
    print "<ul>\n";
    if ($FEXLIB and @lcb_allowed_fex_domains) {
      my $url = $lcb_url;
      $url =~ s/lcb$/fup/;
      print qq'<li>You can <a href="$url?forward=/lcb">authorize<a> ';
      print "your ip if you have an email address within one of these domains:<br>\n";
      print join("<br>\n",@lcb_allowed_fex_domains),"\n";
    }
    if (@lcb_users) {
      print "<p><li>";
      print qq'You can <a href="/lcb/lcb.login">login</a> with your LCB account.';
    }
    print "</ul>\n";
  }
  exit;
}


sub yy {
  my $yy = ($FEXHOME||$LCBHOME).'/bin/yy';
  local $_;

  if ($clip eq 'yy.sh') {

    my $yyurl = "$lcb_url/yy";
    my $body = join("\n",
      "# install yy manually",
      'cd $HOME/bin',
      "curl -sS $yyurl.pl > yy",
      'chmod 755 yy',
      'ls -l $PWD/yy',
      '');
    if ($http_client !~ /curl/) {
      $body .= "\n# install yy automatically:\n".
               "curl -sS $yyurl.sh | sh -x\n";
    }

    nvt_print('HTTP/1.0 200 OK');
    nvt_print("Server: $lcbsrv");
    nvt_print('Content-Length: '.length($body));
    nvt_print('Content-Type: text/plain');
    nvt_print('');
    print $body;

  } elsif ($clip eq 'yy.pl') {
    local $/;
    open $yy,$yy or lcb_die("cannot open $yy - $!\n");
    $_ = <$yy>;
    close $yy;
    isomtime($yy) =~ /(\d+)-(\d+)-(\d+)/;
    my $v = "$1$2$3";
    s/version = 0/version = $v/;
    s/server = '.*'/server = '$ENV{SERVER_NAME}:$ENV{PORT}'/;

    nvt_print('HTTP/1.0 200 OK');
    nvt_print("Server: $lcbsrv");
    nvt_print('Content-Length: '.length);
    nvt_print('Content-Type: application/binary');
    nvt_print('');
    print;

  } else {

    my $yyhref = qq'<a href="/lcb/yy.sh">yy</a>';
#    $yyhref =~ s/sh/pl/ if $lcb_user and not ipin($RA,@lcb_allowed_hosts);
    my $usage = `$yy -h 2>&1`;
    $usage =~ s/.*usage:\n//s;
#    my $examples = `$yy -E 2>&1`;
#    $examples =~ s/.*examples\n/Examples:/s;
#    $examples =~ s/\nyy test.gpg:.*//s;

    nvt_print('HTTP/1.0 200 OK');
    nvt_print("Server: $lcbsrv");
    nvt_print('Content-Type: text/html');
    nvt_print('');
    print join("\n",
      "<HTML>",
      "<HEAD><TITLE>yy</TITLE></HEAD>".
      "<BODY>",
      "<h1>$yyhref : an UNIX CLI client for the shared <a href=\"/lcb/\">LAN clipboard</a> (LCB)</h1>",
      "<ul>",
      "<p><li>$yyhref offers clipboards for exchanging STDIN/STDOUT (pipe), files and directories with LAN users<br>",
      "<p><li>$yyhref can copy&paste text, binary data, files and tar archives<br>",
      "<p><li>$yyhref can be used by any interactive shell like bash<br>",
      "<p><li>$yyhref clipboards are unlimited in number or size<br>",
      "<p><li>$yyhref protects your terminal for binary data output<br>",
      "<p><li>$yyhref default clipboard is \"_\" but you can use any other name, like \"Pflaumensturz\"<br>",
      "<p><li>$yyhref clipboards contain versioned items (1-9), default is item 1<br>",
      "<p><li>$yyhref is pronounced \"&uuml;ps-&uuml;ps\" in German &#9786;<br>",
      "</ul>",
      "<h3>Examples for user koenig</h3>",
      "<pre>",
      '  yy                  # interactive clipboard menu',
      '  uname -a | yy       # copy uname output into clipboard koenig',
      '  yy *jpg             # copy all JPGs into clipboard koenig',
      '  yy -                # copy text from keyboard into clipboard koenig',
      '  yy --               # paste data from clipboard koenig',
      '  yy :3               # paste data from clipboard koenig, item 3',
      '  yy moers: project/  # copy directory project into clipboard moers',
      '  yy moers:           # interactive menu of clipboard moers',
      '  yy moers:q          # list items in clipboard moers',
      '  yy moers:d          # delete last item from clipboard moers',
      '  yy moers: project/  # copy directory project into clipboard moers',
      "</pre>",
      "<p>",
      "<h3>Full usage</h3>",
      "<pre>",
      "$usage",
      "</pre>",
      "<p>",
      "See also:",
      "<a href=\"https://fex.belwue.de/fstools/shell-clipboards.html\">shell clipboards comparison table</a>",
      "</BODY>",
      "");
  }

  exit;
}


sub lcb_login {
  my ($mh,$boundary,$user,$error);
  local $_;

  if ($RM eq 'GET') {
    nvt_print(
      'HTTP/1.0 200 OK',
      "Server: $lcbsrv",
      'Content-Type: text/html',
      '');
    print join("\n",
      "<HTML>",
      "<HEAD><TITLE>LCB login</TITLE></HEAD>".
      "<BODY>",
      '<h1>LCB login</h1>',
      qq'<form action="$ENV{REQUEST_URI}" method="post" enctype="multipart/form-data">',
      qq'  Your LCB user string: <input type="text" size="80" name="user" placeholder="email:token"><p>',
      qq'  <input type="submit" value="submit">',
      qq'</form>',
      '</body></html>',
      '');
  } elsif ($RM eq 'POST') {
    http_read();
    $boundary = $_;
    while (http_read()) {
      last if /^\Q$boundary--/;
      if (/Content-Disposition:.*name="user"/i) {
        http_read();
        http_read();
        $user = $_;
      }
    }
    if ($user) {
      if (is_lcb_user($user) or restricted_user($user)) {
        nvt_print(
          "HTTP/1.0 302 Found",
          "Server: $lcbsrv",
          "Location: /lcb/lcb.paste",
          "Set-Cookie: lcb_user=$user; path=/lcb",
          'Content-Length: 0',
          ''
        );
      } else {
        lcb_die("User $user unknown");
      }
    } else {
      nvt_print(
        "HTTP/1.0 302 Found",
        "Server: $lcbsrv",
        "Location: $ENV{REQUEST_URI}",
        'Content-Length: 0',
        ''
      );
    }
  } else {
    http_error(400);
  }

  exit;
}


sub lcb_logout {
  nvt_print(
    "HTTP/1.0 302 Found",
    "Server: $lcbsrv",
    "Location: /lcb",
    "Set-Cookie: lcb_user=; path=/lcb",
    'Content-Length: 0',
    ''
  );
  exit;
}


sub bash {
  local $_;

  nvt_print(
    'HTTP/1.0 200 OK',
    "Server: $lcbsrv",
    'Content-Type: text/html',
    '');
  print join("\n",
    "<HTML>",
    "<HEAD><TITLE>LCB bash</TITLE></HEAD>".
    "<BODY>",
    "<h1>bash functions for the shared <a href=\"/lcb/\">LAN clipboard</a> (LCB)</h1>",
    "Use these bash functions if you do not have perl and cannot use <a href=\"/lcb/yy\">yy</a>(*):",
    "<pre>",
    "");
  my $curl = 'curl -H "X-User: $LCB_USER"';
  my $bash_curl =
    "export LCB_URL=$lcb_url\n".
    "export LCB_USER=\$(whoami)@\$(hostname)\n".
    "lcbget() { $curl -sS \$LCB_URL/\$1; }\n".
    "lcbput() { cat | $curl -N -i -X PUT --data-binary \@- \$LCB_URL/\$1; }\n";
  if ($ENV{PROTO} eq 'https') {
#    my $openssl = "openssl s_client -connect $ENV{SERVER_NAME}:443 -verify_quiet -quiet";
#    print qq'lcbget() { printf "GET /lcb/%s SDTP/1.0\\n\\n" "\$1" | $openssl; }\n';
#    print qq'lcbput() { ( printf "PUT /lcb/%s SDTP/1.0\\n\\n" "\$1"; cat ) | $openssl -no_ign_eof; }\n';
    print $bash_curl;
  } elsif ("$ENV{HTTP_HOST}:80" =~ /(.+?):(\d+)/) {
    # Simple Data Transfer Protocol
    print qq'lcbget() { exec 9<>/dev/tcp/$1/$2; printf >&9 "GET /lcb/%s SDTP/1.0\\n\\n" "\$1"; cat <&9; }\n';
    print qq'lcbput() { exec 9<>/dev/tcp/$1/$2; printf >&9 "PUT /lcb/%s SDTP/1.0\\n\\n" "\$1"; cat >&9; }\n';
    if ($ENV{SERVER_NAME} =~ /^fex.*uni-stuttgart\.de$/) {
      print "\n# with curl using https:\n";
      $bash_curl =~ s/http:/https:/;
      print $bash_curl;
    }
  }
  print join("\n",
    "</pre>\n",
    "<p>",
    "examples:<br>",
    "<pre>",
    "  lcbput test_data                # copy STDIN",
    "  lcbput test_data < /tmp/data.dd # copy file content",
    "  uname -a | lcbput test_data     # copy pipe data",
    "  tar cvf - . | lcbput test_data  # copy directory",
    "  lcbget test_data:q              # query",
    "  lcbget test_data                # paste",
    "  lcbget test_data:2 | wc         # paste version 2",
    "  lcbget ::                       # list known clipboards",
    "</pre>",
    "<p>",
    "(*) The perl client <a href=\"/lcb/yy\">yy</a> offers more options and better error handling.",
    "</body></html>",
    "");

  exit;
}


sub windows {
  local $_;

  nvt_print(
    'HTTP/1.0 200 OK',
    "Server: $lcbsrv",
    'Content-Type: text/html',
    '');
  print join("\n",
    '<HTML>',
    '<HEAD><TITLE>LCB Windows</TITLE></HEAD>'.
    '<BODY>',
    '<h1>Windows cmd functions for the shared <a href="/lcb/">LAN clipboard</a> (LCB)</h1>',
    'Download <a href="/lcb/lcb.zip">lcb.zip</a> (contains LCB clients for Windows cmd)',
    'and copy the scripts from this zip archive to C:\Windows<p>',
    '<p>',
    '<p>',
    '<pre>',
    'usage examples:',
    '',
    '  lcbput test_data                : copy keyboard input',
    '  lcbput test_data < data.dd      : copy file content',
    '  systeminfo | lcbput test_data   : copy pipe data',
    '  lcbget test_data:q              : query',
    '  lcbget test_data                : paste',
    '  lcbget ::                       : list known clipboards',
    '</pre>',
    '</body></html>',
    '');
  exit;
}


sub writecmd {
  my $file = shift;
  local $_;

  open $file,'>',$file or lcb_die("cannot create $file - $!\n");
  print {$file} '@echo off',$N;
  print {$file} $_,$N foreach @_;
  close $file;
}


sub zip {
  my $file;
  my $curl = 'curl --ssl-no-revoke -H "X-User: %LCB_USER%"';
  my @zip = qw'zip -q -';
  my @cmds;

  push @cmds,"$_.cmd" foreach qw'lcbget lcbput sendto_lcbput lcb2wcb wcb2lcb';

  local $_;
  my @env = (
    qq'set "LCB_URL=$lcb_url"',
    qq'set "LCB_USER=%username%@%computername%"',
  );

  my $dir = $lcbdir.'/lcb.zip';
  unless (-d $dir) {
    mkdir $dir or lcb_die("cannot mkdir $dir - $!\n");
  }
  chdir $dir or lcb_die("cannot cd $dir - $!\n");

  writecmd('lcbget.cmd',
    @env,
    "$curl -sS %LCB_URL%/%1"
  );
  # https://ss64.com/nt/syntax-replace.html
  writecmd('lcbput.cmd',
    @env,
    'set "P1=%1"',
    'set "LCB_CLIPBOARD=%P1: =_%"',
    "$curl -N -i -X PUT --data-binary \@- %LCB_URL%/%LCB_CLIPBOARD%",
  );
  writecmd('lcb2wcb.cmd',
    'powershell "lcbget %1 | set-clipboard"'
  );
  writecmd('wcb2lcb.cmd',
    'powershell "get-clipboard" | lcbput %1'
  );
  writecmd('sendto_lcbput.cmd',
    'setlocal',
    'if exist "%1\*" set USE_TAR=1',
    'if exist "%2"   set USE_TAR=1',
    'if defined USE_TAR (',
    '  tar -cf - %* | lcbput "%username%_%*.tar"',
    ') else (',
    '  type "%1" | lcbput "%username%_%1"',
    ')',
    'endlocal',
  );
  my $lcbd = '%USERPROFILE%\LCB';
  writecmd('INSTALL.cmd',
    "mkdir $lcbd",
    "copy @cmds $lcbd",
    "cd $lcbd",
    'for /f "tokens=3" %%a in (\'reg query "HKCU\Environment" /v Path\') do set OLD_PATH=%%a',
    'reg add "HKCU\Environment" /v Path /d "%OLD_PATH%;%CD%;" /f',
  );

  open my $zip,'-|',@zip,@cmds,'INSTALL.cmd' or lcb_die("cannot zip - $!\n");
  local $/;
  $_ = <$zip>;
  close $zip;

  nvt_print(
    'HTTP/1.0 200 OK',
    "Server: $lcbsrv",
    'Content-Type: application/binary',
    'Content-Length: '.length,
    '');
  print;

  exit;
}


sub query {
  my @X = qw'File Type MD5 Args User Upload-IP';
  my $fmt = "  %10s %s\n";
  local $_;

  unless (-d $clipd) {
    lcb_die("Clipboard $clip does not exist");
  }

  chdir $clipd or lcb_die("cannot chdir $clipd - $!\n");

  if ($in) {
    unless (-s "$in/data") { lcb_die("No clipboard item $clip:$in") }
  } else {
    unless (-s "1/data") { lcb_die("No clipboard $clip") }
  }

  if ($SDTP) {
    $html = 0;
  } else {
    nvt_print('HTTP/1.0 200 OK');
    nvt_print("Server: $lcbsrv");
    if ($html) {
      nvt_print("Content-Type: text/html");
    } else {
      nvt_print("Content-Type: text/plain");
    }
    nvt_print('');

    if ($html) {
      print join("\n",
        qq'<html>',
        qq'<head><TITLE>LAN clipboard $clip</TITLE></HEAD>',
        qq'<body>',
        qq'<h2><a href="/lcb">LCB</a> clipboard <a href="/lcb/$clip/">$clip</a></h2>',
        qq'<pre>',
        '');
    }
  }

  if ($in) {
    my $data = "$in/data";
    my $size = -s $data;
    my @tar;
    $_ = qq'Item <a href="/lcb/$in/$clip">$clip:$in<a>\n';
    s/.*"(.+)".*/$lcb_url$1/ unless $html;
    print;
    printf $fmt,'Date:',isomtime($data);
    printf $fmt,'Size:',$size;
    foreach my $a (@X) {
      my $ad = readline1("$in/$a") or next;
      $ad =~ s/:.*// if $a eq 'User';
      if ($a eq 'Type' and $ad =~ /tar archive/) {
        @tar = (qw'tar tvf',$data);
      }
      printf $fmt,"$a:",$ad;
    }
    if (@tar and open my $tar,'-|',@tar) {
      print "  Content:\n";
      while (<$tar>) {
        print $html ? htmlencode($_) : $_;
      }
      close $tar;
    }
  } else {
#    print "Access: @lcb_allowed_hosts\n";
    my @Q = ();
    print "<ul>\n" if $html;
    foreach my $v (glob '[1-9]') {
      my $data = "$v/data";
      my $size = -s $data || 0;
      my $md5 = readline1("$v/MD5")||0;
      if ($html) {
        $q = qq'<li>Item <a href="/lcb/$v:MD5=$md5/$clip">$clip:$v</a> ';
        if ($allowed or $restricted) {
          $q .= qq'<a href="/lcb/$clip:$v:d?MD5=$md5"><button>delete</button></a>';
          if ($fexsend) {
            $q .= qq' <a href="/lcb/$clip:$v:f?MD5=$md5"><button>fex</button></a>';
          }
        }
      } else {
        $q = "$lcb_url/$v/$clip";
      }
      $q .= "\n";
      $q .= sprintf $fmt,'Date:',isomtime($data);
      $q .= sprintf $fmt,'Size:',$size;
      foreach my $a (@X) {
        my $ad = readline1("$v/$a") or next;
        $ad =~ s/:.*// if $a eq 'User';
        $q .= sprintf $fmt,"$a:",$ad;
      }
      unless ($html) { $q =~ s/<.*?>//g }
      push @Q,$q;
    }
    @Q = reverse(@Q) unless $html;
    print join("\n",@Q);
    print "</ul>\n" if $html;
  }

  if ($html) {
    print "</pre>\n";
    if ($clip =~ /^PUBLIC_/ or $allowed or $restricted) {
      print join("\n",
        qq'<h3>$clip <a href="/lcb/$clip:u">text copy</a> (upload)</h3>',
        qq'<h3>$clip <a href="/lcb/$clip:U">file copy</a> (upload)</h3>',
        '');
    }
    print "</body></html>\n";
  }

  exit;
}


sub upload {
  unless (-f "$clip/1/data") { lcb_die("Clipboard $clip does not exist") }

  nvt_print(
    'HTTP/1.0 200 OK',
    "Server: $lcbsrv",
    'Content-Type: text/html',
    '');

  print join("\n",
    qq'<html>',
    qq'<head><TITLE>LAN clipboard $clip upload</TITLE></HEAD>',
    qq'<body>',
    '');

  if ($allowed or $restricted or $clip =~ /^PUBLIC_/) {
    print join("\n",
      qq'<h3>Webbrowser upload for <a href="/lcb">LCB</a> clipboard <a href="/lcb/$clip:q">$clip</a></h3>',
      qq'<form action="/lcb/$clip" method="post" accept-charset="UTF-8" enctype="multipart/form-data">',
      qq'  <label>',
      $user ?
      qq'  <input type="hidden" name="user" value="$user">':
      qq'  Your email address: <input type="text" size="80" name="user" value=""><p>',
      qq'  <input type="hidden" name="clipboard" value="$clip">',
      qq'  </label>',
      '');
    if ($upload eq 'U') {
      print qq'  <input type="file" name="file" size="80">\n';
    } else {
      print qq'  Paste your text here:<br>\n';
      print qq'  <textarea name="data" cols="100" rows="20"></textarea><br>\n';
    }
    print join("\n",
      qq'  <input type="submit" value="submit">',
      qq'</form>',
    '');
  } else {
    print "<h3>No upload allowed to clipboard $clip for your ip $RA</h3>\n";
    print "Contact $ENV{SERVER_ADMIN} for details.\n";
  }

  print "</body></html>\n";
  exit;
}


sub del {
  local $_;

#  $ _ = $ENV{HTTP_X_MD5}||'';
#  lcb_die("### $clip $clipd $in [$_] ###");

  if (-d $clipd) {
    chdir $clipd or lcb_die("cannot chdir $clipd - $!\n");
  } else {
    lcb_die("Clipboard $clip does not exist");
  }

  if ($delete eq 'D') {
    chdir $lcbdir and system qw'rm -rf',$clip;
  } elsif (defined $in and $in == 0) {
    system qw'rm -rf 0';
  } else {
    $in ||= 1;
    unless (-f "$in/data") {
      lcb_die("$clip:$in does not exist");
    }
    my $md5s = readline1("$in/MD5")||'';
    if ($md5 and $md5 ne $md5s) {
      lcb_die("MD5 does not match, try BACK and RELOAD");
    }
    if (my $md5c = $ENV{HTTP_X_MD5}) {
      if ($md5c ne $md5s) {
        lcb_die("MD5 does not match");
      }
    }
    for (my $i=$in||1; $i<9; $i++) {
      system qw'rm -rf',$i if lstat($i);
      rename $i+1,$i;
    }
  }

  if ($html) {
    my $location = '/lcb';
    $location .= "/$clip:q" if -s '1/data';
    nvt_print(
      "HTTP/1.0 302 Found",
      "Server: $lcbsrv",
      "Location: $location",
      'Content-Length: 0',
      ''
    );
  } else {
    nvt_print(
      'HTTP/1.0 200 OK',
      "Server: $lcbsrv",
      '');
  }
  
  exit;
}


sub clipcopy {
  my $alog = "$nclip/access.log";
  my $msg = sprintf "%s %s %s %s %s\n",
    isodate(time),
    $RA,
    $lcb_user||$user||'unknown',
    $RM,
    $ENV{REQUEST_URI};
  local $_;

  unless (-d "$clipd/1") {
    lcb_die("Clipboard $clip does not exist");
  }
  
  if (lstat($nclip)) {
    lcb_die("Clipboard $nclip does already exist");
  }

  chdir $lcbdir or lcb_die("$lcbdir - $!");
  system qw'cp -a',$clip,$nclip;
  if (open $alog,'>',$alog) {
    printf {$alog} $msg;
    close $alog;
  }
  writelog($log,$msg);

  if ($html) {
    my $location = '/lcb';
    $location .= "/$nclip:q" if -s '1/data';
    nvt_print(
      "HTTP/1.0 302 Found",
      "Server: $lcbsrv",
      "Location: $location",
      'Content-Length: 0',
      ''
    );
  } else {
    nvt_print(
      'HTTP/1.0 200 OK',
      "Server: $lcbsrv",
      'Content-Type: text/plain',
      '');
  }
  
  exit;
}


sub post {
  my $cl = $ENV{CONTENT_LENGTH} || 0;
  my $cookie = '';
  my ($mpart,$mh,$boundary,$error);
  my %post;
  local $_;
  
  http_read();
  $boundary = $_;
  while (http_read()) {
    $mh = $_."\n";
    $mh .= $_."\n" while http_read();
    if ($mh =~ /Content-Disposition:.* name="(file)";\s*filename="(.+)"/i) {
      $post{$1} = $2;
      last;
    } elsif ($mh =~ /Content-Disposition:.*name="(.+)"/i) {
      $mpart = $1;
    } else {
      $mpart = 'UNKNOWN';
    }
    $post{$mpart} = '';
    for (;;) {
      http_read();
      last if /^\Q$boundary/;
      $post{$mpart} .= $_."\n";
    }
    last if /^\Q$boundary--/;
  }
#  nvt_print("HTTP/1.0 200 OK");
#  nvt_print("Content-Type: text/plain");
#  nvt_print("");
#  foreach $mpart (keys %post) {
#    print "[$mpart]\n";
#    print $post{$mpart},"\n";
#  }

  $clip = $post{'clipboard'}||'';
  $clip =~ s/^\s+//;
  $clip =~ s/\s+$//;
  $clip =~ s/^\./_/;
  $clip =~ s/[^$cbcc]/_/g;
  if ($clip =~ /\S/) {
    $allowed = check_upload_allowed($clip);
  } else {
#    for (;;) {
#      $x = $cl-$RB;
#      $bs = $x if $x < $bs;
#      last if $bs <= 0;
#      read(STDIN,$x,$bs) or last;
#    }
    lcb_die("Clipboard name is missing");
  }

  if ($clip =~ /^(\d)$|^(lcb|yy)/i) {
    lcb_die("Clipboard name \"$clip\" is reserved");
  }

  chdir $lcbdir or lcb_die("$lcbdir - $!\n");
  
  $clip =~ s/^\s+//;
  $clip =~ s/\s+$//;
  $clip =~ s/[^$cbcc]/_/g;
  $clip =~ s/^[.-]/_/;
  $clip ||= '__';
  $clip = untaint($clip);
  $clip0 = "$lcbdir/$clip/0";
  my $data = "$clip0/data";

  unless (-d $clip) {
    mkdir $clip or lcb_die("cannot create $lcbdir/$clip - $!");
  }
  test_upload($clip);
  mkdir $clip0 or lcb_die("cannot mkdir $clip0 = $!");
  chdir $clip0 or lcb_die("cannot chdir $clip0 - $!");

  open $data,'>',$data or $error = $!;
  # file upload goes for text copy
  if ($post{'file'}) {
    my $x;
    for (;;) {
      $x = $cl-$RB;
      $bs = $x if $x < $bs;
      last if $bs <= 0;
      $RB += read(STDIN,$x,$bs);
      print {$data} $x or $error = $!;
    }
  } elsif ($post{'data'} and $post{'data'} =~ /\S/) {
    print {$data} $post{'data'} or $error = $!;
  } else {
    system qw'rm -rf',$clip0;
    lcb_die("Paste data is empty");
  }
  close $data;
  if ($error) {
    lcb_die("cannot write $data - $error");
  }

  if ($post{'file'}) {
    my $seek = length($boundary)+4;
    open $data,$data or lcb_die("cannot read $data - $!");
    seek $data,-$seek,2;
    $_ = <$data>||'';
    close $data;
    unless (/\Q$boundary\E--/) {
      lcb_die("file not complete ($seek) [$_]");
    }
    truncate $data,untaint((-s $data)-$seek-2);
    if (open my $x,'>','File') {
      print {$x} $post{'file'},"\n";
      close $x;
    }
  }

  if (open my $x,'>','Upload-IP') {
    print {$x} "$RA\n";
    close $x;
  }

  if (my $user = $post{'user'}) {
    $user =~ s/\s//;
    if ($user =~ /\w/ and open my $x,'>','User') {
      print {$x} $user,"\n";
      close $x;
    }
    $cookie = "Set-Cookie: lcb_user=$user; path=/lcb";
  }

  unless ($post{'data'} or $post{'file'}) {
    system qw'rm -rf',$clip0;
    lcb_die("Paste data is missing");
  }

  finish_upload($data);

  nvt_print(
    'HTTP/1.0 302 Found',
    "Server: $lcbsrv",
    "Location: /lcb/$clip:q",
    'Content-Length: 0',
    $cookie,
    ''
  );

  exit;
}


sub put {
  my $data = $clip0.'/data';
  my @header = split /\n/,$ENV{HTTP_HEADER}||'';
  my $x;
  local $_;

  if ($clip =~ /^(\d)$|^(lcb|yy)/i) {
    lcb_die("Clipboard name \"$clip\" is reserved");
  }
  unless (-d $clipd) { 
    mkdir $clipd or lcb_die("cannot create $clipd - $!") 
  }
  unless (-d $clip) {
    mkdir $clip or lcb_die("cannot create $lcbdir/$clip - $!");
  }
  $allowed = check_upload_allowed($clip);
  test_upload($clip);
  mkdir $clip0 or lcb_die("cannot mkdir $clip0 = $!");
  chdir $clip0 or lcb_die("cannot chdir $clip0 - $!");
  foreach (@header) {
    if (/^X-([A-Z][\w_-]+): (.*)/) {
      my $ht = $1;
      my $hd = $2;
      open $ht,'>',$ht or lcb_die("cannot write $ht - $!");
      print {$ht} $hd,"\n";
      close $ht;
    }
  }

  if ($ENV{PROTO} =~ /http/) {
    nvt_print(
      'HTTP/1.0 202 Accepted',
      "Server: $lcbsrv",
      "X-URL: $lcb_url/$clip",
      "X-Debug: RM=$RM",
      ''
    );
  }

  if (open my $x,'>','Upload-IP') {
    print {$x} "$RA\n";
    close $x;
  }

  open $data,'>',$data or lcb_die("cannot write $data - $!");
  if (my $cl = $ENV{CONTENT_LENGTH}) {
    for (;;) {
      $x = $cl-$RB;
      $bs = $x if $x < $bs;
      last if $bs <= 0;
      $RB += read(STDIN,$x,$bs);
      print {$data} $x or last;
    }
  } else {
#  $SIG{__DIE__} = $SIG{__WARN__} = sub {
#    my $log = '/tmp/lcb.log';
#    if (open $log,'>',$log) {
#      print {$log} "@_\n";
#    }
#    exit 99;
#  };
    foreach $sig (keys %SIG) {
      $SIG{$sig} = sub { print "lcb: signal @_\n" if 0 };
    }
#    printf "lcb line %d\n",__LINE__;
#    printf "lcb writing data %s\n",$data;
#    printf "lcb line %d\n",__LINE__;
    while (read(STDIN,$x,$bs)) {
#      printf "lcb line %d\n",__LINE__;
      print {$data} $x or last;
    }
#    printf "lcb line %d\n",__LINE__;
  }
#  print "lcb closing $data\n";
  close $data;
#  print "lcb closed $data\n";
  finish_upload($data);
#  print "lcb finished upload\n";
  close STDOUT;
  exit;
}


# for PUT and POST
sub finish_upload {
  my $data = shift;
  my $MD5 = 'MD5';
  my $md5hd = 0;
  my $size = -s $data || 0;

  chdir dirname($data) or lcb_die("$data - $!");
  
  if ($size) {
    if ($restricted) {
      if (open my $rd,'>../restricted') {
        if ($restricted_domain) {
          print {$rd} $restricted_domain,"\n";
        } elsif ($restricted_host) {
          print {$rd} $restricted_host,"\n";
        } elsif ($restricted_user) {
          print {$rd} $restricted_user,"\n";
        }
        close $rd;
      }
    }
    system "file -b $data > Type 2>&1";
    if (open $data,$data and my $md5 = Digest::MD5->new) {
      $md5->addfile($data);
      close $data;
      $md5hd = $md5->hexdigest;
      if (open $MD5,'>',$MD5) {
        print {$MD5} "$md5hd\n";
        close $MD5;
      }
    }
    chdir '..' or exit;
    for (my $i=8; $i>=0; $i--) {
      my $ii = $i+1;
      system qw'rm -rf',$ii if lstat($ii);
      rename $i,$ii;
    }
#    if ($http_client =~ /^yy/) {
    if (0 and $RM eq 'PUT') {
      # does not work with stunnel, because of shutdown()-bug
      print "Size: $size\n";
      print "MD5: $md5hd\n";
    }
  } else {
    system qw'rm -rf',$clip0;
  }

  &lcblog;
}


# empty line must return 0
# sets global $_;
sub http_read {
#  my $log = shift;
  $_ = <STDIN>;
  $_ = '' unless defined;
  print {$debuglog} $_ if $debuglog;
  $RB += length;
  s/[$N]//g;
  return length;
}


sub isomtime {
  my @d = localtime((stat shift)[9]);
  return sprintf(
    '%d-%02d-%02d %02d:%02d:%02d',
    $d[5]+1900,$d[4]+1,$d[3],$d[2],$d[1],$d[0]
  );
}


sub is_lcb_user {
  my $u = shift;
  local $_;
  
  if ($u and @lcb_users) {
    foreach (@lcb_users) {
      if (/::/) {
        return $u if $u =~ /^$_/;
      } else {
        return $u if $u eq $_;
      }
    }
  }
  return '';
}


sub lcblog {
  my $alog = "$lcbdir/$clip/access.log";
  my $uri = $ENV{REQUEST_URI};
  my $access = '';
  my $msg = untaint(sprintf("%s %s %s %s %s",
    isodate(time),
    $RA,
    $lcb_user||$user||'unknown',
    $RM,
    $uri
  ));

  if ($RM eq 'POST') {
    $msg .= "/$clip";
  }

  if ($RM ne 'HEAD' and $uri !~ /:[a-z]\b/i and $uri !~ m:/$:) {
    my $i = 1;
    $i = $1 if $uri =~ /:(\d)$/;       # from yy
    $i = $1 if $uri =~ /\/(\d):\w+\//; # from webbrowser / http-client
    if (my $s = -s "$lcbdir/$clip/$i/data") {
      $msg .= " $s";
    }
  }

  $msg .= "\n";
  writelog($log,$msg);
  debug("ALLOWED: $allowed") if $allowed;

  if (open $alog,'>>',$alog) {
    printf {$alog} $msg;
    close $alog;
  }
}


sub lcb_die {
  my $msg = sprintf "%s %s ERROR %s %s %s\n",
    isodate(time),
    $RA,
    $RM||'-',
    $ENV{REQUEST_URI}||'-',
    "@_";

  writelog($log,$msg);
  debug('ERROR:',@_);

#  if ($clip0 and -e $clip0) {
#    my $clip00 = $clip0.'0';
#    system qw'rm -rf',$clip00;
#    rename $clip0,$clip00;
#  }

  if ($RM and $RM eq 'POST') {
    local $SIG{__DIE__} = 'DEFAULT';
    eval {
      my $x;
      local $SIG{ALRM} = sub { die };
      alarm(3);
      while (read(STDIN,$x,65536)) { alarm(3) }
      alarm(0);
    };
  }
  
  if ($SDTP) {
    sdtp_die(@_)
  } elsif ($html) {
    html_error($error||'',@_);
  } else {
#    http_header('666 Bad Request','Content-Type: text/plain');
    print join("\r\n",
      "HTTP/1.0 400 Bad Request : $_[0]",
      "Content-Type: text/plain",
      ""
    );
    print $_,"\n" foreach @_;
  }
  exit;
}


sub untaint {
  my @a = ();
  local $_;
  foreach (@_) {
    /(.*)/s;
    push @a,$1;
  }
  if (scalar(@a) == 1) {
    return $a[0];
  } else {
    return @a;
  }
}


# read one text line unbuffered
sub getaline {
  my $line = '';
  my $c;

  # must use sysread to avoid perl line buffering
  while (sysread STDIN,$c,1) {
    $line .= $c;
    last if $c eq "\n";
  }

  $line =~ s/[$N]//g;
  return $line;
}


# test if ip is in iplist (ipv4/ipv6)
# iplist is an array with ips and ip-ranges
sub ipin {
  my ($ip,@list) = @_;
  my ($i,$ia,$ib);

  $ipe = lc(ipe($ip));
  map { lc } @list;

  foreach $i (@list) {
    if ($ip =~ /\./ and $i =~ /\./ or $ip =~ /:/ and $i =~ /:/) {
      if ($i =~ /(.+)-(.+)/) {
        ($ia,$ib) = ($1,$2);
        my $iae = ipe($ia) or next;
        my $ibe = ipe($ib) or next;
        return "$ipe $iae-$ibe $ia-$ib" if $ipe ge $iae and $ipe le $ibe;
      } else {
        return $ipe if $ipe eq ipe($i)||'';
      }
    }
  }
  return '';
}


# ip expand (ipv4/ipv6)
sub ipe {
  local $_ = shift;
  
  s/:$/:0/;

  if (/^\d+\.\d+\.\d+\.\d+$/) {
    s/\b(\d\d?)\b/sprintf "%03d",$1/ge;
  } elsif (/^[:\w]+:\w+$/) {
    s/\b(\w+)\b/sprintf "%04s",$1/ge;
    s/^:/0000:/;
    while (s/::/::0000:/) { last if length > 39 }
    s/::/:/;
  } else {
    $_ = undef;
  }
  return $_;
}


sub nvt_print {
  local $_;
  foreach (@_) {
    my $x = $_;
    $x =~ s/[$N]//g;
#    $x = encode_utf8($x) if utf8::is_utf8($x);
    syswrite STDOUT,$x.$N;
  }
}


sub readline1 {
  my $file = shift;
  local $_;

  if (open $file,$file) {
    $_ = <$file> // '';
    close $file;
    s/[$N]//g;
  }
  return $_;
}


sub isodate {
  my $time = shift;
  my $isodate = '????-??-?? ??:??:??';

  if ($time) {
    my @d = localtime $time;
    $isodate = sprintf('%d-%02d-%02d %02d:%02d:%02d',
                       $d[5]+1900,$d[4]+1,$d[3],$d[2],$d[1],$d[0]);
  }

  return $isodate;
}


sub mtime {
  my @s = stat(shift) or return;
  return $s[9];
}


sub writelog {
  my $log = shift;
  my $msg = shift;

#  $msg = encode_utf8($msg) if utf8::is_utf8($msg);

  if (open $log,'>>',"$lcbdir/$log") {
    print {$log} $msg;
    close $log;
  }
}


sub http_error {
  my $error = shift;
  my $msg = shift;
  my $URL = $ENV{REQUEST_URL}||'';
  my $URI = $ENV{REQUEST_URI}||'';
  my $isodate = isodate(time);

  $footer ||= '';
  $URI =~ s/\?.*//;

  if ($error eq 400) {
    http_error_header("400 Bad Request");
    nvt_print("Your request $URL is not acceptable.");
  } elsif ($error eq 403) {
    http_error_header("403 Forbidden");
    if ($msg) {
      nvt_print($msg);
    } else {
      nvt_print("You have no permission to request $URL");
    }
  } elsif ($error eq 404) {
    http_error_header("404 Not Found");
    nvt_print("The requested URI $URI was not found on this server.");
  } elsif ($error eq 413) {
    http_error_header("413 Payload Too Large");
    nvt_print("Your HTTP header is too large.");
  } elsif ($error eq 416) {
    http_error_header("416 Requested Range Not Satisfiable");
  } elsif ($error eq 503) {
    http_error_header("503 Service Unavailable");
    # nvt_print("No Perl ipv6 support on this server.");
  } else {
    http_error_header("555 Unknown Error");
    nvt_print("The requested URL $URL produced an internal error.");
  }
  print $isodate,"\n",$footer;
}


sub http_error_header {
  my $error = shift;
  my $uri = $ENV{REQUEST_URI};

  nvt_print(
    "HTTP/1.0 $error",
    "Connection: close",
    "Content-Type: text/html",
    "",
    "<html>",
    "<head><title>$error</title></head>",
    "<body>",
    "<h1>$error</h1>",
  );
}

sub html_error {
  my $error = shift;
  my $msg = "@_";
  my @msg = @_;
  my $isodate = isodate(time);
  local $_;

  $footer ||= '';
#  $x = encode_utf8($msg) if utf8::is_utf8($msg);
  $msg =~ s/[\s\n]+/ /g;
  $msg =~ s/<.+?>//g; # remove HTML
  foreach (@msg) {
#    $_ = encode_utf8($_) if utf8::is_utf8($_);
    s/<script.*?>//gi;
  }

  $SIG{ALRM} = sub {
    $SIG{__DIE__} = 'DEFAULT';
    die "TIMEOUT\n";
  };
  alarm($timeout);

  # cannot send standard HTTP Status-Code 400, because stupid
  # Internet Explorer then refuses to display HTML body!
  http_header("400 Bad Request - $msg");
  print html_header($error);
  print 'ERROR: ',join("<p>\n",@msg),"\n";
  print "<p>\n";
  print $isodate,"\n";
  print "<p>\n";
  print $footer;
  exit;
}


sub html_header {
  my $title = shift;
  my $h1 = shift || $title;
  my $fua = $ENV{HTTP_USER_AGENT}||'';
  my $head;

  # binmode(STDOUT,':utf8'); # for text/html !

  $title =~ s/<.*?>//g;

  # http://www.w3.org/TR/html401/struct/global.html
  # http://www.w3.org/International/O-charset
  if ($fua =~ /^fex/) {
    $head = "<html><body>\n";
  } else {
    $head = qqq(qq(
      '<html>'
      '<head>'
      '  <meta http-equiv="expires" content="0">'
      '  <meta http-equiv="Content-Type" content="text/html;charset=$charset">'
      '  <title>$title</title>'
      '</head>'
    ));
    # '<!-- <style type="text/css">\@import "/fex.css";</style> -->'

    if ($0 =~ /fexdev/) { $head .= "<body bgcolor=\"pink\">\n" }
    else                { $head .= "<body>\n" }

    $h1 =~ s:F\*EX:<a href="/index.html">F*EX</a>:;

    $head .= &$prolog($title) if defined($prolog);

    if (@H1_extra) {
      $head .= sprintf(
        qq'<h1><a href="%s"><img align=center src="%s" border=0></a>%s</h1>\n',
        $H1_extra[0],$H1_extra[1]||'',$h1
      );
    } else {
      $head .= "<h1>$h1</h1>\n";
    }

  }

  return $head;
}


sub http_header {
  my $status = shift;
  my $msg = $status;

  return if $HTTP_HEADER;
  $HTTP_HEADER = $status;

  $msg =~ s/^\d+\s*//;

  nvt_print("HTTP/1.1 $status");
  nvt_print("X-Message: $msg");
  nvt_print("Server: lcb");
  nvt_print("Expires: 0");
  nvt_print("Cache-Control: no-cache");

  unless (grep /^Content-Type:/i,@_) {
    # nvt_print("Content-Type: text/html; charset=ISO-8859-1");
    nvt_print("Content-Type: text/html; charset=$charset");
  }

  nvt_print(@_,'');
}


sub sdtp_die {
  print "SDTP-ERROR: @_\n";
  exit;
}


sub asort {
  return sort { lc($a) cmp lc($b) } @_;
}


sub htmlencode {
  local $_ = shift;
  s/&/&amp;/g;
  s/</&lt;/g;
  return $_;
}


sub slurp {
  my $file = shift;
  local $_;
  local $/;

  if (open $file,$file) {
    $_ = <$file>;
    close $file;
  }

  return $_;
}


sub searchpath {
  my $prg = shift;
  my @PATH = split(':',$ENV{PATH});

  if ($prg =~ m:/:) {
    return $prg if -x $prg and -f $prg;
  } else {
    foreach my $path (@PATH) {
      my $x = "$path/$prg";
      return $x if -x $x and -f $x;
    }
  }

  return '';
}


# superquoting
sub qqq {
  local $_ = shift;
  my ($s,@s);
  my $i = '';
  my $q = "[\'\"]"; # quote delimiter chars " and '

  # remove comment
  while (s/\n#.*?\n/\n/) {}

  # remove first newline and look for default indentation
  s/^((\d+)?)?\n// and $i = ' ' x ($2||0);

  # remove trailing spaces at end
  s/[ \t]*?$//;

  @s = split "\n";

  # first line have a quote delimiter char?
  if (/^\s+$q/) {
    # remove heading spaces and delimiter chars
    foreach (@s) {
      s/^\s*\'// and s/\'\s*$// or
      s/^\s*\"// and s/\"\s*$//;
    }
  } else {
    # find the line with the fewest heading spaces (and count them)
    # (beware of tabs!)
    $s = length;
    foreach (@s) {
      if (/^( *)\S/ and length($1) < $s) { $s = length($1) };
    }
    # adjust indentation
    foreach (@s) {
      s/^ {$s}/$i/;
    }
  }

  return join("\n",@s)."\n";
}


# print superquoted
sub pq {
  my $H = STDOUT;
  local $_;

  if (@_ > 1 and defined fileno $_[0]) { $H = shift }
  $_ = qqq(@_);
  # print needs need binary data, not wide characters
  ## binmode($H,':utf8'); # does not work correctly
  $_ = encode_utf8($_) if utf8::is_utf8($_);
  print {$H} $_;
}


sub allowed_domain { 
  my $ip = shift;
  return unless @lcb_allowed_domains;
  if (qhost($ip) =~ /pointer ([\w\.-]+)\.$/) {
    my $rhost = $1;
    if (qhost($rhost) =~ /address $ip/) {
      foreach my $ad (@lcb_allowed_domains) {
        return $ad if $rhost =~ /\b\Q$ad\E$/;
      }
    }
  }
}


sub restricted_domain { 
  my $ip = shift;
  return unless @lcb_restricted_domains;
  if (qhost($ip) =~ /pointer ([\w\.-]+)\.$/) {
    my $rhost = $1;
    if (qhost($rhost) =~ /address $ip/) {
      foreach my $rd (@lcb_restricted_domains) {
        return $rd if $rhost =~ /\b\Q$rd\E$/;
      }
    }
  }
}


sub restricted_host { 
  my $ip = shift;
  local $_;
  return unless @lcb_restricted_hosts;
  foreach (@lcb_restricted_hosts) {
    if (s/^([\w\@.-]+).([\d.a-f:-]+)/$2/i) {
      my $tag = $1;
      return $tag if ipin($ip,$_);
    }
  }
}


sub restricted_user { 
  my $user = shift;
  local $_;
  return unless @lcb_restricted_users;
  foreach (@lcb_restricted_users) {
    return $user if /^\Q$user\E$/i;
  }
}


sub check_download_allowed {
  my $clip = shift;
  
  return unless $clip;
  return $allowed if $allowed;
#  return $lcb_user if $lcb_user;
#  my $ah = ipin($RA,@lcb_allowed_hosts);
#  return $ah if $ah;
#  my $ad = allowed_domain($RA);
#  return $ad if $ad;
  
  $clip =~ s/:.*//;
  my $clipd = "$lcbdir/$clip";
  
  if ($clip =~ /^yy(\.sh|\.pl)?$|^lcb\.paste$/) {
    return;
  }
  
  if ($restricted) {
    if (my @x = glob("$clipd/[01]/data")) {
      my $rr = readline1("$clipd/restricted")||'';
      $restricted_domain = '' if $restricted_domain ne $rr;
      $restricted_host   = '' if $restricted_host   ne $rr;
      $restricted_user   = '' if $restricted_user   ne $rr;
    }
    return $restricted_domain if $restricted_domain;
    return $restricted_host   if $restricted_host;
    return $restricted_user   if $restricted_user;
  }

  if ($clip =~ /^public_/i) {
    if ($clip =~ /:/) {
      lcb_die(
        "Special access functions from your host ($RA) are not allowed.",
        "Contact $ENV{SERVER_ADMIN} for details."
      );
    }
    return;
  }
  
  lcb_die(
    "Access from your host ($RA) is not allowed or you have not logged in.",
    "Contact $ENV{SERVER_ADMIN} for details."
  );
}


sub check_upload_allowed {
  my $clip = shift;
  
  if ($clip =~ m{[/:]}) { lcb_die("Illegal clipboard name $clip") }
  
  return $allowed if $allowed;
  return 'PUBLIC'  if $clip =~ /^PUBLIC_/;
       
  $clipd = "$lcbdir/$clip";
  
  if ($restricted) {
    if (my @x = glob("$clipd/[01]/data")) {
      my $rr = readline1("$clipd/restricted")||'';
      $restricted_domain = '' if $restricted_domain ne $rr;
      $restricted_host   = '' if $restricted_host   ne $rr;
      $restricted_user   = '' if $restricted_user   ne $rr;
    }
    return $restricted_domain if $restricted_domain;
    return $restricted_host   if $restricted_host;
    return $restricted_user   if $restricted_user;
    lcb_die(
      "Uploads from your host ($RA) to clipboard $clip are not allowed.",
      "Contact $ENV{SERVER_ADMIN} for details."
    );
  }
  
  lcb_die(
    "Uploads from your host ($RA) are not allowed.",
    "Contact $ENV{SERVER_ADMIN} for details."
  );
}


sub check_maint { 
  if ($FEXLIB) {
    if (my $status = readlink "$spooldir/\@MAINTENANCE") {
      lcb_die($status);
    }
  }
}


sub test_upload {
  my $clip = shift;
  my $clip0 = "$lcbdir/$clip/0";
  
  if ($clip =~ m{[/:]}) { lcb_die("Illegal clipboard name $clip") }
  if (my $mt = mtime("$clip0/data")) { 
    if (time < $mt+30) {
      lcb_die("A paste for clipboard $clip is already running") 
    }
    # remove dangling upload directory
    system qw'rm -rf',$clip0;
  }
}


sub qhost {
  my $q = shift;
  local $_ = `host $q 2>/dev/null`;
  return '' if /not found/;
  return $_;
}


sub debug {
  local $_ = join("\n",@_);
  return unless $debuglog;
  if (s/^!//) {
    print {$debuglog} "# $_\n";
    $_ = `$_ 2>&1`;
  }
  s/\n?$/\n/;
  print {$debuglog} $_;
}
