-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathftpserver.pl
executable file
·3332 lines (2827 loc) · 89 KB
/
ftpserver.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env perl
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2022, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
# SPDX-License-Identifier: curl
#
###########################################################################
# This is a server designed for the curl test suite.
#
# In December 2009 we started remaking the server to support more protocols
# that are similar in spirit. Like POP3, IMAP and SMTP in addition to the FTP
# it already supported since a long time. Note that it still only supports one
# protocol per invoke. You need to start multiple servers to support multiple
# protocols simultaneously.
#
# It is meant to exercise curl, it is not meant to be a fully working
# or even very standard compliant server.
#
# You may optionally specify port on the command line, otherwise it'll
# default to port 8921.
#
# All socket/network/TCP related stuff is done by the 'sockfilt' program.
#
BEGIN {
push(@INC, $ENV{'srcdir'}) if(defined $ENV{'srcdir'});
push(@INC, ".");
# sub second timestamping needs Time::HiRes
eval {
no warnings "all";
require Time::HiRes;
import Time::HiRes qw( gettimeofday );
}
}
use strict;
use warnings;
use IPC::Open2;
use Digest::MD5;
require "getpart.pm";
require "ftp.pm";
require "directories.pm";
use serverhelp qw(
servername_str
server_pidfilename
server_logfilename
mainsockf_pidfilename
mainsockf_logfilename
datasockf_pidfilename
datasockf_logfilename
);
use sshhelp qw(
exe_ext
);
#**********************************************************************
# global vars...
#
my $verbose = 0; # set to 1 for debugging
my $idstr = ""; # server instance string
my $idnum = 1; # server instance number
my $ipvnum = 4; # server IPv number (4 or 6)
my $proto = 'ftp'; # default server protocol
my $srcdir; # directory where ftpserver.pl is located
my $srvrname; # server name for presentation purposes
my $cwd_testno; # test case numbers extracted from CWD command
my $testno = 0; # test case number (read from ftpserver.cmd)
my $path = '.';
my $logdir = $path .'/log';
#**********************************************************************
# global vars used for server address and primary listener port
#
my $port = 8921; # default primary listener port
my $listenaddr = '127.0.0.1'; # default address for listener port
#**********************************************************************
# global vars used for file names
#
my $pidfile; # server pid file name
my $portfile=".ftpserver.port"; # server port file name
my $logfile; # server log file name
my $mainsockf_pidfile; # pid file for primary connection sockfilt process
my $mainsockf_logfile; # log file for primary connection sockfilt process
my $datasockf_pidfile; # pid file for secondary connection sockfilt process
my $datasockf_logfile; # log file for secondary connection sockfilt process
#**********************************************************************
# global vars used for server logs advisor read lock handling
#
my $SERVERLOGS_LOCK = 'log/serverlogs.lock';
my $serverlogslocked = 0;
#**********************************************************************
# global vars used for child processes PID tracking
#
my $sfpid; # PID for primary connection sockfilt process
my $slavepid; # PID for secondary connection sockfilt process
#**********************************************************************
# global typeglob filehandle vars to read/write from/to sockfilters
#
local *SFREAD; # used to read from primary connection
local *SFWRITE; # used to write to primary connection
local *DREAD; # used to read from secondary connection
local *DWRITE; # used to write to secondary connection
my $sockfilt_timeout = 5; # default timeout for sockfilter eXsysreads
#**********************************************************************
# global vars which depend on server protocol selection
#
my %commandfunc; # protocol command specific function callbacks
my %displaytext; # text returned to client before callback runs
#**********************************************************************
# global vars customized for each test from the server commands file
#
my $ctrldelay; # set if server should throttle ctrl stream
my $datadelay; # set if server should throttle data stream
my $retrweirdo; # set if ftp server should use RETRWEIRDO
my $retrnosize; # set if ftp server should use RETRNOSIZE
my $pasvbadip; # set if ftp server should use PASVBADIP
my $nosave; # set if ftp server should not save uploaded data
my $nodataconn; # set if ftp srvr doesn't establish or accepts data channel
my $nodataconn425; # set if ftp srvr doesn't establish data ch and replies 425
my $nodataconn421; # set if ftp srvr doesn't establish data ch and replies 421
my $nodataconn150; # set if ftp srvr doesn't establish data ch and replies 150
my $storeresp;
my $postfetch;
my @capabilities; # set if server supports capability commands
my @auth_mechs; # set if server supports authentication commands
my %fulltextreply; #
my %commandreply; #
my %customcount; #
my %delayreply; #
#**********************************************************************
# global variables for to test ftp wildcardmatching or other test that
# need flexible LIST responses.. and corresponding files.
# $ftptargetdir is keeping the fake "name" of LIST directory.
#
my $ftplistparserstate;
my $ftptargetdir="";
#**********************************************************************
# global variables used when running a ftp server to keep state info
# relative to the secondary or data sockfilt process. Values of these
# variables should only be modified using datasockf_state() sub, given
# that they are closely related and relationship is a bit awkward.
#
my $datasockf_state = 'STOPPED'; # see datasockf_state() sub
my $datasockf_mode = 'none'; # ['none','active','passive']
my $datasockf_runs = 'no'; # ['no','yes']
my $datasockf_conn = 'no'; # ['no','yes']
#**********************************************************************
# global vars used for signal handling
#
my $got_exit_signal = 0; # set if program should finish execution ASAP
my $exit_signal; # first signal handled in exit_signal_handler
#**********************************************************************
# Mail related definitions
#
my $TEXT_PASSWORD = "secret";
my $POP3_TIMESTAMP = "<1972.987654321\@curl>";
#**********************************************************************
# exit_signal_handler will be triggered to indicate that the program
# should finish its execution in a controlled way as soon as possible.
# For now, program will also terminate from within this handler.
#
sub exit_signal_handler {
my $signame = shift;
# For now, simply mimic old behavior.
killsockfilters($proto, $ipvnum, $idnum, $verbose);
unlink($pidfile);
unlink($portfile);
if($serverlogslocked) {
$serverlogslocked = 0;
clear_advisor_read_lock($SERVERLOGS_LOCK);
}
exit;
}
#**********************************************************************
# logmsg is general message logging subroutine for our test servers.
#
sub logmsg {
my $now;
# sub second timestamping needs Time::HiRes
if($Time::HiRes::VERSION) {
my ($seconds, $usec) = gettimeofday();
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
localtime($seconds);
$now = sprintf("%02d:%02d:%02d.%06d ", $hour, $min, $sec, $usec);
}
else {
my $seconds = time();
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
localtime($seconds);
$now = sprintf("%02d:%02d:%02d ", $hour, $min, $sec);
}
if(open(LOGFILEFH, ">>$logfile")) {
print LOGFILEFH $now;
print LOGFILEFH @_;
close(LOGFILEFH);
}
}
sub ftpmsg {
# append to the server.input file
open(INPUT, ">>log/server$idstr.input") ||
logmsg "failed to open log/server$idstr.input\n";
print INPUT @_;
close(INPUT);
# use this, open->print->close system only to make the file
# open as little as possible, to make the test suite run
# better on windows/cygwin
}
#**********************************************************************
# eXsysread is a wrapper around perl's sysread() function. This will
# repeat the call to sysread() until it has actually read the complete
# number of requested bytes or an unrecoverable condition occurs.
# On success returns a positive value, the number of bytes requested.
# On failure or timeout returns zero.
#
sub eXsysread {
my $FH = shift;
my $scalar = shift;
my $nbytes = shift;
my $timeout = shift; # A zero timeout disables eXsysread() time limit
#
my $time_limited = 0;
my $timeout_rest = 0;
my $start_time = 0;
my $nread = 0;
my $rc;
$$scalar = "";
if((not defined $nbytes) || ($nbytes < 1)) {
logmsg "Error: eXsysread() failure: " .
"length argument must be positive\n";
return 0;
}
if((not defined $timeout) || ($timeout < 0)) {
logmsg "Error: eXsysread() failure: " .
"timeout argument must be zero or positive\n";
return 0;
}
if($timeout > 0) {
# caller sets eXsysread() time limit
$time_limited = 1;
$timeout_rest = $timeout;
$start_time = int(time());
}
while($nread < $nbytes) {
if($time_limited) {
eval {
local $SIG{ALRM} = sub { die "alarm\n"; };
alarm $timeout_rest;
$rc = sysread($FH, $$scalar, $nbytes - $nread, $nread);
alarm 0;
};
$timeout_rest = $timeout - (int(time()) - $start_time);
if($timeout_rest < 1) {
logmsg "Error: eXsysread() failure: timed out\n";
return 0;
}
}
else {
$rc = sysread($FH, $$scalar, $nbytes - $nread, $nread);
}
if($got_exit_signal) {
logmsg "Error: eXsysread() failure: signalled to die\n";
return 0;
}
if(not defined $rc) {
if($!{EINTR}) {
logmsg "Warning: retrying sysread() interrupted system call\n";
next;
}
if($!{EAGAIN}) {
logmsg "Warning: retrying sysread() due to EAGAIN\n";
next;
}
if($!{EWOULDBLOCK}) {
logmsg "Warning: retrying sysread() due to EWOULDBLOCK\n";
next;
}
logmsg "Error: sysread() failure: $!\n";
return 0;
}
if($rc < 0) {
logmsg "Error: sysread() failure: returned negative value $rc\n";
return 0;
}
if($rc == 0) {
logmsg "Error: sysread() failure: read zero bytes\n";
return 0;
}
$nread += $rc;
}
return $nread;
}
#**********************************************************************
# read_mainsockf attempts to read the given amount of output from the
# sockfilter which is in use for the main or primary connection. This
# reads untranslated sockfilt lingo which may hold data read from the
# main or primary socket. On success returns 1, otherwise zero.
#
sub read_mainsockf {
my $scalar = shift;
my $nbytes = shift;
my $timeout = shift; # Optional argument, if zero blocks indefinitely
my $FH = \*SFREAD;
if(not defined $timeout) {
$timeout = $sockfilt_timeout + ($nbytes >> 12);
}
if(eXsysread($FH, $scalar, $nbytes, $timeout) != $nbytes) {
my ($fcaller, $lcaller) = (caller)[1,2];
logmsg "Error: read_mainsockf() failure at $fcaller " .
"line $lcaller. Due to eXsysread() failure\n";
return 0;
}
return 1;
}
#**********************************************************************
# read_datasockf attempts to read the given amount of output from the
# sockfilter which is in use for the data or secondary connection. This
# reads untranslated sockfilt lingo which may hold data read from the
# data or secondary socket. On success returns 1, otherwise zero.
#
sub read_datasockf {
my $scalar = shift;
my $nbytes = shift;
my $timeout = shift; # Optional argument, if zero blocks indefinitely
my $FH = \*DREAD;
if(not defined $timeout) {
$timeout = $sockfilt_timeout + ($nbytes >> 12);
}
if(eXsysread($FH, $scalar, $nbytes, $timeout) != $nbytes) {
my ($fcaller, $lcaller) = (caller)[1,2];
logmsg "Error: read_datasockf() failure at $fcaller " .
"line $lcaller. Due to eXsysread() failure\n";
return 0;
}
return 1;
}
sub sysread_or_die {
my $FH = shift;
my $scalar = shift;
my $length = shift;
my $fcaller;
my $lcaller;
my $result;
$result = sysread($$FH, $$scalar, $length);
if(not defined $result) {
($fcaller, $lcaller) = (caller)[1,2];
logmsg "Failed to read input\n";
logmsg "Error: $srvrname server, sysread error: $!\n";
logmsg "Exited from sysread_or_die() at $fcaller " .
"line $lcaller. $srvrname server, sysread error: $!\n";
killsockfilters($proto, $ipvnum, $idnum, $verbose);
unlink($pidfile);
unlink($portfile);
if($serverlogslocked) {
$serverlogslocked = 0;
clear_advisor_read_lock($SERVERLOGS_LOCK);
}
exit;
}
elsif($result == 0) {
($fcaller, $lcaller) = (caller)[1,2];
logmsg "Failed to read input\n";
logmsg "Error: $srvrname server, read zero\n";
logmsg "Exited from sysread_or_die() at $fcaller " .
"line $lcaller. $srvrname server, read zero\n";
killsockfilters($proto, $ipvnum, $idnum, $verbose);
unlink($pidfile);
unlink($portfile);
if($serverlogslocked) {
$serverlogslocked = 0;
clear_advisor_read_lock($SERVERLOGS_LOCK);
}
exit;
}
return $result;
}
sub startsf {
my $mainsockfcmd = "./server/sockfilt".exe_ext('SRV')." " .
"--ipv$ipvnum --port $port " .
"--pidfile \"$mainsockf_pidfile\" " .
"--portfile \"$portfile\" " .
"--logfile \"$mainsockf_logfile\"";
$sfpid = open2(*SFREAD, *SFWRITE, $mainsockfcmd);
print STDERR "$mainsockfcmd\n" if($verbose);
print SFWRITE "PING\n";
my $pong;
sysread_or_die(\*SFREAD, \$pong, 5);
if($pong !~ /^PONG/) {
logmsg "Failed sockfilt command: $mainsockfcmd\n";
killsockfilters($proto, $ipvnum, $idnum, $verbose);
unlink($pidfile);
unlink($portfile);
if($serverlogslocked) {
$serverlogslocked = 0;
clear_advisor_read_lock($SERVERLOGS_LOCK);
}
die "Failed to start sockfilt!";
}
}
#**********************************************************************
# Returns the given test's reply data
#
sub getreplydata {
my ($num) = @_;
my $testpart = "";
$num =~ s/^([^0-9]*)//;
if($num > 10000) {
$testpart = $num % 10000;
}
my @data = getpart("reply", "data$testpart");
if((!@data) && ($testpart ne "")) {
@data = getpart("reply", "data");
}
return @data;
}
sub sockfilt {
my $l;
foreach $l (@_) {
printf SFWRITE "DATA\n%04x\n", length($l);
print SFWRITE $l;
}
}
sub sockfiltsecondary {
my $l;
foreach $l (@_) {
printf DWRITE "DATA\n%04x\n", length($l);
print DWRITE $l;
}
}
#**********************************************************************
# Send data to the client on the control stream, which happens to be plain
# stdout.
#
sub sendcontrol {
if(!$ctrldelay) {
# spit it all out at once
sockfilt @_;
}
else {
my $a = join("", @_);
my @a = split("", $a);
for(@a) {
sockfilt $_;
portable_sleep(0.01);
}
}
my $log;
foreach $log (@_) {
my $l = $log;
$l =~ s/\r/[CR]/g;
$l =~ s/\n/[LF]/g;
logmsg "> \"$l\"\n";
}
}
#**********************************************************************
# Send data to the FTP client on the data stream when data connection
# is actually established. Given that this sub should only be called
# when a data connection is supposed to be established, calling this
# without a data connection is an indication of weak logic somewhere.
#
sub senddata {
my $l;
if($datasockf_conn eq 'no') {
logmsg "WARNING: Detected data sending attempt without DATA channel\n";
foreach $l (@_) {
logmsg "WARNING: Data swallowed: $l\n"
}
return;
}
foreach $l (@_) {
if(!$datadelay) {
# spit it all out at once
sockfiltsecondary $l;
}
else {
# pause between each byte
for (split(//,$l)) {
sockfiltsecondary $_;
portable_sleep(0.01);
}
}
}
}
#**********************************************************************
# protocolsetup initializes the 'displaytext' and 'commandfunc' hashes
# for the given protocol. References to protocol command callbacks are
# stored in 'commandfunc' hash, and text which will be returned to the
# client before the command callback runs is stored in 'displaytext'.
#
sub protocolsetup {
my $proto = $_[0];
if($proto eq 'ftp') {
%commandfunc = (
'PORT' => \&PORT_ftp,
'EPRT' => \&PORT_ftp,
'LIST' => \&LIST_ftp,
'NLST' => \&NLST_ftp,
'PASV' => \&PASV_ftp,
'CWD' => \&CWD_ftp,
'PWD' => \&PWD_ftp,
'EPSV' => \&PASV_ftp,
'RETR' => \&RETR_ftp,
'SIZE' => \&SIZE_ftp,
'REST' => \&REST_ftp,
'STOR' => \&STOR_ftp,
'APPE' => \&STOR_ftp, # append looks like upload
'MDTM' => \&MDTM_ftp,
);
%displaytext = (
'USER' => '331 We are happy you popped in!',
'PASS' => '230 Welcome you silly person',
'PORT' => '200 You said PORT - I say FINE',
'TYPE' => '200 I modify TYPE as you wanted',
'LIST' => '150 here comes a directory',
'NLST' => '150 here comes a directory',
'CWD' => '250 CWD command successful.',
'SYST' => '215 UNIX Type: L8', # just fake something
'QUIT' => '221 bye bye baby', # just reply something
'MKD' => '257 Created your requested directory',
'REST' => '350 Yeah yeah we set it there for you',
'DELE' => '200 OK OK OK whatever you say',
'RNFR' => '350 Received your order. Please provide more',
'RNTO' => '250 Ok, thanks. File renaming completed.',
'NOOP' => '200 Yes, I\'m very good at doing nothing.',
'PBSZ' => '500 PBSZ not implemented',
'PROT' => '500 PROT not implemented',
'welcome' => join("",
'220- _ _ ____ _ '."\r\n",
'220- ___| | | | _ \| | '."\r\n",
'220- / __| | | | |_) | | '."\r\n",
'220- | (__| |_| | _ {| |___ '."\r\n",
'220 \___|\___/|_| \_\_____|'."\r\n")
);
}
elsif($proto eq 'pop3') {
%commandfunc = (
'APOP' => \&APOP_pop3,
'AUTH' => \&AUTH_pop3,
'CAPA' => \&CAPA_pop3,
'DELE' => \&DELE_pop3,
'LIST' => \&LIST_pop3,
'NOOP' => \&NOOP_pop3,
'PASS' => \&PASS_pop3,
'QUIT' => \&QUIT_pop3,
'RETR' => \&RETR_pop3,
'RSET' => \&RSET_pop3,
'STAT' => \&STAT_pop3,
'TOP' => \&TOP_pop3,
'UIDL' => \&UIDL_pop3,
'USER' => \&USER_pop3,
);
%displaytext = (
'welcome' => join("",
' _ _ ____ _ '."\r\n",
' ___| | | | _ \| | '."\r\n",
' / __| | | | |_) | | '."\r\n",
' | (__| |_| | _ {| |___ '."\r\n",
' \___|\___/|_| \_\_____|'."\r\n",
'+OK curl POP3 server ready to serve '."\r\n")
);
}
elsif($proto eq 'imap') {
%commandfunc = (
'APPEND' => \&APPEND_imap,
'CAPABILITY' => \&CAPABILITY_imap,
'CHECK' => \&CHECK_imap,
'CLOSE' => \&CLOSE_imap,
'COPY' => \©_imap,
'CREATE' => \&CREATE_imap,
'DELETE' => \&DELETE_imap,
'EXAMINE' => \&EXAMINE_imap,
'EXPUNGE' => \&EXPUNGE_imap,
'FETCH' => \&FETCH_imap,
'LIST' => \&LIST_imap,
'LSUB' => \&LSUB_imap,
'LOGIN' => \&LOGIN_imap,
'LOGOUT' => \&LOGOUT_imap,
'NOOP' => \&NOOP_imap,
'RENAME' => \&RENAME_imap,
'SEARCH' => \&SEARCH_imap,
'SELECT' => \&SELECT_imap,
'STATUS' => \&STATUS_imap,
'STORE' => \&STORE_imap,
'UID' => \&UID_imap,
'IDLE' => \&IDLE_imap,
);
%displaytext = (
'welcome' => join("",
' _ _ ____ _ '."\r\n",
' ___| | | | _ \| | '."\r\n",
' / __| | | | |_) | | '."\r\n",
' | (__| |_| | _ {| |___ '."\r\n",
' \___|\___/|_| \_\_____|'."\r\n",
'* OK curl IMAP server ready to serve'."\r\n")
);
}
elsif($proto eq 'smtp') {
%commandfunc = (
'DATA' => \&DATA_smtp,
'EHLO' => \&EHLO_smtp,
'EXPN' => \&EXPN_smtp,
'HELO' => \&HELO_smtp,
'HELP' => \&HELP_smtp,
'MAIL' => \&MAIL_smtp,
'NOOP' => \&NOOP_smtp,
'RSET' => \&RSET_smtp,
'RCPT' => \&RCPT_smtp,
'VRFY' => \&VRFY_smtp,
'QUIT' => \&QUIT_smtp,
);
%displaytext = (
'welcome' => join("",
'220- _ _ ____ _ '."\r\n",
'220- ___| | | | _ \| | '."\r\n",
'220- / __| | | | |_) | | '."\r\n",
'220- | (__| |_| | _ {| |___ '."\r\n",
'220 \___|\___/|_| \_\_____|'."\r\n")
);
}
}
sub close_dataconn {
my ($closed)=@_; # non-zero if already disconnected
my $datapid = processexists($datasockf_pidfile);
logmsg "=====> Closing $datasockf_mode DATA connection...\n";
if(!$closed) {
if($datapid > 0) {
logmsg "Server disconnects $datasockf_mode DATA connection\n";
print DWRITE "DISC\n";
my $i;
sysread DREAD, $i, 5;
logmsg "Server disconnected $datasockf_mode DATA connection\n";
}
else {
logmsg "Server finds $datasockf_mode DATA connection already ".
"disconnected\n";
}
}
else {
logmsg "Server knows $datasockf_mode DATA connection is already ".
"disconnected\n";
}
if($datapid > 0) {
logmsg "DATA sockfilt for $datasockf_mode data channel quits ".
"(pid $datapid)\n";
print DWRITE "QUIT\n";
pidwait($datapid, 0);
unlink($datasockf_pidfile) if(-f $datasockf_pidfile);
logmsg "DATA sockfilt for $datasockf_mode data channel quit ".
"(pid $datapid)\n";
}
else {
logmsg "DATA sockfilt for $datasockf_mode data channel already ".
"dead\n";
}
logmsg "=====> Closed $datasockf_mode DATA connection\n";
datasockf_state('STOPPED');
}
################
################ SMTP commands
################
# The type of server (SMTP or ESMTP)
my $smtp_type;
# The client (which normally contains the test number)
my $smtp_client;
sub EHLO_smtp {
my ($client) = @_;
my @data;
# TODO: Get the IP address of the client connection to use in the
# EHLO response when the client doesn't specify one but for now use
# 127.0.0.1
if(!$client) {
$client = "[127.0.0.1]";
}
# Set the server type to ESMTP
$smtp_type = "ESMTP";
# Calculate the EHLO response
push @data, "$smtp_type pingpong test server Hello $client";
if((@capabilities) || (@auth_mechs)) {
my $mechs;
for my $c (@capabilities) {
push @data, $c;
}
for my $am (@auth_mechs) {
if(!$mechs) {
$mechs = "$am";
}
else {
$mechs .= " $am";
}
}
if($mechs) {
push @data, "AUTH $mechs";
}
}
# Send the EHLO response
for(my $i = 0; $i < @data; $i++) {
my $d = $data[$i];
if($i < @data - 1) {
sendcontrol "250-$d\r\n";
}
else {
sendcontrol "250 $d\r\n";
}
}
# Store the client (as it may contain the test number)
$smtp_client = $client;
return 0;
}
sub HELO_smtp {
my ($client) = @_;
# TODO: Get the IP address of the client connection to use in the HELO
# response when the client doesn't specify one but for now use 127.0.0.1
if(!$client) {
$client = "[127.0.0.1]";
}
# Set the server type to SMTP
$smtp_type = "SMTP";
# Send the HELO response
sendcontrol "250 $smtp_type pingpong test server Hello $client\r\n";
# Store the client (as it may contain the test number)
$smtp_client = $client;
return 0;
}
sub MAIL_smtp {
my ($args) = @_;
logmsg "MAIL_smtp got $args\n";
if (!$args) {
sendcontrol "501 Unrecognized parameter\r\n";
}
else {
my $from;
my $size;
my $smtputf8 = grep /^SMTPUTF8$/, @capabilities;
my @elements = split(/ /, $args);
# Get the FROM and SIZE parameters
for my $e (@elements) {
if($e =~ /^FROM:(.*)$/) {
$from = $1;
}
elsif($e =~ /^SIZE=(\d+)$/) {
$size = $1;
}
}
# this server doesn't "validate" MAIL FROM addresses
if (length($from)) {
my @found;
my $valid = 1;
# Check the capabilities for SIZE and if the specified size is
# greater than the message size then reject it
if (@found = grep /^SIZE (\d+)$/, @capabilities) {
if ($found[0] =~ /^SIZE (\d+)$/) {
if ($size > $1) {
$valid = 0;
}
}
}
if(!$valid) {
sendcontrol "552 Message size too large\r\n";
}
else {
sendcontrol "250 Sender OK\r\n";
}
}
else {
sendcontrol "501 Invalid address\r\n";
}
}
return 0;
}
sub RCPT_smtp {
my ($args) = @_;
logmsg "RCPT_smtp got $args\n";
# Get the TO parameter
if($args !~ /^TO:(.*)/) {
sendcontrol "501 Unrecognized parameter\r\n";
}
else {
my $smtputf8 = grep /^SMTPUTF8$/, @capabilities;
my $to = $1;
# Validate the to address (only a valid email address inside <> is
# allowed, such as <[email protected]>)
if ((!$smtputf8 && $to =~
/^<([a-zA-Z0-9._%+-]+)\@(([a-zA-Z0-9-]+)\.)+([a-zA-Z]{2,4})>$/) ||
($smtputf8 && $to =~
/^<([a-zA-Z0-9\x{80}-\x{ff}._%+-]+)\@(([a-zA-Z0-9\x{80}-\x{ff}-]+)\.)+([a-zA-Z]{2,4})>$/)) {
sendcontrol "250 Recipient OK\r\n";
}
else {
sendcontrol "501 Invalid address\r\n";
}
}
return 0;
}
sub DATA_smtp {
my ($args) = @_;
if ($args) {
sendcontrol "501 Unrecognized parameter\r\n";
}
elsif ($smtp_client !~ /^(\d*)$/) {
sendcontrol "501 Invalid arguments\r\n";
}
else {
sendcontrol "354 Show me the mail\r\n";
my $testno = $smtp_client;
my $filename = "log/upload.$testno";
logmsg "Store test number $testno in $filename\n";
open(FILE, ">$filename") ||
return 0; # failed to open output
my $line;
my $ulsize=0;
my $disc=0;
my $raw;
while (5 == (sysread \*SFREAD, $line, 5)) {
if($line eq "DATA\n") {
my $i;
my $eob;
sysread \*SFREAD, $i, 5;
my $size = 0;
if($i =~ /^([0-9a-fA-F]{4})\n/) {
$size = hex($1);
}
read_mainsockf(\$line, $size);
$ulsize += $size;
print FILE $line if(!$nosave);
$raw .= $line;
if($raw =~ /(?:^|\x0d\x0a)\x2e\x0d\x0a/) {
# end of data marker!
$eob = 1;
}
logmsg "> Appending $size bytes to file\n";
if($eob) {
logmsg "Found SMTP EOB marker\n";
last;
}
}
elsif($line eq "DISC\n") {
# disconnect!
$disc=1;
last;
}
else {
logmsg "No support for: $line";
last;
}
}
if($nosave) {
print FILE "$ulsize bytes would've been stored here\n";
}
close(FILE);
logmsg "received $ulsize bytes upload\n";
sendcontrol "250 OK, data received!\r\n";
}
return 0;
}
sub NOOP_smtp {
my ($args) = @_;
if($args) {
sendcontrol "501 Unrecognized parameter\r\n";
}
else {
sendcontrol "250 OK\r\n";
}
return 0;
}
sub RSET_smtp {
my ($args) = @_;
if($args) {
sendcontrol "501 Unrecognized parameter\r\n";
}
else {
sendcontrol "250 Resetting\r\n";
}