#!/usr/bin/perl

# CLI client for the shared LAN clipboard
#
# Author: Ulli Horlacher <framstag@belwue.de>
#
# Perl Artistic Licence

use 5.010;
use warnings;
use strict qw(vars subs);
use Config;
use Socket;
use IO::Handle;
use IO::Socket::IP;
use Getopt::Std;
use File::Basename;
use Term::ReadLine;
use Sys::Hostname;
use Time::Local;
use Cwd qw(abs_path getcwd);

use constant MB => 2**20;

$ENV{LANGUAGE} = 'en';
$ENV{LC_MESSAGES} = 'C';

STDOUT->autoflush(1);
STDERR->autoflush(1);

our $version = 20251112;
our $prg = basename($0);
our $bs = 2**20;
our $SH;
  
# our %SSL = (SSL_version => 'TLSv1_2');
our %SSL = ();

my $server = ''; 
my $domain = '';
my $lcb_url = '';
my $via = '';
my $port = 592;
my $cb = '_'; 
my $cbcc = '\w_@.+-';
my ($HOME,$GNUTAR,$windoof,$fexhome,$user,$useragent,$urlarg);
my ($macos,$cygwin,$usage,$length,$sigpipe,$examples,$overwrite,$interactive);
my $hostname = hostname();
my $CASE = my $ESAC = undef;

$user = $ENV{LCB_USER} || sprintf('%s@%s',scalar(getpwuid($<)),$hostname);

$domain = `hostname -d`;
chomp $domain;
if ($domain !~ /\./ and $_ = slurp('/etc/resolv.conf')) {
  $domain = $2 if /^(domain|search).* ([\w.-]+)/m;
}

$_ = $ENV{LCB_SERVER}||'';
if (/^(https?):/) {
  $port = ($1 eq 'https') ? 443 : 80;
  $port = $1 if s/:(\d+)//;
  $server = $1 if m://([\w.-]+):;
  $via = '$LCB_SERVER';
} elsif (/(\w[\w.-]+)/) {
  $server = $1;
  if (/:(\d+)/) {
    $port = $1;
  } elsif ($server =~ /^fex\./) {
    $port = 443;
  }
  $via = '$LCB_SERVER';
} elsif (`avahi-browse -prt _lcb._tcp 2>/dev/null` =~ 
         /^=.*;_lcb\._tcp;.*;([\w.-]+\.local);.*;(\d+);/m) 
{
  $server = $1;
  $port = $2;
  $via = 'Avahi';
} else {
  if ($domain =~ /^(\w[\w.-]+)$/) {
    $server = "fex.$1";
    unless (gethostbyname($server)) {
      $server =~ s/\.[\w-]+/./;
      $server = '' unless gethostbyname($server);
    }
  }
  if ($server) {
    $port = 443;
    warn "$prg: guessing LCB server $server:$port, to override use:\n".
         "    export LCB_SERVER=server:port\n";
    $via = 'domain guess';
  } else {
    $server = 'fex.belwue.de';
    $port = 443;
    $via = 'default';
  }
}

if ($server) {
  $lcb_url =
    $port == 80  ? "http://$server/lcb":
    $port == 443 ? "https://$server/lcb":
    $port        ? "http://$server:$port/lcb":
                   '';
} else {
  die "$prg: unknown LCB_SERVER\n";
}

$version ||= mtime($0);

if ($Config{osname} =~ /^mswin/i) {
  # http://slu.livejournal.com/17395.html
  $windoof = $Config{osname};
  $HOME = $ENV{USERPROFILE};
  $fexhome = $ENV{FEXHOME} || $HOME.'\fex';
  $useragent = sprintf("$prg-$version (%s %s)",
                      $Config{osname},$Config{archname});
  $SSL{SSL_verify_mode} = 0;
} else {
  # $0 = "$prg @ARGV";
  if ($Config{osname} =~ /^darwin/i or $ENV{MACOS}) {
    # https://superuser.com/questions/61185/why-do-i-get-files-like-foo-in-my-tarball-on-os-x
    $ENV{COPYFILE_DISABLE} = 1;
    # http://stackoverflow.com/questions/989349/running-a-command-in-a-new-mac-os-x-terminal-window
    $macos = $Config{osname};
    $HOME = (getpwuid($<))[7]||$ENV{HOME};
    $fexhome = $HOME.'/.fex';
    $_ = `sw_vers -productVersion 2>/dev/null`||'';
    chomp;
    $useragent = "$prg-$version (MacOS $_)";
  } else {
    # beware: fex.pp sets env var FEXHOME !
    $HOME = (getpwuid($<))[7]||$ENV{HOME};
    $fexhome = $HOME.'/.fex';
    my ($os,$osp,$osn,$osv);
    if (open my $osr,'/etc/os-release') {
      while (<$osr>) {
        $osp = $1 if /^PRETTY_NAME="(.+)"/;
        $osn = $1 if /^NAME="(.+)"/;
        $osv = $1 if /^VERSION="(.+)"/;
      }
      close $osr;
    }
    if ($osp and $osp =~ /\d/) {
      $os = $osp;
    } elsif ($osn and $osv) {
      $os = "$osn $osv";
    } else {
      $os = `(lsb_release -d||uname -a)2>/dev/null`||'';
      chomp $os;
      $os =~ s/^Description:\s+//;
    }
    $useragent = "$prg-$version ($os)";
  }
}
if ($Config{osname} eq 'cygwin' or $ENV{CYGWIN}) {
  # https://cygwin.com/faq/faq.html#faq.using.fixing-fork-failures
  $cygwin = 1;
  $SSL{SSL_verify_mode} = 0;
}

my $yyd = "$HOME/.yy";
unless (-d $yyd) { mkdir $yyd,0700 or die "$prg: $yyd - $!\n" }

