Debian Codegraph @

t/bin/ftpd

raw
1 #!/usr/bin/env perl
2
3 use strict;
4 use warnings;
5 use URI;
6 use AnyEvent; ## no critic
7 use AnyEvent::FTP::Server;
8 use JSON::PP qw( encode_json decode_json );
9 use Path::Tiny qw( path );
10 use Getopt::Long qw( GetOptions );
11
12 my $daemon = 0;
13 my $kill = 0;
14 my $host = 'localhost';
15
16 GetOptions(
17 "d" => \$daemon,
18 "k" => \$kill,
19 "hosth=s" => \$host,
20 );
21
22 my $bindir = path(__FILE__)->parent->absolute;
23 my $distdir = $bindir->parent->parent;
24
25 my $config_file = $bindir->child('ftpd.json');
26
27 if(-r $config_file)
28 {
29 my $config = decode_json($config_file->slurp);
30 my $pid = $config->{pid};
31 if(defined $pid)
32 {
33 kill 'KILL', $pid;
34 }
35 }
36
37 exit if $kill;
38
39 if($daemon)
40 {
41 require Proc::Daemon;
42 my $daemon = Proc::Daemon->new(
43 child_STDOUT => $bindir->child('ftpd.log')->stringify,
44 child_STDERR => $bindir->child('ftpd.log')->stringify,
45 );
46 $daemon->Init;
47 }
48
49 my $server = AnyEvent::FTP::Server->new(
50 host => $host,
51 port => 0,
52 default_context => 'AnyEvent::FTP::Server::Context::FSRO',
53 );
54
55 my %config = (
56 user => join('', map { chr(ord('a') + int rand(26)) } (1..10)),
57 pass => join('', map { chr(ord('a') + int rand(26)) } (1..10)),
58 root => $distdir->child('corpus/dist')->stringify,
59 pid => $$,
60 );
61
62 my $url = URI->new("ftp://localhost");
63 $url->host($host);
64 $url->path($config{root});
65 $url->user($config{user});
66 $url->password($config{pass});
67
68 $server->on_bind(sub {
69 my $port = shift;
70 $url->port($port);
71 });
72
73 $server->on_connect(sub {
74 my $con = shift;
75 $con->context->authenticator(sub {
76 my($user, $pass) = @_;
77 $user eq $config{user} && $pass eq $config{pass} ? 1 : 0;
78 });
79 $con->context->bad_authentication_delay(0);
80 });
81
82
83 $server->start;
84
85 $config{url} = $url->as_string;
86 $config_file->spew(encode_json(\%config));
87
88 print "$url\n";
89
90 AnyEvent->condvar->recv;