2 #***************************************************************************
4 # Project ___| | | | _ \| |
6 # | (__| |_| | _ <| |___
7 # \___|\___/|_| \_\_____|
9 # Copyright (C) 1998 - 2013, Daniel Stenberg, <daniel@haxx.se>, et al.
11 # This software is licensed as described in the file COPYING, which
12 # you should have received as part of this distribution. The terms
13 # are also available at http://curl.haxx.se/docs/copyright.html.
15 # You may opt to use, copy, modify, merge, publish, distribute and/or sell
16 # copies of the Software, and permit persons to whom the Software is
17 # furnished to do so, under the terms of the COPYING file.
19 # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
20 # KIND, either express or implied.
22 ###########################################################################
24 # This is a server designed for the curl test suite.
26 # In December 2009 we started remaking the server to support more protocols
27 # that are similar in spirit. Like POP3, IMAP and SMTP in addition to the FTP
28 # it already supported since a long time. Note that it still only supports one
29 # protocol per invoke. You need to start multiple servers to support multiple
30 # protocols simultaneously.
32 # It is meant to exercise curl, it is not meant to be a fully working
33 # or even very standard compliant server.
35 # You may optionally specify port on the command line, otherwise it'll
36 # default to port 8921.
38 # All socket/network/TCP related stuff is done by the 'sockfilt' program.
42 push(@INC, $ENV{'srcdir'}) if(defined $ENV{'srcdir'});
44 # sub second timestamping needs Time::HiRes
48 import Time::HiRes qw( gettimeofday );
58 require "directories.pm";
70 #**********************************************************************
73 my $verbose = 0; # set to 1 for debugging
74 my $idstr = ""; # server instance string
75 my $idnum = 1; # server instance number
76 my $ipvnum = 4; # server IPv number (4 or 6)
77 my $proto = 'ftp'; # default server protocol
78 my $srcdir; # directory where ftpserver.pl is located
79 my $srvrname; # server name for presentation purposes
82 my $logdir = $path .'/log';
84 #**********************************************************************
85 # global vars used for server address and primary listener port
87 my $port = 8921; # default primary listener port
88 my $listenaddr = '127.0.0.1'; # default address for listener port
90 #**********************************************************************
91 # global vars used for file names
93 my $pidfile; # server pid file name
94 my $logfile; # server log file name
95 my $mainsockf_pidfile; # pid file for primary connection sockfilt process
96 my $mainsockf_logfile; # log file for primary connection sockfilt process
97 my $datasockf_pidfile; # pid file for secondary connection sockfilt process
98 my $datasockf_logfile; # log file for secondary connection sockfilt process
100 #**********************************************************************
101 # global vars used for server logs advisor read lock handling
103 my $SERVERLOGS_LOCK = 'log/serverlogs.lock';
104 my $serverlogslocked = 0;
106 #**********************************************************************
107 # global vars used for child processes PID tracking
109 my $sfpid; # PID for primary connection sockfilt process
110 my $slavepid; # PID for secondary connection sockfilt process
112 #**********************************************************************
113 # global typeglob filehandle vars to read/write from/to sockfilters
115 local *SFREAD; # used to read from primary connection
116 local *SFWRITE; # used to write to primary connection
117 local *DREAD; # used to read from secondary connection
118 local *DWRITE; # used to write to secondary connection
120 my $sockfilt_timeout = 5; # default timeout for sockfilter eXsysreads
122 #**********************************************************************
123 # global vars which depend on server protocol selection
125 my %commandfunc; # protocol command specific function callbacks
126 my %displaytext; # text returned to client before callback runs
128 #**********************************************************************
129 # global vars customized for each test from the server commands file
131 my $ctrldelay; # set if server should throttle ctrl stream
132 my $datadelay; # set if server should throttle data stream
133 my $retrweirdo; # set if ftp server should use RETRWEIRDO
134 my $retrnosize; # set if ftp server should use RETRNOSIZE
135 my $pasvbadip; # set if ftp server should use PASVBADIP
136 my $nosave; # set if ftp server should not save uploaded data
137 my $nodataconn; # set if ftp srvr doesn't establish or accepts data channel
138 my $nodataconn425; # set if ftp srvr doesn't establish data ch and replies 425
139 my $nodataconn421; # set if ftp srvr doesn't establish data ch and replies 421
140 my $nodataconn150; # set if ftp srvr doesn't establish data ch and replies 150
141 my $support_capa; # set if server supports capability command
142 my $support_auth; # set if server supports authentication command
147 #**********************************************************************
148 # global variables for to test ftp wildcardmatching or other test that
149 # need flexible LIST responses.. and corresponding files.
150 # $ftptargetdir is keeping the fake "name" of LIST directory.
152 my $ftplistparserstate;
155 #**********************************************************************
156 # global variables used when running a ftp server to keep state info
157 # relative to the secondary or data sockfilt process. Values of these
158 # variables should only be modified using datasockf_state() sub, given
159 # that they are closely related and relationship is a bit awkward.
161 my $datasockf_state = 'STOPPED'; # see datasockf_state() sub
162 my $datasockf_mode = 'none'; # ['none','active','passive']
163 my $datasockf_runs = 'no'; # ['no','yes']
164 my $datasockf_conn = 'no'; # ['no','yes']
166 #**********************************************************************
167 # global vars used for signal handling
169 my $got_exit_signal = 0; # set if program should finish execution ASAP
170 my $exit_signal; # first signal handled in exit_signal_handler
172 #**********************************************************************
173 # exit_signal_handler will be triggered to indicate that the program
174 # should finish its execution in a controlled way as soon as possible.
175 # For now, program will also terminate from within this handler.
177 sub exit_signal_handler {
179 # For now, simply mimic old behavior.
180 killsockfilters($proto, $ipvnum, $idnum, $verbose);
182 if($serverlogslocked) {
183 $serverlogslocked = 0;
184 clear_advisor_read_lock($SERVERLOGS_LOCK);
189 #**********************************************************************
190 # logmsg is general message logging subroutine for our test servers.
194 # sub second timestamping needs Time::HiRes
195 if($Time::HiRes::VERSION) {
196 my ($seconds, $usec) = gettimeofday();
197 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
199 $now = sprintf("%02d:%02d:%02d.%06d ", $hour, $min, $sec, $usec);
202 my $seconds = time();
203 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
205 $now = sprintf("%02d:%02d:%02d ", $hour, $min, $sec);
207 if(open(LOGFILEFH, ">>$logfile")) {
208 print LOGFILEFH $now;
215 # append to the server.input file
216 open(INPUT, ">>log/server$idstr.input") ||
217 logmsg "failed to open log/server$idstr.input\n";
222 # use this, open->print->close system only to make the file
223 # open as little as possible, to make the test suite run
224 # better on windows/cygwin
227 #**********************************************************************
228 # eXsysread is a wrapper around perl's sysread() function. This will
229 # repeat the call to sysread() until it has actually read the complete
230 # number of requested bytes or an unrecoverable condition occurs.
231 # On success returns a positive value, the number of bytes requested.
232 # On failure or timeout returns zero.
238 my $timeout = shift; # A zero timeout disables eXsysread() time limit
240 my $time_limited = 0;
241 my $timeout_rest = 0;
248 if((not defined $nbytes) || ($nbytes < 1)) {
249 logmsg "Error: eXsysread() failure: " .
250 "length argument must be positive\n";
253 if((not defined $timeout) || ($timeout < 0)) {
254 logmsg "Error: eXsysread() failure: " .
255 "timeout argument must be zero or positive\n";
259 # caller sets eXsysread() time limit
261 $timeout_rest = $timeout;
262 $start_time = int(time());
265 while($nread < $nbytes) {
268 local $SIG{ALRM} = sub { die "alarm\n"; };
270 $rc = sysread($FH, $$scalar, $nbytes - $nread, $nread);
273 $timeout_rest = $timeout - (int(time()) - $start_time);
274 if($timeout_rest < 1) {
275 logmsg "Error: eXsysread() failure: timed out\n";
280 $rc = sysread($FH, $$scalar, $nbytes - $nread, $nread);
282 if($got_exit_signal) {
283 logmsg "Error: eXsysread() failure: signalled to die\n";
286 if(not defined $rc) {
288 logmsg "Warning: retrying sysread() interrupted system call\n";
292 logmsg "Warning: retrying sysread() due to EAGAIN\n";
295 if($!{EWOULDBLOCK}) {
296 logmsg "Warning: retrying sysread() due to EWOULDBLOCK\n";
299 logmsg "Error: sysread() failure: $!\n";
303 logmsg "Error: sysread() failure: returned negative value $rc\n";
307 logmsg "Error: sysread() failure: read zero bytes\n";
315 #**********************************************************************
316 # read_mainsockf attempts to read the given amount of output from the
317 # sockfilter which is in use for the main or primary connection. This
318 # reads untranslated sockfilt lingo which may hold data read from the
319 # main or primary socket. On success returns 1, otherwise zero.
324 my $timeout = shift; # Optional argument, if zero blocks indefinitively
327 if(not defined $timeout) {
328 $timeout = $sockfilt_timeout + ($nbytes >> 12);
330 if(eXsysread($FH, $scalar, $nbytes, $timeout) != $nbytes) {
331 my ($fcaller, $lcaller) = (caller)[1,2];
332 logmsg "Error: read_mainsockf() failure at $fcaller " .
333 "line $lcaller. Due to eXsysread() failure\n";
339 #**********************************************************************
340 # read_datasockf attempts to read the given amount of output from the
341 # sockfilter which is in use for the data or secondary connection. This
342 # reads untranslated sockfilt lingo which may hold data read from the
343 # data or secondary socket. On success returns 1, otherwise zero.
348 my $timeout = shift; # Optional argument, if zero blocks indefinitively
351 if(not defined $timeout) {
352 $timeout = $sockfilt_timeout + ($nbytes >> 12);
354 if(eXsysread($FH, $scalar, $nbytes, $timeout) != $nbytes) {
355 my ($fcaller, $lcaller) = (caller)[1,2];
356 logmsg "Error: read_datasockf() failure at $fcaller " .
357 "line $lcaller. Due to eXsysread() failure\n";
371 $result = sysread($$FH, $$scalar, $length);
373 if(not defined $result) {
374 ($fcaller, $lcaller) = (caller)[1,2];
375 logmsg "Failed to read input\n";
376 logmsg "Error: $srvrname server, sysread error: $!\n";
377 logmsg "Exited from sysread_or_die() at $fcaller " .
378 "line $lcaller. $srvrname server, sysread error: $!\n";
379 killsockfilters($proto, $ipvnum, $idnum, $verbose);
381 if($serverlogslocked) {
382 $serverlogslocked = 0;
383 clear_advisor_read_lock($SERVERLOGS_LOCK);
387 elsif($result == 0) {
388 ($fcaller, $lcaller) = (caller)[1,2];
389 logmsg "Failed to read input\n";
390 logmsg "Error: $srvrname server, read zero\n";
391 logmsg "Exited from sysread_or_die() at $fcaller " .
392 "line $lcaller. $srvrname server, read zero\n";
393 killsockfilters($proto, $ipvnum, $idnum, $verbose);
395 if($serverlogslocked) {
396 $serverlogslocked = 0;
397 clear_advisor_read_lock($SERVERLOGS_LOCK);
406 my $mainsockfcmd = "./server/sockfilt " .
407 "--ipv$ipvnum --port $port " .
408 "--pidfile \"$mainsockf_pidfile\" " .
409 "--logfile \"$mainsockf_logfile\"";
410 $sfpid = open2(*SFREAD, *SFWRITE, $mainsockfcmd);
412 print STDERR "$mainsockfcmd\n" if($verbose);
414 print SFWRITE "PING\n";
416 sysread_or_die(\*SFREAD, \$pong, 5);
418 if($pong !~ /^PONG/) {
419 logmsg "Failed sockfilt command: $mainsockfcmd\n";
420 killsockfilters($proto, $ipvnum, $idnum, $verbose);
422 if($serverlogslocked) {
423 $serverlogslocked = 0;
424 clear_advisor_read_lock($SERVERLOGS_LOCK);
426 die "Failed to start sockfilt!";
434 printf SFWRITE "DATA\n%04x\n", length($l);
440 sub sockfiltsecondary {
443 printf DWRITE "DATA\n%04x\n", length($l);
449 # Send data to the client on the control stream, which happens to be plain
454 # spit it all out at once
458 my $a = join("", @_);
459 my @a = split("", $a);
463 select(undef, undef, undef, 0.01);
475 #**********************************************************************
476 # Send data to the FTP client on the data stream when data connection
477 # is actually established. Given that this sub should only be called
478 # when a data connection is supposed to be established, calling this
479 # without a data connection is an indication of weak logic somewhere.
483 if($datasockf_conn eq 'no') {
484 logmsg "WARNING: Detected data sending attempt without DATA channel\n";
486 logmsg "WARNING: Data swallowed: $l\n"
492 # spit it all out at once
493 sockfiltsecondary $l;
496 # pause between each byte
498 sockfiltsecondary $_;
499 select(undef, undef, undef, 0.01);
505 #**********************************************************************
506 # protocolsetup initializes the 'displaytext' and 'commandfunc' hashes
507 # for the given protocol. References to protocol command callbacks are
508 # stored in 'commandfunc' hash, and text which will be returned to the
509 # client before the command callback runs is stored in 'displaytext'.
514 if($proto eq 'ftp') {
516 'PORT' => \&PORT_ftp,
517 'EPRT' => \&PORT_ftp,
518 'LIST' => \&LIST_ftp,
519 'NLST' => \&NLST_ftp,
520 'PASV' => \&PASV_ftp,
523 'EPSV' => \&PASV_ftp,
524 'RETR' => \&RETR_ftp,
525 'SIZE' => \&SIZE_ftp,
526 'REST' => \&REST_ftp,
527 'STOR' => \&STOR_ftp,
528 'APPE' => \&STOR_ftp, # append looks like upload
529 'MDTM' => \&MDTM_ftp,
532 'USER' => '331 We are happy you popped in!',
533 'PASS' => '230 Welcome you silly person',
534 'PORT' => '200 You said PORT - I say FINE',
535 'TYPE' => '200 I modify TYPE as you wanted',
536 'LIST' => '150 here comes a directory',
537 'NLST' => '150 here comes a directory',
538 'CWD' => '250 CWD command successful.',
539 'SYST' => '215 UNIX Type: L8', # just fake something
540 'QUIT' => '221 bye bye baby', # just reply something
541 'MKD' => '257 Created your requested directory',
542 'REST' => '350 Yeah yeah we set it there for you',
543 'DELE' => '200 OK OK OK whatever you say',
544 'RNFR' => '350 Received your order. Please provide more',
545 'RNTO' => '250 Ok, thanks. File renaming completed.',
546 'NOOP' => '200 Yes, I\'m very good at doing nothing.',
547 'PBSZ' => '500 PBSZ not implemented',
548 'PROT' => '500 PROT not implemented',
549 'welcome' => join("",
550 '220- _ _ ____ _ '."\r\n",
551 '220- ___| | | | _ \| | '."\r\n",
552 '220- / __| | | | |_) | | '."\r\n",
553 '220- | (__| |_| | _ <| |___ '."\r\n",
554 '220 \___|\___/|_| \_\_____|'."\r\n")
557 elsif($proto eq 'pop3') {
559 'CAPA' => \&CAPA_pop3,
560 'AUTH' => \&AUTH_pop3,
561 'RETR' => \&RETR_pop3,
562 'LIST' => \&LIST_pop3,
565 'USER' => '+OK We are happy you popped in!',
566 'PASS' => '+OK Access granted',
567 'QUIT' => '+OK byebye',
568 'welcome' => join("",
569 ' _ _ ____ _ '."\r\n",
570 ' ___| | | | _ \| | '."\r\n",
571 ' / __| | | | |_) | | '."\r\n",
572 ' | (__| |_| | _ <| |___ '."\r\n",
573 ' \___|\___/|_| \_\_____|'."\r\n",
574 '+OK cURL POP3 server ready to serve'."\r\n")
577 elsif($proto eq 'imap') {
579 'APPEND' => \&APPEND_imap,
580 'CAPABILITY' => \&CAPABILITY_imap,
581 'EXAMINE' => \&EXAMINE_imap,
582 'FETCH' => \&FETCH_imap,
583 'LIST' => \&LIST_imap,
584 'LOGOUT' => \&LOGOUT_imap,
585 'SELECT' => \&SELECT_imap,
586 'STATUS' => \&STATUS_imap,
587 'STORE' => \&STORE_imap
590 'LOGIN' => ' OK LOGIN completed',
591 'welcome' => join("",
592 ' _ _ ____ _ '."\r\n",
593 ' ___| | | | _ \| | '."\r\n",
594 ' / __| | | | |_) | | '."\r\n",
595 ' | (__| |_| | _ <| |___ '."\r\n",
596 ' \___|\___/|_| \_\_____|'."\r\n",
597 '* OK cURL IMAP server ready to serve'."\r\n")
600 elsif($proto eq 'smtp') {
602 'DATA' => \&DATA_smtp,
603 'RCPT' => \&RCPT_smtp,
606 'EHLO' => "250-SIZE\r\n250 Welcome visitor, stay a while staaaaaay forever",
607 'MAIL' => '200 Note taken',
608 'RCPT' => '200 Receivers accepted',
609 'QUIT' => '200 byebye',
610 'welcome' => join("",
611 '220- _ _ ____ _ '."\r\n",
612 '220- ___| | | | _ \| | '."\r\n",
613 '220- / __| | | | |_) | | '."\r\n",
614 '220- | (__| |_| | _ <| |___ '."\r\n",
615 '220 \___|\___/|_| \_\_____|'."\r\n")
621 my ($closed)=@_; # non-zero if already disconnected
623 my $datapid = processexists($datasockf_pidfile);
625 logmsg "=====> Closing $datasockf_mode DATA connection...\n";
629 logmsg "Server disconnects $datasockf_mode DATA connection\n";
630 print DWRITE "DISC\n";
632 sysread DREAD, $i, 5;
635 logmsg "Server finds $datasockf_mode DATA connection already ".
640 logmsg "Server knows $datasockf_mode DATA connection is already ".
645 print DWRITE "QUIT\n";
646 waitpid($datapid, 0);
647 unlink($datasockf_pidfile) if(-f $datasockf_pidfile);
648 logmsg "DATA sockfilt for $datasockf_mode data channel quits ".
652 logmsg "DATA sockfilt for $datasockf_mode data channel already ".
656 logmsg "=====> Closed $datasockf_mode DATA connection\n";
658 datasockf_state('STOPPED');
662 ################ SMTP commands
671 if($smtp_rcpt =~ /^TO:(.*)/) {
678 if($testno eq "<verifiedserver>") {
679 sendcontrol "554 WE ROOLZ: $$\r\n";
680 return 0; # don't wait for data now
683 $testno =~ s/^([^0-9]*)([0-9]+).*/$2/;
684 sendcontrol "354 Show me the mail\r\n";
687 logmsg "===> rcpt $testno was $smtp_rcpt\n";
689 my $filename = "log/upload.$testno";
691 logmsg "Store test number $testno in $filename\n";
693 open(FILE, ">$filename") ||
694 return 0; # failed to open output
700 while (5 == (sysread \*SFREAD, $line, 5)) {
701 if($line eq "DATA\n") {
704 sysread \*SFREAD, $i, 5;
707 if($i =~ /^([0-9a-fA-F]{4})\n/) {
711 read_mainsockf(\$line, $size);
714 print FILE $line if(!$nosave);
717 if($raw =~ /\x0d\x0a\x2e\x0d\x0a/) {
718 # end of data marker!
721 logmsg "> Appending $size bytes to file\n";
723 logmsg "Found SMTP EOB marker\n";
727 elsif($line eq "DISC\n") {
733 logmsg "No support for: $line";
738 print FILE "$ulsize bytes would've been stored here\n";
741 sendcontrol "250 OK, data received!\r\n";
742 logmsg "received $ulsize bytes upload\n";
753 ################ IMAP commands
756 # global to allow the command functions to read it
759 # what was picked by SELECT
762 # Any IMAP parameter can come in escaped and in double quotes.
763 # This function is dumb (so far) and just removes the quotes if present.
764 sub fix_imap_params {
766 $_ = $1 if /^"(.*)"$/;
770 sub CAPABILITY_imap {
775 sendcontrol "$cmdid BAD Command\r\n";
778 $data = "* CAPABILITY IMAP4";
780 $data .= " AUTH=UNKNOWN";
782 $data .= " pingpong test server\r\n";
785 sendcontrol "$cmdid OK CAPABILITY completed\r\n";
793 fix_imap_params($testno);
795 logmsg "SELECT_imap got test $testno\n";
797 # Example from RFC 3501, 6.3.1. SELECT Command
798 sendcontrol "* 172 EXISTS\r\n";
799 sendcontrol "* 1 RECENT\r\n";
800 sendcontrol "* OK [UNSEEN 12] Message 12 is first unseen\r\n";
801 sendcontrol "* OK [UIDVALIDITY 3857529045] UIDs valid\r\n";
802 sendcontrol "* OK [UIDNEXT 4392] Predicted next UID\r\n";
803 sendcontrol "* FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)\r\n";
804 sendcontrol "* OK [PERMANENTFLAGS (\\Deleted \\Seen \\*)] Limited\r\n";
805 sendcontrol "$cmdid OK [READ-WRITE] SELECT completed\r\n";
814 my ($uid, $how) = split(/ /, $args, 2);
817 fix_imap_params($uid, $how);
819 logmsg "FETCH_imap got $args\n";
821 if($selected eq "verifiedserver") {
822 # this is the secret command that verifies that this actually is
823 # the curl test server
824 my $response = "WE ROOLZ: $$\r\n";
826 print STDERR "FTPD: We returned proof we are the test server\n";
828 $data[0] = $response;
829 logmsg "return proof we are we\n";
832 logmsg "retrieve a mail\n";
834 my $testno = $selected;
835 $testno =~ s/^([^0-9]*)//;
837 if ($testno > 10000) {
838 $testpart = $testno % 10000;
839 $testno = int($testno / 10000);
843 loadtest("$srcdir/data/test$testno");
845 @data = getpart("reply", "data$testpart");
852 sendcontrol "* $uid FETCH ($how {$size}\r\n";
859 sendcontrol "$cmdid OK FETCH completed\r\n";
867 logmsg "APPEND_imap got $args\r\n";
869 $args =~ /^([^ ]+) [^{]*\{(\d+)\}$/;
870 my ($folder, $size) = ($1, $2);
871 fix_imap_params($folder);
873 sendcontrol "+ Ready for literal data\r\n";
875 my $testno = $folder;
876 my $filename = "log/upload.$testno";
878 logmsg "Store test number $testno in $filename\n";
880 open(FILE, ">$filename") ||
881 return 0; # failed to open output
885 while(5 == (sysread \*SFREAD, $line, 5)) {
886 if($line eq "DATA\n") {
887 sysread \*SFREAD, $line, 5;
890 if($line =~ /^([0-9a-fA-F]{4})\n/) {
891 $chunksize = hex($1);
894 read_mainsockf(\$line, $chunksize);
896 my $left = $size - $received;
897 my $datasize = ($left > $chunksize) ? $chunksize : $left;
900 logmsg "> Appending $datasize bytes to file\n";
901 print FILE substr($line, 0, $datasize) if(!$nosave);
902 $line = substr($line, $datasize);
904 $received += $datasize;
905 if($received == $size) {
906 logmsg "Received all data, waiting for final CRLF.\n";
910 if($received == $size && $line eq "\r\n") {
914 elsif($line eq "DISC\n") {
915 logmsg "Unexpected disconnect!\n";
919 logmsg "No support for: $line";
925 print FILE "$size bytes would've been stored here\n";
929 logmsg "received $size bytes upload\n";
931 sendcontrol "$cmdid OK APPEND completed\r\n";
938 my ($uid, $what) = split(/ /, $args, 2);
939 fix_imap_params($uid);
941 logmsg "STORE_imap got $args\n";
943 sendcontrol "* $uid FETCH (FLAGS (\\Seen \\Deleted))\r\n";
944 sendcontrol "$cmdid OK STORE completed\r\n";
951 my ($reference, $mailbox) = split(/ /, $args, 2);
953 fix_imap_params($reference, $mailbox);
955 logmsg "LIST_imap got $args\n";
957 if ($reference eq "verifiedserver") {
958 # this is the secret command that verifies that this actually is
959 # the curl test server
960 @data = ("* LIST () \"/\" \"WE ROOLZ: $$\"\r\n");
962 print STDERR "FTPD: We returned proof we are the test server\n";
964 logmsg "return proof we are we\n";
967 my $testno = $reference;
968 $testno =~ s/^([^0-9]*)//;
970 if ($testno > 10000) {
971 $testpart = $testno % 10000;
972 $testno = int($testno / 10000);
975 loadtest("$srcdir/data/test$testno");
977 @data = getpart("reply", "data$testpart");
984 sendcontrol "$cmdid OK LIST Completed\r\n";
991 fix_imap_params($testno);
993 logmsg "EXAMINE_imap got test $testno\n";
995 # Example from RFC 3501, 6.3.2. EXAMINE Command
996 sendcontrol "* 17 EXISTS\r\n";
997 sendcontrol "* 2 RECENT\r\n";
998 sendcontrol "* OK [UNSEEN 8] Message 8 is first unseen\r\n";
999 sendcontrol "* OK [UIDVALIDITY 3857529045] UIDs valid\r\n";
1000 sendcontrol "* OK [UIDNEXT 4392] Predicted next UID\r\n";
1001 sendcontrol "* FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)\r\n";
1002 sendcontrol "* OK [PERMANENTFLAGS ()] No permanent flags permitted\r\n";
1003 sendcontrol "$cmdid OK [READ-ONLY] EXAMINE completed\r\n";
1010 fix_imap_params($testno);
1012 logmsg "STATUS_imap got test $testno\n";
1014 $testno =~ s/[^0-9]//g;
1016 if ($testno > 10000) {
1017 $testpart = $testno % 10000;
1018 $testno = int($testno / 10000);
1021 loadtest("$srcdir/data/test$testno");
1023 my @data = getpart("reply", "data$testpart");
1029 sendcontrol "$cmdid OK STATUS completed\r\n";
1035 sendcontrol "* BYE cURL IMAP server signing off\r\n";
1036 sendcontrol "$cmdid OK LOGOUT completed\r\n";
1042 ################ POP3 commands
1049 if(!$support_capa) {
1050 push @data, "-ERR Unsupported command: 'CAPA'\r\n";
1053 push @data, "+OK List of capabilities follows\r\n";
1054 push @data, "USER\r\n";
1056 push @data, "SASL UNKNOWN\r\n";
1058 push @data, "IMPLEMENTATION POP3 pingpong test server\r\n";
1059 push @data, ".\r\n";
1073 if(!$support_auth) {
1074 push @data, "-ERR Unsupported command: 'AUTH'\r\n";
1077 push @data, "+OK List of supported mechanisms follows\r\n";
1078 push @data, "UNKNOWN\r\n";
1079 push @data, ".\r\n";
1093 if($testno =~ /^verifiedserver$/) {
1094 # this is the secret command that verifies that this actually is
1095 # the curl test server
1096 my $response = "WE ROOLZ: $$\r\n";
1098 print STDERR "FTPD: We returned proof we are the test server\n";
1100 $data[0] = $response;
1101 logmsg "return proof we are we\n";
1104 logmsg "retrieve a mail\n";
1106 $testno =~ s/^([^0-9]*)//;
1108 if ($testno > 10000) {
1109 $testpart = $testno % 10000;
1110 $testno = int($testno / 10000);
1114 loadtest("$srcdir/data/test$testno");
1116 @data = getpart("reply", "data$testpart");
1119 sendcontrol "+OK Mail transfer starts\r\n";
1125 # end with the magic 3-byte end of mail marker, assumes that the
1126 # mail body ends with a CRLF!
1127 sendcontrol ".\r\n";
1134 # this is a built-in fake-message list
1137 "2 4294967400\r\n", # > 4 GB
1138 "4 200\r\n", # Note that message 3 is a simulated "deleted" message
1141 logmsg "retrieve a message list\n";
1143 sendcontrol "+OK Listing starts\r\n";
1145 for my $d (@pop3list) {
1149 # end with the magic 3-byte end of listing marker
1150 sendcontrol ".\r\n";
1156 ################ FTP commands
1161 logmsg "Set REST position to $rest\n"
1164 sub switch_directory_goto {
1165 my $target_dir = $_;
1167 if(!$ftptargetdir) {
1168 $ftptargetdir = "/";
1171 if($target_dir eq "") {
1172 $ftptargetdir = "/";
1174 elsif($target_dir eq "..") {
1175 if($ftptargetdir eq "/") {
1176 $ftptargetdir = "/";
1179 $ftptargetdir =~ s/[[:alnum:]]+\/$//;
1183 $ftptargetdir .= $target_dir . "/";
1187 sub switch_directory {
1188 my $target_dir = $_[0];
1190 if($target_dir eq "/") {
1191 $ftptargetdir = "/";
1194 my @dirs = split("/", $target_dir);
1196 switch_directory_goto($_);
1202 my ($folder, $fullcommand) = $_[0];
1203 switch_directory($folder);
1204 if($ftptargetdir =~ /^\/fully_simulated/) {
1205 $ftplistparserstate = "enabled";
1208 undef $ftplistparserstate;
1214 $mydir = $ftptargetdir ? $ftptargetdir : "/";
1219 sendcontrol "257 \"$mydir\" is current directory\r\n";
1223 # print "150 ASCII data connection for /bin/ls (193.15.23.1,59196) (0 bytes)\r\n";
1225 # this is a built-in fake-dir ;-)
1226 my @ftpdir=("total 20\r\n",
1227 "drwxr-xr-x 8 98 98 512 Oct 22 13:06 .\r\n",
1228 "drwxr-xr-x 8 98 98 512 Oct 22 13:06 ..\r\n",
1229 "drwxr-xr-x 2 98 98 512 May 2 1996 .NeXT\r\n",
1230 "-r--r--r-- 1 0 1 35 Jul 16 1996 README\r\n",
1231 "lrwxrwxrwx 1 0 1 7 Dec 9 1999 bin -> usr/bin\r\n",
1232 "dr-xr-xr-x 2 0 1 512 Oct 1 1997 dev\r\n",
1233 "drwxrwxrwx 2 98 98 512 May 29 16:04 download.html\r\n",
1234 "dr-xr-xr-x 2 0 1 512 Nov 30 1995 etc\r\n",
1235 "drwxrwxrwx 2 98 1 512 Oct 30 14:33 pub\r\n",
1236 "dr-xr-xr-x 5 0 1 512 Oct 1 1997 usr\r\n");
1238 if($datasockf_conn eq 'no') {
1239 if($nodataconn425) {
1240 sendcontrol "150 Opening data connection\r\n";
1241 sendcontrol "425 Can't open data connection\r\n";
1243 elsif($nodataconn421) {
1244 sendcontrol "150 Opening data connection\r\n";
1245 sendcontrol "421 Connection timed out\r\n";
1247 elsif($nodataconn150) {
1248 sendcontrol "150 Opening data connection\r\n";
1249 # client shall timeout
1252 # client shall timeout
1257 if($ftplistparserstate) {
1258 @ftpdir = ftp_contentlist($ftptargetdir);
1261 logmsg "pass LIST data on data connection\n";
1266 sendcontrol "226 ASCII transfer complete\r\n";
1271 my @ftpdir=("file", "with space", "fake", "..", " ..", "funny", "README");
1273 if($datasockf_conn eq 'no') {
1274 if($nodataconn425) {
1275 sendcontrol "150 Opening data connection\r\n";
1276 sendcontrol "425 Can't open data connection\r\n";
1278 elsif($nodataconn421) {
1279 sendcontrol "150 Opening data connection\r\n";
1280 sendcontrol "421 Connection timed out\r\n";
1282 elsif($nodataconn150) {
1283 sendcontrol "150 Opening data connection\r\n";
1284 # client shall timeout
1287 # client shall timeout
1292 logmsg "pass NLST data on data connection\n";
1297 sendcontrol "226 ASCII transfer complete\r\n";
1304 if ($testno > 10000) {
1305 $testpart = $testno % 10000;
1306 $testno = int($testno / 10000);
1309 loadtest("$srcdir/data/test$testno");
1311 my @data = getpart("reply", "mdtm");
1313 my $reply = $data[0];
1314 chomp $reply if($reply);
1316 if($reply && ($reply =~ /^[+-]?\d+$/) && ($reply < 0)) {
1317 sendcontrol "550 $testno: no such file.\r\n";
1320 sendcontrol "$reply\r\n";
1323 sendcontrol "500 MDTM: no such command.\r\n";
1330 if($ftplistparserstate) {
1331 my $size = wildcard_filesize($ftptargetdir, $testno);
1333 sendcontrol "550 $testno: No such file or directory.\r\n";
1336 sendcontrol "213 $size\r\n";
1341 if($testno =~ /^verifiedserver$/) {
1342 my $response = "WE ROOLZ: $$\r\n";
1343 my $size = length($response);
1344 sendcontrol "213 $size\r\n";
1348 if($testno =~ /(\d+)\/?$/) {
1352 print STDERR "SIZE_ftp: invalid test number: $testno\n";
1357 if($testno > 10000) {
1358 $testpart = $testno % 10000;
1359 $testno = int($testno / 10000);
1362 loadtest("$srcdir/data/test$testno");
1364 my @data = getpart("reply", "size");
1366 my $size = $data[0];
1370 sendcontrol "213 $size\r\n";
1373 sendcontrol "550 $testno: No such file or directory.\r\n";
1378 @data = getpart("reply", "data$testpart");
1380 $size += length($_);
1383 sendcontrol "213 $size\r\n";
1386 sendcontrol "550 $testno: No such file or directory.\r\n";
1395 if($datasockf_conn eq 'no') {
1396 if($nodataconn425) {
1397 sendcontrol "150 Opening data connection\r\n";
1398 sendcontrol "425 Can't open data connection\r\n";
1400 elsif($nodataconn421) {
1401 sendcontrol "150 Opening data connection\r\n";
1402 sendcontrol "421 Connection timed out\r\n";
1404 elsif($nodataconn150) {
1405 sendcontrol "150 Opening data connection\r\n";
1406 # client shall timeout
1409 # client shall timeout
1414 if($ftplistparserstate) {
1415 my @content = wildcard_getfile($ftptargetdir, $testno);
1416 if($content[0] == -1) {
1420 my $size = length $content[1];
1421 sendcontrol "150 Binary data connection for $testno ($size bytes).\r\n",
1422 senddata $content[1];
1424 sendcontrol "226 File transfer complete\r\n";
1429 if($testno =~ /^verifiedserver$/) {
1430 # this is the secret command that verifies that this actually is
1431 # the curl test server
1432 my $response = "WE ROOLZ: $$\r\n";
1433 my $len = length($response);
1434 sendcontrol "150 Binary junk ($len bytes).\r\n";
1435 senddata "WE ROOLZ: $$\r\n";
1437 sendcontrol "226 File transfer complete\r\n";
1439 print STDERR "FTPD: We returned proof we are the test server\n";
1444 $testno =~ s/^([^0-9]*)//;
1446 if ($testno > 10000) {
1447 $testpart = $testno % 10000;
1448 $testno = int($testno / 10000);
1451 loadtest("$srcdir/data/test$testno");
1453 my @data = getpart("reply", "data$testpart");
1457 $size += length($_);
1460 my %hash = getpartattr("reply", "data$testpart");
1462 if($size || $hash{'sendzero'}) {
1465 # move read pointer forward
1467 logmsg "REST $rest was removed from size, makes $size left\n";
1468 $rest = 0; # reset REST offset again
1471 sendcontrol "150 Binary data connection for $testno () ($size bytes).\r\n",
1472 "226 File transfer complete\r\n";
1479 $retrweirdo=0; # switch off the weirdo again!
1482 my $sz = "($size bytes)";
1487 sendcontrol "150 Binary data connection for $testno () $sz.\r\n";
1494 sendcontrol "226 File transfer complete\r\n";
1498 sendcontrol "550 $testno: No such file or directory.\r\n";
1506 my $filename = "log/upload.$testno";
1508 if($datasockf_conn eq 'no') {
1509 if($nodataconn425) {
1510 sendcontrol "150 Opening data connection\r\n";
1511 sendcontrol "425 Can't open data connection\r\n";
1513 elsif($nodataconn421) {
1514 sendcontrol "150 Opening data connection\r\n";
1515 sendcontrol "421 Connection timed out\r\n";
1517 elsif($nodataconn150) {
1518 sendcontrol "150 Opening data connection\r\n";
1519 # client shall timeout
1522 # client shall timeout
1527 logmsg "STOR test number $testno in $filename\n";
1529 sendcontrol "125 Gimme gimme gimme!\r\n";
1531 open(FILE, ">$filename") ||
1532 return 0; # failed to open output
1537 while (5 == (sysread DREAD, $line, 5)) {
1538 if($line eq "DATA\n") {
1540 sysread DREAD, $i, 5;
1543 if($i =~ /^([0-9a-fA-F]{4})\n/) {
1547 read_datasockf(\$line, $size);
1549 #print STDERR " GOT: $size bytes\n";
1552 print FILE $line if(!$nosave);
1553 logmsg "> Appending $size bytes to file\n";
1555 elsif($line eq "DISC\n") {
1561 logmsg "No support for: $line";
1566 print FILE "$ulsize bytes would've been stored here\n";
1569 close_dataconn($disc);
1570 logmsg "received $ulsize bytes upload\n";
1571 sendcontrol "226 File transfer complete\r\n";
1578 my $bindonly = ($nodataconn) ? '--bindonly' : '';
1580 # kill previous data connection sockfilt when alive
1581 if($datasockf_runs eq 'yes') {
1582 killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
1583 logmsg "DATA sockfilt for $datasockf_mode data channel killed\n";
1585 datasockf_state('STOPPED');
1587 logmsg "====> Passive DATA channel requested by client\n";
1589 logmsg "DATA sockfilt for passive data channel starting...\n";
1591 # We fire up a new sockfilt to do the data transfer for us.
1592 my $datasockfcmd = "./server/sockfilt " .
1593 "--ipv$ipvnum $bindonly --port 0 " .
1594 "--pidfile \"$datasockf_pidfile\" " .
1595 "--logfile \"$datasockf_logfile\"";
1596 $slavepid = open2(\*DREAD, \*DWRITE, $datasockfcmd);
1599 datasockf_state('PASSIVE_NODATACONN');
1602 datasockf_state('PASSIVE');
1605 print STDERR "$datasockfcmd\n" if($verbose);
1607 print DWRITE "PING\n";
1609 sysread_or_die(\*DREAD, \$pong, 5);
1611 if($pong =~ /^FAIL/) {
1612 logmsg "DATA sockfilt said: FAIL\n";
1613 logmsg "DATA sockfilt for passive data channel failed\n";
1614 logmsg "DATA sockfilt not running\n";
1615 datasockf_state('STOPPED');
1616 sendcontrol "500 no free ports!\r\n";
1619 elsif($pong !~ /^PONG/) {
1620 logmsg "DATA sockfilt unexpected response: $pong\n";
1621 logmsg "DATA sockfilt for passive data channel failed\n";
1622 logmsg "DATA sockfilt killed now\n";
1623 killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
1624 logmsg "DATA sockfilt not running\n";
1625 datasockf_state('STOPPED');
1626 sendcontrol "500 no free ports!\r\n";
1630 logmsg "DATA sockfilt for passive data channel started (pid $slavepid)\n";
1632 # Find out on what port we listen on or have bound
1634 print DWRITE "PORT\n";
1636 # READ the response code
1637 sysread_or_die(\*DREAD, \$i, 5);
1639 # READ the response size
1640 sysread_or_die(\*DREAD, \$i, 5);
1643 if($i =~ /^([0-9a-fA-F]{4})\n/) {
1647 # READ the response data
1648 read_datasockf(\$i, $size);
1650 # The data is in the format
1653 if($i =~ /IPv(\d)\/(\d+)/) {
1654 # FIX: deal with IP protocol version
1659 logmsg "DATA sockfilt unknown listener port\n";
1660 logmsg "DATA sockfilt for passive data channel failed\n";
1661 logmsg "DATA sockfilt killed now\n";
1662 killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
1663 logmsg "DATA sockfilt not running\n";
1664 datasockf_state('STOPPED');
1665 sendcontrol "500 no free ports!\r\n";
1670 my $str = nodataconn_str();
1671 logmsg "DATA sockfilt for passive data channel ($str) bound on port ".
1675 logmsg "DATA sockfilt for passive data channel listens on port ".
1679 if($cmd ne "EPSV") {
1686 sendcontrol sprintf("227 Entering Passive Mode ($p,%d,%d)\n",
1687 int($pasvport/256), int($pasvport%256));
1691 sendcontrol sprintf("229 Entering Passive Mode (|||%d|)\n", $pasvport);
1694 logmsg "Client has been notified that DATA conn ".
1695 "will be accepted on port $pasvport\n";
1698 my $str = nodataconn_str();
1699 logmsg "====> Client fooled ($str)\n";
1704 local $SIG{ALRM} = sub { die "alarm\n" };
1706 # assume swift operations unless explicitly slow
1707 alarm ($datadelay?20:10);
1712 # FIX: Monitor ctrl conn for disconnect
1714 while(sysread(DREAD, $input, 5)) {
1716 if($input !~ /^CNCT/) {
1717 # we wait for a connected client
1718 logmsg "Odd, we got $input from client\n";
1721 logmsg "Client connects to port $pasvport\n";
1728 logmsg "$srvrname server timed out awaiting data connection ".
1729 "on port $pasvport\n";
1730 logmsg "accept failed or connection not even attempted\n";
1731 logmsg "DATA sockfilt killed now\n";
1732 killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
1733 logmsg "DATA sockfilt not running\n";
1734 datasockf_state('STOPPED');
1738 logmsg "====> Client established passive DATA connection ".
1739 "on port $pasvport\n";
1746 # Support both PORT and EPRT here.
1750 my ($arg, $cmd) = @_;
1754 # kill previous data connection sockfilt when alive
1755 if($datasockf_runs eq 'yes') {
1756 killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
1757 logmsg "DATA sockfilt for $datasockf_mode data channel killed\n";
1759 datasockf_state('STOPPED');
1761 logmsg "====> Active DATA channel requested by client\n";
1763 # We always ignore the given IP and use localhost.
1765 if($cmd eq "PORT") {
1766 if($arg !~ /(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)/) {
1767 logmsg "DATA sockfilt for active data channel not started ".
1768 "(bad PORT-line: $arg)\n";
1769 sendcontrol "500 silly you, go away\r\n";
1773 $addr = "$1.$2.$3.$4";
1775 # EPRT |2|::1|49706|
1776 elsif($cmd eq "EPRT") {
1777 if($arg !~ /(\d+)\|([^\|]+)\|(\d+)/) {
1778 logmsg "DATA sockfilt for active data channel not started ".
1779 "(bad EPRT-line: $arg)\n";
1780 sendcontrol "500 silly you, go away\r\n";
1783 sendcontrol "200 Thanks for dropping by. We contact you later\r\n";
1788 logmsg "DATA sockfilt for active data channel not started ".
1789 "(invalid command: $cmd)\n";
1790 sendcontrol "500 we don't like $cmd now\r\n";
1794 if(!$port || $port > 65535) {
1795 logmsg "DATA sockfilt for active data channel not started ".
1796 "(illegal PORT number: $port)\n";
1801 my $str = nodataconn_str();
1802 logmsg "DATA sockfilt for active data channel not started ($str)\n";
1803 datasockf_state('ACTIVE_NODATACONN');
1804 logmsg "====> Active DATA channel not established\n";
1808 logmsg "DATA sockfilt for active data channel starting...\n";
1810 # We fire up a new sockfilt to do the data transfer for us.
1811 my $datasockfcmd = "./server/sockfilt " .
1812 "--ipv$ipvnum --connect $port --addr \"$addr\" " .
1813 "--pidfile \"$datasockf_pidfile\" " .
1814 "--logfile \"$datasockf_logfile\"";
1815 $slavepid = open2(\*DREAD, \*DWRITE, $datasockfcmd);
1817 datasockf_state('ACTIVE');
1819 print STDERR "$datasockfcmd\n" if($verbose);
1821 print DWRITE "PING\n";
1823 sysread_or_die(\*DREAD, \$pong, 5);
1825 if($pong =~ /^FAIL/) {
1826 logmsg "DATA sockfilt said: FAIL\n";
1827 logmsg "DATA sockfilt for active data channel failed\n";
1828 logmsg "DATA sockfilt not running\n";
1829 datasockf_state('STOPPED');
1830 # client shall timeout awaiting connection from server
1833 elsif($pong !~ /^PONG/) {
1834 logmsg "DATA sockfilt unexpected response: $pong\n";
1835 logmsg "DATA sockfilt for active data channel failed\n";
1836 logmsg "DATA sockfilt killed now\n";
1837 killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
1838 logmsg "DATA sockfilt not running\n";
1839 datasockf_state('STOPPED');
1840 # client shall timeout awaiting connection from server
1844 logmsg "DATA sockfilt for active data channel started (pid $slavepid)\n";
1846 logmsg "====> Active DATA channel connected to client port $port\n";
1851 #**********************************************************************
1852 # datasockf_state is used to change variables that keep state info
1853 # relative to the FTP secondary or data sockfilt process as soon as
1854 # one of the five possible stable states is reached. Variables that
1855 # are modified by this sub may be checked independently but should
1856 # not be changed except by calling this sub.
1858 sub datasockf_state {
1861 if($state eq 'STOPPED') {
1862 # Data sockfilter initial state, not running,
1863 # not connected and not used.
1864 $datasockf_state = $state;
1865 $datasockf_mode = 'none';
1866 $datasockf_runs = 'no';
1867 $datasockf_conn = 'no';
1869 elsif($state eq 'PASSIVE') {
1870 # Data sockfilter accepted connection from client.
1871 $datasockf_state = $state;
1872 $datasockf_mode = 'passive';
1873 $datasockf_runs = 'yes';
1874 $datasockf_conn = 'yes';
1876 elsif($state eq 'ACTIVE') {
1877 # Data sockfilter has connected to client.
1878 $datasockf_state = $state;
1879 $datasockf_mode = 'active';
1880 $datasockf_runs = 'yes';
1881 $datasockf_conn = 'yes';
1883 elsif($state eq 'PASSIVE_NODATACONN') {
1884 # Data sockfilter bound port without listening,
1885 # client won't be able to establish data connection.
1886 $datasockf_state = $state;
1887 $datasockf_mode = 'passive';
1888 $datasockf_runs = 'yes';
1889 $datasockf_conn = 'no';
1891 elsif($state eq 'ACTIVE_NODATACONN') {
1892 # Data sockfilter does not even run,
1893 # client awaits data connection from server in vain.
1894 $datasockf_state = $state;
1895 $datasockf_mode = 'active';
1896 $datasockf_runs = 'no';
1897 $datasockf_conn = 'no';
1900 die "Internal error. Unknown datasockf state: $state!";
1904 #**********************************************************************
1905 # nodataconn_str returns string of efective nodataconn command. Notice
1906 # that $nodataconn may be set alone or in addition to a $nodataconnXXX.
1908 sub nodataconn_str {
1911 $str = 'NODATACONN' if($nodataconn);
1912 $str = 'NODATACONN425' if($nodataconn425);
1913 $str = 'NODATACONN421' if($nodataconn421);
1914 $str = 'NODATACONN150' if($nodataconn150);
1918 #**********************************************************************
1919 # customize configures test server operation for each curl test, reading
1920 # configuration commands/parameters from server commands file each time
1921 # a new client control connection is established with the test server.
1922 # On success returns 1, otherwise zero.
1925 $ctrldelay = 0; # default is no throttling of the ctrl stream
1926 $datadelay = 0; # default is no throttling of the data stream
1927 $retrweirdo = 0; # default is no use of RETRWEIRDO
1928 $retrnosize = 0; # default is no use of RETRNOSIZE
1929 $pasvbadip = 0; # default is no use of PASVBADIP
1930 $nosave = 0; # default is to actually save uploaded data to file
1931 $nodataconn = 0; # default is to establish or accept data channel
1932 $nodataconn425 = 0; # default is to not send 425 without data channel
1933 $nodataconn421 = 0; # default is to not send 421 without data channel
1934 $nodataconn150 = 0; # default is to not send 150 without data channel
1935 $support_capa = 0; # default is to not support capability command
1936 $support_auth = 0; # default is to not support authentication command
1937 %customreply = (); #
1938 %customcount = (); #
1941 open(CUSTOM, "<log/ftpserver.cmd") ||
1944 logmsg "FTPD: Getting commands from log/ftpserver.cmd\n";
1947 if($_ =~ /REPLY ([A-Za-z0-9+\/=]+) (.*)/) {
1948 $customreply{$1}=eval "qq{$2}";
1949 logmsg "FTPD: set custom reply for $1\n";
1951 elsif($_ =~ /COUNT ([A-Z]+) (.*)/) {
1952 # we blank the customreply for this command when having
1953 # been used this number of times
1954 $customcount{$1}=$2;
1955 logmsg "FTPD: blank custom reply for $1 after $2 uses\n";
1957 elsif($_ =~ /DELAY ([A-Z]+) (\d*)/) {
1959 logmsg "FTPD: delay reply for $1 with $2 seconds\n";
1961 elsif($_ =~ /SLOWDOWN/) {
1964 logmsg "FTPD: send response with 0.01 sec delay between each byte\n";
1966 elsif($_ =~ /RETRWEIRDO/) {
1967 logmsg "FTPD: instructed to use RETRWEIRDO\n";
1970 elsif($_ =~ /RETRNOSIZE/) {
1971 logmsg "FTPD: instructed to use RETRNOSIZE\n";
1974 elsif($_ =~ /PASVBADIP/) {
1975 logmsg "FTPD: instructed to use PASVBADIP\n";
1978 elsif($_ =~ /NODATACONN425/) {
1979 # applies to both active and passive FTP modes
1980 logmsg "FTPD: instructed to use NODATACONN425\n";
1984 elsif($_ =~ /NODATACONN421/) {
1985 # applies to both active and passive FTP modes
1986 logmsg "FTPD: instructed to use NODATACONN421\n";
1990 elsif($_ =~ /NODATACONN150/) {
1991 # applies to both active and passive FTP modes
1992 logmsg "FTPD: instructed to use NODATACONN150\n";
1996 elsif($_ =~ /NODATACONN/) {
1997 # applies to both active and passive FTP modes
1998 logmsg "FTPD: instructed to use NODATACONN\n";
2001 elsif($_ =~ /SUPPORTCAPA/) {
2002 logmsg "FTPD: instructed to support CAPABILITY command\n";
2005 elsif($_ =~ /SUPPORTAUTH/) {
2006 logmsg "FTPD: instructed to support AUTHENTICATION command\n";
2009 elsif($_ =~ /NOSAVE/) {
2010 # don't actually store the file we upload - to be used when
2011 # uploading insanely huge amounts
2013 logmsg "FTPD: NOSAVE prevents saving of uploaded data\n";
2019 #----------------------------------------------------------------------
2020 #----------------------------------------------------------------------
2021 #--------------------------- END OF SUBS ----------------------------
2022 #----------------------------------------------------------------------
2023 #----------------------------------------------------------------------
2025 #**********************************************************************
2026 # Parse command line options
2030 # --verbose # verbose
2031 # --srcdir # source directory
2032 # --id # server instance number
2033 # --proto # server protocol
2034 # --pidfile # server pid file
2035 # --logfile # server log file
2036 # --ipv4 # server IP version 4
2037 # --ipv6 # server IP version 6
2038 # --port # server listener port
2039 # --addr # server address for listener port binding
2042 if($ARGV[0] eq '--verbose') {
2045 elsif($ARGV[0] eq '--srcdir') {
2051 elsif($ARGV[0] eq '--id') {
2052 if($ARGV[1] && ($ARGV[1] =~ /^(\d+)$/)) {
2053 $idnum = $1 if($1 > 0);
2057 elsif($ARGV[0] eq '--proto') {
2058 if($ARGV[1] && ($ARGV[1] =~ /^(ftp|imap|pop3|smtp)$/)) {
2063 die "unsupported protocol $ARGV[1]";
2066 elsif($ARGV[0] eq '--pidfile') {
2068 $pidfile = $ARGV[1];
2072 elsif($ARGV[0] eq '--logfile') {
2074 $logfile = $ARGV[1];
2078 elsif($ARGV[0] eq '--ipv4') {
2080 $listenaddr = '127.0.0.1' if($listenaddr eq '::1');
2082 elsif($ARGV[0] eq '--ipv6') {
2084 $listenaddr = '::1' if($listenaddr eq '127.0.0.1');
2086 elsif($ARGV[0] eq '--port') {
2087 if($ARGV[1] && ($ARGV[1] =~ /^(\d+)$/)) {
2088 $port = $1 if($1 > 1024);
2092 elsif($ARGV[0] eq '--addr') {
2094 my $tmpstr = $ARGV[1];
2095 if($tmpstr =~ /^(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)$/) {
2096 $listenaddr = "$1.$2.$3.$4" if($ipvnum == 4);
2098 elsif($ipvnum == 6) {
2099 $listenaddr = $tmpstr;
2100 $listenaddr =~ s/^\[(.*)\]$/$1/;
2106 print STDERR "\nWarning: ftpserver.pl unknown parameter: $ARGV[0]\n";
2111 #***************************************************************************
2112 # Initialize command line option dependant variables
2116 $srcdir = $ENV{'srcdir'} || '.';
2119 $pidfile = "$path/". server_pidfilename($proto, $ipvnum, $idnum);
2122 $logfile = server_logfilename($logdir, $proto, $ipvnum, $idnum);
2125 $mainsockf_pidfile = "$path/".
2126 mainsockf_pidfilename($proto, $ipvnum, $idnum);
2127 $mainsockf_logfile =
2128 mainsockf_logfilename($logdir, $proto, $ipvnum, $idnum);
2130 if($proto eq 'ftp') {
2131 $datasockf_pidfile = "$path/".
2132 datasockf_pidfilename($proto, $ipvnum, $idnum);
2133 $datasockf_logfile =
2134 datasockf_logfilename($logdir, $proto, $ipvnum, $idnum);
2137 $srvrname = servername_str($proto, $ipvnum, $idnum);
2139 $idstr = "$idnum" if($idnum > 1);
2141 protocolsetup($proto);
2143 $SIG{INT} = \&exit_signal_handler;
2144 $SIG{TERM} = \&exit_signal_handler;
2148 logmsg sprintf("%s server listens on port IPv${ipvnum}/${port}\n", uc($proto));
2150 open(PID, ">$pidfile");
2154 logmsg("logged pid $$ in $pidfile\n");
2159 # kill previous data connection sockfilt when alive
2160 if($datasockf_runs eq 'yes') {
2161 killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
2162 logmsg "DATA sockfilt for $datasockf_mode data channel killed now\n";
2164 datasockf_state('STOPPED');
2167 # We read 'sockfilt' commands.
2171 logmsg "Awaiting input\n";
2172 sysread_or_die(\*SFREAD, \$input, 5);
2174 if($input !~ /^CNCT/) {
2175 # we wait for a connected client
2176 logmsg "MAIN sockfilt said: $input";
2179 logmsg "====> Client connect\n";
2181 set_advisor_read_lock($SERVERLOGS_LOCK);
2182 $serverlogslocked = 1;
2187 &customize(); # read test control instructions
2189 my $welcome = $customreply{"welcome"};
2191 $welcome = $displaytext{"welcome"};
2194 # clear it after use
2195 $customreply{"welcome"}="";
2196 if($welcome !~ /\r\n\z/) {
2200 sendcontrol $welcome;
2202 #remove global variables from last connection
2203 if($ftplistparserstate) {
2204 undef $ftplistparserstate;
2207 undef $ftptargetdir;
2211 print STDERR "OUT: $welcome";
2219 # Now we expect to read DATA\n[hex size]\n[prot], where the [prot]
2220 # part only is FTP lingo.
2223 sysread_or_die(\*SFREAD, \$i, 5);
2226 logmsg "MAIN sockfilt said $i";
2235 sysread_or_die(\*SFREAD, \$i, 5);
2238 if($i =~ /^([0-9a-fA-F]{4})\n/) {
2243 read_mainsockf(\$input, $size);
2249 # Loop until command completion
2250 next unless($full =~ /\r\n$/);
2252 # Remove trailing CRLF.
2253 $full =~ s/[\n\r]+$//;
2257 if($proto eq "imap") {
2258 # IMAP is different with its identifier first on the command line
2259 unless(($full =~ /^([^ ]+) ([^ ]+) (.*)/) ||
2260 ($full =~ /^([^ ]+) ([^ ]+)/)) {
2261 sendcontrol "$1 '$full': command not understood.\r\n";
2264 $cmdid=$1; # set the global variable
2268 elsif($full =~ /^([A-Z]{3,4})(\s(.*))?$/i) {
2272 elsif(($proto eq "smtp") && ($full =~ /^[A-Z0-9+\/]{0,512}={0,2}$/i)) {
2273 # SMTP long "commands" are base64 authentication data.
2278 sendcontrol "500 '$full': command not understood.\r\n";
2282 logmsg "< \"$full\"\n";
2285 print STDERR "IN: $full\n";
2290 my $delay = $delayreply{$FTPCMD};
2292 # just go sleep this many seconds!
2293 logmsg("Sleep for $delay seconds\n");
2294 my $twentieths = $delay * 20;
2295 while($twentieths--) {
2296 select(undef, undef, undef, 0.05) unless($got_exit_signal);
2301 $text = $customreply{$FTPCMD};
2304 if($text && ($text ne "")) {
2305 if($customcount{$FTPCMD} && (!--$customcount{$FTPCMD})) {
2306 # used enough number of times, now blank the customreply
2307 $customreply{$FTPCMD}="";
2311 $text = $displaytext{$FTPCMD};
2314 if($text && ($text ne "")) {
2315 if($cmdid && ($cmdid ne "")) {
2316 sendcontrol "$cmdid$text\r\n";
2319 sendcontrol "$text\r\n";
2323 $check=1; # no response yet
2326 unless($fake && ($fake ne "")) {
2327 # only perform this if we're not faking a reply
2328 my $func = $commandfunc{$FTPCMD};
2330 &$func($FTPARG, $FTPCMD);
2331 $check=0; # taken care of
2336 logmsg "$FTPCMD wasn't handled!\n";
2337 if($proto eq 'pop3') {
2338 sendcontrol "-ERR $FTPCMD is not dealt with!\r\n";
2340 elsif($proto eq 'imap') {
2341 sendcontrol "$cmdid BAD $FTPCMD is not dealt with!\r\n";
2344 sendcontrol "500 $FTPCMD is not dealt with!\r\n";
2349 logmsg "====> Client disconnected\n";
2351 if($serverlogslocked) {
2352 $serverlogslocked = 0;
2353 clear_advisor_read_lock($SERVERLOGS_LOCK);
2357 killsockfilters($proto, $ipvnum, $idnum, $verbose);
2359 if($serverlogslocked) {
2360 $serverlogslocked = 0;
2361 clear_advisor_read_lock($SERVERLOGS_LOCK);