# default clipboard
$cb = $1 if ($ENV{LCB_CLIPBOARD}||'') =~ /(.+)/;
$cb = $domain if $cb eq '_' and $server =~ /^fex/;
  
$usage = qq'yy: shared LAN clipboard for copy (upload) & paste (download)
    $lcb_url

usage:
  yy [CLIPBOARD:]             # interactive clipboard selection
  yy [CLIPBOARD:] FILE [...]  # copy file(s) as tar archive
  yy [CLIPBOARD:] DIRECTORY   # copy directory recursivly 
  yy [CLIPBOARD:] -           # copy STDIN
  yy [CLIPBOARD:] - FILE      # copy file as is
  ... | yy [CLIPBOARD:]       # copy STDOUT from pipe
  yy ::                       # list known clipboards
  yy [CLIPBOARD]:ITEM         # paste file(s) or STDOUT
  yy [CLIPBOARD:] --          # paste file(s) or STDOUT without checking
  yy [[CLIPBOARD][:ITEM]]:o   # paste file(s) in overwrite mode
  yy [[CLIPBOARD][:ITEM]]:q   # query meta data (list item(s))
  yy [[CLIPBOARD][:ITEM]]:f   # fex clipboard item
  yy [[CLIPBOARD][:ITEM]]:d   # delete clipboard item
  yy CLIPBOARD:D              # delete clipboard
  yy CLIPBOARD:p              # toggle public mode (rename clipboard)
  yy CLIPBOARD:c:CLONE        # clone CLIPBOARD to CLONE
  yy -t [-p] ANYTHING         # copy ANYTHING as tar archive (-p = public)
  yy -f [-p] FILE             # copy FILE with filename URL (-p = public)
  yy -q                       # query configuration
  yy -e                       # show environment exports
  yy -I                       # show general info about LAN clipboard
  yy -Y                       # show yy installation code
  yy -U                       # self-update
  yy -E                       # show examples

CLIPBOARD contains versioned ITEMs and is is auto-created by copy
CLIPBOARD consists of characters a-z A-Z 0-9 . _ @ + -
If CLIPBOARD ends with .gpg it will be encrypted
ITEM consists of number 1-9 (default is 1) and is rotated by copy
[ARGUMENTS] are optional, see examples (yy -E)
';

my $clipboard = $ENV{LCB_CLIPBOARD}||(getpwuid($<))[0];
my $cbc = sprintf('%-13s # default clipboard',$clipboard);
$examples = qq'yy: shared LAN clipboard for copy (upload) & paste (download), examples

yy                # interactive clipboard menu
uname -a | yy     # copy uname output into clipboard "$clipboard"
yy *jpg           # copy all JPGs into clipboard "$clipboard"
yy -              # copy text from keyboard into clipboard "$clipboard"
yy ABC: project/  # copy directory project into clipboard "ABC"
yy X.gpg: zz      # copy file zz into encrypted clipboard "X.gpg"
yy -tp project/   # copy directory project into clipboard "public_project.tar"
yy -f fex.txt     # copy content of fex.txt into clipboard "fex.txt"
yy --             # paste files from clipboard "$clipboard" without checking
yy :3             # paste data from clipboard "$clipboard" item 3
yy :c:ABC         # clone clipboard "$clipboard" to clipboard "ABC"
yy ABC:           # interactive menu of clipboard "ABC"
yy ABC:q          # list items in clipboard "ABC"
yy ABC:d          # delete last item from clipboard "ABC"
yy test.gpg: test.jpg                      # encrypted copy
yy public_test: test.jpg                   # public (external) copy
yy https://fex.belwue.de/lcb/1/public_test # external paste
  
command        # content     # download URL
-----------------------------------------------------------------------------
yy    test.jpg # tar archive # $lcb_url/$cb
yy -  test.jpg # file data   # $lcb_url/$cb
yy -f test.jpg # file data   # $lcb_url/test.jpg
yy -t test.jpg # tar archive # $lcb_url/test.jpg.tar
  
environment variables (optional):
  LCB_SERVER=$server:$port
  LCB_USER=MYADDRESS:MYTOKEN  # for user based authorization
  LCB_CLIPBOARD=$cbc
  LCB_EXCLUDE=".*"            # exclude files matching shell pattern .*
';

my $term = new Term::ReadLine $0;
$term->ornaments(0) unless $ENV{PERL_RL};

if (-t STDIN and scalar(@ARGV) == 2 and $ARGV[0] eq '-' and -f $ARGV[1]) {
  put(@ARGV);
}

our $opt_h = 0;
our $opt_v = 0;
our $opt_V = 0;
our $opt_o = 0;
our $opt_q = 0;
our $opt_t = 0;
our $opt_f = 0;
our $opt_p = 0;
our $opt_e = 0;
our $opt_I = 0;
our $opt_E = 0;
our $opt_Y = 0;
our $opt_U = 0;
our $opt_6 = 0;

$_ = "$fexhome/config.pl"; require if -f;

if ("@ARGV" =~ /^--\S/) { die $usage }

if ("@ARGV") {
  $opt_v = shift @ARGV if $ARGV[0] eq '-v';
  if ("@ARGV" eq '--') {
    $overwrite = 1;
    get($cb); 
  }
}

getopts('hvVqotfpeIEYU6') or die $usage;

if ($opt_h) {
  print $usage;
  exit;
}

if ($opt_V) {
  print "$prg: version $version\n";
  exit;
}

