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