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 = 20160104;
34 our $CTYPE = 'ISO-8859-1';
35 our $fexsend = $ENV{FEXSEND} || 'fexsend';
36 our $DEBUG = $ENV{DEBUG};
38 my %SSL = (SSL_version => 'TLSv1');
41 # inquire default character set
42 # cannot use "use I18N::Langinfo" because of no windows support!
45 require I18N::Langinfo;
46 I18N::Langinfo->import(qw'langinfo CODESET');
47 $CTYPE = langinfo(CODESET());
50 if ($Config{osname} =~ /^mswin/i) {
51 $windoof = $Config{osname};
52 $ENV{HOME} = $ENV{USERPROFILE};
53 $fexhome = $ENV{FEXHOME} || $ENV{HOME}.'/fex';
54 $tmpdir = $ENV{FEXTMP} || $ENV{TMP} || "$fexhome/tmp";
56 $useragent = sprintf("fexget-$version (%s %s)",
57 $Config{osname},$Config{archname});
58 $SSL{SSL_verify_mode} = 0;
59 chdir $ENV{USERPROFILE}.'\Desktop';
60 # open XX,'>XXXXXX';close XX;
61 } elsif ($Config{osname} =~ /^darwin/i or $ENV{MACOS}) {
62 $0 =~ s:(.*)/:: and $ENV{PATH} .= ":$1";
63 $fexhome = $ENV{FEXHOME} || $ENV{HOME}.'/.fex';
64 $tmpdir = $ENV{FEXTMP} || $ENV{TMPDIR} || "$fexhome/tmp";
66 $_ = `sw_vers -productVersion 2>/dev/null`||'';
68 $useragent = "fexget-$version (MacOS $_)";
70 $0 =~ s:(.*)/:: and $ENV{PATH} .= ":$1";
71 $fexhome = $ENV{FEXHOME} || $ENV{HOME}.'/.fex';
72 $tmpdir = $ENV{FEXTMP} || "$fexhome/tmp";
74 $_ = `(lsb_release -d||uname -a)2>/dev/null`||'';
77 $useragent = "fexget-$version ($_)";
80 if (-f ($_ = '/etc/fex/config.pl')) {
81 eval { require } or warn $@;
85 usage: $0 [-v] [-m limit] [-s filename] [-o] [-k] [-X] [-P proxy:port] F*EX-URL(s)
86 or: $0 [-v] -d F*EX-URL(s)
87 or: $0 [-v] -f F*EX-URL(s) e-mail-address
91 options: -v verbose mode
93 -s save to filename (-s- means: write to STDOUT/pipe)
94 -o overwrite existing file
95 -k keep on server after download
96 -X do not extract archive files or autoview file
97 -d delete without download
98 -f forward a file to another recipient
99 -a get all files (implies -X)
100 -l list files on server
101 -i tag alternate server/account, see: $fexsend -h
102 -P use Proxy for connection to the F*EX server
103 -H show hints and examples
104 argument: F*EX-URL may be file number (see: $0 -l)
108 When you download a file with extension .jpg .gif .png or .tif an image viewer
109 will be started. This can be xv or xdg-open.
110 In $HOME/.fex/config.pl you can set your prefered autoview applications:
113 '\.(gif|jpg|png|tiff?)' => 'my_prefered_image_viewer',
114 '\.(avi|mp4|mov)' => 'vlc -f',
118 For HTTPS you can set the environment variables:
119 SSLVERIFY=1 # activate server identity verification
120 SSLVERSION=TLSv1 # this is the default
121 SSLCAPATH=/etc/ssl/certs # path to trusted (root) certificates
122 SSLCAFILE=/etc/ssl/cert.pem # file with trusted (root) certificates
123 SSLCIPHERLIST=HIGH:!3DES # see http://www.openssl.org/docs/apps/ciphers.html
125 You can set these environment variables also in $HOME/.fex/config.pl, as well as
126 the $opt_* variables, e.g.:
128 $ENV{SSLVERSION} = 'TLSv1';
133 if ($windoof and not @ARGV and not $ENV{PROMPT}) {
134 # restart with cmd.exe to have mouse cut+paste
135 my $cmd = "cmd /k \"$0\"";
141 my $atype = '\.(tgz|tar|zip|7z)$';
143 my $proxy_prefix = '';
146 our ($opt_h,$opt_v,$opt_l,$opt_d,$opt_m,$opt_z,$opt_K,$opt_o,$opt_a);
147 our ($opt_s,$opt_k,$opt_i,$opt_V,$opt_X,$opt_f,$opt_P,$opt_L,$opt_H);
148 $opt_m = $opt_h = $opt_v = $opt_l = $opt_d = $opt_K = $opt_o = $opt_a = 0;
149 $opt_V = $opt_X = $opt_f = $opt_L = $opt_H = 0;
151 $opt_s = $opt_k = $opt_i = $opt_P = '';
152 $_ = "$fexhome/config.pl"; require if -f;
153 getopts('hvVHlLdkzoaXf+m:s:i:K:P:') or die $usage;
154 $opt_k = '?KEEP' if $opt_k;
156 if ($opt_m =~ /(\d+)/) {
162 print "Version: $version\n" if $opt_V;
163 die $usage if $opt_h;
171 my $ffl = "$tmpdir/fexget"; # F*EX files list (cache)
187 my $cmd = "$fexsend -Z";
188 $cmd .= " -i $opt_i" if $opt_i;
189 warn "$cmd\n" if $opt_v;
191 die "$0: cannot run $cmd : $!\n";
200 my $cmd = "$fexsend -L";
201 $cmd .= " -i $opt_i" if $opt_i;
202 warn "$cmd\n" if $opt_v;
204 die "$0: cannot run $cmd : $!\n";
208 if ($opt_P =~ /^([\w.-]+:\d+)(:(\d+))?/) {
210 $chunksize = $3 || 0;
212 die "$0: proxy must be: SERVER:PORT\n";
221 if (open $ffl,$ffl) {
223 push @ARGV,$1 if /^\s+(\d+)/;
232 print "download-URL: ";
233 chomp($url = <STDIN>);
234 if ($url =~ /^http/) {
245 my ($file,%files,$download,$server,$port,$fop,$https);
248 unless ($ENV{FEXID} or -f $ENV{HOME}.'/.fex/id') {
249 die "$0: no local FEXID\n";
252 if ($opt_f =~ /^\d+$|^https?:/) {
253 die "$0: $opt_f is not an e-mail address\n";
257 URL: foreach my $url (@ARGV) {
259 # do not overrun server
262 if ($url !~ /^http/) {
264 open $ffl,$ffl or die "$0: no $ffl, use first: $0 -l\n";
267 if (/^from (.+) :$/) {
269 } elsif (/^\s*(\d+)\)\s+\d+ MB.* (http\S+)/) {
270 push @{$files{all}},$2;
271 push @{$files{$from}},$2;
277 if ($url =~ /^(\d+)$/) {
278 $url = ${files{all}}[$1-1] or die "$0: unknown file number\n";
282 if ($url =~ m{^http(s?)://([\w\.\-]+)(:(\d+))?(/.*fop/\S+)}) {
285 $port = $4 || ($1?443:80);
288 die "$0: unknown F*EX URL $url\n";
292 if ($port == 80) { $proxy_prefix = "http://$server" }
293 elsif ($port == 443) { $proxy_prefix = "" }
294 else { $proxy_prefix = "http://$server:$port" }
297 serverconnect($server,$port);
308 ($file) = grep { $_ = $1 if /^X-File:\s+(.+)/ } @r;
309 $file = $url unless $file;
311 printf "%s deleted\n",urldecode($file);
314 die "$0: server response: $_";
325 print "$file kept\n";
328 die "$0: server response: $_";
333 $download = download($server,$port,$fop);
334 exit if $opt_s eq '-';
335 unlink $download unless -s $download;
336 exit 2 unless -f $download;
343 if (not $opt_X and $download =~ /\.gpg$/) {
345 print "decrypt \"$download\"? ";
348 print "keeping \"$download\"\n";
352 if (system('gpg',$download) == 0) {
354 $download =~ s/\.gpg$//;
360 foreach my $a (keys %autoview) {
361 if ($download =~ /$a$/i and $autoview{$a}) {
362 printf "run \"%s %s\" [Yn] ? ",$autoview{$a},basename($download);
364 system sprintf("%s %s",$autoview{$a},quote($download)) if /^y|^$/i;
369 if ($ENV{DISPLAY} and $download =~ /\.(gif|jpg|png|tiff?)$/i) {
370 # see also mimeopen and xdg-mime
371 # http://unix.stackexchange.com/questions/144047/how-does-xdg-open-do-its-work
372 if (my $xv = $xv || pathsearch('xv') || pathsearch('xdg-open')) {
373 printf "run \"%s %s\" [Yn] ? ",basename($xv),basename($download);
375 system $xv,$download if /^y|^$/i;
380 if ($download =~ /$atype/) {
381 if ($download =~ /\.(tgz|tar.gz)$/) { extract('tar tvzf','tar xvzf') }
382 elsif ($download =~ /\.tar$/) { extract('tar tvf','tar xvf') }
383 elsif ($download =~ /\.zip$/i) { extract('unzip -l','unzip') }
384 elsif ($download =~ /\.7z$/i) { extract('7z l','7z x') }
385 else { die "$0: unknown archive \"$download\"\n" }
389 die "$0: keeping \"$download\"\n";
405 if (-t and not $windoof) {
406 print "Files in archive:\n";
407 system(split(' ',$l),$download);
412 $xd = inquire("extract to directory (Ctrl-C to keep archive): ",$d);
413 last if $xd =~ s:^(\./*)*!?$::;
415 print "keeping $download\n";
420 print "directory $xd does already exist, add \"!\" to overwrite\n";
424 print "cannot mkdir $xd - $!\n";
429 print "cannot chdir $xd - $!\n";
435 print "extracting to $xd :\n" if $xd;
436 system(split(' ',$x),$download);
437 print "extracted to $xd\n" if $xd;
446 if ($url =~ m{^http(s?)://([\w\.\-]+)(:(\d+))?(/fop/.+)}) {
448 $port = $4 || ($1?443:80);
451 die "$0: unknown F*EX URL $url\n";
454 sendheader("$server:$port","GET $del HTTP/1.1","User-Agent: $useragent");
457 last if /^\n/; # ignore HTML output
458 warn "<-- $_" if $opt_v;
461 die "$0: no response from fex server $server\n" unless @r;
469 my ($uri,$dkey,$list,$cmd,$n,$copy);
472 if ($url =~ m{^http(s?)://([\w\.\-]+)(:(\d+))?(/fop/.+)}) {
474 $port = $4 || ($1?443:80);
477 die "$0: unknown F*EX URL $url\n";
482 "GET $uri?COPY HTTP/1.1",
483 "User-Agent: $useragent",
487 die "$0: no reply from fex server $server\n" unless $_;
488 warn "<-- $_" if $opt_v;
490 if (/^HTTP.*already exists/) {
491 if ($uri =~ m:/fop/(\w+)/:) {
494 } elsif (/^HTTP.*200/) {
503 last if /^\n/; # ignore HTML output
504 $dkey = $1 if /^Location:.*\/(\w+)\/.+/;
505 warn "<-- $_" if $opt_v;
508 print "fexsend -l\n" if $opt_v;
509 system 'fexsend -l >/dev/null 2>&1';
510 $list = $ENV{HOME}.'/.fex/tmp/fexlist';
511 open $list,$list or die "$0: cannot open $list - $!\n";
513 if (/^\s+(\d+)\) (\w+)/ and $2 eq $dkey) {
515 $cmd = "fexsend -b $n $opt_f";
516 print "$cmd\n" if $opt_v;
524 $cmd = "fexsend -d $n >/dev/null 2>&1";
525 print "$cmd\n" if $opt_v;
528 warn "$0: forwarding failed\n";
539 if ($url =~ m{^http(s?)://([\w\.\-]+)(:(\d+))?(/fop/.+)}) {
541 $port = $4 || ($1?443:80);
542 $keep = "$5?KEEP=$opt_K";
544 die "$0: unknown F*EX URL $url\n";
547 push @hh,"GET $keep HTTP/1.1",
548 "Host: $server:$port",
549 "User-Agent: $useragent",
553 warn $_,"\n" if $opt_v;
561 die "$0: no response from fex server $server\n" unless @r;
562 grep { warn "\t$_" } @r if $opt_v;
568 my ($server,$port,$fop,$nocheck) = @_;
569 my ($file,$download,$ssl,$pipe,$filesize,$checkstorage);
571 my ($t0,$t1,$t2,$tt,$tm,$ts,$kBs,$b,$bt,$tb,$B,$buf);
581 $pipe = $download = $opt_s;
582 } elsif (-p $opt_s or -c $opt_s) {
584 $nocheck = 'pipe or character device';
586 $download = $file.'.tmp';
587 $seek = -s $download || 0;
590 # ask server for real file name
593 "HEAD $proxy_prefix$fop HTTP/1.1",
594 "User-Agent: $useragent"
596 my $reply = $_ = <$SH>;
597 unless (defined $_ and /\w/) {
598 die "$0: no response from server\n";
600 warn "<-- $_" if $opt_v;
601 unless (/^HTTP\/[\d.]+ 200/) {
603 die "$0: server response: $_";
607 warn "<-- $_" if $opt_v;
609 if (/^Content-Disposition: attachment; filename="(.+)"/i) {
610 $file = locale(decode_utf8($1));
618 $download = $file.'.tmp';
619 $seek = -s $download || 0;
622 push @hh,"GET $proxy_prefix$fop$opt_k HTTP/1.1",
623 "User-Agent: $useragent",
625 push @hh,"Range: bytes=$seek-" if $seek;
627 # HTTPS needs a new connection for actually downloading the file
628 serverconnect($server,$port) if $opt_P and $port == 443;
629 sendheader("$server:$port",@hh);
631 die "$0: no response from fex server $server\n" unless $_;
634 if (/^HTTP\/[\d.]+ 2/) {
635 warn "<-- $_" if $opt_v;
638 warn "<-- $_" if $opt_v;
640 if (/^Content-length:\s*(\d+)/i) {
642 } elsif (/^X-Size: (\d+)/i) {
647 s/HTTP\/[\d.]+ \d+ //;
648 die "$0: bad server reply: $_";
654 if ($opt_s and $opt_s eq $download) {
655 open X,'>',$download or die "$0: cannot write to \"$download\" - $!\n";
656 $checkstorage = $filesize unless $nocheck;
658 if (-e $file and not $opt_o) {
659 die "$0: destination file \"$file\" does already exist\n";
662 open X,'>>',$download or die "$0: cannot write to \"$download\" - $!\n";
664 open X,'>',$download or die "$0: cannot write to \"$download\" - $!\n";
665 $checkstorage = $filesize unless $nocheck;
668 if ($checkstorage and not $nocheck) {
669 my $t0 = my $t1 = my $t2 = time;
672 my $storagetest = $file.'.test';
673 my $error = "$0: cannot write \"$storagetest\"";
674 open $storagetest,'>',$storagetest or die "$error - $!\n";
675 print STDERR "checking storage...\r";
676 while (-s $storagetest < $checkstorage) {
677 syswrite $storagetest,$buf or do {
679 die "\n$error - $!\n";
684 print STDERR "checking storage... ".$n." MB\r";
688 close $storagetest or do {
690 die "\n$error - $!\n";
692 print STDERR "checking storage... ".$n." MB ok!\n";
695 # retry after timeout
696 serverconnect($server,$port);
697 return(download($server,$port,$fop,'nocheck'))
702 $t0 = $t1 = $t2 = int(time);
704 printf STDERR "resuming at byte %s\n",$seek if $seek;
705 print $rcamel[0] if ${'opt_+'};
706 while ($B < $length and $b = read $SH,$buf,$bs) {
712 if (${'opt_+'} and int($t2*10)>$tc) {
713 print $rcamel[$tc%2+1];
716 if (int($t2) > $t1) {
717 $kBs = int($bt/k/($t2-$t1));
718 $kBs = int($tb/k/($t2-$t0)) if $kBs < 10;
721 # smaller block size is better on slow links
722 $bs = 4096 if $bs>4096 and $tb/($t2-$t0)<65536;
724 printf STDERR "%s: %d kB (%d%%) %d kB/s \r",
727 int(($tb+$seek)/($length+$seek)*100),
730 printf STDERR "%s: %d MB (%d%%) %d kB/s \r",
733 int(($tb+$seek)/($length+$seek)*100),
738 if ($t2 == $t0 and $B > $opt_m*k) {
739 print "\nsleeping...\r" if $opt_v;
742 while ($t2 > $t0 and $tb/k/($t2-$t0) > $opt_m) {
743 print "\nsleeping...\r" if $opt_v;
753 print $rcamel[2] if ${'opt_+'};
758 $kBs = int($tb/k/($tt||1));
760 printf STDERR "$file: %d MB, last %d MB in %d s (%d kB/s) \n",
761 int(($tb+$seek)/M),int($tb/M),$tt,$kBs;
763 printf STDERR "$file: %d MB in %d s (%d kB/s) \n",
767 if ($tb != $length) {
772 die "$0: $server annouced $length bytes, but only $tb bytes has been read\n";
776 unless ($pipe or -p $download or -c $download) {
777 my @s = stat $file if -e $file;
778 rename $download,$file
779 or die "$0: cannot rename \"$download\" to \"$file\" - $!\n";
780 chmod $s[2],$file if @s;
783 return sprintf("%s/%s",getcwd(),$file);
788 my $cmd = "$fexsend -L";
789 $cmd .= " -i $opt_i" if $opt_i;
794 open $cmd,"$cmd|" or die "$0: cannot run $cmd : $!\n";
795 open $ffl,'>',$ffl or die "$0: cannot open $ffl : $!\n";
798 if (/\d MB .*http/) {
800 printf {$ffl} "%4d) %s",$n,$_;
802 printf "%4d) %s",$n,$_;
815 if ($CTYPE =~ /UTF-?8/i) {
817 } elsif (grep { $CTYPE =~ /^$_$/i } Encode->encodings()) {
818 return encode($CTYPE,$string);
820 return encode('ISO-8859-1',$string);
831 foreach my $dir (split(':',$ENV{PATH})) {
832 return "$dir/$prg" if -x "$dir/$prg";
846 if (defined $default) {
848 chomp($tty = `tty 2>/dev/null`);
849 eval { local $^W; require "sys/ioctl.ph"; };
852 if (defined(&TIOCSTI) and $tty and open($tty,'>',$tty)) {
854 # push default answer into keyboard buffer
855 foreach my $a (split("",$default)) { ioctl($tty,&TIOCSTI,$a) }
856 chomp($_ = <STDIN>||'');
858 $prompt =~ s/([\?:=]\s*)/ [$default]$1/ or $prompt .= " [$default] ";
860 chomp($_ = <STDIN>||'');
861 $_ = $default unless length;
865 chomp($_ = <STDIN>||'');
873 ### common functions ###
877 my @d = localtime((stat shift)[9]);
878 return sprintf('%d%02d%02d',$d[5]+1900,$d[4]+1,$d[3]);
884 s/\%([a-f\d]{2})/chr(hex($1))/ige;
890 # set SSL/TLS options
891 $SSL{SSL_verify_mode} = $ENV{SSLVERIFY} if defined($ENV{SSLVERIFY});
901 $SSL{$opt} = $ENV{$env} if defined($ENV{$env});
904 if ($SSL{SSL_verify_mode}) {
906 unless ($SSL{SSL_ca_path} or $SSL{SSL_ca_file}) {
907 die "$0: \$SSLVERIFYMODE, but not valid \$SSLCAPATH or \$SSLCAFILE\n";
909 } elsif (defined($SSL{SSL_verify_mode})) {
910 # user has set SSLVERIFY=0 !
913 $SSL{SSL_verify_mode} = 1 if $SSL{SSL_ca_path} or $SSL{SSL_ca_file};
919 return if $SSL{SSL_ca_file} or $SSL{SSL_ca_path};
920 foreach (qw(/etc/ssl/certs/ca-certificates.crt)) {
922 $SSL{SSL_ca_file} = $_;
926 foreach (qw(/etc/ssl/certs /etc/pki/tls/certs)) {
928 $SSL{SSL_ca_path} = $_;
936 my ($server,$port) = @_;
937 my $connect = "CONNECT $server:$port HTTP/1.1";
941 tcpconnect(split(':',$proxy));
943 printf "--> %s\n",$connect if $opt_v;
944 nvtsend($connect,"");
947 printf "<-- $_"if $opt_v;
948 unless (/^HTTP.1.. 200/) {
949 die "$0: proxy error : $_";
952 $SH = IO::Socket::SSL->start_SSL($SH,%SSL);
955 tcpconnect($server,$port);
957 # if ($https and $opt_v) {
958 # printf "%s\n",$SH->get_cipher();
963 # set up tcp/ip connection
965 my ($server,$port) = @_;
973 # eval "use IO::Socket::SSL qw(debug3)";
975 $SH = IO::Socket::SSL->new(
982 $SH = IO::Socket::INET->new(
993 die "$0: cannot connect $server:$port - $@\n";
996 print "TCPCONNECT to $server:$port\n" if $opt_v;
1001 eval "use IO::Socket::SSL";
1002 die "$0: cannot load IO::Socket::SSL\n" if $@;
1003 eval '$SSL{SSL_verify_mode} = 0 if Net::SSLeay::SSLeay() <= 9470143';
1005 foreach my $v (keys %SSL) {
1006 printf "%s => %s\n",$v,$SSL{$v};
1017 push @head,"Host: $sp";
1019 foreach $head (@head) {
1020 print "--> $head\n" if $opt_v;
1021 print {$SH} $head,"\r\n";
1023 print "-->\n" if $opt_v;
1029 local $SIG{PIPE} = sub { $sigpipe = "@_" };
1033 die "$0: internal error: no active network handle\n" unless $SH;
1034 die "$0: remote host has closed the link\n" unless $SH->connected;
1036 foreach my $line (@_) {
1037 print {$SH} $line,"\r\n";
1050 s/([^\w\@\/%^,.=+_:+-])/\\$1/g;
1056 print "## DEBUG: @_\n" if $DEBUG;
1060 # from MIME::Base64::Perl
1067 $res = join '',map(pack('u',$_)=~ /^.(\S*)/, ($_[0]=~/(.{1,45})/gs));
1068 $res =~ tr|` -_|AA-Za-z0-9+/|;
1069 $padding = (3-length($_[0])%3)%3;
1070 $res =~ s/.{$padding}$/'=' x $padding/e if $padding;