# LCB URL?
if ("@ARGV" =~ m{^https?://}) {
  $urlarg = $_ = shift @ARGV;
  $port = /^https/ ? 443 : 80;
  $port = $1 if s/:(\d+)//;
  $server = $1 if m://([\w.-]+):;
  if (m:/lcb/(\d)/([$cbcc]+)$:) {
    $cb = "$2:$1";
  } elsif (m:/lcb/([$cbcc]+)$:) {
    $cb = $1;
  } else {
    die "$prg: $_ is not a LCB URL\n";
  }
  get($cb); 
}

unless ($server) {
  die "$prg: cannot determine LCB server, use: export LCB_SERVER=server:port\n";
}

if ($opt_e) {
  my $dcb = $server =~ /^fex\./ ? $domain : '_';
  printf "export LCB_SERVER=$server:$port\n" if $server;
  printf "export LCB_CLIPBOARD=%s\n",$ENV{LCB_CLIPBOARD}||$dcb;
  foreach my $e (qw(LCB_USER LCB_EXCLUDE)) {
    printf "export %s=%s\n",$e,$ENV{$e}||'';
  }
  exit;
}

if ($opt_6) {
#  eval 'use Net::INET6Glue::INET_is_INET6';
#  if ($@) { die "$prg: $@\n" }
}

if ($opt_E) {
  print $examples;
  exit;
}

if ($opt_Y) {
  print "curl -sS $lcb_url/yy.sh|sh -x\n";
  print "export LCB_SERVER=$server:$port\n";
  print "export LCB_CLIPBOARD=$cb\n";
  exit;
}

if ($opt_U) {
  if ($0 =~ m:^/client/bin/|/sw/:) { die "$prg: use sw update\n" }
  $_ = `curl -sS $lcb_url/yy.pl`;
  if (/shared LAN clipboard/) {
    open $0,'>',$0 or die "$prg: cannot write $0 - $!\n";
    print {$0} $_;
    close $0;
    exec $0,'-V';
  } else {
    die "$prg: $lcb_url/yy.pl contains wrong code\n";
  }
  exit;
}

if ($opt_I) {
  my $wdump;
  my @wdump = qw'w3m lynx links';
  foreach (@wdump) {
    if ($wdump = searchpath($_) and open $wdump,'-|',$wdump,'-dump',$lcb_url) {
      print "\$ $wdump -dump $lcb_url\n" if $opt_v;
      while (<$wdump>) {
        last if /yy/;
        print;
      }
      close $wdump and exit;
    }
  }
  die "$prg: @wdump not installed, see $lcb_url\n";
}

if ($opt_q) {
  print "yy version:        $version\n";
  print "server URL:        $lcb_url (via $via)\n";
  if (open my $lcb,"$prg -v :: 2>&1|") {
    my $ah = '';
    my $ad = '';
    my $rd = '';
    while (<$lcb>) {
      next if /guessing/;
      if (/404 Not Found/) { die "$prg: no LCB on $server:$port\n" }
      if (/^yy:/) { die $_ }
      last if /^<-- $/;
      $ah = $1 if /X-Allowed-Hosts: (.+)/;
      $ad = $1 if /X-Allowed-Domains: (.+)/;
      $rd = $1 if /X-Restricted-Domain: (.+)/;
    }
    my @clipboards = ();
    while (<$lcb>) {
      push @clipboards,$1 if /^(\S+)$/;
    }
    $user =~ s/:.*//;
    print "user:              $user\n";
    print "default clipboard: $cb\n";
    print "known clipboards:  @clipboards\n" if @clipboards;
    print "allowed hosts:     $ah\n" if $ah;
    print "allowed domains:   $ad\n" if $ad;
    print "restricted domain: $rd\n" if $rd;
  }
  exit;
}

if ($opt_t and $opt_f) {
  die "$prg: cannot mix options -t and -f\n";
}

if ($opt_f) {
  if (@ARGV and $ARGV[0] =~ /(.+):$/) {
    $cb = $1;
    shift;
  } else {
    $cb = '';
  }
  if (scalar(@ARGV) != 1) {
    die "usage: $prg -f [-p] FILE\n";
  }
  my $file = shift;
  unless (-f $file) {
    die "$prg: $file does not exist or is not a regular file\n";
  }
  unless (-r $file) {
    die "$prg: $file is not readable\n";
  }
  $cb ||= basename($file);
  $cb =~ s/[^$cbcc]/_/g;
  $cb = 'public_'.$cb if $opt_p;
  put('-',$file);
}

if ($opt_t) {
  my ($A,@A);
  if (@ARGV and $ARGV[0] =~ /(.+):$/) {
    $A = $1;
    $A =~ s/(\.tar)?$//;
    shift;
  }
  unless (@ARGV) {
    die "usage: $prg -t [-p] ANYTHING...\n";
  }
  @A = ();
  foreach (@ARGV) {
    unless (-r) {
      die "$prg: $_ does not exist or is not readable\n";
    }
    if (-d) {
      push @A,$_ unless $A;
    } elsif (-f and not -l) {
      $A ||= basename(dirname(abs_path($_)));
    } else {
      die "$prg: $_ - not file or directory\n";
    }
  }
  if ($A) {
    if (scalar(@ARGV) == 1) {
      @A = @ARGV;
    } else {
      @A = ($A);
    }
  }
  map { 
    s://+:/:g;
    s:^\./::;
    s:/$::;
    basename($_);
  } @A;
  $cb = join('+',@A).'.tar';
  $cb =~ s/[^$cbcc]/_/g;
  $cb = 'public_'.$cb if $opt_p;
  put(@ARGV);
}

$overwrite = $opt_o;

if ("@ARGV" eq '::') { get('::') }

if (scalar(@ARGV) == 1) {
  $_ = $ARGV[0];
  unless (/:/ or -e) {
    die qq'$prg: no such file or directory "$_", do you mean clipboard $_: ?\n';
  }
}

# look for special commands: overwrite, query, delete, public, fex, copy
if (@ARGV) {
  $_ = $ARGV[0];
  s/:+/:/g;
  s/^:/$cb:/;
  $overwrite = s/:o$/:/ and $cb = $_;
  if (/^(.+:\d:[qdf])$/) {
    $cb = $1;
    shift @ARGV;
  } elsif (/^(.+:[qdpf\d]?)$/i) {
    $cb = $1;
    $cb =~ s/:$//;
    shift @ARGV;
  } elsif (/^(.+:c:.+)$/) {
    $cb = $1;
    shift @ARGV;
  }
}

$_ = $cb;
s/:.*//;
if (/[^$cbcc]/) {
  die "$prg: illegal clipboard name \"$_\"\n";
}

if ($cb =~ /^_(:|$)/ and $server =~ /^fex/) {
  my $d = $domain;
  $cb =~ s/_/$d/;
  unless (1 or $cb) {
    die sprintf 
      qq'$prg: cannot use clipboard "_" on $server\n'.
      qq'    use "export LCB_CLIPBOARD=%s" to set default clipboard\n',
      randstring(8);
  }
}

if (-t STDIN and -t STDOUT and $cb !~ /:/ and not @ARGV) {
  $interactive = 1;
  print "\n";
  get("$cb:q");
  print "\n";
  local $| = 1;
  my $mode = 'Get';
  for (;;) {
    if ($mode eq 'Get') {
      print "Enter number or d (delete) or o (overwrite mode) or q (quit)\n";
    }
    if ($mode eq 'Delete') {
      print "Enter number or g (get) or q (quit)\n";
    }
    print "$mode [ ]\b\b";
    for (;;) {
      my $k = ReadKey();
      if ($k eq "\n") {
        print "\r";
        exit;
      }
      if ($k eq 'q') {
        print "$k]\n";
        exit;
      }
      if ($k eq 'o') {
        print "$k]\n";
        print "$mode [ ]\b\b";
        $overwrite = 1;
        redo;
      }
      if ($k eq 'g') {
        print "$k]\n";
        $mode = 'Get';
        last;
      }
      if ($k eq 'd') {
        print "$k]\n";
        $mode = 'Delete';
        last;
      }
      if ($k eq '-' and $mode eq 'Get' and -l "$yyd/$cb/1") {
        print "1]\n\n";
        $interactive = 0;
        get("$cb:1");
      }
      if ($k =~ /\d/ and -l "$yyd/$cb/$k") {
        print "$k]\n";
        if ($mode eq 'Delete') {
          del("$cb:$k");
          if ($k == 1 and not -l "$yyd/$cb/2") {
            system qw'rm -rf',"$yyd/$cb";
            exit;
          }
          print "\n";
          get("$cb:q");
          print "\n";
          if (-l "$yyd/$cb/1") {
            last;
          } else {
            exit;
          }
        }
        if ($mode eq 'Get') {
          get("$cb:$k");
          exit;
        }
      }
    }
  }
  exit;
}


if (-t STDIN) {
  if (@ARGV) {
    if ("@ARGV" eq '--') { 
      get($cb) 
    } else {
      put(@ARGV);
    }
  } else {
    if ($cb =~ s/:d$//) {
      del($cb);
    } else {
      get($cb);
    }
  }
} else {
  if (@ARGV and "@ARGV" !~ /:$/) { 
    die "$prg: no file arguments allowed when reading from pipe (@ARGV)\n";
  }
  put('-');
}
exit;


sub del {
  my $cb = shift;
  my $length = 0;
  my $type = '';
  my ($file,$yycb,$md5);
  local $_;
  
#  serverconnect($server,$port);
#  sendheader("HEAD /lcb/$cb HTTP/1.0");
#  $_ = <$SH>;
#  die "$prg: no response from fex server $server\n" unless $_;
#  s/\r//;
#
#  if (/^HTTP\/[\d.]+ 2/) {
#    warn "<-- $_" if $opt_v;
#    while (<$SH>) {
#      s/\r//g;
#      warn "<-- $_" if $opt_v;
#      last if /^\r?\n/;
#      if (/^Content-length:\s*(\d+)/i) {
#        $length = $1;
#      } elsif (/^X-File: ([^\/]+)\n/) {
#        $file = $1;
#      } elsif (/^X-MD5: (\w+)\n/) {
#        $md5 = $1;
#      } elsif (/^(X|Content)-Type: (.+)/) {
#        $type = $2;
#      }
#    }
#  } else {
#    s/HTTP\/[\d.]+ \d+ //;
#    warn "$prg: server reply: $_";
#    while (<$SH>) {
#      s/\r//g;
#      warn "<-- $_" if $opt_v;
#      last unless /\S/;
#    }
#    warn $_ while <$SH>;
#    exit 1;
#  }
#  
#  while (<$SH>) {
#    s/\r//g;
#    warn "<-- $_" if $opt_v;
#  }

#  die $cb;
  if ($cb =~ /^([$cbcc]+):(\d)$/) {
    $yycb = "$yyd/$1/$2";
  } elsif ($cb =~ /^([$cbcc]+)$/) {
    $yycb = "$yyd/$1/1";
  } else {
    die "$prg: unknown argument $cb\n";
  }
  unless ($md5 = readlink($yycb)) {
    my $q = $cb;
    $q =~ s/:\d$/:q/ or $q =~ s/$/:q/;
    die "$prg: no $yycb, run $prg $q\n"
  }
  
  serverconnect($server,$port);
  sendheader(
    "GET /lcb/$cb:d HTTP/1.0",
    "X-MD5: $md5",
  );
  
  $_ = <$SH>;
  die "$prg: no response from fex server $server\n" unless $_;
  s/\r//;
  warn "<-- $_" if $opt_v;

  if (/^HTTP\/[\d.]+ 2/) {
    while (<$SH>) {
      s/\r//g;
      warn "<-- $_" if $opt_v;
      warn "$prg: server error: $1\n" if /^X-Error: (.+)/;
    }
  } else {
    s/HTTP\/[\d.]+ \d+ //;
    s/Bad Request : //;
    warn "$prg: server reply: $_";
    while (<$SH>) {
      s/\r//g;
      warn "<-- $_" if $opt_v;
      last unless /\S/;
    }
    warn $_ while <$SH>;
    exit 1;
  }
}


sub get {
  my $req = shift;
  my $cb = $req =~ /([$cbcc]+):./ ? $1 : $req;
  my $length = 0;
  my $type = '';
  my $B = 0;
  my $keep = '-k';
  my $pwf = "$yyd/$cb/password";
  my @gpg = qw'gpg --yes --batch -q -d';
  my ($b,$out,$file,$yycb,$md5,$tar,$password);
  local $_;

  serverconnect($server,$port);
  sendheader("GET /lcb/$req HTTP/1.0");
  $_ = <$SH>;
  die "$prg: no response from fex server $server\n" unless $_;
  s/\r//;
  warn "<-- $_" if $opt_v;

  if (/^HTTP\/[\d.]+ 2/) {
    while (<$SH>) {
      s/\r//g;
      warn "<-- $_" if $opt_v;
      warn "$prg: server error: $1\n" if /^X-Error: (.+)/;
      last if /^\r?\n/;
      if (/^Content-length:\s*(\d+)/i) {
        $length = $1;
      } elsif (/^X-File: ([^\/]+)\n/) {
        $file = $1;
      } elsif (/^X-MD5: (\w+)\n/) {
        $md5 = $1;
      } elsif (/^X-Args: (.+)/) {
        $tar = $1;
      } elsif (/^(X|Content)-Type: (.+)/) {
        $type = $2;
      }
    }
  } else {
    s/HTTP\/[\d.]+ \d+ //;
    s/Bad Request : //;
    warn "$prg: server reply: $_";
    while (<$SH>) {
      s/\r//g;
      warn "<-- $_" if $opt_v;
      last unless /\S/;
    }
    warn $_ while <$SH>;
    exit 1;
  }

  if ($req eq '::') {
    print while <$SH>;
    exit;
  }
    
  if ($req !~ /:q$/ and "@ARGV" ne '--' and $md5 and not $urlarg) {
    my $n = 1;
    $n = $1 if $req =~ /:(\d)$/;
    if ("$req:" =~ /(.+?):/) {
      my $x = $1;
      my $m = readlink("$yyd/$x/$n") or
        die "$prg: $yyd/$x/$n does not exist, run $prg $x:q\n";
      if ($m ne $md5) {
        if ($interactive) {
          die "$prg: MD5 $yyd/$x/$n does not match, rerun $prg $x:\n"
        } else {
          die "$prg: MD5 $yyd/$x/$n does not match, run $prg $x:q\n"
        }
      }
    } else {
      die "$prg: unknown query $req\n";
    }
  }
  
  if ($req =~ /:q$/) {
    if ($req !~ /^:/ and $req !~ /:.*:/ and $req =~ /^(.+):/) {
      $yycb = "$yyd/$1";
      system "rm -f $yycb/[1-9]";
      mkdir $yycb;
      unless (-d $yycb) { die "$prg: $yycb - $!\n" }
    }
    # query
    my @Q = ();
    local $/ ="\n\n";
    while (<$SH>) {
      print if $opt_v;
      next unless /\w/;
      s/^\n+//;
      s/\n+$//;
#     s!Item (\S+):(\d)!$lcb_url/$2/$1!;
      s:^(http.*/lcb/(\d+)/.*):[$2] $1:;
      my $n = $2;
      if (/ MD5: (\w+)/) {
        symlink $1,"$yycb/$n";
      }
      push @Q,$_;
    }
    print "\n" if $opt_v;
    print join("\n\n",@Q),"\n";
    return;
  }
  
  if ($cb =~ /\.gpg$/) {
    if (-s $pwf) {
      push @gpg,'--passphrase-file',$pwf;
    } else {
      # gpg itself prompts with "Enter passphrase"
      # which will confuse most users - gpg keyring!
      $password = $term->readline('Decryption password: ');
      exit unless $password;
      push @gpg,'--passphrase',$password;
    }
  }
  
  if (-t STDOUT) {
    if ($file) {
      if (-e $file and not $overwrite) {
        die qq'$prg: "$file" does already exist\n';
      }
      $out = $file;
      if ($cb =~ /\.gpg$/) {
        push @gpg,'-o',$file;
        warn "| @gpg\n" if $opt_v;
        open $out,'|-',@gpg or die "$prg: cannot run gpg - $!\n";
      } else {
        open $out,'>',$file or die qq'$prg: cannot write "$file" - $1\n';
      }
      warn qq'$prg: writing "$file"\n';
    } elsif ($req ne '::' and $req !~ /:[a-z]$|.:c:./i ) {
      if ($type =~ /tar archive/ or $tar) {
        $GNUTAR ||= `tar --help 2>&1` =~ /\bGNU\b/;
        my @tar = qw'tar';
        if ($_=$ENV{LCB_EXCLUDE}) {
          foreach my $x (split) {
            if ($GNUTAR) {
              push @tar,"--exclude=$x"
            } else {
              push @tar,'--exclude',$x
            }
          }
        }
        push @tar,'-k' unless $overwrite;
        push @tar,qw'-xvf -';
        warn "| @tar\n" if $opt_v;
        if ($cb =~ /\.gpg$/) {
          push @gpg,qw'-o -';
          warn "| @gpg\n" if $opt_v;
          open $out,"| @gpg | @tar" or die "$prg: gpg/tar error\n";
        } else {
          open $out,'|-',@tar or die "$prg: tar extraction error\n";
        }
        warn "$prg: extracting...\n";
      } elsif ($interactive) {
        my $cmd = $term->readline('Shell command: ');
        print "\n";
        $cmd =~ s/^\s+//;
        $cmd =~ s/\s+$//;
        if ($cmd and $cmd ne '-') {
          $out = $cmd;
          $cmd = '|'.$cmd if $cmd !~ /^[>|]/;
          $cmd = "|@gpg$cmd" if $cb =~ /\.gpg$/;
          open $out,$cmd or exit 1;
        } else {
          if ($cb =~ /\.gpg$/) {
            $out = '-';
            warn "| @gpg\n" if $opt_v;
            open $out,'|-',@gpg or exit 1;
          }
        }
      } else {
        $out = '-';
        if ($cb =~ /\.gpg$/) {
          warn "| @gpg\n" if $opt_v;
          open $out,'|-',@gpg or die "$prg: cannot run gpg - $!\n";
        } else {
          open $out,'|cat' or exit 1;
        }
      }
    }
  } else {
    if ($cb =~ /\.gpg$/) {
      $out = '-';
      push @gpg,'-o',$out;
      warn "| @gpg\n" if $opt_v;
      open $out,'|-',@gpg or die "$prg: cannot run gpg - $!\n";
    }
  }

  if (0 and $type =~ /ASCII text/) {
    while (<$SH>) {
      s/\r\n/\n/;
      print;
    }
  } else {
    my $t0 = my $t1 = my $t2 = time;
    while (($B < $length or not $length) and $b = read $SH,$_,$bs) {
      $B += $b;
      if ($out) {
        print {$out} $_ or exit;
      } else {
        print;
      }
      $t2 = time;
      if ($t2 > $t1) {
        printf STDERR "%d MB\r",int($B/MB);
        $t1 = $t0;
      }
    }
  }

  if ($out) { close $out or exit 1 }
  
  if ($cb =~ /\.gpg$/ and $password and $interactive and not -s $pwf) {
    print "\nStore password for clipboard $cb? ";
    $_ = ReadKey();
    if (/y/i) {
      print "yes\n";
      mkdir dirname($pwf),0700;
      open $pwf,'>',$pwf or die "$prg: cannot write $pwf - $!\n";
      print {$pwf} $password,"\n";
      close $pwf;
    } else {
      print "no\n";
    }
  }
  
  exit;
}


sub put {
  my @args = @_;
  my $B = 0;
  my ($file,$in,$dirarg,$b,$url,$H1);
  my @request = ("PUT /lcb/$cb HTTP/1.0");
  my $waiting = "waiting for server ok...\r";
  my $pwf = "$yyd/$cb/password";
  my @gpg = (qw'gpg --yes --batch -q -c -o -');
  local $_;

  if (@args and $args[0] ne '-') {
    foreach (@args) {
      die qq'$prg: "$_" does not exist\n' unless -e;
      die qq'$prg: cannot read "$_"\n'    unless -r;
      if (-d and not -l) {
        s:/*$:/:;
        $dirarg = 1;
      }
    }
  }
  
  if (@args and "@args" ne '-') {
    if ($args[0] eq '-') {
      if (scalar(@args)>2) { die "$prg: only one file argument is possible\n" }
      $file = $args[1];
      push @request,"X-File: ".basename($file);
    } else {
      push @request,"X-Args: @args";
    }
  }
  
  if ($cb =~ /\.gpg$/) {
    if (-s $pwf) {
      push @gpg,'--passphrase-file',$pwf;
    } else {
      my $password = $term->readline('Encryption password: ');
      exit unless $password;
      print "\nStore this password for clipboard $cb? ";
      $_ = ReadKey();
      if (/y/i) {
        print "yes\n";
        mkdir dirname($pwf),0700;
        open $pwf,'>',$pwf or die "$prg: cannot write $pwf - $!\n";
        print {$pwf} $password,"\n";
        close $pwf;
        push @gpg,'--passphrase-file',$pwf;
      } else {
        print "no\n";
        push @gpg,'--passphrase',$password;
      }
    }
  }
  
  serverconnect($server,$port);
  sendheader(@request);
  $_ = <$SH>;
  die "$prg: no response from fex server $server\n" unless $_;
  s/\r//;
  warn "<-- $_" if $opt_v;

  unless (/^HTTP\/[\d.]+ 2/) {
    s/HTTP\/[\d.]+ \d+ //;
    warn "$prg: server reply: $_";
    while (<$SH>) {
      s/\r//g;
      warn "<-- $_" if $opt_v;
      warn "$prg: server error: $1\n" if /^X-Error: (.+)/;
      last unless /\S/;
    }
    warn $_ while <$SH>;
    exit 1;
  }
  
  while (<$SH>) {
    s/\r//;
    warn "<-- $_" if $opt_v;
    warn "$prg: server error: $1\n" if /^X-Error: (.+)/;
    $H1 = $1 if /<h1>(.+)</;
    $url = $1 if /^X-URL: (http\S+)/;
    last unless /\S/;
  }
  
  if ("@args" eq '-') {
    if ($cb =~ /\.gpg$/) {
      warn "| @gpg |\n" if $opt_v;
      open $in,'-|',@gpg or die "$prg: cannot run gpg - $!\n";
    } else {
      open $in,'>&=STDIN' or die "$prg: cannot open STDIN - $!\n";
    }
  } elsif ($file) {
    open $file,$file or die "$prg: cannot read $file - $!\n";
    close $file;
    if ($cb =~ /\.gpg$/) {
      warn "| @gpg $file |\n" if $opt_v;
      open $in,'-|',@gpg,$file or die "$prg: cannot run gpg - $!\n";
    } else {
      open $in,$file or die "$prg: cannot open $file - $!\n";
    }
  } else {
    $GNUTAR ||= `tar --help 2>&1` =~ /\bGNU\b/;
    my @tar = qw'tar';
    if ($dirarg and $GNUTAR) {
      push @tar,qw'--exclude=.snapshot* --exclude=.del';
    }
    if ($_=$ENV{LCB_EXCLUDE}) {
      foreach my $x (split) {
        if ($GNUTAR) {
          push @tar,"--exclude=$x"
        } else {
          push @tar,'--exclude',$x
        }
      }
    }
    push @tar,qw'-cvf -';
    if (scalar(@args) == 1 and $args[0] =~ s:(.+)/(.):$2:) {
      my $dir = $1;
      chdir $dir or die "$prg: $dir - $!\n";
      warn "\$ cd $dir\n" if $opt_v;
    }
    warn "\$ @tar @args\n" if $opt_v;
    if ($cb =~ /\.gpg$/) {
      warn "| @gpg |\n" if $opt_v;
      open $in,"@tar @args | @gpg |" or die "$prg: tar/gpg error\n";
    } else {
      open $in,'-|',@tar,@args or die "$prg: tar error\n";
    }
  }
#  my $tmp = '/tmp/lcb.tmp'; open $tmp,'>',$tmp or die $!;
  warn "--> (DATA)\n" if $opt_v;
  my $t0 = my $t1 = 0;
  while ($b=read $in,$_,$bs) {
    $B += $b;
#    print {$tmp} $_;
    print {$SH} $_ or die "$prg: server has closed the connection";
    $t0 = time;
    if ($t0 > $t1) {
#      printf STDERR "%d MB\r",int($B/MB);
      printf STDERR "%s B\r",d3($B);
      $t1 = $t0;
    }
  }
  $SH->flush;
  shutdown($SH,1) or die "$prg: $!";
#  close $tmp;
  printf STDERR "%s B\n",d3($B);
#  printf STDERR "%d MB\n",int($B/MB);
#  print STDERR "$B bytes\n" if $opt_v;
  print STDERR $waiting;
  $waiting =~ s/[ -~]/ /g;
  local $SIG{PIPE} = sub { 
    $waiting = '';
    warn "no reply from server      \n" if $opt_v;
  };
  while (<$SH>) {
    print STDERR $waiting if $waiting;
    $waiting = '';
    print STDERR "<-- $_" if $opt_v;
  }
  if ($waiting) {
    print STDERR $waiting;
    warn "no reply from server      \n" if $opt_v;
  }
  close $SH;
  if ($B and $url) { 
    if ($url =~ m{http://fex.*uni-stuttgart\.de}) {
      $url =~ s/:\d+//;
      $url =~ s/http/https/;
    }
    warn "$url\n";
  } else {
    warn "$prg: server error\n";
    warn "  $H1\n" if $H1;
    die "$prg: use option -v for debugging output\n";
  }
  exit;
}


sub serverconnect {
  my ($server,$port) = @_;
  my $connect = "CONNECT $server:$port HTTP/1.1";
  local $_;

  if ($SH) {
    close $SH;
    undef $SH;
  }

  if ($opt_6) {
    if ($port == 443) {
      # eval "use IO::Socket::SSL qw(debug3)";
      &enable_ssl;
      $SH = IO::Socket::SSL->new(
        PeerAddr => $server,
        PeerPort => $port,
        Proto    => 'tcp',
        Domain   => AF_INET6,
        %SSL
      );
    } else {
      $SH = IO::Socket::IP->new(
        PeerAddr => $server,
        PeerPort => $port,
        Proto    => 'tcp',
        Family   => AF_INET,
        PeerAddr => $server,
        PeerPort => $port,
        Proto    => 'tcp',
        Family   => AF_INET6,
      );
    }
  } else {
    if ($port == 443) {
      # eval "use IO::Socket::SSL qw(debug3)";
      &enable_ssl;
      # prefer IPv4
      $SH = IO::Socket::SSL->new(
        PeerAddr => $server,
        PeerPort => $port,
        Proto    => 'tcp',
        Domain   => AF_INET,
        %SSL
      ) or IO::Socket::SSL->new(
        PeerAddr => $server,
        PeerPort => $port,
        Proto    => 'tcp',
        Domain   => AF_INET6,
        %SSL
      );
    } else {
      # prefer IPv4
      $SH = IO::Socket::IP->new(
        PeerAddr => $server,
        PeerPort => $port,
        Proto    => 'tcp',
        Family   => AF_INET,
      ) or IO::Socket::IP->new(
        PeerAddr => $server,
        PeerPort => $port,
        Proto    => 'tcp',
        Family   => AF_INET6,
      );
    }
  }

  warn "$prg: $@\n" if $@;

  if ($SH) {
    $SH->autoflush;
    binmode $SH;
  } else {
    die "$prg: cannot connect $server:$port - $@\n";
  }

  my $ipv = ($SH->sockdomain == PF_INET)  ? 'IPv4' :
            ($SH->sockdomain == PF_INET6) ? 'IPv6' :
                                            'unknown';

  warn "TCPCONNECT to $server:$port ($ipv)\n" if $opt_v;
}


sub sendheader {
  my @head = (shift);
  my $head;

  push @head,"Host: $server:$port";
  push @head,"User-Agent: $useragent";
  push @head,"X-User: $user";
  push @head,@_;
  push @head,"";

  foreach $head (@head) {
    chomp $head;
    warn "--> $head\n" if $opt_v;
    print {$SH} $head,"\r\n";
  }
}


sub nvtsend {
  local $SIG{PIPE} = sub { $sigpipe = "@_" };

  $sigpipe = '';

  die "$prg: internal error: no active network handle\n" unless $SH;
  die "$prg: remote host has closed the link\n" unless $SH->connected;

  foreach my $line (@_) {
    warn "--> $line\n" if $opt_v;
    print {$SH} $line,"\r\n";
    if ($sigpipe) {
      undef $SH;
      return 0;
    }
  }

  return 1;
}


sub enable_ssl {
  eval "use IO::Socket::SSL";
  die "$prg: cannot load IO::Socket::SSL\n" if $@;
  # needed for CentOS (Redhat, too?)
  foreach (qw'/etc/ssl/cert.pem /etc/ssl/certs/ca-bundle.crt') {
    $SSL{SSL_ca_file} = $_ if -f;
  }
  &get_ssl_env;
  eval '$SSL{SSL_verify_mode} = 0 if Net::SSLeay::SSLeay() <= 9470143';
  if ($opt_v) {
    foreach my $v (keys %SSL) {
      printf STDERR "%s => %s\n",$v,$SSL{$v};
    }
  }
}


sub get_ssl_env {
  # set SSL/TLS options
  if (defined($ENV{SSLVERIFY})) {
    $SSL{SSL_verify_mode} = $ENV{SSLVERIFY};
  }
  foreach my $opt (qw(
    SSL_version
    SSL_cipher_list
    SSL_verify_mode
    SSL_ca_path
    SSL_ca_file)
  ) {
    my $env = uc($opt);
    $env =~ s/_//g;
    $SSL{$opt} = $ENV{$env} if defined($ENV{$env});
  }

  if ($SSL{SSL_verify_mode} and $SSL{SSL_verify_mode} ne 'SSL_VERIFY_NONE') {
    &search_ca;
    unless ($SSL{SSL_ca_path} or $SSL{SSL_ca_file}) {
      die "$prg: \$SSLVERIFYMODE, but not valid \$SSLCAPATH or \$SSLCAFILE\n";
    }
  } elsif (defined($SSL{SSL_verify_mode})) {
    # user has set SSLVERIFY=0 !
  } else {
    &search_ca;
    $SSL{SSL_verify_mode} = 1 if $SSL{SSL_ca_path} or $SSL{SSL_ca_file};
  }
}


sub search_ca {
  local $_;

  return if $SSL{SSL_ca_file} or $SSL{SSL_ca_path};

  foreach (qw(/etc/ssl/certs/ca-certificates.crt)) {
    if (-f) {
      $SSL{SSL_ca_file} = $_;
      return;
    }
  }

  foreach (qw(/etc/ssl/certs /etc/pki/tls/certs)) {
    if (-d) {
      $SSL{SSL_ca_path} = $_;
      return;
    }
  }
}


# no more in use
sub default_clipboard {
  $_ = lstat("$yyd/_");
  if (-t STDIN and not (-l or -d or $ENV{LCB_CLIPBOARD})) {
    for (;;) {
      $_ = $term->readline('Clipboard: ');
      s/^\s+//;
      s/\s+$//;
      s/[^$cbcc]/_/g;
      $cb = $_ || '_';
      if ($server =~ /^fex\b/ and $cb eq '_') {
        print "Cannot use clipboard _ on $server\n";
      } else {
        last;
      }
    }
    my $cbd = "$yyd/$cb";
    unless (-d $cbd) { mkdir $cbd or die "$prg: cannot mkdir $cbd - $!\n" }
    if ($cb ne '_') {
      symlink $cb,"$yyd/_" or die "$prg: cannot mksymlink $yyd/_ - $!\n";
      print "default clipboard: $yyd/_ -> $cb\n";
    }
  }
  $cb = readlink("$yyd/_")||'_' if $cb eq '_'; 
}


sub shellquote {
  local $_ = shift;
  s/([^\w\@\/!^%:_.,=+-])/\\$1/g;
  return $_;
}


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


sub searchpath {
  my ($prg,$path,@PATH);

  @PATH = split(':',$ENV{PATH});
  foreach $prg (@_) {
    foreach $path (@PATH) {
      return $prg if -x "$path/$prg" and -f "$path/$prg";
    }
  }
  return '';
}


sub ReadKey {
  my $key;
  local $SIG{INT} = sub { stty('reset'); exit };

  stty('raw');
  # loop necessary for ESXi support
  $key = getc(STDIN) while not defined $key;
  stty('reset');
  return $key;
}


sub stty {
  if (shift eq 'raw') {
    system qw'stty -echo -icanon eol',"\001";
  } else {
    system qw'stty echo icanon eol',"\000";
  }
}


sub randstring {
    my $n = shift;
    my @rc = ('a'..'z');
    my $rn = @rc;
    my $rs;

    for (1..$n) { $rs .= $rc[int(rand($rn))] };
    return $rs;
}


sub d3 {
  local $_ = shift;
  while (s/(\d)(\d\d\d\b)/$1,$2/) {};
  return $_;
}


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

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

  return $_;
}


# tar(bsdtar): manipulate archive files
# First option must be a mode specifier:
#   -c Create  -r Add/Replace  -t List  -u Update  -x Extract
# Common Options:
#   -b #  Use # 512-byte records per I/O block
#   -f <filename>  Location of archive
#   -v    Verbose
#   -w    Interactive
# Create: tar -c [options] [<file> | <dir> | @<archive> | -C <dir> ]
#   <file>, <dir>  add these items to archive
#   -z, -j, -J, --lzma  Compress archive with gzip/bzip2/xz/lzma
#   --format {ustar|pax|cpio|shar}  Select archive format
#   --exclude <pattern>  Skip files that match pattern
#   -C <dir>  Change to <dir> before processing remaining files
#   @<archive>  Add entries from <archive> to output
# List: tar -t [options] [<patterns>]
#   <patterns>  If specified, list only entries that match
# Extract: tar -x [options] [<patterns>]
#   <patterns>  If specified, extract only entries that match
#   -k    Keep (don't overwrite) existing files
#   -m    Don't restore modification times
#   -O    Write entries to stdout, don't restore to disk
#   -p    Restore permissions (including ACLs, owner, file flags)
# bsdtar 3.5.3 - libarchive 3.5.3 zlib/1.2.11 liblzma/5.0.5 bz2lib/1.0.8 
