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 = 20150826;
34 our $CTYPE = 'ISO-8859-1';
35 our $fexsend = $ENV{FEXSEND} || 'fexsend';
37 my %SSL = (SSL_version => 'TLSv1');
40 # inquire default character set
41 # cannot use "use I18N::Langinfo" because of no windows support!
44 require I18N::Langinfo;
45 I18N::Langinfo->import(qw'langinfo CODESET');
46 $CTYPE = langinfo(CODESET());
49 if ($Config{osname} =~ /^mswin/i) {
50 $windoof = $Config{osname};
51 $ENV{HOME} = $ENV{USERPROFILE};
52 $fexhome = $ENV{FEXHOME} || $ENV{HOME}.'/fex';
53 $tmpdir = $ENV{FEXTMP} || $ENV{TMP} || "$fexhome/tmp";
55 $useragent = sprintf("fexget-$version (%s %s)",
56 $Config{osname},$Config{archname});
57 $SSL{SSL_verify_mode} = 0;
58 chdir $ENV{USERPROFILE}.'\Desktop';
59 # open XX,'>XXXXXX';close XX;
61 $0 =~ s:(.*)/:: and $ENV{PATH} .= ":$1";
62 $fexhome = $ENV{FEXHOME} || $ENV{HOME}.'/.fex';
63 $tmpdir = $ENV{FEXTMP} || "$fexhome/tmp";
65 $_ = `(lsb_release -d||uname -a)2>/dev/null`||'';
68 $useragent = "fexget-$version ($_)";
71 if (-f ($_ = '/etc/fex/config.pl')) {
72 eval { require } or warn $@;
76 usage: $0 [-v] [-m limit] [-s filename] [-o] [-k] [-X] [-P proxy:port] F*EX-URL(s)
77 or: $0 [-v] -d F*EX-URL(s)
78 or: $0 [-v] -f F*EX-URL(s) e-mail-address
82 options: -v verbose mode
84 -s save to filename (-s- means: write to STDOUT/pipe)
85 -o overwrite existing file
86 -k keep on server after download
87 -X do not extract archive files or autoview file
88 -d delete without download
89 -f forward a file to another recipient
90 -a get all files (implies -X)
91 -l list files on server
92 -i tag alternate server/account, see: $fexsend -h
93 -P use Proxy for connection to the F*EX server
94 -H show hints and examples
95 argument: F*EX-URL may be file number (see: $0 -l)
99 When you download a file with extension .jpg .gif .png or .tif an image viewer
100 will be started. This can be xv or xdg-open.
101 In $HOME/.fex/config.pl you can set your prefered autoview applications:
104 '\.(gif|jpg|png|tiff?)' => 'my_prefered_image_viewer',
105 '\.(avi|mp4|mov)' => 'vlc -f',
109 For HTTPS you can set the environment variables:
110 SSLVERIFY=1 # activate server identity verification
111 SSLVERSION=TLSv1 # this is the default
112 SSLCAPATH=/etc/ssl/certs # path to trusted (root) certificates
113 SSLCAFILE=/etc/ssl/cert.pem # file with trusted (root) certificates
114 SSLCIPHERLIST=HIGH:!3DES # see http://www.openssl.org/docs/apps/ciphers.html
116 You can set these environment variables also in $HOME/.fex/config.pl, as well as
117 the $opt_* variables, e.g.:
119 $ENV{SSLVERSION} = 'TLSv1';
124 if ($windoof and not @ARGV and not $ENV{PROMPT}) {
125 # restart with cmd.exe to have mouse cut+paste
126 my $cmd = "cmd /k \"$0\"";
132 my $atype = '\.(tgz|tar|zip|7z)$';
134 my $proxy_prefix = '';
137 our ($opt_h,$opt_v,$opt_l,$opt_d,$opt_m,$opt_z,$opt_K,$opt_o,$opt_a);
138 our ($opt_s,$opt_k,$opt_i,$opt_V,$opt_X,$opt_f,$opt_P,$opt_L,$opt_H);
139 $opt_m = $opt_h = $opt_v = $opt_l = $opt_d = $opt_K = $opt_o = $opt_a = 0;
140 $opt_V = $opt_X = $opt_f = $opt_L = $opt_H = 0;
142 $opt_s = $opt_k = $opt_i = $opt_P = '';
143 $_ = "$fexhome/config.pl"; require if -f;
144 getopts('hvVHlLdkzoaXf+m:s:i:K:P:') or die $usage;
145 $opt_k = '?KEEP' if $opt_k;
147 if ($opt_m =~ /(\d+)/) {
153 print "Version: $version\n" if $opt_V;
154 die $usage if $opt_h;
162 my $ffl = "$tmpdir/fexget"; # F*EX files list (cache)
178 my $cmd = "$fexsend -Z";
179 $cmd .= " -i $opt_i" if $opt_i;
180 warn "$cmd\n" if $opt_v;
182 die "$0: cannot run $cmd : $!\n";
191 my $cmd = "$fexsend -L";
192 $cmd .= " -i $opt_i" if $opt_i;
193 warn "$cmd\n" if $opt_v;
195 die "$0: cannot run $cmd : $!\n";
199 if ($opt_P =~ /^([\w.-]+:\d+)(:(\d+))?/) {
201 $chunksize = $3 || 0;
203 die "$0: proxy must be: SERVER:PORT\n";
212 if (open $ffl,$ffl) {
214 push @ARGV,$1 if /^\s+(\d+)/;
223 print "download-URL: ";
224 chomp($url = <STDIN>);
225 if ($url =~ /^http/) {
236 my ($file,%files,$download,$server,$port,$fop);
239 unless ($ENV{FEXID} or -f $ENV{HOME}.'/.fex/id') {
240 die "$0: no local FEXID\n";
243 if ($opt_f =~ /^\d+$|^https?:/) {
244 die "$0: $opt_f is not an e-mail address\n";
248 URL: foreach my $url (@ARGV) {
250 # do not overrun server
253 if ($url !~ /^http/) {
255 open $ffl,$ffl or die "$0: no $ffl, use first: $0 -l\n";
258 if (/^from (.+) :$/) {
260 } elsif (/^\s*(\d+)\)\s+\d+ MB.* (http\S+)/) {
261 push @{$files{all}},$2;
262 push @{$files{$from}},$2;
268 if ($url =~ /^(\d+)$/) {
269 $url = ${files{all}}[$1-1] or die "$0: unknown file number\n";
273 if ($url =~ m{^http(s?)://([\w\.\-]+)(:(\d+))?(/.*fop/\S+)}) {
275 $port = $4 || ($1?443:80);
278 die "$0: unknown F*EX URL $url\n";
282 if ($port == 80) { $proxy_prefix = "http://$server" }
283 elsif ($port == 443) { $proxy_prefix = "" }
284 else { $proxy_prefix = "http://$server:$port" }
287 serverconnect($server,$port);
298 ($file) = grep { $_ = $1 if /^X-File:\s+(.+)/ } @r;
299 $file = $url unless $file;
301 printf "%s deleted\n",urldecode($file);
304 die "$0: server response: $_";
315 print "$file kept\n";
318 die "$0: server response: $_";
323 $download = download($server,$port,$fop);
324 exit if $opt_s eq '-';
325 unlink $download unless -s $download;
326 exit 2 unless -f $download;
333 if (not $opt_X and $download =~ /\.gpg$/) {
335 print "decrypt \"$download\"? ";
338 print "keeping \"$download\"\n";
342 if (system('gpg',$download) == 0) {
344 $download =~ s/\.gpg$//;
350 foreach my $a (keys %autoview) {
351 if ($download =~ /$a$/i and $autoview{$a}) {
352 printf "run \"%s %s\" [Yn] ? ",$autoview{$a},basename($download);
354 system sprintf("%s %s",$autoview{$a},quote($download)) if /^y|^$/i;
359 if ($ENV{DISPLAY} and $download =~ /\.(gif|jpg|png|tiff?)$/i) {
360 # see also mimeopen and xdg-mime
361 if (my $xv = $xv || pathsearch('xv') || pathsearch('xdg-open')) {
362 printf "run \"%s %s\" [Yn] ? ",basename($xv),basename($download);
364 system $xv,$download if /^y|^$/i;
369 if ($download =~ /$atype/) {
370 if ($download =~ /\.(tgz|tar.gz)$/) { extract('tar tvzf','tar xvzf') }
371 elsif ($download =~ /\.tar$/) { extract('tar tvf','tar xvf') }
372 elsif ($download =~ /\.zip$/i) { extract('unzip -l','unzip') }
373 elsif ($download =~ /\.7z$/i) { extract('7z l','7z x') }
374 else { die "$0: unknown archive \"$download\"\n" }
378 die "$0: keeping \"$download\"\n";
394 if (-t and not $windoof) {
395 print "Files in archive:\n";
396 system(split(' ',$l),$download);
400 $xd = inquire("extract to directory (Ctrl-C to keep archive): ",$d);
401 last if $xd =~ s:^(\./*)*!?$:./:;
403 print "keeping $download\n";
408 print "directory $xd does already exist, add \"!\" to overwrite\n";
412 print "cannot mkdir $xd - $!\n";
417 print "cannot chdir $xd - $!\n";
423 print "extracting to $xd :\n";
424 system(split(' ',$x),$download);
433 if ($url =~ m{^http(s?)://([\w\.\-]+)(:(\d+))?(/fop/.+)}) {
435 $port = $4 || ($1?443:80);
438 die "$0: unknown F*EX URL $url\n";
441 sendheader("$server:$port","GET $del HTTP/1.1","User-Agent: $useragent");
444 last if /^\n/; # ignore HTML output
445 warn "<-- $_" if $opt_v;
448 die "$0: no response from fex server $server\n" unless @r;
456 my ($uri,$dkey,$list,$cmd,$n);
459 if ($url =~ m{^http(s?)://([\w\.\-]+)(:(\d+))?(/fop/.+)}) {
461 $port = $4 || ($1?443:80);
464 die "$0: unknown F*EX URL $url\n";
469 "GET $uri?COPY HTTP/1.1",
470 "User-Agent: $useragent",
474 die "$0: no reply from fex server $server\n" unless $_;
475 warn "<-- $_" if $opt_v;
477 unless (/^HTTP.*200/) {
484 last if /^\n/; # ignore HTML output
485 $dkey = $1 if /^Location:.*\/(\w+)\/.+/;
486 warn "<-- $_" if $opt_v;
489 $cmd = 'fexsend -l >/dev/null 2>&1';
490 print "$cmd\n" if $opt_v;
491 system 'fexsend -l >/dev/null 2>&1';
492 $list = $ENV{HOME}.'/.fex/tmp/fexlist';
493 open $list,$list or die "$0: cannot open $list - $!\n";
495 if (/^\s+(\d+)\) (\w+)/ and $2 eq $dkey) {
497 $cmd = "fexsend -b $n $opt_f";
498 print "$cmd\n" if $opt_v;
506 $cmd = "fexsend -d $n >/dev/null 2>&1";
507 print "$cmd\n" if $opt_v;
510 warn "$0: forwarding failed\n";
521 if ($url =~ m{^http(s?)://([\w\.\-]+)(:(\d+))?(/fop/.+)}) {
523 $port = $4 || ($1?443:80);
524 $keep = "$5?KEEP=$opt_K";
526 die "$0: unknown F*EX URL $url\n";
529 push @hh,"GET $keep HTTP/1.1",
530 "Host: $server:$port",
531 "User-Agent: $useragent",
535 warn $_,"\n" if $opt_v;
543 die "$0: no response from fex server $server\n" unless @r;
544 grep { warn "\t$_" } @r if $opt_v;
550 my ($server,$port,$fop,$nocheck) = @_;
551 my ($file,$download,$ssl,$pipe,$filesize,$checkstorage);
553 my ($t0,$t1,$t2,$tt,$tm,$ts,$kBs,$b,$bt,$tb,$B,$buf);
563 $pipe = $download = $opt_s;
564 } elsif (-p $opt_s or -c $opt_s) {
567 $download = $file.'.tmp';
568 $seek = -s $download || 0;
571 # ask server for real file name
572 serverconnect($server, $port);
573 sendheader("$server:$port","HEAD $proxy_prefix$fop HTTP/1.1","User-Agent: $useragent");
574 my $reply = $_ = <$SH>;
575 unless (defined $_ and /\w/) {
576 die "$0: no response from server\n";
578 warn "<-- $_" if $opt_v;
579 unless (/^HTTP\/[\d.]+ 200/) {
581 die "$0: server response: $_";
585 warn "<-- $_" if $opt_v;
587 if (/^Content-Disposition: attachment; filename="(.+)"/i) {
588 $file = locale(decode_utf8($1));
596 $download = $file.'.tmp';
597 $seek = -s $download || 0;
600 push @hh,"GET $proxy_prefix$fop$opt_k HTTP/1.1",
601 "User-Agent: $useragent",
603 push @hh,"Range: bytes=$seek-" if $seek;
605 # HTTPS needs a new connection for actually downloading the file
606 serverconnect($server,$port) if $opt_P and $port == 443;
607 sendheader("$server:$port",@hh);
609 die "$0: no response from fex server $server\n" unless $_;
612 if (/^HTTP\/[\d.]+ 2/) {
613 warn "<-- $_" if $opt_v;
616 warn "<-- $_" if $opt_v;
618 if (/^Content-length:\s*(\d+)/i) {
620 } elsif (/^X-Size: (\d+)/i) {
625 s/HTTP\/[\d.]+ \d+ //;
626 die "$0: bad server reply: $_";
632 if ($opt_s and $opt_s eq $download) {
633 open X,'>',$download or die "$0: cannot write to \"$download\" - $!\n";
634 $checkstorage = $filesize unless $nocheck;
636 if (-e $file and not $opt_o) {
637 die "$0: destination file \"$file\" does already exist\n";
640 open X,'>>',$download or die "$0: cannot write to \"$download\" - $!\n";
642 open X,'>',$download or die "$0: cannot write to \"$download\" - $!\n";
643 $checkstorage = $filesize unless $nocheck;
646 if ($checkstorage and not $nocheck) {
649 print STDERR "checking storage...\r";
651 while (-s $download < $checkstorage) {
652 syswrite X,$buf or do {
654 die "\n$0: cannot write $download - $!\n";
657 print STDERR "checking storage... ".$n." MB\r";
661 die "\n$0: cannot write $download - $!\n";
663 print STDERR "checking storage... ".$n." MB ok!\n";
666 open X,'>',$download or die "$0: cannot write to \"$download\" - $!\n";
668 # retry after timeout
669 return(download($server,$port,$fop,'nocheck'))
674 $t0 = $t1 = $t2 = int(time);
676 printf STDERR "resuming at byte %s\n",$seek if $seek;
677 print $rcamel[0] if ${'opt_+'};
678 while ($B < $length and $b = read $SH,$buf,$bs) {
684 if (${'opt_+'} and int($t2*10)>$tc) {
685 print $rcamel[$tc%2+1];
688 if (int($t2) > $t1) {
689 $kBs = int($bt/k/($t2-$t1));
690 $kBs = int($tb/k/($t2-$t0)) if $kBs < 10;
693 # smaller block size is better on slow links
694 $bs = 4096 if $bs>4096 and $tb/($t2-$t0)<65536;
696 printf STDERR "%s: %d kB (%d%%) %d kB/s \r",
699 int(($tb+$seek)/($length+$seek)*100),
702 printf STDERR "%s: %d MB (%d%%) %d kB/s \r",
705 int(($tb+$seek)/($length+$seek)*100),
710 if ($t2 == $t0 and $B > $opt_m*k) {
711 print "\nsleeping...\r" if $opt_v;
714 while ($t2 > $t0 and $tb/k/($t2-$t0) > $opt_m) {
715 print "\nsleeping...\r" if $opt_v;
725 print $rcamel[2] if ${'opt_+'};
730 $kBs = int($tb/k/($tt||1));
732 printf STDERR "$file: %d MB, last %d MB in %d s (%d kB/s) \n",
733 int(($tb+$seek)/M),int($tb/M),$tt,$kBs;
735 printf STDERR "$file: %d MB in %d s (%d kB/s) \n",
739 if ($tb != $length) {
744 die "$0: $server annouced $length bytes, but only $tb bytes has been read\n";
748 unless ($pipe or -p $download or -c $download) {
749 my @s = stat $file if -e $file;
750 rename $download,$file
751 or die "$0: cannot rename \"$download\" to \"$file\" - $!\n";
752 chmod $s[2],$file if @s;
755 return sprintf("%s/%s",getcwd(),$file);
760 my $cmd = "$fexsend -L";
761 $cmd .= " -i $opt_i" if $opt_i;
766 open $cmd,"$cmd|" or die "$0: cannot run $cmd : $!\n";
767 open $ffl,'>',$ffl or die "$0: cannot open $ffl : $!\n";
770 if (/\d MB .*http/) {
772 printf {$ffl} "%4d) %s",$n,$_;
774 printf "%4d) %s",$n,$_;
787 if ($CTYPE =~ /UTF-?8/i) {
789 } elsif (grep { $CTYPE =~ /^$_$/i } Encode->encodings()) {
790 return encode($CTYPE,$string);
792 return encode('ISO-8859-1',$string);
803 foreach my $dir (split(':',$ENV{PATH})) {
804 return "$dir/$prg" if -x "$dir/$prg";
811 s/([^\w¡-ÿ_%\/=~:.,-])/\\$1/g;
825 if (defined $default) {
827 chomp($tty = `tty 2>/dev/null`);
828 eval { local $^W; require "sys/ioctl.ph"; };
831 if (defined(&TIOCSTI) and $tty and open($tty,'>',$tty)) {
833 foreach my $a (split("",$default)) { ioctl($tty,&TIOCSTI,$a) }
834 chomp($_ = <STDIN>||'');
836 $prompt =~ s/([\?:=]\s*)/ [$default]$1/ or $prompt .= " [$default]";
838 chomp($_ = <STDIN>||'');
839 $_ = $default unless length;
843 chomp($_ = <STDIN>||'');
851 ### common functions ###
855 my @d = localtime((stat shift)[9]);
856 return sprintf('%d%02d%02d',$d[5]+1900,$d[4]+1,$d[3]);
862 s/\%([a-f\d]{2})/chr(hex($1))/ige;
868 # set SSL/TLS options
869 $SSL{SSL_verify_mode} = $ENV{SSLVERIFY} if defined($ENV{SSLVERIFY});
879 $SSL{$opt} = $ENV{$env} if defined($ENV{$env});
882 if ($SSL{SSL_verify_mode}) {
884 unless ($SSL{SSL_ca_path} or $SSL{SSL_ca_file}) {
885 die "$0: \$SSLVERIFYMODE, but not valid \$SSLCAPATH or \$SSLCAFILE\n";
887 } elsif (defined($SSL{SSL_verify_mode})) {
888 # user has set SSLVERIFY=0 !
891 $SSL{SSL_verify_mode} = 1 if $SSL{SSL_ca_path} or $SSL{SSL_ca_file};
897 return if $SSL{SSL_ca_file} or $SSL{SSL_ca_path};
898 foreach (qw(/etc/ssl/certs/ca-certificates.crt)) {
900 $SSL{SSL_ca_file} = $_;
904 foreach (qw(/etc/ssl/certs /etc/pki/tls/certs)) {
906 $SSL{SSL_ca_path} = $_;
914 my ($server,$port) = @_;
915 my $connect = "CONNECT $server:$port HTTP/1.1";
918 if ($opt_v and $port == 443 and %SSL) {
919 foreach my $v (keys %SSL) {
920 printf "%s => %s\n",$v,$SSL{$v};
925 tcpconnect(split(':',$proxy));
927 printf "--> %s\n",$connect if $opt_v;
928 nvtsend($connect,"");
931 printf "<-- $_"if $opt_v;
932 unless (/^HTTP.1.. 200/) {
933 die "$0: proxy error : $_";
935 eval "use IO::Socket::SSL";
936 die "$0: cannot load IO::Socket::SSL\n" if $@;
937 $SH = IO::Socket::SSL->start_SSL($SH,%SSL);
940 tcpconnect($server,$port);
942 # if ($port == 443 and $opt_v) {
943 # printf "%s\n",$SH->get_cipher();
948 # set up tcp/ip connection
950 my ($server,$port) = @_;
958 # eval "use IO::Socket::SSL qw(debug3)";
959 eval "use IO::Socket::SSL";
960 die "$0: cannot load IO::Socket::SSL\n" if $@;
961 $SH = IO::Socket::SSL->new(
968 $SH = IO::Socket::INET->new(
978 die "$0: cannot connect $server:$port - $@\n";
981 print "TCPCONNECT to $server:$port\n" if $opt_v;
990 push @head,"Host: $sp";
992 foreach $head (@head) {
993 print "--> $head\n" if $opt_v;
994 print {$SH} $head,"\r\n";
996 print "-->\n" if $opt_v;
1002 local $SIG{PIPE} = sub { $sigpipe = "@_" };
1006 die "$0: internal error: no active network handle\n" unless $SH;
1007 die "$0: remote host has closed the link\n" unless $SH->connected;
1009 foreach my $line (@_) {
1010 print {$SH} $line,"\r\n";
1021 # from MIME::Base64::Perl
1028 $res = join '',map(pack('u',$_)=~ /^.(\S*)/, ($_[0]=~/(.{1,45})/gs));
1029 $res =~ tr|` -_|AA-Za-z0-9+/|;
1030 $padding = (3-length($_[0])%3)%3;
1031 $res =~ s/.{$padding}$/'=' x $padding/e if $padding;