2 #***************************************************************************
4 # Project ___| | | | _ \| |
6 # | (__| |_| | _ <| |___
7 # \___|\___/|_| \_\_____|
9 # Copyright (C) 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 https://curl.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 # SPDX-License-Identifier: curl
24 ###########################################################################
26 # This is a server designed for the curl test suite.
28 # In December 2009 we started remaking the server to support more protocols
29 # that are similar in spirit. Like POP3, IMAP and SMTP in addition to the FTP
30 # it already supported since a long time. Note that it still only supports one
31 # protocol per invoke. You need to start multiple servers to support multiple
32 # protocols simultaneously.
34 # It is meant to exercise curl, it is not meant to be a fully working
35 # or even very standard compliant server.
37 # You may optionally specify port on the command line, otherwise it'll
38 # default to port 8921.
40 # All socket/network/TCP related stuff is done by the 'sockfilt' program.
47 push(@INC, $ENV{'srcdir'}) if(defined $ENV{'srcdir'});
86 #**********************************************************************
89 my $verbose = 0; # set to 1 for debugging
90 my $idstr = ""; # server instance string
91 my $idnum = 1; # server instance number
92 my $ipvnum = 4; # server IPv number (4 or 6)
93 my $proto = 'ftp'; # default server protocol
94 my $srcdir; # directory where ftpserver.pl is located
95 my $srvrname; # server name for presentation purposes
96 my $cwd_testno; # test case numbers extracted from CWD command
97 my $testno = 0; # test case number (read from server.cmd)
99 my $logdir = $path .'/log';
102 #**********************************************************************
103 # global vars used for server address and primary listener port
105 my $port = 8921; # default primary listener port
106 my $listenaddr = '127.0.0.1'; # default address for listener port
108 #**********************************************************************
109 # global vars used for file names
111 my $PORTFILE="ftpserver.port"; # server port file name
112 my $portfile; # server port file path
113 my $pidfile; # server pid file name
114 my $mainsockf_pidfile; # pid file for primary connection sockfilt process
115 my $mainsockf_logfile; # log file for primary connection sockfilt process
116 my $datasockf_pidfile; # pid file for secondary connection sockfilt process
117 my $datasockf_logfile; # log file for secondary connection sockfilt process
119 #**********************************************************************
120 # global vars used for server logs advisor read lock handling
122 my $serverlogs_lockfile;
123 my $serverlogslocked = 0;
125 #**********************************************************************
126 # global vars used for child processes PID tracking
128 my $sfpid; # PID for primary connection sockfilt process
129 my $slavepid; # PID for secondary connection sockfilt process
131 #**********************************************************************
132 # global typeglob filehandle vars to read/write from/to sockfilters
134 local *SFREAD; # used to read from primary connection
135 local *SFWRITE; # used to write to primary connection
136 local *DREAD; # used to read from secondary connection
137 local *DWRITE; # used to write to secondary connection
139 my $sockfilt_timeout = 5; # default timeout for sockfilter eXsysreads
141 #**********************************************************************
142 # global vars which depend on server protocol selection
144 my %commandfunc; # protocol command specific function callbacks
145 my %displaytext; # text returned to client before callback runs
147 #**********************************************************************
148 # global vars customized for each test from the server commands file
150 my $ctrldelay; # set if server should throttle ctrl stream
151 my $datadelay; # set if server should throttle data stream
152 my $retrweirdo; # set if ftp server should use RETRWEIRDO
153 my $retrnosize; # set if ftp server should use RETRNOSIZE
154 my $retrsize; # set if ftp server should use RETRSIZE
155 my $pasvbadip; # set if ftp server should use PASVBADIP
156 my $nosave; # set if ftp server should not save uploaded data
157 my $nodataconn; # set if ftp srvr doesn't establish or accepts data channel
158 my $nodataconn425; # set if ftp srvr doesn't establish data ch and replies 425
159 my $nodataconn421; # set if ftp srvr doesn't establish data ch and replies 421
160 my $nodataconn150; # set if ftp srvr doesn't establish data ch and replies 150
163 my @capabilities; # set if server supports capability commands
164 my @auth_mechs; # set if server supports authentication commands
170 #**********************************************************************
171 # global variables for to test ftp wildcardmatching or other test that
172 # need flexible LIST responses.. and corresponding files.
173 # $ftptargetdir is keeping the fake "name" of LIST directory.
175 my $ftplistparserstate;
178 #**********************************************************************
179 # global variables used when running a ftp server to keep state info
180 # relative to the secondary or data sockfilt process. Values of these
181 # variables should only be modified using datasockf_state() sub, given
182 # that they are closely related and relationship is a bit awkward.
184 my $datasockf_state = 'STOPPED'; # see datasockf_state() sub
185 my $datasockf_mode = 'none'; # ['none','active','passive']
186 my $datasockf_runs = 'no'; # ['no','yes']
187 my $datasockf_conn = 'no'; # ['no','yes']
189 #**********************************************************************
190 # global vars used for signal handling
192 my $got_exit_signal = 0; # set if program should finish execution ASAP
193 my $exit_signal; # first signal handled in exit_signal_handler
195 #**********************************************************************
196 # Mail related definitions
198 my $TEXT_PASSWORD = "secret";
199 my $POP3_TIMESTAMP = "<1972.987654321\@curl>";
201 #**********************************************************************
202 # exit_signal_handler will be triggered to indicate that the program
203 # should finish its execution in a controlled way as soon as possible.
204 # For now, program will also terminate from within this handler.
206 sub exit_signal_handler {
208 # For now, simply mimic old behavior.
209 killsockfilters($piddir, $proto, $ipvnum, $idnum, $verbose);
212 if($serverlogslocked) {
213 $serverlogslocked = 0;
214 clear_advisor_read_lock($serverlogs_lockfile);
220 # append to the server.input file
221 open(my $input, ">>", "$logdir/server$idstr.input") ||
222 logmsg "failed to open $logdir/server$idstr.input\n";
227 # use this, open->print->close system only to make the file
228 # open as little as possible, to make the test suite run
229 # better on windows/cygwin
232 #**********************************************************************
233 # eXsysread is a wrapper around perl's sysread() function. This will
234 # repeat the call to sysread() until it has actually read the complete
235 # number of requested bytes or an unrecoverable condition occurs.
236 # On success returns a positive value, the number of bytes requested.
237 # On failure or timeout returns zero.
243 my $timeout = shift; # A zero timeout disables eXsysread() time limit
245 my $time_limited = 0;
246 my $timeout_rest = 0;
253 if((not defined $nbytes) || ($nbytes < 1)) {
254 logmsg "Error: eXsysread() failure: " .
255 "length argument must be positive\n";
258 if((not defined $timeout) || ($timeout < 0)) {
259 logmsg "Error: eXsysread() failure: " .
260 "timeout argument must be zero or positive\n";
264 # caller sets eXsysread() time limit
266 $timeout_rest = $timeout;
267 $start_time = int(time());
270 while($nread < $nbytes) {
273 local $SIG{ALRM} = sub { die "alarm\n"; };
275 $rc = sysread($FH, $$scalar, $nbytes - $nread, $nread);
278 $timeout_rest = $timeout - (int(time()) - $start_time);
279 if($timeout_rest < 1) {
280 logmsg "Error: eXsysread() failure: timed out\n";
285 $rc = sysread($FH, $$scalar, $nbytes - $nread, $nread);
287 if($got_exit_signal) {
288 logmsg "Error: eXsysread() failure: signalled to die\n";
291 if(not defined $rc) {
293 logmsg "Warning: retrying sysread() interrupted system call\n";
297 logmsg "Warning: retrying sysread() due to EAGAIN\n";
300 if($!{EWOULDBLOCK}) {
301 logmsg "Warning: retrying sysread() due to EWOULDBLOCK\n";
304 logmsg "Error: sysread() failure: $!\n";
308 logmsg "Error: sysread() failure: returned negative value $rc\n";
312 logmsg "Error: sysread() failure: read zero bytes\n";
320 #**********************************************************************
321 # read_mainsockf attempts to read the given amount of output from the
322 # sockfilter which is in use for the main or primary connection. This
323 # reads untranslated sockfilt lingo which may hold data read from the
324 # main or primary socket. On success returns 1, otherwise zero.
329 my $timeout = shift; # Optional argument, if zero blocks indefinitely
332 if(not defined $timeout) {
333 $timeout = $sockfilt_timeout + ($nbytes >> 12);
335 if(eXsysread($FH, $scalar, $nbytes, $timeout) != $nbytes) {
336 my ($fcaller, $lcaller) = (caller)[1,2];
337 logmsg "Error: read_mainsockf() failure at $fcaller " .
338 "line $lcaller. Due to eXsysread() failure\n";
344 #**********************************************************************
345 # read_datasockf attempts to read the given amount of output from the
346 # sockfilter which is in use for the data or secondary connection. This
347 # reads untranslated sockfilt lingo which may hold data read from the
348 # data or secondary socket. On success returns 1, otherwise zero.
353 my $timeout = shift; # Optional argument, if zero blocks indefinitely
356 if(not defined $timeout) {
357 $timeout = $sockfilt_timeout + ($nbytes >> 12);
359 if(eXsysread($FH, $scalar, $nbytes, $timeout) != $nbytes) {
360 my ($fcaller, $lcaller) = (caller)[1,2];
361 logmsg "Error: read_datasockf() failure at $fcaller " .
362 "line $lcaller. Due to eXsysread() failure\n";
376 $result = sysread($$FH, $$scalar, $length);
378 if(not defined $result) {
379 ($fcaller, $lcaller) = (caller)[1,2];
380 logmsg "Failed to read input\n";
381 logmsg "Error: $srvrname server, sysread error: $!\n";
382 logmsg "Exited from sysread_or_die() at $fcaller " .
383 "line $lcaller. $srvrname server, sysread error: $!\n";
384 killsockfilters($piddir, $proto, $ipvnum, $idnum, $verbose);
387 if($serverlogslocked) {
388 $serverlogslocked = 0;
389 clear_advisor_read_lock($serverlogs_lockfile);
393 elsif($result == 0) {
394 ($fcaller, $lcaller) = (caller)[1,2];
395 logmsg "Failed to read input\n";
396 logmsg "Error: $srvrname server, read zero\n";
397 logmsg "Exited from sysread_or_die() at $fcaller " .
398 "line $lcaller. $srvrname server, read zero\n";
399 killsockfilters($piddir, $proto, $ipvnum, $idnum, $verbose);
402 if($serverlogslocked) {
403 $serverlogslocked = 0;
404 clear_advisor_read_lock($serverlogs_lockfile);
413 my @mainsockfcmd = ("./server/sockfilt".exe_ext('SRV'),
416 "--pidfile", $mainsockf_pidfile,
417 "--portfile", $portfile,
418 "--logfile", $mainsockf_logfile);
419 $sfpid = open2(*SFREAD, *SFWRITE, @mainsockfcmd);
421 print STDERR "@mainsockfcmd\n" if($verbose);
423 print SFWRITE "PING\n";
425 sysread_or_die(\*SFREAD, \$pong, 5);
427 if($pong !~ /^PONG/) {
428 logmsg "Failed sockfilt command: @mainsockfcmd\n";
429 killsockfilters($piddir, $proto, $ipvnum, $idnum, $verbose);
432 if($serverlogslocked) {
433 $serverlogslocked = 0;
434 clear_advisor_read_lock($serverlogs_lockfile);
436 die "Failed to start sockfilt!";
440 #**********************************************************************
441 # Returns the given test's reply data
447 $num =~ s/^([^0-9]*)//;
449 $testpart = $num % 10000;
452 my @data = getpart("reply", "data$testpart");
453 if((!@data) && ($testpart ne "")) {
454 @data = getpart("reply", "data");
463 printf SFWRITE "DATA\n%04x\n", length($l);
468 sub sockfiltsecondary {
471 printf DWRITE "DATA\n%04x\n", length($l);
476 #**********************************************************************
477 # Send data to the client on the control stream, which happens to be plain
482 # spit it all out at once
486 my $a = join("", @_);
487 my @a = split("", $a);
491 portable_sleep(0.01);
503 #**********************************************************************
504 # Send data to the FTP client on the data stream when data connection
505 # is actually established. Given that this sub should only be called
506 # when a data connection is supposed to be established, calling this
507 # without a data connection is an indication of weak logic somewhere.
511 if($datasockf_conn eq 'no') {
512 logmsg "WARNING: Detected data sending attempt without DATA channel\n";
514 logmsg "WARNING: Data swallowed: $l\n"
521 # spit it all out at once
522 sockfiltsecondary $l;
525 # pause between each byte
527 sockfiltsecondary $_;
528 portable_sleep(0.01);
534 #**********************************************************************
535 # protocolsetup initializes the 'displaytext' and 'commandfunc' hashes
536 # for the given protocol. References to protocol command callbacks are
537 # stored in 'commandfunc' hash, and text which will be returned to the
538 # client before the command callback runs is stored in 'displaytext'.
543 if($proto eq 'ftp') {
545 'PORT' => \&PORT_ftp,
546 'EPRT' => \&PORT_ftp,
547 'LIST' => \&LIST_ftp,
548 'NLST' => \&NLST_ftp,
549 'PASV' => \&PASV_ftp,
552 'EPSV' => \&PASV_ftp,
553 'RETR' => \&RETR_ftp,
554 'SIZE' => \&SIZE_ftp,
555 'REST' => \&REST_ftp,
556 'STOR' => \&STOR_ftp,
557 'APPE' => \&STOR_ftp, # append looks like upload
558 'MDTM' => \&MDTM_ftp,
561 'USER' => '331 We are happy you popped in!',
562 'PASS' => '230 Welcome you silly person',
563 'PORT' => '200 You said PORT - I say FINE',
564 'TYPE' => '200 I modify TYPE as you wanted',
565 'LIST' => '150 here comes a directory',
566 'NLST' => '150 here comes a directory',
567 'CWD' => '250 CWD command successful.',
568 'SYST' => '215 UNIX Type: L8', # just fake something
569 'QUIT' => '221 bye bye baby', # just reply something
570 'MKD' => '257 Created your requested directory',
571 'REST' => '350 Yeah yeah we set it there for you',
572 'DELE' => '200 OK OK OK whatever you say',
573 'RNFR' => '350 Received your order. Please provide more',
574 'RNTO' => '250 Ok, thanks. File renaming completed.',
575 'NOOP' => '200 Yes, I\'m very good at doing nothing.',
576 'PBSZ' => '500 PBSZ not implemented',
577 'PROT' => '500 PROT not implemented',
578 'welcome' => join("",
579 '220- _ _ ____ _ '."\r\n",
580 '220- ___| | | | _ \| | '."\r\n",
581 '220- / __| | | | |_) | | '."\r\n",
582 '220- | (__| |_| | _ {| |___ '."\r\n",
583 '220 \___|\___/|_| \_\_____|'."\r\n")
586 elsif($proto eq 'pop3') {
588 'APOP' => \&APOP_pop3,
589 'AUTH' => \&AUTH_pop3,
590 'CAPA' => \&CAPA_pop3,
591 'DELE' => \&DELE_pop3,
592 'LIST' => \&LIST_pop3,
593 'NOOP' => \&NOOP_pop3,
594 'PASS' => \&PASS_pop3,
595 'QUIT' => \&QUIT_pop3,
596 'RETR' => \&RETR_pop3,
597 'RSET' => \&RSET_pop3,
598 'STAT' => \&STAT_pop3,
600 'UIDL' => \&UIDL_pop3,
601 'USER' => \&USER_pop3,
604 'welcome' => join("",
605 ' _ _ ____ _ '."\r\n",
606 ' ___| | | | _ \| | '."\r\n",
607 ' / __| | | | |_) | | '."\r\n",
608 ' | (__| |_| | _ {| |___ '."\r\n",
609 ' \___|\___/|_| \_\_____|'."\r\n",
610 '+OK curl POP3 server ready to serve '."\r\n")
613 elsif($proto eq 'imap') {
615 'APPEND' => \&APPEND_imap,
616 'CAPABILITY' => \&CAPABILITY_imap,
617 'CHECK' => \&CHECK_imap,
618 'CLOSE' => \&CLOSE_imap,
619 'COPY' => \©_imap,
620 'CREATE' => \&CREATE_imap,
621 'DELETE' => \&DELETE_imap,
622 'EXAMINE' => \&EXAMINE_imap,
623 'EXPUNGE' => \&EXPUNGE_imap,
624 'FETCH' => \&FETCH_imap,
625 'LIST' => \&LIST_imap,
626 'LSUB' => \&LSUB_imap,
627 'LOGIN' => \&LOGIN_imap,
628 'LOGOUT' => \&LOGOUT_imap,
629 'NOOP' => \&NOOP_imap,
630 'RENAME' => \&RENAME_imap,
631 'SEARCH' => \&SEARCH_imap,
632 'SELECT' => \&SELECT_imap,
633 'STATUS' => \&STATUS_imap,
634 'STORE' => \&STORE_imap,
636 'IDLE' => \&IDLE_imap,
639 'welcome' => join("",
640 ' _ _ ____ _ '."\r\n",
641 ' ___| | | | _ \| | '."\r\n",
642 ' / __| | | | |_) | | '."\r\n",
643 ' | (__| |_| | _ {| |___ '."\r\n",
644 ' \___|\___/|_| \_\_____|'."\r\n",
645 '* OK curl IMAP server ready to serve'."\r\n")
648 elsif($proto eq 'smtp') {
650 'DATA' => \&DATA_smtp,
651 'EHLO' => \&EHLO_smtp,
652 'EXPN' => \&EXPN_smtp,
653 'HELO' => \&HELO_smtp,
654 'HELP' => \&HELP_smtp,
655 'MAIL' => \&MAIL_smtp,
656 'NOOP' => \&NOOP_smtp,
657 'RSET' => \&RSET_smtp,
658 'RCPT' => \&RCPT_smtp,
659 'VRFY' => \&VRFY_smtp,
660 'QUIT' => \&QUIT_smtp,
663 'welcome' => join("",
664 '220- _ _ ____ _ '."\r\n",
665 '220- ___| | | | _ \| | '."\r\n",
666 '220- / __| | | | |_) | | '."\r\n",
667 '220- | (__| |_| | _ {| |___ '."\r\n",
668 '220 \___|\___/|_| \_\_____|'."\r\n")
673 # Perform the disconnecgt handshake with sockfilt on the secondary connection
674 # (the only connection we actively disconnect).
675 # This involves waiting for the disconnect acknowledgmeent after the DISC
676 # command, while throwing away anything else that might come in before
679 print DWRITE "DISC\n";
682 while (5 == ($nr = sysread DREAD, $line, 5)) {
683 if($line eq "DATA\n") {
684 # Must read the data bytes to stay in sync
686 sysread DREAD, $i, 5;
689 if($i =~ /^([0-9a-fA-F]{4})\n/) {
693 read_datasockf(\$line, $size);
695 logmsg "> Throwing away $size bytes on closed connection\n";
697 elsif($line eq "DISC\n") {
698 logmsg "Fancy that; client wants to DISC, too\n";
699 printf DWRITE "ACKD\n";
701 elsif($line eq "ACKD\n") {
702 # Got the ack we were waiting for
706 logmsg "Ignoring: $line";
707 # sockfilt should not be sending us any other commands
711 logmsg "Error: pipe read error ($!) while waiting for ACKD";
714 logmsg "Error: pipe EOF while waiting for ACKD";
719 my ($closed)=@_; # non-zero if already disconnected
721 my $datapid = processexists($datasockf_pidfile);
723 logmsg "=====> Closing $datasockf_mode DATA connection...\n";
727 logmsg "Server disconnects $datasockf_mode DATA connection\n";
729 logmsg "Server disconnected $datasockf_mode DATA connection\n";
732 logmsg "Server finds $datasockf_mode DATA connection already ".
737 logmsg "Server knows $datasockf_mode DATA connection is already ".
742 logmsg "DATA sockfilt for $datasockf_mode data channel quits ".
744 print DWRITE "QUIT\n";
745 pidwait($datapid, 0);
746 unlink($datasockf_pidfile) if(-f $datasockf_pidfile);
747 logmsg "DATA sockfilt for $datasockf_mode data channel quit ".
751 logmsg "DATA sockfilt for $datasockf_mode data channel already ".
755 logmsg "=====> Closed $datasockf_mode DATA connection\n";
757 datasockf_state('STOPPED');
761 ################ SMTP commands
764 # The type of server (SMTP or ESMTP)
767 # The client (which normally contains the test number)
774 # TODO: Get the IP address of the client connection to use in the
775 # EHLO response when the client doesn't specify one but for now use
778 $client = "[127.0.0.1]";
781 # Set the server type to ESMTP
782 $smtp_type = "ESMTP";
784 # Calculate the EHLO response
785 push @data, "$smtp_type pingpong test server Hello $client";
787 if((@capabilities) || (@auth_mechs)) {
790 for my $c (@capabilities) {
794 for my $am (@auth_mechs) {
804 push @data, "AUTH $mechs";
808 # Send the EHLO response
809 for(my $i = 0; $i < @data; $i++) {
813 sendcontrol "250-$d\r\n";
816 sendcontrol "250 $d\r\n";
820 # Store the client (as it may contain the test number)
821 $smtp_client = $client;
829 # TODO: Get the IP address of the client connection to use in the HELO
830 # response when the client doesn't specify one but for now use 127.0.0.1
832 $client = "[127.0.0.1]";
835 # Set the server type to SMTP
838 # Send the HELO response
839 sendcontrol "250 $smtp_type pingpong test server Hello $client\r\n";
841 # Store the client (as it may contain the test number)
842 $smtp_client = $client;
850 logmsg "MAIL_smtp got $args\n";
853 sendcontrol "501 Unrecognized parameter\r\n";
858 my $smtputf8 = grep /^SMTPUTF8$/, @capabilities;
859 my @elements = split(/ /, $args);
861 # Get the FROM and SIZE parameters
862 for my $e (@elements) {
863 if($e =~ /^FROM:(.*)$/) {
866 elsif($e =~ /^SIZE=(\d+)$/) {
871 # this server doesn't "validate" MAIL FROM addresses
876 # Check the capabilities for SIZE and if the specified size is
877 # greater than the message size then reject it
878 if (@found = grep /^SIZE (\d+)$/, @capabilities) {
879 if ($found[0] =~ /^SIZE (\d+)$/) {
887 sendcontrol "552 Message size too large\r\n";
890 sendcontrol "250 Sender OK\r\n";
894 sendcontrol "501 Invalid address\r\n";
904 logmsg "RCPT_smtp got $args\n";
906 # Get the TO parameter
907 if($args !~ /^TO:(.*)/) {
908 sendcontrol "501 Unrecognized parameter\r\n";
911 my $smtputf8 = grep /^SMTPUTF8$/, @capabilities;
914 # Validate the to address (only a valid email address inside <> is
915 # allowed, such as <user@example.com>)
916 if ((!$smtputf8 && $to =~
917 /^<([a-zA-Z0-9._%+-]+)\@(([a-zA-Z0-9-]+)\.)+([a-zA-Z]{2,4})>$/) ||
919 /^<([a-zA-Z0-9\x{80}-\x{ff}._%+-]+)\@(([a-zA-Z0-9\x{80}-\x{ff}-]+)\.)+([a-zA-Z]{2,4})>$/)) {
920 sendcontrol "250 Recipient OK\r\n";
923 sendcontrol "501 Invalid address\r\n";
934 sendcontrol "501 Unrecognized parameter\r\n";
936 elsif ($smtp_client !~ /^(\d*)$/) {
937 sendcontrol "501 Invalid arguments\r\n";
940 sendcontrol "354 Show me the mail\r\n";
942 my $testno = $smtp_client;
943 my $filename = "$logdir/upload.$testno";
945 logmsg "Store test number $testno in $filename\n";
947 open(my $file, ">", "$filename") ||
948 return 0; # failed to open output
954 while (5 == (sysread \*SFREAD, $line, 5)) {
955 if($line eq "DATA\n") {
958 sysread \*SFREAD, $i, 5;
961 if($i =~ /^([0-9a-fA-F]{4})\n/) {
965 read_mainsockf(\$line, $size);
968 print $file $line if(!$nosave);
971 if($raw =~ /(?:^|\x0d\x0a)\x2e\x0d\x0a/) {
972 # end of data marker!
976 logmsg "> Appending $size bytes to file\n";
979 logmsg "Found SMTP EOB marker\n";
983 elsif($line eq "DISC\n") {
986 printf SFWRITE "ACKD\n";
990 logmsg "No support for: $line";
996 print $file "$ulsize bytes would've been stored here\n";
1001 logmsg "received $ulsize bytes upload\n";
1003 sendcontrol "250 OK, data received!\r\n";
1013 sendcontrol "501 Unrecognized parameter\r\n";
1016 sendcontrol "250 OK\r\n";
1026 sendcontrol "501 Unrecognized parameter\r\n";
1029 sendcontrol "250 Resetting\r\n";
1038 # One argument is optional
1040 logmsg "HELP_smtp got $args\n";
1043 if($smtp_client eq "verifiedserver") {
1044 # This is the secret command that verifies that this actually is
1045 # the curl test server
1046 sendcontrol "214 WE ROOLZ: $$\r\n";
1049 print STDERR "FTPD: We returned proof we are the test server\n";
1052 logmsg "return proof we are we\n";
1055 sendcontrol "214-This server supports the following commands:\r\n";
1058 sendcontrol "214 HELO EHLO RCPT DATA RSET MAIL VRFY EXPN QUIT HELP AUTH\r\n";
1061 sendcontrol "214 HELO EHLO RCPT DATA RSET MAIL VRFY EXPN QUIT HELP\r\n";
1070 my ($username, $address) = split(/ /, $args, 2);
1072 logmsg "VRFY_smtp got $args\n";
1074 if($username eq "") {
1075 sendcontrol "501 Unrecognized parameter\r\n";
1078 my $smtputf8 = grep /^SMTPUTF8$/, @capabilities;
1080 # Validate the username (only a valid local or external username is
1081 # allowed, such as user or user@example.com)
1082 if ((!$smtputf8 && $username =~
1083 /^([a-zA-Z0-9._%+-]+)(\@(([a-zA-Z0-9-]+)\.)+([a-zA-Z]{2,4}))?$/) ||
1084 ($smtputf8 && $username =~
1085 /^([a-zA-Z0-9\x{80}-\x{ff}._%+-]+)(\@(([a-zA-Z0-9\x{80}-\x{ff}-]+)\.)+([a-zA-Z]{2,4}))?$/)) {
1087 my @data = getreplydata($smtp_client);
1091 /^([a-zA-Z0-9._%+-]+)\@(([a-zA-Z0-9-]+)\.)+([a-zA-Z]{2,4})$/) {
1092 push @data, "250 <$username\@example.com>\r\n"
1095 push @data, "250 <$username>\r\n"
1104 sendcontrol "501 Invalid address\r\n";
1112 my ($list_name) = @_;
1114 logmsg "EXPN_smtp got $list_name\n";
1117 sendcontrol "501 Unrecognized parameter\r\n";
1120 my @data = getreplydata($smtp_client);
1131 sendcontrol "221 curl $smtp_type server signing off\r\n";
1136 # What was deleted by IMAP STORE / POP3 DELE commands
1140 ################ IMAP commands
1143 # global to allow the command functions to read it
1146 # what was picked by SELECT
1149 # Any IMAP parameter can come in escaped and in double quotes.
1150 # This function is dumb (so far) and just removes the quotes if present.
1151 sub fix_imap_params {
1153 $_ = $1 if /^"(.*)"$/;
1157 sub CAPABILITY_imap {
1158 if((!@capabilities) && (!@auth_mechs)) {
1159 sendcontrol "$cmdid BAD Command\r\n";
1164 # Calculate the CAPABILITY response
1165 $data = "* CAPABILITY IMAP4";
1167 for my $c (@capabilities) {
1171 for my $am (@auth_mechs) {
1172 $data .= " AUTH=$am";
1175 $data .= " pingpong test server\r\n";
1177 # Send the CAPABILITY response
1179 sendcontrol "$cmdid OK CAPABILITY completed\r\n";
1187 my ($user, $password) = split(/ /, $args, 2);
1188 fix_imap_params($user, $password);
1190 logmsg "LOGIN_imap got $args\n";
1193 sendcontrol "$cmdid BAD Command Argument\r\n";
1196 sendcontrol "$cmdid OK LOGIN completed\r\n";
1204 fix_imap_params($mailbox);
1206 logmsg "SELECT_imap got test $mailbox\n";
1208 if($mailbox eq "") {
1209 sendcontrol "$cmdid BAD Command Argument\r\n";
1212 # Example from RFC 3501, 6.3.1. SELECT Command
1213 sendcontrol "* 172 EXISTS\r\n";
1214 sendcontrol "* 1 RECENT\r\n";
1215 sendcontrol "* OK [UNSEEN 12] Message 12 is first unseen\r\n";
1216 sendcontrol "* OK [UIDVALIDITY 3857529045] UIDs valid\r\n";
1217 sendcontrol "* OK [UIDNEXT 4392] Predicted next UID\r\n";
1218 sendcontrol "* FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)\r\n";
1219 sendcontrol "* OK [PERMANENTFLAGS (\\Deleted \\Seen \\*)] Limited\r\n";
1220 sendcontrol "$cmdid OK [READ-WRITE] SELECT completed\r\n";
1222 $selected = $mailbox;
1230 my ($uid, $how) = split(/ /, $args, 2);
1231 fix_imap_params($uid, $how);
1233 logmsg "FETCH_imap got $args\n";
1235 if ($selected eq "") {
1236 sendcontrol "$cmdid BAD Command received in Invalid state\r\n";
1242 if($selected eq "verifiedserver") {
1243 # this is the secret command that verifies that this actually is
1244 # the curl test server
1245 my $response = "WE ROOLZ: $$\r\n";
1247 print STDERR "FTPD: We returned proof we are the test server\n";
1249 $data[0] = $response;
1250 logmsg "return proof we are we\n";
1254 logmsg "retrieve a mail\n";
1256 @data = getreplydata($selected);
1260 $size += length($_);
1263 sendcontrol "* $uid FETCH ($how {$size}\r\n";
1269 # Set the custom extra header content with POSTFETCH
1270 sendcontrol "$postfetch)\r\n";
1271 sendcontrol "$cmdid OK FETCH completed\r\n";
1280 logmsg "APPEND_imap got $args\r\n";
1282 $args =~ /^([^ ]+) [^{]*\{(\d+)\}$/;
1283 my ($mailbox, $size) = ($1, $2);
1284 fix_imap_params($mailbox);
1286 if($mailbox eq "") {
1287 sendcontrol "$cmdid BAD Command Argument\r\n";
1290 sendcontrol "+ Ready for literal data\r\n";
1292 my $testno = $mailbox;
1293 my $filename = "$logdir/upload.$testno";
1295 logmsg "Store test number $testno in $filename\n";
1297 open(my $file, ">", "$filename") ||
1298 return 0; # failed to open output
1302 while(5 == (sysread \*SFREAD, $line, 5)) {
1303 if($line eq "DATA\n") {
1304 sysread \*SFREAD, $line, 5;
1307 if($line =~ /^([0-9a-fA-F]{4})\n/) {
1308 $chunksize = hex($1);
1311 read_mainsockf(\$line, $chunksize);
1313 my $left = $size - $received;
1314 my $datasize = ($left > $chunksize) ? $chunksize : $left;
1317 logmsg "> Appending $datasize bytes to file\n";
1318 print $file substr($line, 0, $datasize) if(!$nosave);
1319 $line = substr($line, $datasize);
1321 $received += $datasize;
1322 if($received == $size) {
1323 logmsg "Received all data, waiting for final CRLF.\n";
1327 if($received == $size && $line eq "\r\n") {
1331 elsif($line eq "DISC\n") {
1332 logmsg "Unexpected disconnect!\n";
1333 printf SFWRITE "ACKD\n";
1337 logmsg "No support for: $line";
1343 print $file "$size bytes would've been stored here\n";
1348 logmsg "received $size bytes upload\n";
1350 sendcontrol "$cmdid OK APPEND completed\r\n";
1358 my ($uid, $what, $value) = split(/ /, $args, 3);
1359 fix_imap_params($uid);
1361 logmsg "STORE_imap got $args\n";
1363 if ($selected eq "") {
1364 sendcontrol "$cmdid BAD Command received in Invalid state\r\n";
1366 elsif (($uid eq "") || ($what ne "+Flags") || ($value eq "")) {
1367 sendcontrol "$cmdid BAD Command Argument\r\n";
1370 if($value eq "\\Deleted") {
1371 push(@deleted, $uid);
1374 sendcontrol "* $uid FETCH (FLAGS (\\Seen $value))\r\n";
1375 sendcontrol "$cmdid OK STORE completed\r\n";
1383 my ($reference, $mailbox) = split(/ /, $args, 2);
1384 fix_imap_params($reference, $mailbox);
1386 logmsg "LIST_imap got $args\n";
1388 if ($reference eq "") {
1389 sendcontrol "$cmdid BAD Command Argument\r\n";
1391 elsif ($reference eq "verifiedserver") {
1392 # this is the secret command that verifies that this actually is
1393 # the curl test server
1394 sendcontrol "* LIST () \"/\" \"WE ROOLZ: $$\"\r\n";
1395 sendcontrol "$cmdid OK LIST Completed\r\n";
1398 print STDERR "FTPD: We returned proof we are the test server\n";
1401 logmsg "return proof we are we\n";
1404 my @data = getreplydata($reference);
1410 sendcontrol "$cmdid OK LIST Completed\r\n";
1418 my ($reference, $mailbox) = split(/ /, $args, 2);
1419 fix_imap_params($reference, $mailbox);
1421 logmsg "LSUB_imap got $args\n";
1423 if ($reference eq "") {
1424 sendcontrol "$cmdid BAD Command Argument\r\n";
1427 my @data = getreplydata($reference);
1433 sendcontrol "$cmdid OK LSUB Completed\r\n";
1441 fix_imap_params($mailbox);
1443 logmsg "EXAMINE_imap got $mailbox\n";
1445 if ($mailbox eq "") {
1446 sendcontrol "$cmdid BAD Command Argument\r\n";
1449 my @data = getreplydata($mailbox);
1455 sendcontrol "$cmdid OK [READ-ONLY] EXAMINE completed\r\n";
1463 my ($mailbox, $what) = split(/ /, $args, 2);
1464 fix_imap_params($mailbox);
1466 logmsg "STATUS_imap got $args\n";
1468 if ($mailbox eq "") {
1469 sendcontrol "$cmdid BAD Command Argument\r\n";
1472 my @data = getreplydata($mailbox);
1478 sendcontrol "$cmdid OK STATUS completed\r\n";
1486 fix_imap_params($what);
1488 logmsg "SEARCH_imap got $what\n";
1490 if ($selected eq "") {
1491 sendcontrol "$cmdid BAD Command received in Invalid state\r\n";
1493 elsif ($what eq "") {
1494 sendcontrol "$cmdid BAD Command Argument\r\n";
1497 my @data = getreplydata($selected);
1503 sendcontrol "$cmdid OK SEARCH completed\r\n";
1511 fix_imap_params($args);
1513 logmsg "CREATE_imap got $args\n";
1516 sendcontrol "$cmdid BAD Command Argument\r\n";
1519 sendcontrol "$cmdid OK CREATE completed\r\n";
1527 fix_imap_params($args);
1529 logmsg "DELETE_imap got $args\n";
1532 sendcontrol "$cmdid BAD Command Argument\r\n";
1535 sendcontrol "$cmdid OK DELETE completed\r\n";
1543 my ($from_mailbox, $to_mailbox) = split(/ /, $args, 2);
1544 fix_imap_params($from_mailbox, $to_mailbox);
1546 logmsg "RENAME_imap got $args\n";
1548 if (($from_mailbox eq "") || ($to_mailbox eq "")) {
1549 sendcontrol "$cmdid BAD Command Argument\r\n";
1552 sendcontrol "$cmdid OK RENAME completed\r\n";
1559 if ($selected eq "") {
1560 sendcontrol "$cmdid BAD Command received in Invalid state\r\n";
1563 sendcontrol "$cmdid OK CHECK completed\r\n";
1570 if ($selected eq "") {
1571 sendcontrol "$cmdid BAD Command received in Invalid state\r\n";
1574 sendcontrol "$cmdid BAD Command Argument\r\n";
1577 sendcontrol "$cmdid OK CLOSE completed\r\n";
1586 if ($selected eq "") {
1587 sendcontrol "$cmdid BAD Command received in Invalid state\r\n";
1591 # Report the number of existing messages as per the SELECT
1593 sendcontrol "* 172 EXISTS\r\n";
1596 # Report the message UIDs being deleted
1597 for my $d (@deleted) {
1598 sendcontrol "* $d EXPUNGE\r\n";
1604 sendcontrol "$cmdid OK EXPUNGE completed\r\n";
1612 my ($uid, $mailbox) = split(/ /, $args, 2);
1613 fix_imap_params($uid, $mailbox);
1615 logmsg "COPY_imap got $args\n";
1617 if (($uid eq "") || ($mailbox eq "")) {
1618 sendcontrol "$cmdid BAD Command Argument\r\n";
1621 sendcontrol "$cmdid OK COPY completed\r\n";
1628 logmsg "IDLE received\n";
1630 sendcontrol "+ entering idle mode\r\n";
1636 my ($command) = split(/ /, $args, 1);
1637 fix_imap_params($command);
1639 logmsg "UID_imap got $args\n";
1641 if ($selected eq "") {
1642 sendcontrol "$cmdid BAD Command received in Invalid state\r\n";
1644 elsif (substr($command, 0, 5) eq "FETCH"){
1645 my $func = $commandfunc{"FETCH"};
1647 &$func($args, $command);
1650 elsif (($command ne "COPY") &&
1651 ($command ne "STORE") && ($command ne "SEARCH")) {
1652 sendcontrol "$cmdid BAD Command Argument\r\n";
1655 my @data = getreplydata($selected);
1661 sendcontrol "$cmdid OK $command completed\r\n";
1673 "* 14 FETCH (FLAGS (\\Seen \\Deleted))\r\n",
1677 sendcontrol "$cmdid BAD Command Argument\r\n";
1684 sendcontrol "$cmdid OK NOOP completed\r\n";
1691 sendcontrol "* BYE curl IMAP server signing off\r\n";
1692 sendcontrol "$cmdid OK LOGOUT completed\r\n";
1698 ################ POP3 commands
1701 # Who is attempting to log in
1708 # Calculate the capability list based on the specified capabilities
1709 # (except APOP) and any authentication mechanisms
1710 for my $c (@capabilities) {
1711 push @list, "$c\r\n" unless $c eq "APOP";
1714 for my $am (@auth_mechs) {
1724 push @list, "SASL $mechs\r\n";
1728 sendcontrol "-ERR Unrecognized command\r\n";
1733 # Calculate the CAPA response
1734 push @data, "+OK List of capabilities follows\r\n";
1737 push @data, "$l\r\n";
1740 push @data, "IMPLEMENTATION POP3 pingpong test server\r\n";
1742 # Send the CAPA response
1747 # End with the magic 3-byte end of listing marker
1748 sendcontrol ".\r\n";
1756 my ($user, $secret) = split(/ /, $args, 2);
1758 if (!grep /^APOP$/, @capabilities) {
1759 sendcontrol "-ERR Unrecognized command\r\n";
1761 elsif (($user eq "") || ($secret eq "")) {
1762 sendcontrol "-ERR Protocol error\r\n";
1765 my $digest = Digest::MD5::md5_hex($POP3_TIMESTAMP, $TEXT_PASSWORD);
1767 if ($secret ne $digest) {
1768 sendcontrol "-ERR Login failure\r\n";
1771 sendcontrol "+OK Login successful\r\n";
1780 sendcontrol "-ERR Unrecognized command\r\n";
1785 # Calculate the AUTH response
1786 push @data, "+OK List of supported mechanisms follows\r\n";
1788 for my $am (@auth_mechs) {
1789 push @data, "$am\r\n";
1792 # Send the AUTH response
1797 # End with the magic 3-byte end of listing marker
1798 sendcontrol ".\r\n";
1807 logmsg "USER_pop3 got $user\n";
1810 sendcontrol "-ERR Protocol error\r\n";
1815 sendcontrol "+OK\r\n";
1822 my ($password) = @_;
1824 logmsg "PASS_pop3 got $password\n";
1826 sendcontrol "+OK Login successful\r\n";
1835 if($msgid =~ /^verifiedserver$/) {
1836 # this is the secret command that verifies that this actually is
1837 # the curl test server
1838 my $response = "WE ROOLZ: $$\r\n";
1840 print STDERR "FTPD: We returned proof we are the test server\n";
1842 $data[0] = $response;
1843 logmsg "return proof we are we\n";
1847 logmsg "retrieve a mail\n";
1849 @data = getreplydata($msgid);
1852 sendcontrol "+OK Mail transfer starts\r\n";
1858 # end with the magic 3-byte end of mail marker, assumes that the
1859 # mail body ends with a CRLF!
1860 sendcontrol ".\r\n";
1866 # This is a built-in fake-message list
1869 "2 4294967400\r\n", # > 4 GB
1873 logmsg "retrieve a message list\n";
1875 sendcontrol "+OK Listing starts\r\n";
1881 # End with the magic 3-byte end of listing marker
1882 sendcontrol ".\r\n";
1890 logmsg "DELE_pop3 got $msgid\n";
1893 sendcontrol "-ERR Protocol error\r\n";
1896 push (@deleted, $msgid);
1898 sendcontrol "+OK\r\n";
1908 sendcontrol "-ERR Protocol error\r\n";
1911 # Send statistics for the built-in fake message list as
1912 # detailed in the LIST_pop3 function above
1913 sendcontrol "+OK 3 4294967800\r\n";
1923 sendcontrol "-ERR Protocol error\r\n";
1926 sendcontrol "+OK\r\n";
1933 # This is a built-in fake-message UID list
1937 "3 4\r\n", # Note that UID 3 is a simulated "deleted" message
1940 if (!grep /^UIDL$/, @capabilities) {
1941 sendcontrol "-ERR Unrecognized command\r\n";
1944 logmsg "retrieve a message UID list\n";
1946 sendcontrol "+OK Listing starts\r\n";
1952 # End with the magic 3-byte end of listing marker
1953 sendcontrol ".\r\n";
1961 my ($msgid, $lines) = split(/ /, $args, 2);
1963 logmsg "TOP_pop3 got $args\n";
1965 if (!grep /^TOP$/, @capabilities) {
1966 sendcontrol "-ERR Unrecognized command\r\n";
1968 elsif (($msgid eq "") || ($lines eq "")) {
1969 sendcontrol "-ERR Protocol error\r\n";
1972 if ($lines == "0") {
1973 logmsg "retrieve header of mail\n";
1976 logmsg "retrieve top $lines lines of mail\n";
1979 my @data = getreplydata($msgid);
1981 sendcontrol "+OK Mail transfer starts\r\n";
1988 # End with the magic 3-byte end of mail marker, assumes that the
1989 # mail body ends with a CRLF!
1990 sendcontrol ".\r\n";
2000 sendcontrol "-ERR Protocol error\r\n";
2004 logmsg "resetting @deleted message(s)\n";
2009 sendcontrol "+OK\r\n";
2017 logmsg "deleting @deleted message(s)\n";
2022 sendcontrol "+OK curl POP3 server signing off\r\n";
2028 ################ FTP commands
2033 logmsg "Set REST position to $rest\n"
2036 sub switch_directory_goto {
2037 my $target_dir = $_;
2039 if(!$ftptargetdir) {
2040 $ftptargetdir = "/";
2043 if($target_dir eq "") {
2044 $ftptargetdir = "/";
2046 elsif($target_dir eq "..") {
2047 if($ftptargetdir eq "/") {
2048 $ftptargetdir = "/";
2051 $ftptargetdir =~ s/[[:alnum:]]+\/$//;
2055 $ftptargetdir .= $target_dir . "/";
2059 sub switch_directory {
2060 my $target_dir = $_[0];
2062 if($target_dir =~ /^test-(\d+)/) {
2065 elsif($target_dir eq "/") {
2066 $ftptargetdir = "/";
2069 my @dirs = split("/", $target_dir);
2071 switch_directory_goto($_);
2077 my ($folder, $fullcommand) = $_[0];
2078 switch_directory($folder);
2079 if($ftptargetdir =~ /^\/fully_simulated/) {
2080 $ftplistparserstate = "enabled";
2083 undef $ftplistparserstate;
2089 $mydir = $ftptargetdir ? $ftptargetdir : "/";
2094 sendcontrol "257 \"$mydir\" is current directory\r\n";
2098 # print "150 ASCII data connection for /bin/ls (193.15.23.1,59196) (0 bytes)\r\n";
2100 # this is a built-in fake-dir ;-)
2101 my @ftpdir=("total 20\r\n",
2102 "drwxr-xr-x 8 98 98 512 Oct 22 13:06 .\r\n",
2103 "drwxr-xr-x 8 98 98 512 Oct 22 13:06 ..\r\n",
2104 "drwxr-xr-x 2 98 98 512 May 2 1996 .NeXT\r\n",
2105 "-r--r--r-- 1 0 1 35 Jul 16 1996 README\r\n",
2106 "lrwxrwxrwx 1 0 1 7 Dec 9 1999 bin -> usr/bin\r\n",
2107 "dr-xr-xr-x 2 0 1 512 Oct 1 1997 dev\r\n",
2108 "drwxrwxrwx 2 98 98 512 May 29 16:04 download.html\r\n",
2109 "dr-xr-xr-x 2 0 1 512 Nov 30 1995 etc\r\n",
2110 "drwxrwxrwx 2 98 1 512 Oct 30 14:33 pub\r\n",
2111 "dr-xr-xr-x 5 0 1 512 Oct 1 1997 usr\r\n");
2113 if($datasockf_conn eq 'no') {
2114 if($nodataconn425) {
2115 sendcontrol "150 Opening data connection\r\n";
2116 sendcontrol "425 Can't open data connection\r\n";
2118 elsif($nodataconn421) {
2119 sendcontrol "150 Opening data connection\r\n";
2120 sendcontrol "421 Connection timed out\r\n";
2122 elsif($nodataconn150) {
2123 sendcontrol "150 Opening data connection\r\n";
2124 # client shall timeout
2127 # client shall timeout
2132 if($ftplistparserstate) {
2133 @ftpdir = ftp_contentlist($ftptargetdir);
2136 logmsg "pass LIST data on data connection\n";
2139 loadtest("$logdir/test$cwd_testno");
2141 my @data = getpart("reply", "data");
2144 # convert all \n to \r\n for ASCII transfer
2145 $send =~ s/\r\n/\n/g;
2146 $send =~ s/\n/\r\n/g;
2147 logmsg "send $send as data\n";
2150 $cwd_testno = 0; # forget it again
2153 # old hard-coded style
2159 sendcontrol "226 ASCII transfer complete\r\n";
2164 my @ftpdir=("file", "with space", "fake", "..", " ..", "funny", "README");
2166 if($datasockf_conn eq 'no') {
2167 if($nodataconn425) {
2168 sendcontrol "150 Opening data connection\r\n";
2169 sendcontrol "425 Can't open data connection\r\n";
2171 elsif($nodataconn421) {
2172 sendcontrol "150 Opening data connection\r\n";
2173 sendcontrol "421 Connection timed out\r\n";
2175 elsif($nodataconn150) {
2176 sendcontrol "150 Opening data connection\r\n";
2177 # client shall timeout
2180 # client shall timeout
2185 logmsg "pass NLST data on data connection\n";
2190 sendcontrol "226 ASCII transfer complete\r\n";
2197 if ($testno > 10000) {
2198 $testpart = $testno % 10000;
2199 $testno = int($testno / 10000);
2202 loadtest("$logdir/test$testno");
2204 my @data = getpart("reply", "mdtm");
2206 my $reply = $data[0];
2207 chomp $reply if($reply);
2209 if($reply && ($reply =~ /^[+-]?\d+$/) && ($reply < 0)) {
2210 sendcontrol "550 $testno: no such file.\r\n";
2213 sendcontrol "$reply\r\n";
2216 sendcontrol "500 MDTM: no such command.\r\n";
2223 if($ftplistparserstate) {
2224 my $size = wildcard_filesize($ftptargetdir, $testno);
2226 sendcontrol "550 $testno: No such file or directory.\r\n";
2229 sendcontrol "213 $size\r\n";
2234 if($testno =~ /^verifiedserver$/) {
2235 my $response = "WE ROOLZ: $$\r\n";
2236 my $size = length($response);
2237 sendcontrol "213 $size\r\n";
2241 if($testno =~ /(\d+)\/?$/) {
2245 print STDERR "SIZE_ftp: invalid test number: $testno\n";
2250 if($testno > 10000) {
2251 $testpart = $testno % 10000;
2252 $testno = int($testno / 10000);
2255 loadtest("$logdir/test$testno");
2256 my @data = getpart("reply", "size");
2258 my $size = $data[0];
2262 sendcontrol "213 $size\r\n";
2265 sendcontrol "550 $testno: No such file or directory.\r\n";
2270 @data = getpart("reply", "data$testpart");
2272 $size += length($_);
2275 sendcontrol "213 $size\r\n";
2278 sendcontrol "550 $testno: No such file or directory.\r\n";
2287 if($datasockf_conn eq 'no') {
2288 if($nodataconn425) {
2289 sendcontrol "150 Opening data connection\r\n";
2290 sendcontrol "425 Can't open data connection\r\n";
2292 elsif($nodataconn421) {
2293 sendcontrol "150 Opening data connection\r\n";
2294 sendcontrol "421 Connection timed out\r\n";
2296 elsif($nodataconn150) {
2297 sendcontrol "150 Opening data connection\r\n";
2298 # client shall timeout
2301 # client shall timeout
2306 if($ftplistparserstate) {
2307 my @content = wildcard_getfile($ftptargetdir, $testno);
2308 if($content[0] == -1) {
2312 my $size = length $content[1];
2313 sendcontrol "150 Binary data connection for $testno ($size bytes).\r\n",
2314 senddata $content[1];
2316 sendcontrol "226 File transfer complete\r\n";
2321 if($testno =~ /^verifiedserver$/) {
2322 # this is the secret command that verifies that this actually is
2323 # the curl test server
2324 my $response = "WE ROOLZ: $$\r\n";
2325 my $len = length($response);
2326 sendcontrol "150 Binary junk ($len bytes).\r\n";
2327 senddata "WE ROOLZ: $$\r\n";
2329 sendcontrol "226 File transfer complete\r\n";
2331 print STDERR "FTPD: We returned proof we are the test server\n";
2336 $testno =~ s/^([^0-9]*)//;
2338 if ($testno > 10000) {
2339 $testpart = $testno % 10000;
2340 $testno = int($testno / 10000);
2343 loadtest("$logdir/test$testno");
2345 my @data = getpart("reply", "data$testpart");
2349 $size += length($_);
2352 my %hash = getpartattr("reply", "data$testpart");
2354 if($size || $hash{'sendzero'}) {
2357 # move read pointer forward
2359 logmsg "REST $rest was removed from size, makes $size left\n";
2360 $rest = 0; # reset REST offset again
2363 sendcontrol "150 Binary data connection for $testno () ($size bytes).\r\n",
2364 "226 File transfer complete\r\n";
2371 $retrweirdo=0; # switch off the weirdo again!
2374 my $sz = "($size bytes)";
2378 elsif($retrsize > 0) {
2379 $sz = "($retrsize bytes)";
2382 sendcontrol "150 Binary data connection for $testno () $sz.\r\n";
2389 sendcontrol "226 File transfer complete\r\n";
2393 sendcontrol "550 $testno: No such file or directory.\r\n";
2401 my $filename = "$logdir/upload.$testno";
2403 if($datasockf_conn eq 'no') {
2404 if($nodataconn425) {
2405 sendcontrol "150 Opening data connection\r\n";
2406 sendcontrol "425 Can't open data connection\r\n";
2408 elsif($nodataconn421) {
2409 sendcontrol "150 Opening data connection\r\n";
2410 sendcontrol "421 Connection timed out\r\n";
2412 elsif($nodataconn150) {
2413 sendcontrol "150 Opening data connection\r\n";
2414 # client shall timeout
2417 # client shall timeout
2422 logmsg "STOR test number $testno in $filename\n";
2424 sendcontrol "125 Gimme gimme gimme!\r\n";
2426 open(my $file, ">", "$filename") ||
2427 return 0; # failed to open output
2432 while (5 == (sysread DREAD, $line, 5)) {
2433 if($line eq "DATA\n") {
2435 sysread DREAD, $i, 5;
2438 if($i =~ /^([0-9a-fA-F]{4})\n/) {
2442 read_datasockf(\$line, $size);
2444 #print STDERR " GOT: $size bytes\n";
2447 print $file $line if(!$nosave);
2448 logmsg "> Appending $size bytes to file\n";
2450 elsif($line eq "DISC\n") {
2453 printf DWRITE "ACKD\n";
2457 logmsg "No support for: $line";
2466 print $file "$ulsize bytes would've been stored here\n";
2469 close_dataconn($disc);
2470 logmsg "received $ulsize bytes upload\n";
2472 sendcontrol "$storeresp\r\n";
2475 sendcontrol "226 File transfer complete\r\n";
2484 # kill previous data connection sockfilt when alive
2485 if($datasockf_runs eq 'yes') {
2486 killsockfilters($piddir, $proto, $ipvnum, $idnum, $verbose, 'data');
2487 logmsg "DATA sockfilt for $datasockf_mode data channel killed\n";
2489 datasockf_state('STOPPED');
2491 logmsg "====> Passive DATA channel requested by client\n";
2493 logmsg "DATA sockfilt for passive data channel starting...\n";
2495 # We fire up a new sockfilt to do the data transfer for us.
2496 my @datasockfcmd = ("./server/sockfilt".exe_ext('SRV'),
2497 "--ipv$ipvnum", "--port", 0,
2498 "--pidfile", $datasockf_pidfile,
2499 "--logfile", $datasockf_logfile);
2501 push(@datasockfcmd, '--bindonly');
2503 $slavepid = open2(\*DREAD, \*DWRITE, @datasockfcmd);
2506 datasockf_state('PASSIVE_NODATACONN');
2509 datasockf_state('PASSIVE');
2512 print STDERR "@datasockfcmd\n" if($verbose);
2514 print DWRITE "PING\n";
2516 sysread_or_die(\*DREAD, \$pong, 5);
2518 if($pong =~ /^FAIL/) {
2519 logmsg "DATA sockfilt said: FAIL\n";
2520 logmsg "DATA sockfilt for passive data channel failed\n";
2521 logmsg "DATA sockfilt not running\n";
2522 datasockf_state('STOPPED');
2523 sendcontrol "500 no free ports!\r\n";
2526 elsif($pong !~ /^PONG/) {
2527 logmsg "DATA sockfilt unexpected response: $pong\n";
2528 logmsg "DATA sockfilt for passive data channel failed\n";
2529 logmsg "DATA sockfilt killed now\n";
2530 killsockfilters($piddir, $proto, $ipvnum, $idnum, $verbose, 'data');
2531 logmsg "DATA sockfilt not running\n";
2532 datasockf_state('STOPPED');
2533 sendcontrol "500 no free ports!\r\n";
2537 logmsg "DATA sockfilt for passive data channel started (pid $slavepid)\n";
2539 # Find out on what port we listen on or have bound
2541 print DWRITE "PORT\n";
2543 # READ the response code
2544 sysread_or_die(\*DREAD, \$i, 5);
2546 # READ the response size
2547 sysread_or_die(\*DREAD, \$i, 5);
2550 if($i =~ /^([0-9a-fA-F]{4})\n/) {
2554 # READ the response data
2555 read_datasockf(\$i, $size);
2557 # The data is in the format
2560 if($i =~ /IPv(\d)\/(\d+)/) {
2561 # FIX: deal with IP protocol version
2566 logmsg "DATA sockfilt unknown listener port\n";
2567 logmsg "DATA sockfilt for passive data channel failed\n";
2568 logmsg "DATA sockfilt killed now\n";
2569 killsockfilters($piddir, $proto, $ipvnum, $idnum, $verbose, 'data');
2570 logmsg "DATA sockfilt not running\n";
2571 datasockf_state('STOPPED');
2572 sendcontrol "500 no free ports!\r\n";
2577 my $str = nodataconn_str();
2578 logmsg "DATA sockfilt for passive data channel ($str) bound on port ".
2582 logmsg "DATA sockfilt for passive data channel listens on port ".
2586 if($cmd ne "EPSV") {
2593 sendcontrol sprintf("227 Entering Passive Mode ($p,%d,%d)\n",
2594 int($pasvport/256), int($pasvport%256));
2598 sendcontrol sprintf("229 Entering Passive Mode (|||%d|)\n", $pasvport);
2601 logmsg "Client has been notified that DATA conn ".
2602 "will be accepted on port $pasvport\n";
2605 my $str = nodataconn_str();
2606 logmsg "====> Client fooled ($str)\n";
2611 local $SIG{ALRM} = sub { die "alarm\n" };
2613 # assume swift operations unless explicitly slow
2614 alarm ($datadelay?20:2);
2619 # FIX: Monitor ctrl conn for disconnect
2621 while(sysread(DREAD, $input, 5)) {
2623 if($input !~ /^CNCT/) {
2624 # we wait for a connected client
2625 logmsg "Odd, we got $input from client\n";
2628 logmsg "Client connects to port $pasvport\n";
2635 logmsg "$srvrname server timed out awaiting data connection ".
2636 "on port $pasvport\n";
2637 logmsg "accept failed or connection not even attempted\n";
2638 logmsg "DATA sockfilt killed now\n";
2639 killsockfilters($piddir, $proto, $ipvnum, $idnum, $verbose, 'data');
2640 logmsg "DATA sockfilt not running\n";
2641 datasockf_state('STOPPED');
2645 logmsg "====> Client established passive DATA connection ".
2646 "on port $pasvport\n";
2653 # Support both PORT and EPRT here.
2657 my ($arg, $cmd) = @_;
2661 # kill previous data connection sockfilt when alive
2662 if($datasockf_runs eq 'yes') {
2663 killsockfilters($piddir, $proto, $ipvnum, $idnum, $verbose, 'data');
2664 logmsg "DATA sockfilt for $datasockf_mode data channel killed\n";
2666 datasockf_state('STOPPED');
2668 logmsg "====> Active DATA channel requested by client\n";
2670 # We always ignore the given IP and use localhost.
2672 if($cmd eq "PORT") {
2673 if($arg !~ /(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)/) {
2674 logmsg "DATA sockfilt for active data channel not started ".
2675 "(bad PORT-line: $arg)\n";
2676 sendcontrol "500 silly you, go away\r\n";
2680 $addr = "$1.$2.$3.$4";
2682 # EPRT |2|::1|49706|
2683 elsif($cmd eq "EPRT") {
2684 if($arg !~ /(\d+)\|([^\|]+)\|(\d+)/) {
2685 logmsg "DATA sockfilt for active data channel not started ".
2686 "(bad EPRT-line: $arg)\n";
2687 sendcontrol "500 silly you, go away\r\n";
2690 sendcontrol "200 Thanks for dropping by. We contact you later\r\n";
2695 logmsg "DATA sockfilt for active data channel not started ".
2696 "(invalid command: $cmd)\n";
2697 sendcontrol "500 we don't like $cmd now\r\n";
2701 if(!$port || $port > 65535) {
2702 logmsg "DATA sockfilt for active data channel not started ".
2703 "(illegal PORT number: $port)\n";
2708 my $str = nodataconn_str();
2709 logmsg "DATA sockfilt for active data channel not started ($str)\n";
2710 datasockf_state('ACTIVE_NODATACONN');
2711 logmsg "====> Active DATA channel not established\n";
2715 logmsg "DATA sockfilt for active data channel starting...\n";
2717 # We fire up a new sockfilt to do the data transfer for us.
2718 my @datasockfcmd = ("./server/sockfilt".exe_ext('SRV'),
2719 "--ipv$ipvnum", "--connect", $port, "--addr", $addr,
2720 "--pidfile", $datasockf_pidfile,
2721 "--logfile", $datasockf_logfile);
2722 $slavepid = open2(\*DREAD, \*DWRITE, @datasockfcmd);
2724 datasockf_state('ACTIVE');
2726 print STDERR "@datasockfcmd\n" if($verbose);
2728 print DWRITE "PING\n";
2730 sysread_or_die(\*DREAD, \$pong, 5);
2732 if($pong =~ /^FAIL/) {
2733 logmsg "DATA sockfilt said: FAIL\n";
2734 logmsg "DATA sockfilt for active data channel failed\n";
2735 logmsg "DATA sockfilt not running\n";
2736 datasockf_state('STOPPED');
2737 # client shall timeout awaiting connection from server
2740 elsif($pong !~ /^PONG/) {
2741 logmsg "DATA sockfilt unexpected response: $pong\n";
2742 logmsg "DATA sockfilt for active data channel failed\n";
2743 logmsg "DATA sockfilt killed now\n";
2744 killsockfilters($piddir, $proto, $ipvnum, $idnum, $verbose, 'data');
2745 logmsg "DATA sockfilt not running\n";
2746 datasockf_state('STOPPED');
2747 # client shall timeout awaiting connection from server
2751 logmsg "DATA sockfilt for active data channel started (pid $slavepid)\n";
2753 logmsg "====> Active DATA channel connected to client port $port\n";
2758 #**********************************************************************
2759 # datasockf_state is used to change variables that keep state info
2760 # relative to the FTP secondary or data sockfilt process as soon as
2761 # one of the five possible stable states is reached. Variables that
2762 # are modified by this sub may be checked independently but should
2763 # not be changed except by calling this sub.
2765 sub datasockf_state {
2768 if($state eq 'STOPPED') {
2769 # Data sockfilter initial state, not running,
2770 # not connected and not used.
2771 $datasockf_state = $state;
2772 $datasockf_mode = 'none';
2773 $datasockf_runs = 'no';
2774 $datasockf_conn = 'no';
2776 elsif($state eq 'PASSIVE') {
2777 # Data sockfilter accepted connection from client.
2778 $datasockf_state = $state;
2779 $datasockf_mode = 'passive';
2780 $datasockf_runs = 'yes';
2781 $datasockf_conn = 'yes';
2783 elsif($state eq 'ACTIVE') {
2784 # Data sockfilter has connected to client.
2785 $datasockf_state = $state;
2786 $datasockf_mode = 'active';
2787 $datasockf_runs = 'yes';
2788 $datasockf_conn = 'yes';
2790 elsif($state eq 'PASSIVE_NODATACONN') {
2791 # Data sockfilter bound port without listening,
2792 # client won't be able to establish data connection.
2793 $datasockf_state = $state;
2794 $datasockf_mode = 'passive';
2795 $datasockf_runs = 'yes';
2796 $datasockf_conn = 'no';
2798 elsif($state eq 'ACTIVE_NODATACONN') {
2799 # Data sockfilter does not even run,
2800 # client awaits data connection from server in vain.
2801 $datasockf_state = $state;
2802 $datasockf_mode = 'active';
2803 $datasockf_runs = 'no';
2804 $datasockf_conn = 'no';
2807 die "Internal error. Unknown datasockf state: $state!";
2811 #**********************************************************************
2812 # nodataconn_str returns string of effective nodataconn command. Notice
2813 # that $nodataconn may be set alone or in addition to a $nodataconnXXX.
2815 sub nodataconn_str {
2818 $str = 'NODATACONN' if($nodataconn);
2819 $str = 'NODATACONN425' if($nodataconn425);
2820 $str = 'NODATACONN421' if($nodataconn421);
2821 $str = 'NODATACONN150' if($nodataconn150);
2825 #**********************************************************************
2826 # customize configures test server operation for each curl test, reading
2827 # configuration commands/parameters from server commands file each time
2828 # a new client control connection is established with the test server.
2829 # On success returns 1, otherwise zero.
2832 $ctrldelay = 0; # default is no throttling of the ctrl stream
2833 $datadelay = 0; # default is no throttling of the data stream
2834 $retrweirdo = 0; # default is no use of RETRWEIRDO
2835 $retrnosize = 0; # default is no use of RETRNOSIZE
2836 $retrsize = 0; # default is no use of RETRSIZE
2837 $pasvbadip = 0; # default is no use of PASVBADIP
2838 $nosave = 0; # default is to actually save uploaded data to file
2839 $nodataconn = 0; # default is to establish or accept data channel
2840 $nodataconn425 = 0; # default is to not send 425 without data channel
2841 $nodataconn421 = 0; # default is to not send 421 without data channel
2842 $nodataconn150 = 0; # default is to not send 150 without data channel
2843 $storeresp = ""; # send as ultimate STOR response
2844 $postfetch = ""; # send as header after a FETCH response
2845 @capabilities = (); # default is to not support capability commands
2846 @auth_mechs = (); # default is to not support authentication commands
2847 %fulltextreply = ();#
2848 %commandreply = (); #
2849 %customcount = (); #
2852 open(my $custom, "<", "$logdir/$SERVERCMD") ||
2855 logmsg "FTPD: Getting commands from $logdir/$SERVERCMD\n";
2858 if($_ =~ /REPLY \"([A-Z]+ [A-Za-z0-9+-\/=\*. ]+)\" (.*)/) {
2859 $fulltextreply{$1}=eval "qq{$2}";
2860 logmsg "FTPD: set custom reply for $1\n";
2862 elsif($_ =~ /REPLY(LF|) ([A-Za-z0-9+\/=\*]*) (.*)/) {
2863 $commandreply{$2}=eval "qq{$3}";
2865 $commandreply{$2}.="\r\n";
2868 $commandreply{$2}.="\n";
2871 logmsg "FTPD: set custom reply for empty command\n";
2874 logmsg "FTPD: set custom reply for $2 command\n";
2877 elsif($_ =~ /COUNT ([A-Z]+) (.*)/) {
2878 # we blank the custom reply for this command when having
2879 # been used this number of times
2880 $customcount{$1}=$2;
2881 logmsg "FTPD: blank custom reply for $1 command after $2 uses\n";
2883 elsif($_ =~ /DELAY ([A-Z]+) (\d*)/) {
2885 logmsg "FTPD: delay reply for $1 with $2 seconds\n";
2887 elsif($_ =~ /POSTFETCH (.*)/) {
2888 logmsg "FTPD: read POSTFETCH header data\n";
2891 elsif($_ =~ /SLOWDOWN/) {
2894 logmsg "FTPD: send response with 0.01 sec delay between each byte\n";
2896 elsif($_ =~ /RETRWEIRDO/) {
2897 logmsg "FTPD: instructed to use RETRWEIRDO\n";
2900 elsif($_ =~ /RETRNOSIZE/) {
2901 logmsg "FTPD: instructed to use RETRNOSIZE\n";
2904 elsif($_ =~ /RETRSIZE (\d+)/) {
2906 logmsg "FTPD: instructed to use RETRSIZE = $1\n";
2908 elsif($_ =~ /PASVBADIP/) {
2909 logmsg "FTPD: instructed to use PASVBADIP\n";
2912 elsif($_ =~ /NODATACONN425/) {
2913 # applies to both active and passive FTP modes
2914 logmsg "FTPD: instructed to use NODATACONN425\n";
2918 elsif($_ =~ /NODATACONN421/) {
2919 # applies to both active and passive FTP modes
2920 logmsg "FTPD: instructed to use NODATACONN421\n";
2924 elsif($_ =~ /NODATACONN150/) {
2925 # applies to both active and passive FTP modes
2926 logmsg "FTPD: instructed to use NODATACONN150\n";
2930 elsif($_ =~ /NODATACONN/) {
2931 # applies to both active and passive FTP modes
2932 logmsg "FTPD: instructed to use NODATACONN\n";
2935 elsif($_ =~ /^STOR (.*)/) {
2937 logmsg "FTPD: instructed to use respond to STOR with '$storeresp'\n";
2939 elsif($_ =~ /CAPA (.*)/) {
2940 logmsg "FTPD: instructed to support CAPABILITY command\n";
2941 @capabilities = split(/ (?!(?:[^" ]|[^"] [^"])+")/, $1);
2942 foreach (@capabilities) {
2943 $_ = $1 if /^"(.*)"$/;
2946 elsif($_ =~ /AUTH (.*)/) {
2947 logmsg "FTPD: instructed to support AUTHENTICATION command\n";
2948 @auth_mechs = split(/ /, $1);
2950 elsif($_ =~ /NOSAVE/) {
2951 # don't actually store the file we upload - to be used when
2952 # uploading insanely huge amounts
2954 logmsg "FTPD: NOSAVE prevents saving of uploaded data\n";
2956 elsif($_ =~ /^Testnum (\d+)/){
2958 logmsg "FTPD: run test case number: $testno\n";
2964 #----------------------------------------------------------------------
2965 #----------------------------------------------------------------------
2966 #--------------------------- END OF SUBS ----------------------------
2967 #----------------------------------------------------------------------
2968 #----------------------------------------------------------------------
2970 #**********************************************************************
2971 # Parse command line options
2975 # --verbose # verbose
2976 # --srcdir # source directory
2977 # --id # server instance number
2978 # --proto # server protocol
2979 # --pidfile # server pid file
2980 # --portfile # server port file
2981 # --logfile # server log file
2982 # --logdir # server log directory
2983 # --ipv4 # server IP version 4
2984 # --ipv6 # server IP version 6
2985 # --port # server listener port
2986 # --addr # server address for listener port binding
2989 if($ARGV[0] eq '--verbose') {
2992 elsif($ARGV[0] eq '--srcdir') {
2998 elsif($ARGV[0] eq '--id') {
2999 if($ARGV[1] && ($ARGV[1] =~ /^(\d+)$/)) {
3000 $idnum = $1 if($1 > 0);
3004 elsif($ARGV[0] eq '--proto') {
3005 if($ARGV[1] && ($ARGV[1] =~ /^(ftp|imap|pop3|smtp)$/)) {
3010 die "unsupported protocol $ARGV[1]";
3013 elsif($ARGV[0] eq '--pidfile') {
3015 $pidfile = $ARGV[1];
3019 elsif($ARGV[0] eq '--portfile') {
3021 $portfile = $ARGV[1];
3025 elsif($ARGV[0] eq '--logfile') {
3027 $logfile = $ARGV[1];
3031 elsif($ARGV[0] eq '--logdir') {
3037 elsif($ARGV[0] eq '--ipv4') {
3039 $listenaddr = '127.0.0.1' if($listenaddr eq '::1');
3041 elsif($ARGV[0] eq '--ipv6') {
3043 $listenaddr = '::1' if($listenaddr eq '127.0.0.1');
3045 elsif($ARGV[0] eq '--port') {
3046 if($ARGV[1] =~ /^(\d+)$/) {
3051 elsif($ARGV[0] eq '--addr') {
3053 my $tmpstr = $ARGV[1];
3054 if($tmpstr =~ /^(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)$/) {
3055 $listenaddr = "$1.$2.$3.$4" if($ipvnum == 4);
3057 elsif($ipvnum == 6) {
3058 $listenaddr = $tmpstr;
3059 $listenaddr =~ s/^\[(.*)\]$/$1/;
3065 print STDERR "\nWarning: ftpserver.pl unknown parameter: $ARGV[0]\n";
3070 #***************************************************************************
3071 # Initialize command line option dependent variables
3075 # Use our pidfile directory to store the other pidfiles
3076 $piddir = dirname($pidfile);
3079 # Use the current directory to store all the pidfiles
3081 $pidfile = server_pidfilename($piddir, $proto, $ipvnum, $idnum);
3084 $portfile = $piddir . "/" . $PORTFILE;
3087 $srcdir = $ENV{'srcdir'} || '.';
3090 $logfile = server_logfilename($logdir, $proto, $ipvnum, $idnum);
3093 $mainsockf_pidfile = mainsockf_pidfilename($piddir, $proto, $ipvnum, $idnum);
3094 $mainsockf_logfile =
3095 mainsockf_logfilename($logdir, $proto, $ipvnum, $idnum);
3097 if($proto eq 'ftp') {
3098 $datasockf_pidfile = datasockf_pidfilename($piddir, $proto, $ipvnum, $idnum);
3099 $datasockf_logfile =
3100 datasockf_logfilename($logdir, $proto, $ipvnum, $idnum);
3103 $srvrname = servername_str($proto, $ipvnum, $idnum);
3104 $serverlogs_lockfile = "$logdir/$LOCKDIR/${srvrname}.lock";
3106 $idstr = "$idnum" if($idnum > 1);
3108 protocolsetup($proto);
3110 $SIG{INT} = \&exit_signal_handler;
3111 $SIG{TERM} = \&exit_signal_handler;
3116 if($portfile && !$port) {
3118 open(my $p, "<", "$portfile");
3124 logmsg sprintf("%s server listens on port IPv${ipvnum}/${port}\n", uc($proto));
3126 open(my $pid, ">", "$pidfile");
3130 logmsg("logged pid $$ in $pidfile\n");
3134 # kill previous data connection sockfilt when alive
3135 if($datasockf_runs eq 'yes') {
3136 killsockfilters($piddir, $proto, $ipvnum, $idnum, $verbose, 'data');
3137 logmsg "DATA sockfilt for $datasockf_mode data channel killed now\n";
3139 datasockf_state('STOPPED');
3142 # We read 'sockfilt' commands.
3146 logmsg "Awaiting input\n";
3147 sysread_or_die(\*SFREAD, \$input, 5);
3149 if($input !~ /^CNCT/) {
3150 # we wait for a connected client
3151 logmsg "MAIN sockfilt said: $input";
3154 logmsg "====> Client connect\n";
3156 set_advisor_read_lock($serverlogs_lockfile);
3157 $serverlogslocked = 1;
3162 &customize(); # read test control instructions
3163 loadtest("$logdir/test$testno");
3165 my $welcome = $commandreply{"welcome"};
3167 $welcome = $displaytext{"welcome"};
3170 # clear it after use
3171 $commandreply{"welcome"}="";
3172 if($welcome !~ /\r\n\z/) {
3176 sendcontrol $welcome;
3178 #remove global variables from last connection
3179 if($ftplistparserstate) {
3180 undef $ftplistparserstate;
3187 print STDERR "OUT: $welcome";
3195 # Now we expect to read DATA\n[hex size]\n[prot], where the [prot]
3196 # part only is FTP lingo.
3199 sysread_or_die(\*SFREAD, \$i, 5);
3202 logmsg "MAIN sockfilt said $i";
3205 printf SFWRITE "ACKD\n";
3212 sysread_or_die(\*SFREAD, \$i, 5);
3215 if($i =~ /^([0-9a-fA-F]{4})\n/) {
3220 read_mainsockf(\$input, $size);
3226 # Loop until command completion
3227 next unless($full =~ /\r\n$/);
3229 # Remove trailing CRLF.
3230 $full =~ s/[\n\r]+$//;
3234 if($proto eq "imap") {
3235 # IMAP is different with its identifier first on the command line
3236 if(($full =~ /^([^ ]+) ([^ ]+) (.*)/) ||
3237 ($full =~ /^([^ ]+) ([^ ]+)/)) {
3238 $cmdid=$1; # set the global variable
3242 # IMAP authentication cancellation
3243 elsif($full =~ /^\*$/) {
3244 # Command id has already been set
3248 # IMAP long "commands" are base64 authentication data
3249 elsif($full =~ /^[A-Z0-9+\/]*={0,2}$/i) {
3250 # Command id has already been set
3255 sendcontrol "$full BAD Command\r\n";
3259 elsif($full =~ /^([A-Z]{3,4})(\s(.*))?$/i) {
3263 elsif($proto eq "pop3") {
3264 # POP3 authentication cancellation
3265 if($full =~ /^\*$/) {
3269 # POP3 long "commands" are base64 authentication data
3270 elsif($full =~ /^[A-Z0-9+\/]*={0,2}$/i) {
3275 sendcontrol "-ERR Unrecognized command\r\n";
3279 elsif($proto eq "smtp") {
3280 # SMTP authentication cancellation
3281 if($full =~ /^\*$/) {
3285 # SMTP long "commands" are base64 authentication data
3286 elsif($full =~ /^[A-Z0-9+\/]{0,512}={0,2}$/i) {
3291 sendcontrol "500 Unrecognized command\r\n";
3296 sendcontrol "500 Unrecognized command\r\n";
3300 logmsg "< \"$full\"\n";
3303 print STDERR "IN: $full\n";
3308 my $delay = $delayreply{$FTPCMD};
3310 # just go sleep this many seconds!
3311 logmsg("Sleep for $delay seconds\n");
3312 my $twentieths = $delay * 20;
3313 while($twentieths--) {
3314 portable_sleep(0.05) unless($got_exit_signal);
3318 my $check = 1; # no response yet
3320 # See if there is a custom reply for the full text
3321 my $fulltext = $FTPARG ? $FTPCMD . " " . $FTPARG : $FTPCMD;
3322 my $text = $fulltextreply{$fulltext};
3323 if($text && ($text ne "")) {
3324 sendcontrol "$text\r\n";
3328 # See if there is a custom reply for the command
3329 $text = $commandreply{$FTPCMD};
3330 if($text && ($text ne "")) {
3331 if($customcount{$FTPCMD} && (!--$customcount{$FTPCMD})) {
3332 # used enough times so blank the custom command reply
3333 $commandreply{$FTPCMD}="";
3340 # See if there is any display text for the command
3341 $text = $displaytext{$FTPCMD};
3342 if($text && ($text ne "")) {
3343 if($proto eq 'imap') {
3344 sendcontrol "$cmdid $text\r\n";
3347 sendcontrol "$text\r\n";
3353 # only perform this if we're not faking a reply
3354 my $func = $commandfunc{uc($FTPCMD)};
3356 &$func($FTPARG, $FTPCMD);
3363 logmsg "$FTPCMD wasn't handled!\n";
3364 if($proto eq 'pop3') {
3365 sendcontrol "-ERR $FTPCMD is not dealt with!\r\n";
3367 elsif($proto eq 'imap') {
3368 sendcontrol "$cmdid BAD $FTPCMD is not dealt with!\r\n";
3371 sendcontrol "500 $FTPCMD is not dealt with!\r\n";
3376 logmsg "====> Client disconnected\n";
3378 if($serverlogslocked) {
3379 $serverlogslocked = 0;
3380 clear_advisor_read_lock($serverlogs_lockfile);
3384 killsockfilters($piddir, $proto, $ipvnum, $idnum, $verbose);
3386 if($serverlogslocked) {
3387 $serverlogslocked = 0;
3388 clear_advisor_read_lock($serverlogs_lockfile);