Debian Codegraph @

deps/curl/tests/ftpserver.pl

raw
1 #!/usr/bin/env perl
2 #***************************************************************************
3 # _ _ ____ _
4 # Project ___| | | | _ \| |
5 # / __| | | | |_) | |
6 # | (__| |_| | _ <| |___
7 # \___|\___/|_| \_\_____|
8 #
9 # Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
10 #
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.haxx.se/docs/copyright.html.
14 #
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.
18 #
19 # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
20 # KIND, either express or implied.
21 #
22 ###########################################################################
23
24 # This is a server designed for the curl test suite.
25 #
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.
31 #
32 # It is meant to exercise curl, it is not meant to be a fully working
33 # or even very standard compliant server.
34 #
35 # You may optionally specify port on the command line, otherwise it'll
36 # default to port 8921.
37 #
38 # All socket/network/TCP related stuff is done by the 'sockfilt' program.
39 #
40
41 BEGIN {
42 push(@INC, $ENV{'srcdir'}) if(defined $ENV{'srcdir'});
43 push(@INC, ".");
44 # sub second timestamping needs Time::HiRes
45 eval {
46 no warnings "all";
47 require Time::HiRes;
48 import Time::HiRes qw( gettimeofday );
49 }
50 }
51
52 use strict;
53 use warnings;
54 use IPC::Open2;
55 use Digest::MD5;
56
57 require "getpart.pm";
58 require "ftp.pm";
59 require "directories.pm";
60
61 use serverhelp qw(
62 servername_str
63 server_pidfilename
64 server_logfilename
65 mainsockf_pidfilename
66 mainsockf_logfilename
67 datasockf_pidfilename
68 datasockf_logfilename
69 );
70
71 use sshhelp qw(
72 exe_ext
73 );
74
75 #**********************************************************************
76 # global vars...
77 #
78 my $verbose = 0; # set to 1 for debugging
79 my $idstr = ""; # server instance string
80 my $idnum = 1; # server instance number
81 my $ipvnum = 4; # server IPv number (4 or 6)
82 my $proto = 'ftp'; # default server protocol
83 my $srcdir; # directory where ftpserver.pl is located
84 my $srvrname; # server name for presentation purposes
85 my $cwd_testno; # test case numbers extracted from CWD command
86 my $path = '.';
87 my $logdir = $path .'/log';
88
89 #**********************************************************************
90 # global vars used for server address and primary listener port
91 #
92 my $port = 8921; # default primary listener port
93 my $listenaddr = '127.0.0.1'; # default address for listener port
94
95 #**********************************************************************
96 # global vars used for file names
97 #
98 my $pidfile; # server pid file name
99 my $logfile; # server log file name
100 my $mainsockf_pidfile; # pid file for primary connection sockfilt process
101 my $mainsockf_logfile; # log file for primary connection sockfilt process
102 my $datasockf_pidfile; # pid file for secondary connection sockfilt process
103 my $datasockf_logfile; # log file for secondary connection sockfilt process
104
105 #**********************************************************************
106 # global vars used for server logs advisor read lock handling
107 #
108 my $SERVERLOGS_LOCK = 'log/serverlogs.lock';
109 my $serverlogslocked = 0;
110
111 #**********************************************************************
112 # global vars used for child processes PID tracking
113 #
114 my $sfpid; # PID for primary connection sockfilt process
115 my $slavepid; # PID for secondary connection sockfilt process
116
117 #**********************************************************************
118 # global typeglob filehandle vars to read/write from/to sockfilters
119 #
120 local *SFREAD; # used to read from primary connection
121 local *SFWRITE; # used to write to primary connection
122 local *DREAD; # used to read from secondary connection
123 local *DWRITE; # used to write to secondary connection
124
125 my $sockfilt_timeout = 5; # default timeout for sockfilter eXsysreads
126
127 #**********************************************************************
128 # global vars which depend on server protocol selection
129 #
130 my %commandfunc; # protocol command specific function callbacks
131 my %displaytext; # text returned to client before callback runs
132
133 #**********************************************************************
134 # global vars customized for each test from the server commands file
135 #
136 my $ctrldelay; # set if server should throttle ctrl stream
137 my $datadelay; # set if server should throttle data stream
138 my $retrweirdo; # set if ftp server should use RETRWEIRDO
139 my $retrnosize; # set if ftp server should use RETRNOSIZE
140 my $pasvbadip; # set if ftp server should use PASVBADIP
141 my $nosave; # set if ftp server should not save uploaded data
142 my $nodataconn; # set if ftp srvr doesn't establish or accepts data channel
143 my $nodataconn425; # set if ftp srvr doesn't establish data ch and replies 425
144 my $nodataconn421; # set if ftp srvr doesn't establish data ch and replies 421
145 my $nodataconn150; # set if ftp srvr doesn't establish data ch and replies 150
146 my @capabilities; # set if server supports capability commands
147 my @auth_mechs; # set if server supports authentication commands
148 my %fulltextreply; #
149 my %commandreply; #
150 my %customcount; #
151 my %delayreply; #
152
153 #**********************************************************************
154 # global variables for to test ftp wildcardmatching or other test that
155 # need flexible LIST responses.. and corresponding files.
156 # $ftptargetdir is keeping the fake "name" of LIST directory.
157 #
158 my $ftplistparserstate;
159 my $ftptargetdir="";
160
161 #**********************************************************************
162 # global variables used when running a ftp server to keep state info
163 # relative to the secondary or data sockfilt process. Values of these
164 # variables should only be modified using datasockf_state() sub, given
165 # that they are closely related and relationship is a bit awkward.
166 #
167 my $datasockf_state = 'STOPPED'; # see datasockf_state() sub
168 my $datasockf_mode = 'none'; # ['none','active','passive']
169 my $datasockf_runs = 'no'; # ['no','yes']
170 my $datasockf_conn = 'no'; # ['no','yes']
171
172 #**********************************************************************
173 # global vars used for signal handling
174 #
175 my $got_exit_signal = 0; # set if program should finish execution ASAP
176 my $exit_signal; # first signal handled in exit_signal_handler
177
178 #**********************************************************************
179 # Mail related definitions
180 #
181 my $TEXT_PASSWORD = "secret";
182 my $POP3_TIMESTAMP = "<1972.987654321\@curl>";
183
184 #**********************************************************************
185 # exit_signal_handler will be triggered to indicate that the program
186 # should finish its execution in a controlled way as soon as possible.
187 # For now, program will also terminate from within this handler.
188 #
189 sub exit_signal_handler {
190 my $signame = shift;
191 # For now, simply mimic old behavior.
192 killsockfilters($proto, $ipvnum, $idnum, $verbose);
193 unlink($pidfile);
194 if($serverlogslocked) {
195 $serverlogslocked = 0;
196 clear_advisor_read_lock($SERVERLOGS_LOCK);
197 }
198 exit;
199 }
200
201 #**********************************************************************
202 # logmsg is general message logging subroutine for our test servers.
203 #
204 sub logmsg {
205 my $now;
206 # sub second timestamping needs Time::HiRes
207 if($Time::HiRes::VERSION) {
208 my ($seconds, $usec) = gettimeofday();
209 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
210 localtime($seconds);
211 $now = sprintf("%02d:%02d:%02d.%06d ", $hour, $min, $sec, $usec);
212 }
213 else {
214 my $seconds = time();
215 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
216 localtime($seconds);
217 $now = sprintf("%02d:%02d:%02d ", $hour, $min, $sec);
218 }
219 if(open(LOGFILEFH, ">>$logfile")) {
220 print LOGFILEFH $now;
221 print LOGFILEFH @_;
222 close(LOGFILEFH);
223 }
224 }
225
226 sub ftpmsg {
227 # append to the server.input file
228 open(INPUT, ">>log/server$idstr.input") ||
229 logmsg "failed to open log/server$idstr.input\n";
230
231 print INPUT @_;
232 close(INPUT);
233
234 # use this, open->print->close system only to make the file
235 # open as little as possible, to make the test suite run
236 # better on windows/cygwin
237 }
238
239 #**********************************************************************
240 # eXsysread is a wrapper around perl's sysread() function. This will
241 # repeat the call to sysread() until it has actually read the complete
242 # number of requested bytes or an unrecoverable condition occurs.
243 # On success returns a positive value, the number of bytes requested.
244 # On failure or timeout returns zero.
245 #
246 sub eXsysread {
247 my $FH = shift;
248 my $scalar = shift;
249 my $nbytes = shift;
250 my $timeout = shift; # A zero timeout disables eXsysread() time limit
251 #
252 my $time_limited = 0;
253 my $timeout_rest = 0;
254 my $start_time = 0;
255 my $nread = 0;
256 my $rc;
257
258 $$scalar = "";
259
260 if((not defined $nbytes) || ($nbytes < 1)) {
261 logmsg "Error: eXsysread() failure: " .
262 "length argument must be positive\n";
263 return 0;
264 }
265 if((not defined $timeout) || ($timeout < 0)) {
266 logmsg "Error: eXsysread() failure: " .
267 "timeout argument must be zero or positive\n";
268 return 0;
269 }
270 if($timeout > 0) {
271 # caller sets eXsysread() time limit
272 $time_limited = 1;
273 $timeout_rest = $timeout;
274 $start_time = int(time());
275 }
276
277 while($nread < $nbytes) {
278 if($time_limited) {
279 eval {
280 local $SIG{ALRM} = sub { die "alarm\n"; };
281 alarm $timeout_rest;
282 $rc = sysread($FH, $$scalar, $nbytes - $nread, $nread);
283 alarm 0;
284 };
285 $timeout_rest = $timeout - (int(time()) - $start_time);
286 if($timeout_rest < 1) {
287 logmsg "Error: eXsysread() failure: timed out\n";
288 return 0;
289 }
290 }
291 else {
292 $rc = sysread($FH, $$scalar, $nbytes - $nread, $nread);
293 }
294 if($got_exit_signal) {
295 logmsg "Error: eXsysread() failure: signalled to die\n";
296 return 0;
297 }
298 if(not defined $rc) {
299 if($!{EINTR}) {
300 logmsg "Warning: retrying sysread() interrupted system call\n";
301 next;
302 }
303 if($!{EAGAIN}) {
304 logmsg "Warning: retrying sysread() due to EAGAIN\n";
305 next;
306 }
307 if($!{EWOULDBLOCK}) {
308 logmsg "Warning: retrying sysread() due to EWOULDBLOCK\n";
309 next;
310 }
311 logmsg "Error: sysread() failure: $!\n";
312 return 0;
313 }
314 if($rc < 0) {
315 logmsg "Error: sysread() failure: returned negative value $rc\n";
316 return 0;
317 }
318 if($rc == 0) {
319 logmsg "Error: sysread() failure: read zero bytes\n";
320 return 0;
321 }
322 $nread += $rc;
323 }
324 return $nread;
325 }
326
327 #**********************************************************************
328 # read_mainsockf attempts to read the given amount of output from the
329 # sockfilter which is in use for the main or primary connection. This
330 # reads untranslated sockfilt lingo which may hold data read from the
331 # main or primary socket. On success returns 1, otherwise zero.
332 #
333 sub read_mainsockf {
334 my $scalar = shift;
335 my $nbytes = shift;
336 my $timeout = shift; # Optional argument, if zero blocks indefinitively
337 my $FH = \*SFREAD;
338
339 if(not defined $timeout) {
340 $timeout = $sockfilt_timeout + ($nbytes >> 12);
341 }
342 if(eXsysread($FH, $scalar, $nbytes, $timeout) != $nbytes) {
343 my ($fcaller, $lcaller) = (caller)[1,2];
344 logmsg "Error: read_mainsockf() failure at $fcaller " .
345 "line $lcaller. Due to eXsysread() failure\n";
346 return 0;
347 }
348 return 1;
349 }
350
351 #**********************************************************************
352 # read_datasockf attempts to read the given amount of output from the
353 # sockfilter which is in use for the data or secondary connection. This
354 # reads untranslated sockfilt lingo which may hold data read from the
355 # data or secondary socket. On success returns 1, otherwise zero.
356 #
357 sub read_datasockf {
358 my $scalar = shift;
359 my $nbytes = shift;
360 my $timeout = shift; # Optional argument, if zero blocks indefinitively
361 my $FH = \*DREAD;
362
363 if(not defined $timeout) {
364 $timeout = $sockfilt_timeout + ($nbytes >> 12);
365 }
366 if(eXsysread($FH, $scalar, $nbytes, $timeout) != $nbytes) {
367 my ($fcaller, $lcaller) = (caller)[1,2];
368 logmsg "Error: read_datasockf() failure at $fcaller " .
369 "line $lcaller. Due to eXsysread() failure\n";
370 return 0;
371 }
372 return 1;
373 }
374
375 sub sysread_or_die {
376 my $FH = shift;
377 my $scalar = shift;
378 my $length = shift;
379 my $fcaller;
380 my $lcaller;
381 my $result;
382
383 $result = sysread($$FH, $$scalar, $length);
384
385 if(not defined $result) {
386 ($fcaller, $lcaller) = (caller)[1,2];
387 logmsg "Failed to read input\n";
388 logmsg "Error: $srvrname server, sysread error: $!\n";
389 logmsg "Exited from sysread_or_die() at $fcaller " .
390 "line $lcaller. $srvrname server, sysread error: $!\n";
391 killsockfilters($proto, $ipvnum, $idnum, $verbose);
392 unlink($pidfile);
393 if($serverlogslocked) {
394 $serverlogslocked = 0;
395 clear_advisor_read_lock($SERVERLOGS_LOCK);
396 }
397 exit;
398 }
399 elsif($result == 0) {
400 ($fcaller, $lcaller) = (caller)[1,2];
401 logmsg "Failed to read input\n";
402 logmsg "Error: $srvrname server, read zero\n";
403 logmsg "Exited from sysread_or_die() at $fcaller " .
404 "line $lcaller. $srvrname server, read zero\n";
405 killsockfilters($proto, $ipvnum, $idnum, $verbose);
406 unlink($pidfile);
407 if($serverlogslocked) {
408 $serverlogslocked = 0;
409 clear_advisor_read_lock($SERVERLOGS_LOCK);
410 }
411 exit;
412 }
413
414 return $result;
415 }
416
417 sub startsf {
418 my $mainsockfcmd = "./server/sockfilt".exe_ext('SRV')." " .
419 "--ipv$ipvnum --port $port " .
420 "--pidfile \"$mainsockf_pidfile\" " .
421 "--logfile \"$mainsockf_logfile\"";
422 $sfpid = open2(*SFREAD, *SFWRITE, $mainsockfcmd);
423
424 print STDERR "$mainsockfcmd\n" if($verbose);
425
426 print SFWRITE "PING\n";
427 my $pong;
428 sysread_or_die(\*SFREAD, \$pong, 5);
429
430 if($pong !~ /^PONG/) {
431 logmsg "Failed sockfilt command: $mainsockfcmd\n";
432 killsockfilters($proto, $ipvnum, $idnum, $verbose);
433 unlink($pidfile);
434 if($serverlogslocked) {
435 $serverlogslocked = 0;
436 clear_advisor_read_lock($SERVERLOGS_LOCK);
437 }
438 die "Failed to start sockfilt!";
439 }
440 }
441
442 #**********************************************************************
443 # Returns the given test's reply data
444 #
445 sub getreplydata {
446 my ($testno) = @_;
447 my $testpart = "";
448
449 $testno =~ s/^([^0-9]*)//;
450 if($testno > 10000) {
451 $testpart = $testno % 10000;
452 $testno = int($testno / 10000);
453 }
454
455 loadtest("$srcdir/data/test$testno");
456
457 my @data = getpart("reply", "data$testpart");
458 if((!@data) && ($testpart ne "")) {
459 @data = getpart("reply", "data");
460 }
461
462 return @data;
463 }
464
465 sub sockfilt {
466 my $l;
467 foreach $l (@_) {
468 printf SFWRITE "DATA\n%04x\n", length($l);
469 print SFWRITE $l;
470 }
471 }
472
473 sub sockfiltsecondary {
474 my $l;
475 foreach $l (@_) {
476 printf DWRITE "DATA\n%04x\n", length($l);
477 print DWRITE $l;
478 }
479 }
480
481 #**********************************************************************
482 # Send data to the client on the control stream, which happens to be plain
483 # stdout.
484 #
485 sub sendcontrol {
486 if(!$ctrldelay) {
487 # spit it all out at once
488 sockfilt @_;
489 }
490 else {
491 my $a = join("", @_);
492 my @a = split("", $a);
493
494 for(@a) {
495 sockfilt $_;
496 select(undef, undef, undef, 0.01);
497 }
498 }
499 my $log;
500 foreach $log (@_) {
501 my $l = $log;
502 $l =~ s/\r/[CR]/g;
503 $l =~ s/\n/[LF]/g;
504 logmsg "> \"$l\"\n";
505 }
506 }
507
508 #**********************************************************************
509 # Send data to the FTP client on the data stream when data connection
510 # is actually established. Given that this sub should only be called
511 # when a data connection is supposed to be established, calling this
512 # without a data connection is an indication of weak logic somewhere.
513 #
514 sub senddata {
515 my $l;
516 if($datasockf_conn eq 'no') {
517 logmsg "WARNING: Detected data sending attempt without DATA channel\n";
518 foreach $l (@_) {
519 logmsg "WARNING: Data swallowed: $l\n"
520 }
521 return;
522 }
523
524 foreach $l (@_) {
525 if(!$datadelay) {
526 # spit it all out at once
527 sockfiltsecondary $l;
528 }
529 else {
530 # pause between each byte
531 for (split(//,$l)) {
532 sockfiltsecondary $_;
533 select(undef, undef, undef, 0.01);
534 }
535 }
536 }
537 }
538
539 #**********************************************************************
540 # protocolsetup initializes the 'displaytext' and 'commandfunc' hashes
541 # for the given protocol. References to protocol command callbacks are
542 # stored in 'commandfunc' hash, and text which will be returned to the
543 # client before the command callback runs is stored in 'displaytext'.
544 #
545 sub protocolsetup {
546 my $proto = $_[0];
547
548 if($proto eq 'ftp') {
549 %commandfunc = (
550 'PORT' => \&PORT_ftp,
551 'EPRT' => \&PORT_ftp,
552 'LIST' => \&LIST_ftp,
553 'NLST' => \&NLST_ftp,
554 'PASV' => \&PASV_ftp,
555 'CWD' => \&CWD_ftp,
556 'PWD' => \&PWD_ftp,
557 'EPSV' => \&PASV_ftp,
558 'RETR' => \&RETR_ftp,
559 'SIZE' => \&SIZE_ftp,
560 'REST' => \&REST_ftp,
561 'STOR' => \&STOR_ftp,
562 'APPE' => \&STOR_ftp, # append looks like upload
563 'MDTM' => \&MDTM_ftp,
564 );
565 %displaytext = (
566 'USER' => '331 We are happy you popped in!',
567 'PASS' => '230 Welcome you silly person',
568 'PORT' => '200 You said PORT - I say FINE',
569 'TYPE' => '200 I modify TYPE as you wanted',
570 'LIST' => '150 here comes a directory',
571 'NLST' => '150 here comes a directory',
572 'CWD' => '250 CWD command successful.',
573 'SYST' => '215 UNIX Type: L8', # just fake something
574 'QUIT' => '221 bye bye baby', # just reply something
575 'MKD' => '257 Created your requested directory',
576 'REST' => '350 Yeah yeah we set it there for you',
577 'DELE' => '200 OK OK OK whatever you say',
578 'RNFR' => '350 Received your order. Please provide more',
579 'RNTO' => '250 Ok, thanks. File renaming completed.',
580 'NOOP' => '200 Yes, I\'m very good at doing nothing.',
581 'PBSZ' => '500 PBSZ not implemented',
582 'PROT' => '500 PROT not implemented',
583 'welcome' => join("",
584 '220- _ _ ____ _ '."\r\n",
585 '220- ___| | | | _ \| | '."\r\n",
586 '220- / __| | | | |_) | | '."\r\n",
587 '220- | (__| |_| | _ {| |___ '."\r\n",
588 '220 \___|\___/|_| \_\_____|'."\r\n")
589 );
590 }
591 elsif($proto eq 'pop3') {
592 %commandfunc = (
593 'APOP' => \&APOP_pop3,
594 'AUTH' => \&AUTH_pop3,
595 'CAPA' => \&CAPA_pop3,
596 'DELE' => \&DELE_pop3,
597 'LIST' => \&LIST_pop3,
598 'NOOP' => \&NOOP_pop3,
599 'PASS' => \&PASS_pop3,
600 'QUIT' => \&QUIT_pop3,
601 'RETR' => \&RETR_pop3,
602 'RSET' => \&RSET_pop3,
603 'STAT' => \&STAT_pop3,
604 'TOP' => \&TOP_pop3,
605 'UIDL' => \&UIDL_pop3,
606 'USER' => \&USER_pop3,
607 );
608 %displaytext = (
609 'welcome' => join("",
610 ' _ _ ____ _ '."\r\n",
611 ' ___| | | | _ \| | '."\r\n",
612 ' / __| | | | |_) | | '."\r\n",
613 ' | (__| |_| | _ {| |___ '."\r\n",
614 ' \___|\___/|_| \_\_____|'."\r\n",
615 '+OK curl POP3 server ready to serve '."\r\n")
616 );
617 }
618 elsif($proto eq 'imap') {
619 %commandfunc = (
620 'APPEND' => \&APPEND_imap,
621 'CAPABILITY' => \&CAPABILITY_imap,
622 'CHECK' => \&CHECK_imap,
623 'CLOSE' => \&CLOSE_imap,
624 'COPY' => \&COPY_imap,
625 'CREATE' => \&CREATE_imap,
626 'DELETE' => \&DELETE_imap,
627 'EXAMINE' => \&EXAMINE_imap,
628 'EXPUNGE' => \&EXPUNGE_imap,
629 'FETCH' => \&FETCH_imap,
630 'LIST' => \&LIST_imap,
631 'LSUB' => \&LSUB_imap,
632 'LOGIN' => \&LOGIN_imap,
633 'LOGOUT' => \&LOGOUT_imap,
634 'NOOP' => \&NOOP_imap,
635 'RENAME' => \&RENAME_imap,
636 'SEARCH' => \&SEARCH_imap,
637 'SELECT' => \&SELECT_imap,
638 'STATUS' => \&STATUS_imap,
639 'STORE' => \&STORE_imap,
640 'UID' => \&UID_imap,
641 );
642 %displaytext = (
643 'welcome' => join("",
644 ' _ _ ____ _ '."\r\n",
645 ' ___| | | | _ \| | '."\r\n",
646 ' / __| | | | |_) | | '."\r\n",
647 ' | (__| |_| | _ {| |___ '."\r\n",
648 ' \___|\___/|_| \_\_____|'."\r\n",
649 '* OK curl IMAP server ready to serve'."\r\n")
650 );
651 }
652 elsif($proto eq 'smtp') {
653 %commandfunc = (
654 'DATA' => \&DATA_smtp,
655 'EHLO' => \&EHLO_smtp,
656 'EXPN' => \&EXPN_smtp,
657 'HELO' => \&HELO_smtp,
658 'HELP' => \&HELP_smtp,
659 'MAIL' => \&MAIL_smtp,
660 'NOOP' => \&NOOP_smtp,
661 'RSET' => \&RSET_smtp,
662 'RCPT' => \&RCPT_smtp,
663 'VRFY' => \&VRFY_smtp,
664 'QUIT' => \&QUIT_smtp,
665 );
666 %displaytext = (
667 'welcome' => join("",
668 '220- _ _ ____ _ '."\r\n",
669 '220- ___| | | | _ \| | '."\r\n",
670 '220- / __| | | | |_) | | '."\r\n",
671 '220- | (__| |_| | _ {| |___ '."\r\n",
672 '220 \___|\___/|_| \_\_____|'."\r\n")
673 );
674 }
675 }
676
677 sub close_dataconn {
678 my ($closed)=@_; # non-zero if already disconnected
679
680 my $datapid = processexists($datasockf_pidfile);
681
682 logmsg "=====> Closing $datasockf_mode DATA connection...\n";
683
684 if(!$closed) {
685 if($datapid > 0) {
686 logmsg "Server disconnects $datasockf_mode DATA connection\n";
687 print DWRITE "DISC\n";
688 my $i;
689 sysread DREAD, $i, 5;
690 }
691 else {
692 logmsg "Server finds $datasockf_mode DATA connection already ".
693 "disconnected\n";
694 }
695 }
696 else {
697 logmsg "Server knows $datasockf_mode DATA connection is already ".
698 "disconnected\n";
699 }
700
701 if($datapid > 0) {
702 print DWRITE "QUIT\n";
703 waitpid($datapid, 0);
704 unlink($datasockf_pidfile) if(-f $datasockf_pidfile);
705 logmsg "DATA sockfilt for $datasockf_mode data channel quits ".
706 "(pid $datapid)\n";
707 }
708 else {
709 logmsg "DATA sockfilt for $datasockf_mode data channel already ".
710 "dead\n";
711 }
712
713 logmsg "=====> Closed $datasockf_mode DATA connection\n";
714
715 datasockf_state('STOPPED');
716 }
717
718 ################
719 ################ SMTP commands
720 ################
721
722 # The type of server (SMTP or ESMTP)
723 my $smtp_type;
724
725 # The client (which normally contains the test number)
726 my $smtp_client;
727
728 sub EHLO_smtp {
729 my ($client) = @_;
730 my @data;
731
732 # TODO: Get the IP address of the client connection to use in the
733 # EHLO response when the client doesn't specify one but for now use
734 # 127.0.0.1
735 if(!$client) {
736 $client = "[127.0.0.1]";
737 }
738
739 # Set the server type to ESMTP
740 $smtp_type = "ESMTP";
741
742 # Calculate the EHLO response
743 push @data, "$smtp_type pingpong test server Hello $client";
744
745 if((@capabilities) || (@auth_mechs)) {
746 my $mechs;
747
748 for my $c (@capabilities) {
749 push @data, $c;
750 }
751
752 for my $am (@auth_mechs) {
753 if(!$mechs) {
754 $mechs = "$am";
755 }
756 else {
757 $mechs .= " $am";
758 }
759 }
760
761 if($mechs) {
762 push @data, "AUTH $mechs";
763 }
764 }
765
766 # Send the EHLO response
767 for(my $i = 0; $i < @data; $i++) {
768 my $d = $data[$i];
769
770 if($i < @data - 1) {
771 sendcontrol "250-$d\r\n";
772 }
773 else {
774 sendcontrol "250 $d\r\n";
775 }
776 }
777
778 # Store the client (as it may contain the test number)
779 $smtp_client = $client;
780
781 return 0;
782 }
783
784 sub HELO_smtp {
785 my ($client) = @_;
786
787 # TODO: Get the IP address of the client connection to use in the HELO
788 # response when the client doesn't specify one but for now use 127.0.0.1
789 if(!$client) {
790 $client = "[127.0.0.1]";
791 }
792
793 # Set the server type to SMTP
794 $smtp_type = "SMTP";
795
796 # Send the HELO response
797 sendcontrol "250 $smtp_type pingpong test server Hello $client\r\n";
798
799 # Store the client (as it may contain the test number)
800 $smtp_client = $client;
801
802 return 0;
803 }
804
805 sub MAIL_smtp {
806 my ($args) = @_;
807
808 logmsg "MAIL_smtp got $args\n";
809
810 if (!$args) {
811 sendcontrol "501 Unrecognized parameter\r\n";
812 }
813 else {
814 my $from;
815 my $size;
816 my $smtputf8 = grep /^SMTPUTF8$/, @capabilities;
817 my @elements = split(/ /, $args);
818
819 # Get the FROM and SIZE parameters
820 for my $e (@elements) {
821 if($e =~ /^FROM:(.*)$/) {
822 $from = $1;
823 }
824 elsif($e =~ /^SIZE=(\d+)$/) {
825 $size = $1;
826 }
827 }
828
829 # Validate the from address (only <> and a valid email address inside
830 # <> are allowed, such as <[email protected]>)
831 if (($from eq "<>") ||
832 (!$smtputf8 && $from =~
833 /^<([a-zA-Z0-9._%+-]+)\@(([a-zA-Z0-9-]+)\.)+([a-zA-Z]{2,4})>$/) ||
834 ($smtputf8 && $from =~
835 /^<([a-zA-Z0-9\x{80}-\x{ff}._%+-]+)\@(([a-zA-Z0-9\x{80}-\x{ff}-]+)\.)+([a-zA-Z]{2,4})>$/)) {
836 my @found;
837 my $valid = 1;
838
839 # Check the capabilities for SIZE and if the specified size is
840 # greater than the message size then reject it
841 if (@found = grep /^SIZE (\d+)$/, @capabilities) {
842 if ($found[0] =~ /^SIZE (\d+)$/) {
843 if ($size > $1) {
844 $valid = 0;
845 }
846 }
847 }
848
849 if(!$valid) {
850 sendcontrol "552 Message size too large\r\n";
851 }
852 else {
853 sendcontrol "250 Sender OK\r\n";
854 }
855 }
856 else {
857 sendcontrol "501 Invalid address\r\n";
858 }
859 }
860
861 return 0;
862 }
863
864 sub RCPT_smtp {
865 my ($args) = @_;
866
867 logmsg "RCPT_smtp got $args\n";
868
869 # Get the TO parameter
870 if($args !~ /^TO:(.*)/) {
871 sendcontrol "501 Unrecognized parameter\r\n";
872 }
873 else {
874 my $smtputf8 = grep /^SMTPUTF8$/, @capabilities;
875 my $to = $1;
876
877 # Validate the to address (only a valid email address inside <> is
878 # allowed, such as <[email protected]>)
879 if ((!$smtputf8 && $to =~
880 /^<([a-zA-Z0-9._%+-]+)\@(([a-zA-Z0-9-]+)\.)+([a-zA-Z]{2,4})>$/) ||
881 ($smtputf8 && $to =~
882 /^<([a-zA-Z0-9\x{80}-\x{ff}._%+-]+)\@(([a-zA-Z0-9\x{80}-\x{ff}-]+)\.)+([a-zA-Z]{2,4})>$/)) {
883 sendcontrol "250 Recipient OK\r\n";
884 }
885 else {
886 sendcontrol "501 Invalid address\r\n";
887 }
888 }
889
890 return 0;
891 }
892
893 sub DATA_smtp {
894 my ($args) = @_;
895
896 if ($args) {
897 sendcontrol "501 Unrecognized parameter\r\n";
898 }
899 elsif ($smtp_client !~ /^(\d*)$/) {
900 sendcontrol "501 Invalid arguments\r\n";
901 }
902 else {
903 sendcontrol "354 Show me the mail\r\n";
904
905 my $testno = $smtp_client;
906 my $filename = "log/upload.$testno";
907
908 logmsg "Store test number $testno in $filename\n";
909
910 open(FILE, ">$filename") ||
911 return 0; # failed to open output
912
913 my $line;
914 my $ulsize=0;
915 my $disc=0;
916 my $raw;
917 while (5 == (sysread \*SFREAD, $line, 5)) {
918 if($line eq "DATA\n") {
919 my $i;
920 my $eob;
921 sysread \*SFREAD, $i, 5;
922
923 my $size = 0;
924 if($i =~ /^([0-9a-fA-F]{4})\n/) {
925 $size = hex($1);
926 }
927
928 read_mainsockf(\$line, $size);
929
930 $ulsize += $size;
931 print FILE $line if(!$nosave);
932
933 $raw .= $line;
934 if($raw =~ /(?:^|\x0d\x0a)\x2e\x0d\x0a/) {
935 # end of data marker!
936 $eob = 1;
937 }
938
939 logmsg "> Appending $size bytes to file\n";
940
941 if($eob) {
942 logmsg "Found SMTP EOB marker\n";
943 last;
944 }
945 }
946 elsif($line eq "DISC\n") {
947 # disconnect!
948 $disc=1;
949 last;
950 }
951 else {
952 logmsg "No support for: $line";
953 last;
954 }
955 }
956
957 if($nosave) {
958 print FILE "$ulsize bytes would've been stored here\n";
959 }
960
961 close(FILE);
962
963 logmsg "received $ulsize bytes upload\n";
964
965 sendcontrol "250 OK, data received!\r\n";
966 }
967
968 return 0;
969 }
970
971 sub NOOP_smtp {
972 my ($args) = @_;
973
974 if($args) {
975 sendcontrol "501 Unrecognized parameter\r\n";
976 }
977 else {
978 sendcontrol "250 OK\r\n";
979 }
980
981 return 0;
982 }
983
984 sub RSET_smtp {
985 my ($args) = @_;
986
987 if($args) {
988 sendcontrol "501 Unrecognized parameter\r\n";
989 }
990 else {
991 sendcontrol "250 Resetting\r\n";
992 }
993
994 return 0;
995 }
996
997 sub HELP_smtp {
998 my ($args) = @_;
999
1000 # One argument is optional
1001 if($args) {
1002 logmsg "HELP_smtp got $args\n";
1003 }
1004
1005 if($smtp_client eq "verifiedserver") {
1006 # This is the secret command that verifies that this actually is
1007 # the curl test server
1008 sendcontrol "214 WE ROOLZ: $$\r\n";
1009
1010 if($verbose) {
1011 print STDERR "FTPD: We returned proof we are the test server\n";
1012 }
1013
1014 logmsg "return proof we are we\n";
1015 }
1016 else {
1017 sendcontrol "214-This server supports the following commands:\r\n";
1018
1019 if(@auth_mechs) {
1020 sendcontrol "214 HELO EHLO RCPT DATA RSET MAIL VRFY EXPN QUIT HELP AUTH\r\n";
1021 }
1022 else {
1023 sendcontrol "214 HELO EHLO RCPT DATA RSET MAIL VRFY EXPN QUIT HELP\r\n";
1024 }
1025 }
1026
1027 return 0;
1028 }
1029
1030 sub VRFY_smtp {
1031 my ($args) = @_;
1032 my ($username, $address) = split(/ /, $args, 2);
1033
1034 logmsg "VRFY_smtp got $args\n";
1035
1036 if($username eq "") {
1037 sendcontrol "501 Unrecognized parameter\r\n";
1038 }
1039 else {
1040 my $smtputf8 = grep /^SMTPUTF8$/, @capabilities;
1041
1042 # Validate the username (only a valid local or external username is
1043 # allowed, such as user or [email protected])
1044 if ((!$smtputf8 && $username =~
1045 /^([a-zA-Z0-9._%+-]+)(\@(([a-zA-Z0-9-]+)\.)+([a-zA-Z]{2,4}))?$/) ||
1046 ($smtputf8 && $username =~
1047 /^([a-zA-Z0-9\x{80}-\x{ff}._%+-]+)(\@(([a-zA-Z0-9\x{80}-\x{ff}-]+)\.)+([a-zA-Z]{2,4}))?$/)) {
1048
1049 my @data = getreplydata($smtp_client);
1050
1051 if(!@data) {
1052 if ($username !~
1053 /^([a-zA-Z0-9._%+-]+)\@(([a-zA-Z0-9-]+)\.)+([a-zA-Z]{2,4})$/) {
1054 push @data, "250 <$username\@example.com>\r\n"
1055 }
1056 else {
1057 push @data, "250 <$username>\r\n"
1058 }
1059 }
1060
1061 for my $d (@data) {
1062 sendcontrol $d;
1063 }
1064 }
1065 else {
1066 sendcontrol "501 Invalid address\r\n";
1067 }
1068 }
1069
1070 return 0;
1071 }
1072
1073 sub EXPN_smtp {
1074 my ($list_name) = @_;
1075
1076 logmsg "EXPN_smtp got $list_name\n";
1077
1078 if(!$list_name) {
1079 sendcontrol "501 Unrecognized parameter\r\n";
1080 }
1081 else {
1082 my @data = getreplydata($smtp_client);
1083
1084 for my $d (@data) {
1085 sendcontrol $d;
1086 }
1087 }
1088
1089 return 0;
1090 }
1091
1092 sub QUIT_smtp {
1093 sendcontrol "221 curl $smtp_type server signing off\r\n";
1094
1095 return 0;
1096 }
1097
1098 # What was deleted by IMAP STORE / POP3 DELE commands
1099 my @deleted;
1100
1101 ################
1102 ################ IMAP commands
1103 ################
1104
1105 # global to allow the command functions to read it
1106 my $cmdid;
1107
1108 # what was picked by SELECT
1109 my $selected;
1110
1111 # Any IMAP parameter can come in escaped and in double quotes.
1112 # This function is dumb (so far) and just removes the quotes if present.
1113 sub fix_imap_params {
1114 foreach (@_) {
1115 $_ = $1 if /^"(.*)"$/;
1116 }
1117 }
1118
1119 sub CAPABILITY_imap {
1120 if((!@capabilities) && (!@auth_mechs)) {
1121 sendcontrol "$cmdid BAD Command\r\n";
1122 }
1123 else {
1124 my $data;
1125
1126 # Calculate the CAPABILITY response
1127 $data = "* CAPABILITY IMAP4";
1128
1129 for my $c (@capabilities) {
1130 $data .= " $c";
1131 }
1132
1133 for my $am (@auth_mechs) {
1134 $data .= " AUTH=$am";
1135 }
1136
1137 $data .= " pingpong test server\r\n";
1138
1139 # Send the CAPABILITY response
1140 sendcontrol $data;
1141 sendcontrol "$cmdid OK CAPABILITY completed\r\n";
1142 }
1143
1144 return 0;
1145 }
1146
1147 sub LOGIN_imap {
1148 my ($args) = @_;
1149 my ($user, $password) = split(/ /, $args, 2);
1150 fix_imap_params($user, $password);
1151
1152 logmsg "LOGIN_imap got $args\n";
1153
1154 if ($user eq "") {
1155 sendcontrol "$cmdid BAD Command Argument\r\n";
1156 }
1157 else {
1158 sendcontrol "$cmdid OK LOGIN completed\r\n";
1159 }
1160
1161 return 0;
1162 }
1163
1164 sub SELECT_imap {
1165 my ($mailbox) = @_;
1166 fix_imap_params($mailbox);
1167
1168 logmsg "SELECT_imap got test $mailbox\n";
1169
1170 if($mailbox eq "") {
1171 sendcontrol "$cmdid BAD Command Argument\r\n";
1172 }
1173 else {
1174 # Example from RFC 3501, 6.3.1. SELECT Command
1175 sendcontrol "* 172 EXISTS\r\n";
1176 sendcontrol "* 1 RECENT\r\n";
1177 sendcontrol "* OK [UNSEEN 12] Message 12 is first unseen\r\n";
1178 sendcontrol "* OK [UIDVALIDITY 3857529045] UIDs valid\r\n";
1179 sendcontrol "* OK [UIDNEXT 4392] Predicted next UID\r\n";
1180 sendcontrol "* FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)\r\n";
1181 sendcontrol "* OK [PERMANENTFLAGS (\\Deleted \\Seen \\*)] Limited\r\n";
1182 sendcontrol "$cmdid OK [READ-WRITE] SELECT completed\r\n";
1183
1184 $selected = $mailbox;
1185 }
1186
1187 return 0;
1188 }
1189
1190 sub FETCH_imap {
1191 my ($args) = @_;
1192 my ($uid, $how) = split(/ /, $args, 2);
1193 fix_imap_params($uid, $how);
1194
1195 logmsg "FETCH_imap got $args\n";
1196
1197 if ($selected eq "") {
1198 sendcontrol "$cmdid BAD Command received in Invalid state\r\n";
1199 }
1200 else {
1201 my @data;
1202 my $size;
1203
1204 if($selected eq "verifiedserver") {
1205 # this is the secret command that verifies that this actually is
1206 # the curl test server
1207 my $response = "WE ROOLZ: $$\r\n";
1208 if($verbose) {
1209 print STDERR "FTPD: We returned proof we are the test server\n";
1210 }
1211 $data[0] = $response;
1212 logmsg "return proof we are we\n";
1213 }
1214 else {
1215 # send mail content
1216 logmsg "retrieve a mail\n";
1217
1218 @data = getreplydata($selected);
1219 }
1220
1221 for (@data) {
1222 $size += length($_);
1223 }
1224
1225 sendcontrol "* $uid FETCH ($how {$size}\r\n";
1226
1227 for my $d (@data) {
1228 sendcontrol $d;
1229 }
1230
1231 sendcontrol ")\r\n";
1232 sendcontrol "$cmdid OK FETCH completed\r\n";
1233 }
1234
1235 return 0;
1236 }
1237
1238 sub APPEND_imap {
1239 my ($args) = @_;
1240
1241 logmsg "APPEND_imap got $args\r\n";
1242
1243 $args =~ /^([^ ]+) [^{]*\{(\d+)\}$/;
1244 my ($mailbox, $size) = ($1, $2);
1245 fix_imap_params($mailbox);
1246
1247 if($mailbox eq "") {
1248 sendcontrol "$cmdid BAD Command Argument\r\n";
1249 }
1250 else {
1251 sendcontrol "+ Ready for literal data\r\n";
1252
1253 my $testno = $mailbox;
1254 my $filename = "log/upload.$testno";
1255
1256 logmsg "Store test number $testno in $filename\n";
1257
1258 open(FILE, ">$filename") ||
1259 return 0; # failed to open output
1260
1261 my $received = 0;
1262 my $line;
1263 while(5 == (sysread \*SFREAD, $line, 5)) {
1264 if($line eq "DATA\n") {
1265 sysread \*SFREAD, $line, 5;
1266
1267 my $chunksize = 0;
1268 if($line =~ /^([0-9a-fA-F]{4})\n/) {
1269 $chunksize = hex($1);
1270 }
1271
1272 read_mainsockf(\$line, $chunksize);
1273
1274 my $left = $size - $received;
1275 my $datasize = ($left > $chunksize) ? $chunksize : $left;
1276
1277 if($datasize > 0) {
1278 logmsg "> Appending $datasize bytes to file\n";
1279 print FILE substr($line, 0, $datasize) if(!$nosave);
1280 $line = substr($line, $datasize);
1281
1282 $received += $datasize;
1283 if($received == $size) {
1284 logmsg "Received all data, waiting for final CRLF.\n";
1285 }
1286 }
1287
1288 if($received == $size && $line eq "\r\n") {
1289 last;
1290 }
1291 }
1292 elsif($line eq "DISC\n") {
1293 logmsg "Unexpected disconnect!\n";
1294 last;
1295 }
1296 else {
1297 logmsg "No support for: $line";
1298 last;
1299 }
1300 }
1301
1302 if($nosave) {
1303 print FILE "$size bytes would've been stored here\n";
1304 }
1305
1306 close(FILE);
1307
1308 logmsg "received $size bytes upload\n";
1309
1310 sendcontrol "$cmdid OK APPEND completed\r\n";
1311 }
1312
1313 return 0;
1314 }
1315
1316 sub STORE_imap {
1317 my ($args) = @_;
1318 my ($uid, $what, $value) = split(/ /, $args, 3);
1319 fix_imap_params($uid);
1320
1321 logmsg "STORE_imap got $args\n";
1322
1323 if ($selected eq "") {
1324 sendcontrol "$cmdid BAD Command received in Invalid state\r\n";
1325 }
1326 elsif (($uid eq "") || ($what ne "+Flags") || ($value eq "")) {
1327 sendcontrol "$cmdid BAD Command Argument\r\n";
1328 }
1329 else {
1330 if($value eq "\\Deleted") {
1331 push(@deleted, $uid);
1332 }
1333
1334 sendcontrol "* $uid FETCH (FLAGS (\\Seen $value))\r\n";
1335 sendcontrol "$cmdid OK STORE completed\r\n";
1336 }
1337
1338 return 0;
1339 }
1340
1341 sub LIST_imap {
1342 my ($args) = @_;
1343 my ($reference, $mailbox) = split(/ /, $args, 2);
1344 fix_imap_params($reference, $mailbox);
1345
1346 logmsg "LIST_imap got $args\n";
1347
1348 if ($reference eq "") {
1349 sendcontrol "$cmdid BAD Command Argument\r\n";
1350 }
1351 elsif ($reference eq "verifiedserver") {
1352 # this is the secret command that verifies that this actually is
1353 # the curl test server
1354 sendcontrol "* LIST () \"/\" \"WE ROOLZ: $$\"\r\n";
1355 sendcontrol "$cmdid OK LIST Completed\r\n";
1356
1357 if($verbose) {
1358 print STDERR "FTPD: We returned proof we are the test server\n";
1359 }
1360
1361 logmsg "return proof we are we\n";
1362 }
1363 else {
1364 my @data = getreplydata($reference);
1365
1366 for my $d (@data) {
1367 sendcontrol $d;
1368 }
1369
1370 sendcontrol "$cmdid OK LIST Completed\r\n";
1371 }
1372
1373 return 0;
1374 }
1375
1376 sub LSUB_imap {
1377 my ($args) = @_;
1378 my ($reference, $mailbox) = split(/ /, $args, 2);
1379 fix_imap_params($reference, $mailbox);
1380
1381 logmsg "LSUB_imap got $args\n";
1382
1383 if ($reference eq "") {
1384 sendcontrol "$cmdid BAD Command Argument\r\n";
1385 }
1386 else {
1387 my @data = getreplydata($reference);
1388
1389 for my $d (@data) {
1390 sendcontrol $d;
1391 }
1392
1393 sendcontrol "$cmdid OK LSUB Completed\r\n";
1394 }
1395
1396 return 0;
1397 }
1398
1399 sub EXAMINE_imap {
1400 my ($mailbox) = @_;
1401 fix_imap_params($mailbox);
1402
1403 logmsg "EXAMINE_imap got $mailbox\n";
1404
1405 if ($mailbox eq "") {
1406 sendcontrol "$cmdid BAD Command Argument\r\n";
1407 }
1408 else {
1409 my @data = getreplydata($mailbox);
1410
1411 for my $d (@data) {
1412 sendcontrol $d;
1413 }
1414
1415 sendcontrol "$cmdid OK [READ-ONLY] EXAMINE completed\r\n";
1416 }
1417
1418 return 0;
1419 }
1420
1421 sub STATUS_imap {
1422 my ($args) = @_;
1423 my ($mailbox, $what) = split(/ /, $args, 2);
1424 fix_imap_params($mailbox);
1425
1426 logmsg "STATUS_imap got $args\n";
1427
1428 if ($mailbox eq "") {
1429 sendcontrol "$cmdid BAD Command Argument\r\n";
1430 }
1431 else {
1432 my @data = getreplydata($mailbox);
1433
1434 for my $d (@data) {
1435 sendcontrol $d;
1436 }
1437
1438 sendcontrol "$cmdid OK STATUS completed\r\n";
1439 }
1440
1441 return 0;
1442 }
1443
1444 sub SEARCH_imap {
1445 my ($what) = @_;
1446 fix_imap_params($what);
1447
1448 logmsg "SEARCH_imap got $what\n";
1449
1450 if ($selected eq "") {
1451 sendcontrol "$cmdid BAD Command received in Invalid state\r\n";
1452 }
1453 elsif ($what eq "") {
1454 sendcontrol "$cmdid BAD Command Argument\r\n";
1455 }
1456 else {
1457 my @data = getreplydata($selected);
1458
1459 for my $d (@data) {
1460 sendcontrol $d;
1461 }
1462
1463 sendcontrol "$cmdid OK SEARCH completed\r\n";
1464 }
1465
1466 return 0;
1467 }
1468
1469 sub CREATE_imap {
1470 my ($args) = @_;
1471 fix_imap_params($args);
1472
1473 logmsg "CREATE_imap got $args\n";
1474
1475 if ($args eq "") {
1476 sendcontrol "$cmdid BAD Command Argument\r\n";
1477 }
1478 else {
1479 sendcontrol "$cmdid OK CREATE completed\r\n";
1480 }
1481
1482 return 0;
1483 }
1484
1485 sub DELETE_imap {
1486 my ($args) = @_;
1487 fix_imap_params($args);
1488
1489 logmsg "DELETE_imap got $args\n";
1490
1491 if ($args eq "") {
1492 sendcontrol "$cmdid BAD Command Argument\r\n";
1493 }
1494 else {
1495 sendcontrol "$cmdid OK DELETE completed\r\n";
1496 }
1497
1498 return 0;
1499 }
1500
1501 sub RENAME_imap {
1502 my ($args) = @_;
1503 my ($from_mailbox, $to_mailbox) = split(/ /, $args, 2);
1504 fix_imap_params($from_mailbox, $to_mailbox);
1505
1506 logmsg "RENAME_imap got $args\n";
1507
1508 if (($from_mailbox eq "") || ($to_mailbox eq "")) {
1509 sendcontrol "$cmdid BAD Command Argument\r\n";
1510 }
1511 else {
1512 sendcontrol "$cmdid OK RENAME completed\r\n";
1513 }
1514
1515 return 0;
1516 }
1517
1518 sub CHECK_imap {
1519 if ($selected eq "") {
1520 sendcontrol "$cmdid BAD Command received in Invalid state\r\n";
1521 }
1522 else {
1523 sendcontrol "$cmdid OK CHECK completed\r\n";
1524 }
1525
1526 return 0;
1527 }
1528
1529 sub CLOSE_imap {
1530 if ($selected eq "") {
1531 sendcontrol "$cmdid BAD Command received in Invalid state\r\n";
1532 }
1533 elsif (!@deleted) {
1534 sendcontrol "$cmdid BAD Command Argument\r\n";
1535 }
1536 else {
1537 sendcontrol "$cmdid OK CLOSE completed\r\n";
1538
1539 @deleted = ();
1540 }
1541
1542 return 0;
1543 }
1544
1545 sub EXPUNGE_imap {
1546 if ($selected eq "") {
1547 sendcontrol "$cmdid BAD Command received in Invalid state\r\n";
1548 }
1549 else {
1550 if (!@deleted) {
1551 # Report the number of existing messages as per the SELECT
1552 # command
1553 sendcontrol "* 172 EXISTS\r\n";
1554 }
1555 else {
1556 # Report the message UIDs being deleted
1557 for my $d (@deleted) {
1558 sendcontrol "* $d EXPUNGE\r\n";
1559 }
1560
1561 @deleted = ();
1562 }
1563
1564 sendcontrol "$cmdid OK EXPUNGE completed\r\n";
1565 }
1566
1567 return 0;
1568 }
1569
1570 sub COPY_imap {
1571 my ($args) = @_;
1572 my ($uid, $mailbox) = split(/ /, $args, 2);
1573 fix_imap_params($uid, $mailbox);
1574
1575 logmsg "COPY_imap got $args\n";
1576
1577 if (($uid eq "") || ($mailbox eq "")) {
1578 sendcontrol "$cmdid BAD Command Argument\r\n";
1579 }
1580 else {
1581 sendcontrol "$cmdid OK COPY completed\r\n";
1582 }
1583
1584 return 0;
1585 }
1586
1587 sub UID_imap {
1588 my ($args) = @_;
1589 my ($command) = split(/ /, $args, 1);
1590 fix_imap_params($command);
1591
1592 logmsg "UID_imap got $args\n";
1593
1594 if ($selected eq "") {
1595 sendcontrol "$cmdid BAD Command received in Invalid state\r\n";
1596 }
1597 elsif (substr($command, 0, 5) eq "FETCH"){
1598 my $func = $commandfunc{"FETCH"};
1599 if($func) {
1600 &$func($args, $command);
1601 }
1602 }
1603 elsif (($command ne "COPY") &&
1604 ($command ne "STORE") && ($command ne "SEARCH")) {
1605 sendcontrol "$cmdid BAD Command Argument\r\n";
1606 }
1607 else {
1608 my @data = getreplydata($selected);
1609
1610 for my $d (@data) {
1611 sendcontrol $d;
1612 }
1613
1614 sendcontrol "$cmdid OK $command completed\r\n";
1615 }
1616
1617 return 0;
1618 }
1619
1620 sub NOOP_imap {
1621 my ($args) = @_;
1622 my @data = (
1623 "* 22 EXPUNGE\r\n",
1624 "* 23 EXISTS\r\n",
1625 "* 3 RECENT\r\n",
1626 "* 14 FETCH (FLAGS (\\Seen \\Deleted))\r\n",
1627 );
1628
1629 if ($args) {
1630 sendcontrol "$cmdid BAD Command Argument\r\n";
1631 }
1632 else {
1633 for my $d (@data) {
1634 sendcontrol $d;
1635 }
1636
1637 sendcontrol "$cmdid OK NOOP completed\r\n";
1638 }
1639
1640 return 0;
1641 }
1642
1643 sub LOGOUT_imap {
1644 sendcontrol "* BYE curl IMAP server signing off\r\n";
1645 sendcontrol "$cmdid OK LOGOUT completed\r\n";
1646
1647 return 0;
1648 }
1649
1650 ################
1651 ################ POP3 commands
1652 ################
1653
1654 # Who is attempting to log in
1655 my $username;
1656
1657 sub CAPA_pop3 {
1658 my @list = ();
1659 my $mechs;
1660
1661 # Calculate the capability list based on the specified capabilities
1662 # (except APOP) and any authentication mechanisms
1663 for my $c (@capabilities) {
1664 push @list, "$c\r\n" unless $c eq "APOP";
1665 }
1666
1667 for my $am (@auth_mechs) {
1668 if(!$mechs) {
1669 $mechs = "$am";
1670 }
1671 else {
1672 $mechs .= " $am";
1673 }
1674 }
1675
1676 if($mechs) {
1677 push @list, "SASL $mechs\r\n";
1678 }
1679
1680 if(!@list) {
1681 sendcontrol "-ERR Unrecognized command\r\n";
1682 }
1683 else {
1684 my @data = ();
1685
1686 # Calculate the CAPA response
1687 push @data, "+OK List of capabilities follows\r\n";
1688
1689 for my $l (@list) {
1690 push @data, "$l\r\n";
1691 }
1692
1693 push @data, "IMPLEMENTATION POP3 pingpong test server\r\n";
1694
1695 # Send the CAPA response
1696 for my $d (@data) {
1697 sendcontrol $d;
1698 }
1699
1700 # End with the magic 3-byte end of listing marker
1701 sendcontrol ".\r\n";
1702 }
1703
1704 return 0;
1705 }
1706
1707 sub APOP_pop3 {
1708 my ($args) = @_;
1709 my ($user, $secret) = split(/ /, $args, 2);
1710
1711 if (!grep /^APOP$/, @capabilities) {
1712 sendcontrol "-ERR Unrecognized command\r\n";
1713 }
1714 elsif (($user eq "") || ($secret eq "")) {
1715 sendcontrol "-ERR Protocol error\r\n";
1716 }
1717 else {
1718 my $digest = Digest::MD5::md5_hex($POP3_TIMESTAMP, $TEXT_PASSWORD);
1719
1720 if ($secret ne $digest) {
1721 sendcontrol "-ERR Login failure\r\n";
1722 }
1723 else {
1724 sendcontrol "+OK Login successful\r\n";
1725 }
1726 }
1727
1728 return 0;
1729 }
1730
1731 sub AUTH_pop3 {
1732 if(!@auth_mechs) {
1733 sendcontrol "-ERR Unrecognized command\r\n";
1734 }
1735 else {
1736 my @data = ();
1737
1738 # Calculate the AUTH response
1739 push @data, "+OK List of supported mechanisms follows\r\n";
1740
1741 for my $am (@auth_mechs) {
1742 push @data, "$am\r\n";
1743 }
1744
1745 # Send the AUTH response
1746 for my $d (@data) {
1747 sendcontrol $d;
1748 }
1749
1750 # End with the magic 3-byte end of listing marker
1751 sendcontrol ".\r\n";
1752 }
1753
1754 return 0;
1755 }
1756
1757 sub USER_pop3 {
1758 my ($user) = @_;
1759
1760 logmsg "USER_pop3 got $user\n";
1761
1762 if (!$user) {
1763 sendcontrol "-ERR Protocol error\r\n";
1764 }
1765 else {
1766 $username = $user;
1767
1768 sendcontrol "+OK\r\n";
1769 }
1770
1771 return 0;
1772 }
1773
1774 sub PASS_pop3 {
1775 my ($password) = @_;
1776
1777 logmsg "PASS_pop3 got $password\n";
1778
1779 sendcontrol "+OK Login successful\r\n";
1780
1781 return 0;
1782 }
1783
1784 sub RETR_pop3 {
1785 my ($msgid) = @_;
1786 my @data;
1787
1788 if($msgid =~ /^verifiedserver$/) {
1789 # this is the secret command that verifies that this actually is
1790 # the curl test server
1791 my $response = "WE ROOLZ: $$\r\n";
1792 if($verbose) {
1793 print STDERR "FTPD: We returned proof we are the test server\n";
1794 }
1795 $data[0] = $response;
1796 logmsg "return proof we are we\n";
1797 }
1798 else {
1799 # send mail content
1800 logmsg "retrieve a mail\n";
1801
1802 @data = getreplydata($msgid);
1803 }
1804
1805 sendcontrol "+OK Mail transfer starts\r\n";
1806
1807 for my $d (@data) {
1808 sendcontrol $d;
1809 }
1810
1811 # end with the magic 3-byte end of mail marker, assumes that the
1812 # mail body ends with a CRLF!
1813 sendcontrol ".\r\n";
1814
1815 return 0;
1816 }
1817
1818 sub LIST_pop3 {
1819 # This is a built-in fake-message list
1820 my @data = (
1821 "1 100\r\n",
1822 "2 4294967400\r\n", # > 4 GB
1823 "3 200\r\n",
1824 );
1825
1826 logmsg "retrieve a message list\n";
1827
1828 sendcontrol "+OK Listing starts\r\n";
1829
1830 for my $d (@data) {
1831 sendcontrol $d;
1832 }
1833
1834 # End with the magic 3-byte end of listing marker
1835 sendcontrol ".\r\n";
1836
1837 return 0;
1838 }
1839
1840 sub DELE_pop3 {
1841 my ($msgid) = @_;
1842
1843 logmsg "DELE_pop3 got $msgid\n";
1844
1845 if (!$msgid) {
1846 sendcontrol "-ERR Protocol error\r\n";
1847 }
1848 else {
1849 push (@deleted, $msgid);
1850
1851 sendcontrol "+OK\r\n";
1852 }
1853
1854 return 0;
1855 }
1856
1857 sub STAT_pop3 {
1858 my ($args) = @_;
1859
1860 if ($args) {
1861 sendcontrol "-ERR Protocol error\r\n";
1862 }
1863 else {
1864 # Send statistics for the built-in fake message list as
1865 # detailed in the LIST_pop3 function above
1866 sendcontrol "+OK 3 4294967800\r\n";
1867 }
1868
1869 return 0;
1870 }
1871
1872 sub NOOP_pop3 {
1873 my ($args) = @_;
1874
1875 if ($args) {
1876 sendcontrol "-ERR Protocol error\r\n";
1877 }
1878 else {
1879 sendcontrol "+OK\r\n";
1880 }
1881
1882 return 0;
1883 }
1884
1885 sub UIDL_pop3 {
1886 # This is a built-in fake-message UID list
1887 my @data = (
1888 "1 1\r\n",
1889 "2 2\r\n",
1890 "3 4\r\n", # Note that UID 3 is a simulated "deleted" message
1891 );
1892
1893 if (!grep /^UIDL$/, @capabilities) {
1894 sendcontrol "-ERR Unrecognized command\r\n";
1895 }
1896 else {
1897 logmsg "retrieve a message UID list\n";
1898
1899 sendcontrol "+OK Listing starts\r\n";
1900
1901 for my $d (@data) {
1902 sendcontrol $d;
1903 }
1904
1905 # End with the magic 3-byte end of listing marker
1906 sendcontrol ".\r\n";
1907 }
1908
1909 return 0;
1910 }
1911
1912 sub TOP_pop3 {
1913 my ($args) = @_;
1914 my ($msgid, $lines) = split(/ /, $args, 2);
1915
1916 logmsg "TOP_pop3 got $args\n";
1917
1918 if (!grep /^TOP$/, @capabilities) {
1919 sendcontrol "-ERR Unrecognized command\r\n";
1920 }
1921 elsif (($msgid eq "") || ($lines eq "")) {
1922 sendcontrol "-ERR Protocol error\r\n";
1923 }
1924 else {
1925 if ($lines == "0") {
1926 logmsg "retrieve header of mail\n";
1927 }
1928 else {
1929 logmsg "retrieve top $lines lines of mail\n";
1930 }
1931
1932 my @data = getreplydata($msgid);
1933
1934 sendcontrol "+OK Mail transfer starts\r\n";
1935
1936 # Send mail content
1937 for my $d (@data) {
1938 sendcontrol $d;
1939 }
1940
1941 # End with the magic 3-byte end of mail marker, assumes that the
1942 # mail body ends with a CRLF!
1943 sendcontrol ".\r\n";
1944 }
1945
1946 return 0;
1947 }
1948
1949 sub RSET_pop3 {
1950 my ($args) = @_;
1951
1952 if ($args) {
1953 sendcontrol "-ERR Protocol error\r\n";
1954 }
1955 else {
1956 if (@deleted) {
1957 logmsg "resetting @deleted message(s)\n";
1958
1959 @deleted = ();
1960 }
1961
1962 sendcontrol "+OK\r\n";
1963 }
1964
1965 return 0;
1966 }
1967
1968 sub QUIT_pop3 {
1969 if(@deleted) {
1970 logmsg "deleting @deleted message(s)\n";
1971
1972 @deleted = ();
1973 }
1974
1975 sendcontrol "+OK curl POP3 server signing off\r\n";
1976
1977 return 0;
1978 }
1979
1980 ################
1981 ################ FTP commands
1982 ################
1983 my $rest=0;
1984 sub REST_ftp {
1985 $rest = $_[0];
1986 logmsg "Set REST position to $rest\n"
1987 }
1988
1989 sub switch_directory_goto {
1990 my $target_dir = $_;
1991
1992 if(!$ftptargetdir) {
1993 $ftptargetdir = "/";
1994 }
1995
1996 if($target_dir eq "") {
1997 $ftptargetdir = "/";
1998 }
1999 elsif($target_dir eq "..") {
2000 if($ftptargetdir eq "/") {
2001 $ftptargetdir = "/";
2002 }
2003 else {
2004 $ftptargetdir =~ s/[[:alnum:]]+\/$//;
2005 }
2006 }
2007 else {
2008 $ftptargetdir .= $target_dir . "/";
2009 }
2010 }
2011
2012 sub switch_directory {
2013 my $target_dir = $_[0];
2014
2015 if($target_dir =~ /^test-(\d+)/) {
2016 $cwd_testno = $1;
2017 }
2018 elsif($target_dir eq "/") {
2019 $ftptargetdir = "/";
2020 }
2021 else {
2022 my @dirs = split("/", $target_dir);
2023 for(@dirs) {
2024 switch_directory_goto($_);
2025 }
2026 }
2027 }
2028
2029 sub CWD_ftp {
2030 my ($folder, $fullcommand) = $_[0];
2031 switch_directory($folder);
2032 if($ftptargetdir =~ /^\/fully_simulated/) {
2033 $ftplistparserstate = "enabled";
2034 }
2035 else {
2036 undef $ftplistparserstate;
2037 }
2038 }
2039
2040 sub PWD_ftp {
2041 my $mydir;
2042 $mydir = $ftptargetdir ? $ftptargetdir : "/";
2043
2044 if($mydir ne "/") {
2045 $mydir =~ s/\/$//;
2046 }
2047 sendcontrol "257 \"$mydir\" is current directory\r\n";
2048 }
2049
2050 sub LIST_ftp {
2051 # print "150 ASCII data connection for /bin/ls (193.15.23.1,59196) (0 bytes)\r\n";
2052
2053 # this is a built-in fake-dir ;-)
2054 my @ftpdir=("total 20\r\n",
2055 "drwxr-xr-x 8 98 98 512 Oct 22 13:06 .\r\n",
2056 "drwxr-xr-x 8 98 98 512 Oct 22 13:06 ..\r\n",
2057 "drwxr-xr-x 2 98 98 512 May 2 1996 .NeXT\r\n",
2058 "-r--r--r-- 1 0 1 35 Jul 16 1996 README\r\n",
2059 "lrwxrwxrwx 1 0 1 7 Dec 9 1999 bin -> usr/bin\r\n",
2060 "dr-xr-xr-x 2 0 1 512 Oct 1 1997 dev\r\n",
2061 "drwxrwxrwx 2 98 98 512 May 29 16:04 download.html\r\n",
2062 "dr-xr-xr-x 2 0 1 512 Nov 30 1995 etc\r\n",
2063 "drwxrwxrwx 2 98 1 512 Oct 30 14:33 pub\r\n",
2064 "dr-xr-xr-x 5 0 1 512 Oct 1 1997 usr\r\n");
2065
2066 if($datasockf_conn eq 'no') {
2067 if($nodataconn425) {
2068 sendcontrol "150 Opening data connection\r\n";
2069 sendcontrol "425 Can't open data connection\r\n";
2070 }
2071 elsif($nodataconn421) {
2072 sendcontrol "150 Opening data connection\r\n";
2073 sendcontrol "421 Connection timed out\r\n";
2074 }
2075 elsif($nodataconn150) {
2076 sendcontrol "150 Opening data connection\r\n";
2077 # client shall timeout
2078 }
2079 else {
2080 # client shall timeout
2081 }
2082 return 0;
2083 }
2084
2085 if($ftplistparserstate) {
2086 @ftpdir = ftp_contentlist($ftptargetdir);
2087 }
2088
2089 logmsg "pass LIST data on data connection\n";
2090
2091 if($cwd_testno) {
2092 loadtest("$srcdir/data/test$cwd_testno");
2093
2094 my @data = getpart("reply", "data");
2095 for(@data) {
2096 my $send = $_;
2097 # convert all \n to \r\n for ASCII transfer
2098 $send =~ s/\r\n/\n/g;
2099 $send =~ s/\n/\r\n/g;
2100 logmsg "send $send as data\n";
2101 senddata $send;
2102 }
2103 $cwd_testno = 0; # forget it again
2104 }
2105 else {
2106 # old hard-coded style
2107 for(@ftpdir) {
2108 senddata $_;
2109 }
2110 }
2111 close_dataconn(0);
2112 sendcontrol "226 ASCII transfer complete\r\n";
2113 return 0;
2114 }
2115
2116 sub NLST_ftp {
2117 my @ftpdir=("file", "with space", "fake", "..", " ..", "funny", "README");
2118
2119 if($datasockf_conn eq 'no') {
2120 if($nodataconn425) {
2121 sendcontrol "150 Opening data connection\r\n";
2122 sendcontrol "425 Can't open data connection\r\n";
2123 }
2124 elsif($nodataconn421) {
2125 sendcontrol "150 Opening data connection\r\n";
2126 sendcontrol "421 Connection timed out\r\n";
2127 }
2128 elsif($nodataconn150) {
2129 sendcontrol "150 Opening data connection\r\n";
2130 # client shall timeout
2131 }
2132 else {
2133 # client shall timeout
2134 }
2135 return 0;
2136 }
2137
2138 logmsg "pass NLST data on data connection\n";
2139 for(@ftpdir) {
2140 senddata "$_\r\n";
2141 }
2142 close_dataconn(0);
2143 sendcontrol "226 ASCII transfer complete\r\n";
2144 return 0;
2145 }
2146
2147 sub MDTM_ftp {
2148 my $testno = $_[0];
2149 my $testpart = "";
2150 if ($testno > 10000) {
2151 $testpart = $testno % 10000;
2152 $testno = int($testno / 10000);
2153 }
2154
2155 loadtest("$srcdir/data/test$testno");
2156
2157 my @data = getpart("reply", "mdtm");
2158
2159 my $reply = $data[0];
2160 chomp $reply if($reply);
2161
2162 if($reply && ($reply =~ /^[+-]?\d+$/) && ($reply < 0)) {
2163 sendcontrol "550 $testno: no such file.\r\n";
2164 }
2165 elsif($reply) {
2166 sendcontrol "$reply\r\n";
2167 }
2168 else {
2169 sendcontrol "500 MDTM: no such command.\r\n";
2170 }
2171 return 0;
2172 }
2173
2174 sub SIZE_ftp {
2175 my $testno = $_[0];
2176 if($ftplistparserstate) {
2177 my $size = wildcard_filesize($ftptargetdir, $testno);
2178 if($size == -1) {
2179 sendcontrol "550 $testno: No such file or directory.\r\n";
2180 }
2181 else {
2182 sendcontrol "213 $size\r\n";
2183 }
2184 return 0;
2185 }
2186
2187 if($testno =~ /^verifiedserver$/) {
2188 my $response = "WE ROOLZ: $$\r\n";
2189 my $size = length($response);
2190 sendcontrol "213 $size\r\n";
2191 return 0;
2192 }
2193
2194 if($testno =~ /(\d+)\/?$/) {
2195 $testno = $1;
2196 }
2197 else {
2198 print STDERR "SIZE_ftp: invalid test number: $testno\n";
2199 return 1;
2200 }
2201
2202 my $testpart = "";
2203 if($testno > 10000) {
2204 $testpart = $testno % 10000;
2205 $testno = int($testno / 10000);
2206 }
2207
2208 loadtest("$srcdir/data/test$testno");
2209
2210 my @data = getpart("reply", "size");
2211
2212 my $size = $data[0];
2213
2214 if($size) {
2215 if($size > -1) {
2216 sendcontrol "213 $size\r\n";
2217 }
2218 else {
2219 sendcontrol "550 $testno: No such file or directory.\r\n";
2220 }
2221 }
2222 else {
2223 $size=0;
2224 @data = getpart("reply", "data$testpart");
2225 for(@data) {
2226 $size += length($_);
2227 }
2228 if($size) {
2229 sendcontrol "213 $size\r\n";
2230 }
2231 else {
2232 sendcontrol "550 $testno: No such file or directory.\r\n";
2233 }
2234 }
2235 return 0;
2236 }
2237
2238 sub RETR_ftp {
2239 my ($testno) = @_;
2240
2241 if($datasockf_conn eq 'no') {
2242 if($nodataconn425) {
2243 sendcontrol "150 Opening data connection\r\n";
2244 sendcontrol "425 Can't open data connection\r\n";
2245 }
2246 elsif($nodataconn421) {
2247 sendcontrol "150 Opening data connection\r\n";
2248 sendcontrol "421 Connection timed out\r\n";
2249 }
2250 elsif($nodataconn150) {
2251 sendcontrol "150 Opening data connection\r\n";
2252 # client shall timeout
2253 }
2254 else {
2255 # client shall timeout
2256 }
2257 return 0;
2258 }
2259
2260 if($ftplistparserstate) {
2261 my @content = wildcard_getfile($ftptargetdir, $testno);
2262 if($content[0] == -1) {
2263 #file not found
2264 }
2265 else {
2266 my $size = length $content[1];
2267 sendcontrol "150 Binary data connection for $testno ($size bytes).\r\n",
2268 senddata $content[1];
2269 close_dataconn(0);
2270 sendcontrol "226 File transfer complete\r\n";
2271 }
2272 return 0;
2273 }
2274
2275 if($testno =~ /^verifiedserver$/) {
2276 # this is the secret command that verifies that this actually is
2277 # the curl test server
2278 my $response = "WE ROOLZ: $$\r\n";
2279 my $len = length($response);
2280 sendcontrol "150 Binary junk ($len bytes).\r\n";
2281 senddata "WE ROOLZ: $$\r\n";
2282 close_dataconn(0);
2283 sendcontrol "226 File transfer complete\r\n";
2284 if($verbose) {
2285 print STDERR "FTPD: We returned proof we are the test server\n";
2286 }
2287 return 0;
2288 }
2289
2290 $testno =~ s/^([^0-9]*)//;
2291 my $testpart = "";
2292 if ($testno > 10000) {
2293 $testpart = $testno % 10000;
2294 $testno = int($testno / 10000);
2295 }
2296
2297 loadtest("$srcdir/data/test$testno");
2298
2299 my @data = getpart("reply", "data$testpart");
2300
2301 my $size=0;
2302 for(@data) {
2303 $size += length($_);
2304 }
2305
2306 my %hash = getpartattr("reply", "data$testpart");
2307
2308 if($size || $hash{'sendzero'}) {
2309
2310 if($rest) {
2311 # move read pointer forward
2312 $size -= $rest;
2313 logmsg "REST $rest was removed from size, makes $size left\n";
2314 $rest = 0; # reset REST offset again
2315 }
2316 if($retrweirdo) {
2317 sendcontrol "150 Binary data connection for $testno () ($size bytes).\r\n",
2318 "226 File transfer complete\r\n";
2319
2320 for(@data) {
2321 my $send = $_;
2322 senddata $send;
2323 }
2324 close_dataconn(0);
2325 $retrweirdo=0; # switch off the weirdo again!
2326 }
2327 else {
2328 my $sz = "($size bytes)";
2329 if($retrnosize) {
2330 $sz = "size?";
2331 }
2332
2333 sendcontrol "150 Binary data connection for $testno () $sz.\r\n";
2334
2335 for(@data) {
2336 my $send = $_;
2337 senddata $send;
2338 }
2339 close_dataconn(0);
2340 sendcontrol "226 File transfer complete\r\n";
2341 }
2342 }
2343 else {
2344 sendcontrol "550 $testno: No such file or directory.\r\n";
2345 }
2346 return 0;
2347 }
2348
2349 sub STOR_ftp {
2350 my $testno=$_[0];
2351
2352 my $filename = "log/upload.$testno";
2353
2354 if($datasockf_conn eq 'no') {
2355 if($nodataconn425) {
2356 sendcontrol "150 Opening data connection\r\n";
2357 sendcontrol "425 Can't open data connection\r\n";
2358 }
2359 elsif($nodataconn421) {
2360 sendcontrol "150 Opening data connection\r\n";
2361 sendcontrol "421 Connection timed out\r\n";
2362 }
2363 elsif($nodataconn150) {
2364 sendcontrol "150 Opening data connection\r\n";
2365 # client shall timeout
2366 }
2367 else {
2368 # client shall timeout
2369 }
2370 return 0;
2371 }
2372
2373 logmsg "STOR test number $testno in $filename\n";
2374
2375 sendcontrol "125 Gimme gimme gimme!\r\n";
2376
2377 open(FILE, ">$filename") ||
2378 return 0; # failed to open output
2379
2380 my $line;
2381 my $ulsize=0;
2382 my $disc=0;
2383 while (5 == (sysread DREAD, $line, 5)) {
2384 if($line eq "DATA\n") {
2385 my $i;
2386 sysread DREAD, $i, 5;
2387
2388 my $size = 0;
2389 if($i =~ /^([0-9a-fA-F]{4})\n/) {
2390 $size = hex($1);
2391 }
2392
2393 read_datasockf(\$line, $size);
2394
2395 #print STDERR " GOT: $size bytes\n";
2396
2397 $ulsize += $size;
2398 print FILE $line if(!$nosave);
2399 logmsg "> Appending $size bytes to file\n";
2400 }
2401 elsif($line eq "DISC\n") {
2402 # disconnect!
2403 $disc=1;
2404 last;
2405 }
2406 else {
2407 logmsg "No support for: $line";
2408 last;
2409 }
2410 }
2411 if($nosave) {
2412 print FILE "$ulsize bytes would've been stored here\n";
2413 }
2414 close(FILE);
2415 close_dataconn($disc);
2416 logmsg "received $ulsize bytes upload\n";
2417 sendcontrol "226 File transfer complete\r\n";
2418 return 0;
2419 }
2420
2421 sub PASV_ftp {
2422 my ($arg, $cmd)=@_;
2423 my $pasvport;
2424 my $bindonly = ($nodataconn) ? '--bindonly' : '';
2425
2426 # kill previous data connection sockfilt when alive
2427 if($datasockf_runs eq 'yes') {
2428 killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
2429 logmsg "DATA sockfilt for $datasockf_mode data channel killed\n";
2430 }
2431 datasockf_state('STOPPED');
2432
2433 logmsg "====> Passive DATA channel requested by client\n";
2434
2435 logmsg "DATA sockfilt for passive data channel starting...\n";
2436
2437 # We fire up a new sockfilt to do the data transfer for us.
2438 my $datasockfcmd = "./server/sockfilt".exe_ext('SRV')." " .
2439 "--ipv$ipvnum $bindonly --port 0 " .
2440 "--pidfile \"$datasockf_pidfile\" " .
2441 "--logfile \"$datasockf_logfile\"";
2442 $slavepid = open2(\*DREAD, \*DWRITE, $datasockfcmd);
2443
2444 if($nodataconn) {
2445 datasockf_state('PASSIVE_NODATACONN');
2446 }
2447 else {
2448 datasockf_state('PASSIVE');
2449 }
2450
2451 print STDERR "$datasockfcmd\n" if($verbose);
2452
2453 print DWRITE "PING\n";
2454 my $pong;
2455 sysread_or_die(\*DREAD, \$pong, 5);
2456
2457 if($pong =~ /^FAIL/) {
2458 logmsg "DATA sockfilt said: FAIL\n";
2459 logmsg "DATA sockfilt for passive data channel failed\n";
2460 logmsg "DATA sockfilt not running\n";
2461 datasockf_state('STOPPED');
2462 sendcontrol "500 no free ports!\r\n";
2463 return;
2464 }
2465 elsif($pong !~ /^PONG/) {
2466 logmsg "DATA sockfilt unexpected response: $pong\n";
2467 logmsg "DATA sockfilt for passive data channel failed\n";
2468 logmsg "DATA sockfilt killed now\n";
2469 killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
2470 logmsg "DATA sockfilt not running\n";
2471 datasockf_state('STOPPED');
2472 sendcontrol "500 no free ports!\r\n";
2473 return;
2474 }
2475
2476 logmsg "DATA sockfilt for passive data channel started (pid $slavepid)\n";
2477
2478 # Find out on what port we listen on or have bound
2479 my $i;
2480 print DWRITE "PORT\n";
2481
2482 # READ the response code
2483 sysread_or_die(\*DREAD, \$i, 5);
2484
2485 # READ the response size
2486 sysread_or_die(\*DREAD, \$i, 5);
2487
2488 my $size = 0;
2489 if($i =~ /^([0-9a-fA-F]{4})\n/) {
2490 $size = hex($1);
2491 }
2492
2493 # READ the response data
2494 read_datasockf(\$i, $size);
2495
2496 # The data is in the format
2497 # IPvX/NNN
2498
2499 if($i =~ /IPv(\d)\/(\d+)/) {
2500 # FIX: deal with IP protocol version
2501 $pasvport = $2;
2502 }
2503
2504 if(!$pasvport) {
2505 logmsg "DATA sockfilt unknown listener port\n";
2506 logmsg "DATA sockfilt for passive data channel failed\n";
2507 logmsg "DATA sockfilt killed now\n";
2508 killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
2509 logmsg "DATA sockfilt not running\n";
2510 datasockf_state('STOPPED');
2511 sendcontrol "500 no free ports!\r\n";
2512 return;
2513 }
2514
2515 if($nodataconn) {
2516 my $str = nodataconn_str();
2517 logmsg "DATA sockfilt for passive data channel ($str) bound on port ".
2518 "$pasvport\n";
2519 }
2520 else {
2521 logmsg "DATA sockfilt for passive data channel listens on port ".
2522 "$pasvport\n";
2523 }
2524
2525 if($cmd ne "EPSV") {
2526 # PASV reply
2527 my $p=$listenaddr;
2528 $p =~ s/\./,/g;
2529 if($pasvbadip) {
2530 $p="1,2,3,4";
2531 }
2532 sendcontrol sprintf("227 Entering Passive Mode ($p,%d,%d)\n",
2533 int($pasvport/256), int($pasvport%256));
2534 }
2535 else {
2536 # EPSV reply
2537 sendcontrol sprintf("229 Entering Passive Mode (|||%d|)\n", $pasvport);
2538 }
2539
2540 logmsg "Client has been notified that DATA conn ".
2541 "will be accepted on port $pasvport\n";
2542
2543 if($nodataconn) {
2544 my $str = nodataconn_str();
2545 logmsg "====> Client fooled ($str)\n";
2546 return;
2547 }
2548
2549 eval {
2550 local $SIG{ALRM} = sub { die "alarm\n" };
2551
2552 # assume swift operations unless explicitly slow
2553 alarm ($datadelay?20:10);
2554
2555 # Wait for 'CNCT'
2556 my $input;
2557
2558 # FIX: Monitor ctrl conn for disconnect
2559
2560 while(sysread(DREAD, $input, 5)) {
2561
2562 if($input !~ /^CNCT/) {
2563 # we wait for a connected client
2564 logmsg "Odd, we got $input from client\n";
2565 next;
2566 }
2567 logmsg "Client connects to port $pasvport\n";
2568 last;
2569 }
2570 alarm 0;
2571 };
2572 if ($@) {
2573 # timed out
2574 logmsg "$srvrname server timed out awaiting data connection ".
2575 "on port $pasvport\n";
2576 logmsg "accept failed or connection not even attempted\n";
2577 logmsg "DATA sockfilt killed now\n";
2578 killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
2579 logmsg "DATA sockfilt not running\n";
2580 datasockf_state('STOPPED');
2581 return;
2582 }
2583 else {
2584 logmsg "====> Client established passive DATA connection ".
2585 "on port $pasvport\n";
2586 }
2587
2588 return;
2589 }
2590
2591 #
2592 # Support both PORT and EPRT here.
2593 #
2594
2595 sub PORT_ftp {
2596 my ($arg, $cmd) = @_;
2597 my $port;
2598 my $addr;
2599
2600 # kill previous data connection sockfilt when alive
2601 if($datasockf_runs eq 'yes') {
2602 killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
2603 logmsg "DATA sockfilt for $datasockf_mode data channel killed\n";
2604 }
2605 datasockf_state('STOPPED');
2606
2607 logmsg "====> Active DATA channel requested by client\n";
2608
2609 # We always ignore the given IP and use localhost.
2610
2611 if($cmd eq "PORT") {
2612 if($arg !~ /(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)/) {
2613 logmsg "DATA sockfilt for active data channel not started ".
2614 "(bad PORT-line: $arg)\n";
2615 sendcontrol "500 silly you, go away\r\n";
2616 return;
2617 }
2618 $port = ($5<<8)+$6;
2619 $addr = "$1.$2.$3.$4";
2620 }
2621 # EPRT |2|::1|49706|
2622 elsif($cmd eq "EPRT") {
2623 if($arg !~ /(\d+)\|([^\|]+)\|(\d+)/) {
2624 logmsg "DATA sockfilt for active data channel not started ".
2625 "(bad EPRT-line: $arg)\n";
2626 sendcontrol "500 silly you, go away\r\n";
2627 return;
2628 }
2629 sendcontrol "200 Thanks for dropping by. We contact you later\r\n";
2630 $port = $3;
2631 $addr = $2;
2632 }
2633 else {
2634 logmsg "DATA sockfilt for active data channel not started ".
2635 "(invalid command: $cmd)\n";
2636 sendcontrol "500 we don't like $cmd now\r\n";
2637 return;
2638 }
2639
2640 if(!$port || $port > 65535) {
2641 logmsg "DATA sockfilt for active data channel not started ".
2642 "(illegal PORT number: $port)\n";
2643 return;
2644 }
2645
2646 if($nodataconn) {
2647 my $str = nodataconn_str();
2648 logmsg "DATA sockfilt for active data channel not started ($str)\n";
2649 datasockf_state('ACTIVE_NODATACONN');
2650 logmsg "====> Active DATA channel not established\n";
2651 return;
2652 }
2653
2654 logmsg "DATA sockfilt for active data channel starting...\n";
2655
2656 # We fire up a new sockfilt to do the data transfer for us.
2657 my $datasockfcmd = "./server/sockfilt".exe_ext('SRV')." " .
2658 "--ipv$ipvnum --connect $port --addr \"$addr\" " .
2659 "--pidfile \"$datasockf_pidfile\" " .
2660 "--logfile \"$datasockf_logfile\"";
2661 $slavepid = open2(\*DREAD, \*DWRITE, $datasockfcmd);
2662
2663 datasockf_state('ACTIVE');
2664
2665 print STDERR "$datasockfcmd\n" if($verbose);
2666
2667 print DWRITE "PING\n";
2668 my $pong;
2669 sysread_or_die(\*DREAD, \$pong, 5);
2670
2671 if($pong =~ /^FAIL/) {
2672 logmsg "DATA sockfilt said: FAIL\n";
2673 logmsg "DATA sockfilt for active data channel failed\n";
2674 logmsg "DATA sockfilt not running\n";
2675 datasockf_state('STOPPED');
2676 # client shall timeout awaiting connection from server
2677 return;
2678 }
2679 elsif($pong !~ /^PONG/) {
2680 logmsg "DATA sockfilt unexpected response: $pong\n";
2681 logmsg "DATA sockfilt for active data channel failed\n";
2682 logmsg "DATA sockfilt killed now\n";
2683 killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
2684 logmsg "DATA sockfilt not running\n";
2685 datasockf_state('STOPPED');
2686 # client shall timeout awaiting connection from server
2687 return;
2688 }
2689
2690 logmsg "DATA sockfilt for active data channel started (pid $slavepid)\n";
2691
2692 logmsg "====> Active DATA channel connected to client port $port\n";
2693
2694 return;
2695 }
2696
2697 #**********************************************************************
2698 # datasockf_state is used to change variables that keep state info
2699 # relative to the FTP secondary or data sockfilt process as soon as
2700 # one of the five possible stable states is reached. Variables that
2701 # are modified by this sub may be checked independently but should
2702 # not be changed except by calling this sub.
2703 #
2704 sub datasockf_state {
2705 my $state = $_[0];
2706
2707 if($state eq 'STOPPED') {
2708 # Data sockfilter initial state, not running,
2709 # not connected and not used.
2710 $datasockf_state = $state;
2711 $datasockf_mode = 'none';
2712 $datasockf_runs = 'no';
2713 $datasockf_conn = 'no';
2714 }
2715 elsif($state eq 'PASSIVE') {
2716 # Data sockfilter accepted connection from client.
2717 $datasockf_state = $state;
2718 $datasockf_mode = 'passive';
2719 $datasockf_runs = 'yes';
2720 $datasockf_conn = 'yes';
2721 }
2722 elsif($state eq 'ACTIVE') {
2723 # Data sockfilter has connected to client.
2724 $datasockf_state = $state;
2725 $datasockf_mode = 'active';
2726 $datasockf_runs = 'yes';
2727 $datasockf_conn = 'yes';
2728 }
2729 elsif($state eq 'PASSIVE_NODATACONN') {
2730 # Data sockfilter bound port without listening,
2731 # client won't be able to establish data connection.
2732 $datasockf_state = $state;
2733 $datasockf_mode = 'passive';
2734 $datasockf_runs = 'yes';
2735 $datasockf_conn = 'no';
2736 }
2737 elsif($state eq 'ACTIVE_NODATACONN') {
2738 # Data sockfilter does not even run,
2739 # client awaits data connection from server in vain.
2740 $datasockf_state = $state;
2741 $datasockf_mode = 'active';
2742 $datasockf_runs = 'no';
2743 $datasockf_conn = 'no';
2744 }
2745 else {
2746 die "Internal error. Unknown datasockf state: $state!";
2747 }
2748 }
2749
2750 #**********************************************************************
2751 # nodataconn_str returns string of effective nodataconn command. Notice
2752 # that $nodataconn may be set alone or in addition to a $nodataconnXXX.
2753 #
2754 sub nodataconn_str {
2755 my $str;
2756 # order matters
2757 $str = 'NODATACONN' if($nodataconn);
2758 $str = 'NODATACONN425' if($nodataconn425);
2759 $str = 'NODATACONN421' if($nodataconn421);
2760 $str = 'NODATACONN150' if($nodataconn150);
2761 return "$str";
2762 }
2763
2764 #**********************************************************************
2765 # customize configures test server operation for each curl test, reading
2766 # configuration commands/parameters from server commands file each time
2767 # a new client control connection is established with the test server.
2768 # On success returns 1, otherwise zero.
2769 #
2770 sub customize {
2771 $ctrldelay = 0; # default is no throttling of the ctrl stream
2772 $datadelay = 0; # default is no throttling of the data stream
2773 $retrweirdo = 0; # default is no use of RETRWEIRDO
2774 $retrnosize = 0; # default is no use of RETRNOSIZE
2775 $pasvbadip = 0; # default is no use of PASVBADIP
2776 $nosave = 0; # default is to actually save uploaded data to file
2777 $nodataconn = 0; # default is to establish or accept data channel
2778 $nodataconn425 = 0; # default is to not send 425 without data channel
2779 $nodataconn421 = 0; # default is to not send 421 without data channel
2780 $nodataconn150 = 0; # default is to not send 150 without data channel
2781 @capabilities = (); # default is to not support capability commands
2782 @auth_mechs = (); # default is to not support authentication commands
2783 %fulltextreply = ();#
2784 %commandreply = (); #
2785 %customcount = (); #
2786 %delayreply = (); #
2787
2788 open(CUSTOM, "<log/ftpserver.cmd") ||
2789 return 1;
2790
2791 logmsg "FTPD: Getting commands from log/ftpserver.cmd\n";
2792
2793 while(<CUSTOM>) {
2794 if($_ =~ /REPLY \"([A-Z]+ [A-Za-z0-9+-\/=\*. ]+)\" (.*)/) {
2795 $fulltextreply{$1}=eval "qq{$2}";
2796 logmsg "FTPD: set custom reply for $1\n";
2797 }
2798 elsif($_ =~ /REPLY(LF|) ([A-Za-z0-9+\/=\*]*) (.*)/) {
2799 $commandreply{$2}=eval "qq{$3}";
2800 if($1 ne "LF") {
2801 $commandreply{$2}.="\r\n";
2802 }
2803 else {
2804 $commandreply{$2}.="\n";
2805 }
2806 if($2 eq "") {
2807 logmsg "FTPD: set custom reply for empty command\n";
2808 }
2809 else {
2810 logmsg "FTPD: set custom reply for $2 command\n";
2811 }
2812 }
2813 elsif($_ =~ /COUNT ([A-Z]+) (.*)/) {
2814 # we blank the custom reply for this command when having
2815 # been used this number of times
2816 $customcount{$1}=$2;
2817 logmsg "FTPD: blank custom reply for $1 command after $2 uses\n";
2818 }
2819 elsif($_ =~ /DELAY ([A-Z]+) (\d*)/) {
2820 $delayreply{$1}=$2;
2821 logmsg "FTPD: delay reply for $1 with $2 seconds\n";
2822 }
2823 elsif($_ =~ /SLOWDOWN/) {
2824 $ctrldelay=1;
2825 $datadelay=1;
2826 logmsg "FTPD: send response with 0.01 sec delay between each byte\n";
2827 }
2828 elsif($_ =~ /RETRWEIRDO/) {
2829 logmsg "FTPD: instructed to use RETRWEIRDO\n";
2830 $retrweirdo=1;
2831 }
2832 elsif($_ =~ /RETRNOSIZE/) {
2833 logmsg "FTPD: instructed to use RETRNOSIZE\n";
2834 $retrnosize=1;
2835 }
2836 elsif($_ =~ /PASVBADIP/) {
2837 logmsg "FTPD: instructed to use PASVBADIP\n";
2838 $pasvbadip=1;
2839 }
2840 elsif($_ =~ /NODATACONN425/) {
2841 # applies to both active and passive FTP modes
2842 logmsg "FTPD: instructed to use NODATACONN425\n";
2843 $nodataconn425=1;
2844 $nodataconn=1;
2845 }
2846 elsif($_ =~ /NODATACONN421/) {
2847 # applies to both active and passive FTP modes
2848 logmsg "FTPD: instructed to use NODATACONN421\n";
2849 $nodataconn421=1;
2850 $nodataconn=1;
2851 }
2852 elsif($_ =~ /NODATACONN150/) {
2853 # applies to both active and passive FTP modes
2854 logmsg "FTPD: instructed to use NODATACONN150\n";
2855 $nodataconn150=1;
2856 $nodataconn=1;
2857 }
2858 elsif($_ =~ /NODATACONN/) {
2859 # applies to both active and passive FTP modes
2860 logmsg "FTPD: instructed to use NODATACONN\n";
2861 $nodataconn=1;
2862 }
2863 elsif($_ =~ /CAPA (.*)/) {
2864 logmsg "FTPD: instructed to support CAPABILITY command\n";
2865 @capabilities = split(/ (?!(?:[^" ]|[^"] [^"])+")/, $1);
2866 foreach (@capabilities) {
2867 $_ = $1 if /^"(.*)"$/;
2868 }
2869 }
2870 elsif($_ =~ /AUTH (.*)/) {
2871 logmsg "FTPD: instructed to support AUTHENTICATION command\n";
2872 @auth_mechs = split(/ /, $1);
2873 }
2874 elsif($_ =~ /NOSAVE/) {
2875 # don't actually store the file we upload - to be used when
2876 # uploading insanely huge amounts
2877 $nosave = 1;
2878 logmsg "FTPD: NOSAVE prevents saving of uploaded data\n";
2879 }
2880 }
2881 close(CUSTOM);
2882 }
2883
2884 #----------------------------------------------------------------------
2885 #----------------------------------------------------------------------
2886 #--------------------------- END OF SUBS ----------------------------
2887 #----------------------------------------------------------------------
2888 #----------------------------------------------------------------------
2889
2890 #**********************************************************************
2891 # Parse command line options
2892 #
2893 # Options:
2894 #
2895 # --verbose # verbose
2896 # --srcdir # source directory
2897 # --id # server instance number
2898 # --proto # server protocol
2899 # --pidfile # server pid file
2900 # --logfile # server log file
2901 # --ipv4 # server IP version 4
2902 # --ipv6 # server IP version 6
2903 # --port # server listener port
2904 # --addr # server address for listener port binding
2905 #
2906 while(@ARGV) {
2907 if($ARGV[0] eq '--verbose') {
2908 $verbose = 1;
2909 }
2910 elsif($ARGV[0] eq '--srcdir') {
2911 if($ARGV[1]) {
2912 $srcdir = $ARGV[1];
2913 shift @ARGV;
2914 }
2915 }
2916 elsif($ARGV[0] eq '--id') {
2917 if($ARGV[1] && ($ARGV[1] =~ /^(\d+)$/)) {
2918 $idnum = $1 if($1 > 0);
2919 shift @ARGV;
2920 }
2921 }
2922 elsif($ARGV[0] eq '--proto') {
2923 if($ARGV[1] && ($ARGV[1] =~ /^(ftp|imap|pop3|smtp)$/)) {
2924 $proto = $1;
2925 shift @ARGV;
2926 }
2927 else {
2928 die "unsupported protocol $ARGV[1]";
2929 }
2930 }
2931 elsif($ARGV[0] eq '--pidfile') {
2932 if($ARGV[1]) {
2933 $pidfile = $ARGV[1];
2934 shift @ARGV;
2935 }
2936 }
2937 elsif($ARGV[0] eq '--logfile') {
2938 if($ARGV[1]) {
2939 $logfile = $ARGV[1];
2940 shift @ARGV;
2941 }
2942 }
2943 elsif($ARGV[0] eq '--ipv4') {
2944 $ipvnum = 4;
2945 $listenaddr = '127.0.0.1' if($listenaddr eq '::1');
2946 }
2947 elsif($ARGV[0] eq '--ipv6') {
2948 $ipvnum = 6;
2949 $listenaddr = '::1' if($listenaddr eq '127.0.0.1');
2950 }
2951 elsif($ARGV[0] eq '--port') {
2952 if($ARGV[1] && ($ARGV[1] =~ /^(\d+)$/)) {
2953 $port = $1 if($1 > 1024);
2954 shift @ARGV;
2955 }
2956 }
2957 elsif($ARGV[0] eq '--addr') {
2958 if($ARGV[1]) {
2959 my $tmpstr = $ARGV[1];
2960 if($tmpstr =~ /^(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)$/) {
2961 $listenaddr = "$1.$2.$3.$4" if($ipvnum == 4);
2962 }
2963 elsif($ipvnum == 6) {
2964 $listenaddr = $tmpstr;
2965 $listenaddr =~ s/^\[(.*)\]$/$1/;
2966 }
2967 shift @ARGV;
2968 }
2969 }
2970 else {
2971 print STDERR "\nWarning: ftpserver.pl unknown parameter: $ARGV[0]\n";
2972 }
2973 shift @ARGV;
2974 }
2975
2976 #***************************************************************************
2977 # Initialize command line option dependent variables
2978 #
2979
2980 if(!$srcdir) {
2981 $srcdir = $ENV{'srcdir'} || '.';
2982 }
2983 if(!$pidfile) {
2984 $pidfile = "$path/". server_pidfilename($proto, $ipvnum, $idnum);
2985 }
2986 if(!$logfile) {
2987 $logfile = server_logfilename($logdir, $proto, $ipvnum, $idnum);
2988 }
2989
2990 $mainsockf_pidfile = "$path/".
2991 mainsockf_pidfilename($proto, $ipvnum, $idnum);
2992 $mainsockf_logfile =
2993 mainsockf_logfilename($logdir, $proto, $ipvnum, $idnum);
2994
2995 if($proto eq 'ftp') {
2996 $datasockf_pidfile = "$path/".
2997 datasockf_pidfilename($proto, $ipvnum, $idnum);
2998 $datasockf_logfile =
2999 datasockf_logfilename($logdir, $proto, $ipvnum, $idnum);
3000 }
3001
3002 $srvrname = servername_str($proto, $ipvnum, $idnum);
3003
3004 $idstr = "$idnum" if($idnum > 1);
3005
3006 protocolsetup($proto);
3007
3008 $SIG{INT} = \&exit_signal_handler;
3009 $SIG{TERM} = \&exit_signal_handler;
3010
3011 startsf();
3012
3013 logmsg sprintf("%s server listens on port IPv${ipvnum}/${port}\n", uc($proto));
3014
3015 open(PID, ">$pidfile");
3016 print PID $$."\n";
3017 close(PID);
3018
3019 logmsg("logged pid $$ in $pidfile\n");
3020
3021
3022 while(1) {
3023
3024 # kill previous data connection sockfilt when alive
3025 if($datasockf_runs eq 'yes') {
3026 killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
3027 logmsg "DATA sockfilt for $datasockf_mode data channel killed now\n";
3028 }
3029 datasockf_state('STOPPED');
3030
3031 #
3032 # We read 'sockfilt' commands.
3033 #
3034 my $input;
3035
3036 logmsg "Awaiting input\n";
3037 sysread_or_die(\*SFREAD, \$input, 5);
3038
3039 if($input !~ /^CNCT/) {
3040 # we wait for a connected client
3041 logmsg "MAIN sockfilt said: $input";
3042 next;
3043 }
3044 logmsg "====> Client connect\n";
3045
3046 set_advisor_read_lock($SERVERLOGS_LOCK);
3047 $serverlogslocked = 1;
3048
3049 # flush data:
3050 $| = 1;
3051
3052 &customize(); # read test control instructions
3053
3054 my $welcome = $commandreply{"welcome"};
3055 if(!$welcome) {
3056 $welcome = $displaytext{"welcome"};
3057 }
3058 else {
3059 # clear it after use
3060 $commandreply{"welcome"}="";
3061 if($welcome !~ /\r\n\z/) {
3062 $welcome .= "\r\n";
3063 }
3064 }
3065 sendcontrol $welcome;
3066
3067 #remove global variables from last connection
3068 if($ftplistparserstate) {
3069 undef $ftplistparserstate;
3070 }
3071 if($ftptargetdir) {
3072 $ftptargetdir = "";
3073 }
3074
3075 if($verbose) {
3076 print STDERR "OUT: $welcome";
3077 }
3078
3079 my $full = "";
3080
3081 while(1) {
3082 my $i;
3083
3084 # Now we expect to read DATA\n[hex size]\n[prot], where the [prot]
3085 # part only is FTP lingo.
3086
3087 # COMMAND
3088 sysread_or_die(\*SFREAD, \$i, 5);
3089
3090 if($i !~ /^DATA/) {
3091 logmsg "MAIN sockfilt said $i";
3092 if($i =~ /^DISC/) {
3093 # disconnect
3094 last;
3095 }
3096 next;
3097 }
3098
3099 # SIZE of data
3100 sysread_or_die(\*SFREAD, \$i, 5);
3101
3102 my $size = 0;
3103 if($i =~ /^([0-9a-fA-F]{4})\n/) {
3104 $size = hex($1);
3105 }
3106
3107 # data
3108 read_mainsockf(\$input, $size);
3109
3110 ftpmsg $input;
3111
3112 $full .= $input;
3113
3114 # Loop until command completion
3115 next unless($full =~ /\r\n$/);
3116
3117 # Remove trailing CRLF.
3118 $full =~ s/[\n\r]+$//;
3119
3120 my $FTPCMD;
3121 my $FTPARG;
3122 if($proto eq "imap") {
3123 # IMAP is different with its identifier first on the command line
3124 if(($full =~ /^([^ ]+) ([^ ]+) (.*)/) ||
3125 ($full =~ /^([^ ]+) ([^ ]+)/)) {
3126 $cmdid=$1; # set the global variable
3127 $FTPCMD=$2;
3128 $FTPARG=$3;
3129 }
3130 # IMAP authentication cancellation
3131 elsif($full =~ /^\*$/) {
3132 # Command id has already been set
3133 $FTPCMD="*";
3134 $FTPARG="";
3135 }
3136 # IMAP long "commands" are base64 authentication data
3137 elsif($full =~ /^[A-Z0-9+\/]*={0,2}$/i) {
3138 # Command id has already been set
3139 $FTPCMD=$full;
3140 $FTPARG="";
3141 }
3142 else {
3143 sendcontrol "$full BAD Command\r\n";
3144 last;
3145 }
3146 }
3147 elsif($full =~ /^([A-Z]{3,4})(\s(.*))?$/i) {
3148 $FTPCMD=$1;
3149 $FTPARG=$3;
3150 }
3151 elsif($proto eq "pop3") {
3152 # POP3 authentication cancellation
3153 if($full =~ /^\*$/) {
3154 $FTPCMD="*";
3155 $FTPARG="";
3156 }
3157 # POP3 long "commands" are base64 authentication data
3158 elsif($full =~ /^[A-Z0-9+\/]*={0,2}$/i) {
3159 $FTPCMD=$full;
3160 $FTPARG="";
3161 }
3162 else {
3163 sendcontrol "-ERR Unrecognized command\r\n";
3164 last;
3165 }
3166 }
3167 elsif($proto eq "smtp") {
3168 # SMTP authentication cancellation
3169 if($full =~ /^\*$/) {
3170 $FTPCMD="*";
3171 $FTPARG="";
3172 }
3173 # SMTP long "commands" are base64 authentication data
3174 elsif($full =~ /^[A-Z0-9+\/]{0,512}={0,2}$/i) {
3175 $FTPCMD=$full;
3176 $FTPARG="";
3177 }
3178 else {
3179 sendcontrol "500 Unrecognized command\r\n";
3180 last;
3181 }
3182 }
3183 else {
3184 sendcontrol "500 Unrecognized command\r\n";
3185 last;
3186 }
3187
3188 logmsg "< \"$full\"\n";
3189
3190 if($verbose) {
3191 print STDERR "IN: $full\n";
3192 }
3193
3194 $full = "";
3195
3196 my $delay = $delayreply{$FTPCMD};
3197 if($delay) {
3198 # just go sleep this many seconds!
3199 logmsg("Sleep for $delay seconds\n");
3200 my $twentieths = $delay * 20;
3201 while($twentieths--) {
3202 select(undef, undef, undef, 0.05) unless($got_exit_signal);
3203 }
3204 }
3205
3206 my $check = 1; # no response yet
3207
3208 # See if there is a custom reply for the full text
3209 my $fulltext = $FTPARG ? $FTPCMD . " " . $FTPARG : $FTPCMD;
3210 my $text = $fulltextreply{$fulltext};
3211 if($text && ($text ne "")) {
3212 sendcontrol "$text\r\n";
3213 $check = 0;
3214 }
3215 else {
3216 # See if there is a custom reply for the command
3217 $text = $commandreply{$FTPCMD};
3218 if($text && ($text ne "")) {
3219 if($customcount{$FTPCMD} && (!--$customcount{$FTPCMD})) {
3220 # used enough times so blank the custom command reply
3221 $commandreply{$FTPCMD}="";
3222 }
3223
3224 sendcontrol $text;
3225 $check = 0;
3226 }
3227 else {
3228 # See if there is any display text for the command
3229 $text = $displaytext{$FTPCMD};
3230 if($text && ($text ne "")) {
3231 if($proto eq 'imap') {
3232 sendcontrol "$cmdid $text\r\n";
3233 }
3234 else {
3235 sendcontrol "$text\r\n";
3236 }
3237
3238 $check = 0;
3239 }
3240
3241 # only perform this if we're not faking a reply
3242 my $func = $commandfunc{uc($FTPCMD)};
3243 if($func) {
3244 &$func($FTPARG, $FTPCMD);
3245 $check = 0;
3246 }
3247 }
3248 }
3249
3250 if($check) {
3251 logmsg "$FTPCMD wasn't handled!\n";
3252 if($proto eq 'pop3') {
3253 sendcontrol "-ERR $FTPCMD is not dealt with!\r\n";
3254 }
3255 elsif($proto eq 'imap') {
3256 sendcontrol "$cmdid BAD $FTPCMD is not dealt with!\r\n";
3257 }
3258 else {
3259 sendcontrol "500 $FTPCMD is not dealt with!\r\n";
3260 }
3261 }
3262
3263 } # while(1)
3264 logmsg "====> Client disconnected\n";
3265
3266 if($serverlogslocked) {
3267 $serverlogslocked = 0;
3268 clear_advisor_read_lock($SERVERLOGS_LOCK);
3269 }
3270 }
3271
3272 killsockfilters($proto, $ipvnum, $idnum, $verbose);
3273 unlink($pidfile);
3274 if($serverlogslocked) {
3275 $serverlogslocked = 0;
3276 clear_advisor_read_lock($SERVERLOGS_LOCK);
3277 }
3278
3279 exit;