3 # CLI client for the FEX service for retrieving files
7 # Author: Ulli Horlacher <framstag@rus.uni-stuttgart.de>
9 # Perl Artistic Licence
12 use strict qw'vars subs';
21 use Time::HiRes 'time';
22 use constant k => 2**10;
23 use constant M => 2**20;
25 eval 'use Net::INET6Glue::INET_is_INET6';
30 our ($fexhome,$idf,$tmpdir,$windoof,$useragent);
32 our $bs = 2**16; # blocksize for tcp-reading and writing file
33 our $version = 20160328;
34 our $CTYPE = 'ISO-8859-1';
35 our $fexsend = $ENV{FEXSEND} || 'fexsend';
36 our $DEBUG = $ENV{DEBUG};
39 my %SSL = (SSL_version => 'TLSv1');
42 # inquire default character set
43 # cannot use "use I18N::Langinfo" because of no windows support!
46 require I18N::Langinfo;
47 I18N::Langinfo->import(qw'langinfo CODESET');
48 $CTYPE = langinfo(CODESET());
51 if ($Config{osname} =~ /^mswin/i) {
52 $windoof = $Config{osname};
53 $ENV{HOME} = $ENV{USERPROFILE};
54 $fexhome = $ENV{FEXHOME} || $ENV{HOME}.'/fex';
55 $tmpdir = $ENV{FEXTMP} || $ENV{TMP} || "$fexhome/tmp";
57 $useragent = sprintf("fexget-$version (%s %s)",
58 $Config{osname},$Config{archname});
59 $SSL{SSL_verify_mode} = 0;
60 chdir $ENV{USERPROFILE}.'\Desktop';
61 # open XX,'>XXXXXX';close XX;
62 } elsif ($Config{osname} =~ /^darwin/i or $ENV{MACOS}) {
63 $0 =~ s:(.*)/:: and $ENV{PATH} .= ":$1";
64 $fexhome = $ENV{FEXHOME} || $ENV{HOME}.'/.fex';
65 $tmpdir = $ENV{FEXTMP} || $ENV{TMPDIR} || "$fexhome/tmp";
67 $_ = `sw_vers -productVersion 2>/dev/null`||'';
69 $useragent = "fexget-$version (MacOS $_)";
71 $0 =~ s:(.*)/:: and $ENV{PATH} .= ":$1";
72 $fexhome = $ENV{FEXHOME} || $ENV{HOME}.'/.fex';
73 $tmpdir = $ENV{FEXTMP} || "$fexhome/tmp";
75 $_ = `(lsb_release -d||uname -a)2>/dev/null`||'';
78 $useragent = "fexget-$version ($_)";
81 if (-f ($_ = '/etc/fex/config.pl')) {
82 eval { require } or warn $@;
86 usage: $0 [-v] [-m limit] [-s filename] [-o] [-k] [-X] [-P proxy:port] F*EX-URL(s)
87 or: $0 [-v] -d F*EX-URL(s)
88 or: $0 [-v] -f F*EX-URL(s) e-mail-address
92 options: -v verbose mode
94 -s save to filename (-s- means: write to STDOUT/pipe)
95 -o overwrite existing file
96 -k keep on server after download
97 -X do not extract archive files or autoview file
98 -d delete without download
99 -f forward a file to another recipient
100 -a get all files (implies -X)
101 -l list files on server
102 -i tag alternate server/account, see: $fexsend -h
103 -P use Proxy for connection to the F*EX server
104 -H show hints and examples
105 argument: F*EX-URL may be file number (see: $0 -l)
109 When you download a file with extension .jpg .gif .png or .tif an image viewer
110 will be started. This can be xv or xdg-open.
111 In $HOME/.fex/config.pl you can set your prefered autoview applications:
114 '\.(gif|jpg|png|tiff?)' => 'my_prefered_image_viewer',
115 '\.(avi|mp4|mov)' => 'vlc -f',
119 For HTTPS you can set the environment variables:
120 SSLVERIFY=1 # activate server identity verification
121 SSLVERSION=TLSv1 # this is the default
122 SSLCAPATH=/etc/ssl/certs # path to trusted (root) certificates
123 SSLCAFILE=/etc/ssl/cert.pem # file with trusted (root) certificates
124 SSLCIPHERLIST=HIGH:!3DES # see http://www.openssl.org/docs/apps/ciphers.html
126 You can set these environment variables also in $HOME/.fex/config.pl, as well as
127 the $opt_* variables, e.g.:
129 $ENV{SSLVERSION} = 'TLSv1';
134 if ($windoof and not @ARGV and not $ENV{PROMPT}) {
135 # restart with cmd.exe to have mouse cut+paste
136 my $cmd = "cmd /k \"$0\"";
142 my $atype = '\.(tgz|tar|zip|7z)$';
144 my $proxy_prefix = '';
147 our ($opt_h,$opt_v,$opt_l,$opt_d,$opt_m,$opt_z,$opt_K,$opt_o,$opt_a);
148 our ($opt_s,$opt_k,$opt_i,$opt_V,$opt_X,$opt_f,$opt_P,$opt_L,$opt_H);
149 $opt_m = $opt_h = $opt_v = $opt_l = $opt_d = $opt_K = $opt_o = $opt_a = 0;
150 $opt_V = $opt_X = $opt_f = $opt_L = $opt_H = 0;
152 $opt_s = $opt_k = $opt_i = $opt_P = '';
153 $_ = "$fexhome/config.pl"; require if -f;
154 getopts('hvVHlLdkzoaXVf+m:s:i:K:P:') or die $usage;
155 $opt_k = '?KEEP' if $opt_k;
157 if ($opt_m =~ /(\d+)/) {
164 print "Version: $version\n";
166 print "Upgrade fexget? ";
169 my $new = `wget -nv -O- http://fex.belwue.de/download/fexget`;
170 if ($new !~ /upgrade fexget/) {
171 die "$0: bad update\n";
173 system qw'cp -a',$_0,$_0.'_old';
175 open $_0,'>',$_0 or die "$0: cannot write $_0. - $!\n";
181 exit if "@ARGV" eq '.';
184 die $usage if $opt_h;
192 my $ffl = "$tmpdir/fexget"; # F*EX files list (cache)
201 "
\e[A \\\\/\\\\/ \n",
202 "
\e[A //\\\\//\\\\\n"
207 my $cmd = "$fexsend -Z";
208 $cmd .= " -i $opt_i" if $opt_i;
209 warn "$cmd\n" if $opt_v;
211 die "$0: cannot run $cmd : $!\n";
220 my $cmd = "$fexsend -L";
221 $cmd .= " -i $opt_i" if $opt_i;
222 warn "$cmd\n" if $opt_v;
224 die "$0: cannot run $cmd : $!\n";
228 if ($opt_P =~ /^([\w.-]+:\d+)(:(\d+))?/) {
230 $chunksize = $3 || 0;
232 die "$0: proxy must be: SERVER:PORT\n";
241 if (open $ffl,$ffl) {
243 push @ARGV,$1 if /^\s+(\d+)/;
252 print "download-URL: ";
253 chomp($url = <STDIN>);
254 if ($url =~ /^http/) {
265 my ($file,%files,$download,$server,$port,$fop,$https);
268 unless ($ENV{FEXID} or -f $ENV{HOME}.'/.fex/id') {
269 die "$0: no local FEXID\n";
272 if ($opt_f =~ /^\d+$|^https?:/) {
273 die "$0: $opt_f is not an e-mail address\n";
277 URL: foreach my $url (@ARGV) {
279 # do not overrun server
282 if ($url !~ /^http/) {
284 open $ffl,$ffl or die "$0: no $ffl, use first: $0 -l\n";
287 if (/^from (.+) :$/) {
289 } elsif (/^\s*(\d+)\)\s+\d+ MB.* (http\S+)/) {
290 push @{$files{all}},$2;
291 push @{$files{$from}},$2;
297 if ($url =~ /^(\d+)$/) {
298 $url = ${files{all}}[$1-1] or die "$0: unknown file number\n";
302 if ($url =~ m{^http(s?)://([\w\.\-]+)(:(\d+))?(/.*fop/\S+)}) {
305 $port = $4 || ($1?443:80);
308 die "$0: unknown F*EX URL $url\n";
312 if ($port == 80) { $proxy_prefix = "http://$server" }
313 elsif ($port == 443) { $proxy_prefix = "" }
314 else { $proxy_prefix = "http://$server:$port" }
317 serverconnect($server,$port);
328 ($file) = grep { $_ = $1 if /^X-File:\s+(.+)/ } @r;
329 $file = $url unless $file;
331 printf "%s deleted\n",urldecode($file);
334 die "$0: server response: $_";
345 print "$file kept\n";
348 die "$0: server response: $_";
353 $download = download($server,$port,$fop);
354 exit if $opt_s eq '-';
355 unlink $download unless -s $download;
356 exit 2 unless -f $download;
363 if (not $opt_X and $download =~ /\.gpg$/) {
365 print "decrypt \"$download\"? ";
368 print "keeping \"$download\"\n";
372 if (system('gpg',$download) == 0) {
374 $download =~ s/\.gpg$//;
380 foreach my $a (keys %autoview) {
381 if ($download =~ /$a$/i and $autoview{$a}) {
382 printf "run \"%s %s\" [Yn] ? ",$autoview{$a},basename($download);
384 system sprintf("%s %s",$autoview{$a},quote($download)) if /^y|^$/i;
389 if ($ENV{DISPLAY} and $download =~ /\.(gif|jpg|png|tiff?)$/i) {
390 # see also mimeopen and xdg-mime
391 # http://unix.stackexchange.com/questions/144047/how-does-xdg-open-do-its-work
392 if (my $xv = $xv || pathsearch('xv') || pathsearch('xdg-open')) {
393 printf "run \"%s %s\" [Yn] ? ",basename($xv),basename($download);
395 system $xv,$download if /^y|^$/i;
400 if ($download =~ /$atype/) {
401 if ($download =~ /\.(tgz|tar.gz)$/) { extract('tar tvzf','tar xvzf') }
402 elsif ($download =~ /\.tar$/) { extract('tar tvf','tar xvf') }
403 elsif ($download =~ /\.zip$/i) { extract('unzip -l','unzip') }
404 elsif ($download =~ /\.7z$/i) { extract('7z l','7z x') }
405 else { die "$0: unknown archive \"$download\"\n" }
409 die "$0: keeping \"$download\"\n";
425 if (-t and not $windoof) {
426 print "Files in archive:\n";
427 system(split(' ',$l),$download);
432 $xd = inquire("extract to directory (Ctrl-C to keep archive): ",$d);
433 last if $xd =~ s:^(\./*)*!?$::;
435 print "keeping $download\n";
440 print "directory $xd does already exist, add \"!\" to overwrite\n";
444 print "cannot mkdir $xd - $!\n";
449 print "cannot chdir $xd - $!\n";
455 print "extracting to $xd :\n" if $xd;
456 system(split(' ',$x),$download);
457 print "extracted to $xd\n" if $xd;
466 if ($url =~ m{^http(s?)://([\w\.\-]+)(:(\d+))?(/fop/.+)}) {
468 $port = $4 || ($1?443:80);
471 die "$0: unknown F*EX URL $url\n";
474 sendheader("$server:$port","GET $del HTTP/1.1","User-Agent: $useragent");
477 last if /^\n/; # ignore HTML output
478 warn "<-- $_" if $opt_v;
481 die "$0: no response from fex server $server\n" unless @r;
489 my ($uri,$dkey,$list,$cmd,$n,$copy);
492 if ($url =~ m{^http(s?)://([\w\.\-]+)(:(\d+))?(/fop/.+)}) {
494 $port = $4 || ($1?443:80);
497 die "$0: unknown F*EX URL $url\n";
502 "GET $uri?COPY HTTP/1.1",
503 "User-Agent: $useragent",
507 die "$0: no reply from fex server $server\n" unless $_;
508 warn "<-- $_" if $opt_v;
510 if (/^HTTP.*already exists/) {
511 if ($uri =~ m:/fop/(\w+)/:) {
514 } elsif (/^HTTP.*200/) {
523 last if /^\n/; # ignore HTML output
524 $dkey = $1 if /^Location:.*\/(\w+)\/.+/;
525 warn "<-- $_" if $opt_v;
528 print "fexsend -l\n" if $opt_v;
529 system 'fexsend -l >/dev/null 2>&1';
530 $list = $ENV{HOME}.'/.fex/tmp/fexlist';
531 open $list,$list or die "$0: cannot open $list - $!\n";
533 if (/^\s+(\d+)\) (\w+)/ and $2 eq $dkey) {
535 $cmd = "fexsend -b $n $opt_f";
536 print "$cmd\n" if $opt_v;
544 $cmd = "fexsend -d $n >/dev/null 2>&1";
545 print "$cmd\n" if $opt_v;
548 warn "$0: forwarding failed\n";
559 if ($url =~ m{^http(s?)://([\w\.\-]+)(:(\d+))?(/fop/.+)}) {
561 $port = $4 || ($1?443:80);
562 $keep = "$5?KEEP=$opt_K";
564 die "$0: unknown F*EX URL $url\n";
567 push @hh,"GET $keep HTTP/1.1",
568 "Host: $server:$port",
569 "User-Agent: $useragent",
573 warn $_,"\n" if $opt_v;
581 die "$0: no response from fex server $server\n" unless @r;
582 grep { warn "\t$_" } @r if $opt_v;
588 my ($server,$port,$fop,$nocheck) = @_;
589 my ($file,$download,$ssl,$pipe,$filesize,$checkstorage,$dkey);
591 my ($t0,$t1,$t2,$tt,$tm,$ts,$kBs,$b,$bt,$tb,$B,$buf);
601 $pipe = $download = $opt_s;
602 } elsif (-p $opt_s or -c $opt_s) {
604 $nocheck = 'pipe or character device';
606 $download = $file.'.tmp';
607 $seek = -s $download || 0;
610 # ask server for real file name
613 "HEAD $proxy_prefix$fop HTTP/1.1",
614 "User-Agent: $useragent"
616 my $reply = $_ = <$SH>;
617 unless (defined $_ and /\w/) {
618 die "$0: no response from server\n";
620 warn "<-- $_" if $opt_v;
621 unless (/^HTTP\/[\d.]+ 200/) {
623 die "$0: server response: $_";
627 warn "<-- $_" if $opt_v;
629 if (/^Content-Disposition: attachment; filename="(.+)"/i) {
630 $file = locale(decode_utf8($1));
638 $download = $file.'.tmp';
639 $seek = -s $download || 0;
642 $fop =~ m:/fop/(\w+)/: and $dkey=$1 or $dkey='';
644 push @hh,"GET $proxy_prefix$fop$opt_k HTTP/1.1",
645 "User-Agent: $useragent",
646 "Cookie: dkey=$dkey",
648 push @hh,"Range: bytes=$seek-" if $seek;
650 # HTTPS needs a new connection for actually downloading the file
651 serverconnect($server,$port) if $opt_P and $port == 443;
652 sendheader("$server:$port",@hh);
654 die "$0: no response from fex server $server\n" unless $_;
657 if (/^HTTP\/[\d.]+ 2/) {
658 warn "<-- $_" if $opt_v;
661 warn "<-- $_" if $opt_v;
663 if (/^Content-length:\s*(\d+)/i) {
665 } elsif (/^X-Size: (\d+)/i) {
670 s/HTTP\/[\d.]+ \d+ //;
671 die "$0: bad server reply: $_";
677 if ($opt_s and $opt_s eq $download) {
678 open X,'>',$download or die "$0: cannot write to \"$download\" - $!\n";
679 $checkstorage = $filesize unless $nocheck;
681 if (-e $file and not $opt_o) {
682 die "$0: destination file \"$file\" does already exist\n";
685 open X,'>>',$download or die "$0: cannot write to \"$download\" - $!\n";
687 open X,'>',$download or die "$0: cannot write to \"$download\" - $!\n";
688 $checkstorage = $filesize unless $nocheck;
691 if ($checkstorage and not $nocheck) {
692 my $t0 = my $t1 = my $t2 = time;
695 my $storagetest = $file.'.test';
696 my $error = "$0: cannot write \"$storagetest\"";
697 open $storagetest,'>',$storagetest or die "$error - $!\n";
698 print STDERR "checking storage...\r";
699 while (-s $storagetest < $checkstorage) {
700 syswrite $storagetest,$buf or do {
702 die "\n$error - $!\n";
707 print STDERR "checking storage... ".$n." MB\r";
711 close $storagetest or do {
713 die "\n$error - $!\n";
715 print STDERR "checking storage... ".$n." MB ok!\n";
718 # retry after timeout
719 serverconnect($server,$port);
720 return(download($server,$port,$fop,'nocheck'))
725 $t0 = $t1 = $t2 = int(time);
727 printf STDERR "resuming at byte %s\n",$seek if $seek;
728 print $rcamel[0] if ${'opt_+'};
729 while ($B < $length and $b = read $SH,$buf,$bs) {
735 if (${'opt_+'} and int($t2*10)>$tc) {
736 print $rcamel[$tc%2+1];
739 if (int($t2) > $t1) {
740 $kBs = int($bt/k/($t2-$t1));
741 $kBs = int($tb/k/($t2-$t0)) if $kBs < 10;
744 # smaller block size is better on slow links
745 $bs = 4096 if $bs>4096 and $tb/($t2-$t0)<65536;
747 printf STDERR "%s: %d kB (%d%%) %d kB/s \r",
750 int(($tb+$seek)/($length+$seek)*100),
753 printf STDERR "%s: %d MB (%d%%) %d kB/s \r",
756 int(($tb+$seek)/($length+$seek)*100),
761 if ($t2 == $t0 and $B > $opt_m*k) {
762 print "\nsleeping...\r" if $opt_v;
765 while ($t2 > $t0 and $tb/k/($t2-$t0) > $opt_m) {
766 print "\nsleeping...\r" if $opt_v;
776 print $rcamel[2] if ${'opt_+'};
781 $kBs = int($tb/k/($tt||1));
783 printf STDERR "$file: %d MB, last %d MB in %d s (%d kB/s) \n",
784 int(($tb+$seek)/M),int($tb/M),$tt,$kBs;
786 printf STDERR "$file: %d MB in %d s (%d kB/s) \n",
790 if ($tb != $length) {
795 die "$0: $server annouced $length bytes, but only $tb bytes has been read\n";
799 unless ($pipe or -p $download or -c $download) {
800 my @s = stat $file if -e $file;
801 rename $download,$file
802 or die "$0: cannot rename \"$download\" to \"$file\" - $!\n";
803 chmod $s[2],$file if @s;
806 return sprintf("%s/%s",getcwd(),$file);
811 my $cmd = "$fexsend -L";
812 $cmd .= " -i $opt_i" if $opt_i;
817 open $cmd,"$cmd|" or die "$0: cannot run $cmd : $!\n";
818 open $ffl,'>',$ffl or die "$0: cannot open $ffl : $!\n";
821 if (/\d MB .*http/) {
823 printf {$ffl} "%4d) %s",$n,$_;
825 printf "%4d) %s",$n,$_;
838 if ($CTYPE =~ /UTF-?8/i) {
840 } elsif (grep { $CTYPE =~ /^$_$/i } Encode->encodings()) {
841 return encode($CTYPE,$string);
843 return encode('ISO-8859-1',$string);
854 foreach my $dir (split(':',$ENV{PATH})) {
855 return "$dir/$prg" if -x "$dir/$prg";
869 if (defined $default) {
871 chomp($tty = `tty 2>/dev/null`);
872 eval { local $^W; require "sys/ioctl.ph"; };
875 if (defined(&TIOCSTI) and $tty and open($tty,'>',$tty)) {
877 # push default answer into keyboard buffer
878 foreach my $a (split("",$default)) { ioctl($tty,&TIOCSTI,$a) }
879 chomp($_ = <STDIN>||'');
881 $prompt =~ s/([\?:=]\s*)/ [$default]$1/ or $prompt .= " [$default] ";
883 chomp($_ = <STDIN>||'');
884 $_ = $default unless length;
888 chomp($_ = <STDIN>||'');
896 ### common functions ###
900 my @d = localtime((stat shift)[9]);
901 return sprintf('%d%02d%02d',$d[5]+1900,$d[4]+1,$d[3]);
907 s/\%([a-f\d]{2})/chr(hex($1))/ige;
913 # set SSL/TLS options
914 $SSL{SSL_verify_mode} = $ENV{SSLVERIFY} if defined($ENV{SSLVERIFY});
924 $SSL{$opt} = $ENV{$env} if defined($ENV{$env});
927 if ($SSL{SSL_verify_mode}) {
929 unless ($SSL{SSL_ca_path} or $SSL{SSL_ca_file}) {
930 die "$0: \$SSLVERIFYMODE, but not valid \$SSLCAPATH or \$SSLCAFILE\n";
932 } elsif (defined($SSL{SSL_verify_mode})) {
933 # user has set SSLVERIFY=0 !
936 $SSL{SSL_verify_mode} = 1 if $SSL{SSL_ca_path} or $SSL{SSL_ca_file};
942 return if $SSL{SSL_ca_file} or $SSL{SSL_ca_path};
943 foreach (qw(/etc/ssl/certs/ca-certificates.crt)) {
945 $SSL{SSL_ca_file} = $_;
949 foreach (qw(/etc/ssl/certs /etc/pki/tls/certs)) {
951 $SSL{SSL_ca_path} = $_;
959 my ($server,$port) = @_;
960 my $connect = "CONNECT $server:$port HTTP/1.1";
964 tcpconnect(split(':',$proxy));
966 printf "--> %s\n",$connect if $opt_v;
967 nvtsend($connect,"");
970 printf "<-- $_"if $opt_v;
971 unless (/^HTTP.1.. 200/) {
972 die "$0: proxy error : $_";
975 $SH = IO::Socket::SSL->start_SSL($SH,%SSL);
978 tcpconnect($server,$port);
980 # if ($https and $opt_v) {
981 # printf "%s\n",$SH->get_cipher();
986 # set up tcp/ip connection
988 my ($server,$port) = @_;
996 # eval "use IO::Socket::SSL qw(debug3)";
998 $SH = IO::Socket::SSL->new(
1005 $SH = IO::Socket::INET->new(
1006 PeerAddr => $server,
1016 die "$0: cannot connect $server:$port - $@\n";
1019 print "TCPCONNECT to $server:$port\n" if $opt_v;
1024 eval "use IO::Socket::SSL";
1025 die "$0: cannot load IO::Socket::SSL\n" if $@;
1026 eval '$SSL{SSL_verify_mode} = 0 if Net::SSLeay::SSLeay() <= 9470143';
1028 foreach my $v (keys %SSL) {
1029 printf "%s => %s\n",$v,$SSL{$v};
1040 push @head,"Host: $sp";
1042 foreach $head (@head) {
1043 print "--> $head\n" if $opt_v;
1044 print {$SH} $head,"\r\n";
1046 print "-->\n" if $opt_v;
1052 local $SIG{PIPE} = sub { $sigpipe = "@_" };
1056 die "$0: internal error: no active network handle\n" unless $SH;
1057 die "$0: remote host has closed the link\n" unless $SH->connected;
1059 foreach my $line (@_) {
1060 print {$SH} $line,"\r\n";
1073 s/([^\w\@\/%^,.=+_:+-])/\\$1/g;
1079 print "## DEBUG: @_\n" if $DEBUG;
1083 # from MIME::Base64::Perl
1090 $res = join '',map(pack('u',$_)=~ /^.(\S*)/, ($_[0]=~/(.{1,45})/gs));
1091 $res =~ tr|` -_|AA-Za-z0-9+/|;
1092 $padding = (3-length($_[0])%3)%3;
1093 $res =~ s/.{$padding}$/'=' x $padding/e if $padding;