Debian Codegraph @

t/server

raw
1 #!/usr/bin/env perl
2 =head1 NAME
3
4 t/server/start - simple POP3 server for testing Mail::Transport::POP3
5
6 =head1 SYNOPSIS
7
8 open( $pop3,"$^X t/server/start t/messages | " );
9
10 open( $pop3,"$^X t/server/start t/messages minimal | " );
11
12 open( $pop3,"$^X t/server/start t/messages apoponly | " );
13
14 open( $pop3,"$^X t/server/start t/messages autodelete | " );
15
16 open( $pop3,"$^X t/server/start t/messages noextra | " );
17
18 open( $pop3,"$^X t/server/start t/messages standardport | " );
19
20 =head1 DESCRIPTION
21
22 This POP3 server is created for testing the Mail::Transport::POP3 only. It
23 B<cannot be used> as real POP3 server (yet).
24
25 The server takes on a randomly selected, free port to prevent interference
26 with existing applications. Start the server by running this script from
27 another script while capturing the output to STDOUT, e.g. like:
28
29 open( my $pop3,"$^X t/server/start t/messages |" )
30 or die "Could not start POP3 server: $!\n";
31 my $port = <$pop3>;
32
33 The returned $pop3 file handle produces informational texts: it will tell
34 you the port which is occupied by the server, and when the server shuts down.
35 It will also report some statistics on the performance of the server.
36
37 The server will be bound to localhost (127.0.0.1) at the port number of the
38 first line that is printed to STDOUT by this script.
39
40 The first parameter to the script indicates the directory in which the actual
41 messages (each message as a seperate file) are located. In the example, this
42 is "t/messages".
43
44 Any other parameters to the script are optional: they consist of keywords to
45 indicate any settings or peculiarities of certain POP3 server implementations.
46 The following keywords are recognised:
47
48 =over 2
49
50 =item minimal
51
52 If the keyword "minimal" is specified, only the minimal set of POP3 commands
53 will be allowed (i.e. USER, PASS, STAT, LIST, RETR, DELE, RSET, NOOP and QUIT).
54 The optional POP3 commands (APOP, TOP and UIDL) are also supported if this
55 keyword is B<not> specified.
56
57 =item apoponly
58
59 If the keyword "apoponly" is specified, then authorization will only be
60 allowed with the APOP command (i.e. authorization with USER will yield a
61 negative response). Please note that you cannot use this together with the
62 "minimal" keyword, as APOP is one of the optional POP3 commands (which is
63 excluded if you use the "minimal" keyword).
64
65 =item autodelete
66
67 If the keyword "autodelete" is specified, any messages that are completely
68 retrieved with RETR or TOP (without specification of number of lines in the
69 body to return) will be automatically marked for deletion. This will cause
70 those messages to be deleted if the session is finished with a QUIT command.
71 This coincides with system resource restrictions imposed by some providers.
72
73 =item noextra
74
75 If the keyword "noextra" is specified, then all messages will be served with
76 a check for a CRLF pair at the end of the original messasge: if a CRLF is
77 found, then only ".\r\n" will be added to indicate the end of a message that
78 are retrieved with RETR or TOP.
79
80 =item standardport
81
82 If the keyword "standardport" is specified, then an attempt will be made to
83 start the POP3 server on port 110, the standard POP3 port. Please note that
84 this will only be successful if the current user has sufficient privileges
85 (usually only the root user will be allowed to listen on ports < 1024).
86
87 =back
88
89 User name is always "user" and the correct password is always "password".
90 Any other combination will always fail. APOP authorization can be used if
91 the "minimal" keyword is B<not> specified. The following script will help
92 you in debugging APOP authorization:
93
94 use Digest::MD5 qw(md5_hex);
95 while (<>) {
96 s#\r?\n?$##s;
97 print md5_hex( $_.'password' )."\n";
98 }
99
100 Copy the string that was sent by the initial greeting of the server (including
101 the <> brackets), paste this into the running script, press ENTER. The script
102 will respond with a 32 character hexadecimal string. Copy that and the enter
103 the authorization thus:
104
105 APOP user 0123456789abcdef0123456789abcdef
106
107 Note that the above hex string is only an example of course.
108
109 The following commands do B<not> exist in the POP3 protocol, but are intended
110 to simulate certain events.
111
112 The BREAK command can be used to simulate the breaking of a connection.
113 After a BREAK is received, the connection is broken by the server (without
114 sending a response to the client). No messages will be deleted even if any
115 messages were marked for deletion. This can also be used to simulate a
116 timeout, of course.
117
118 The EXIT command can be used for test-suites: when sent from the client, it
119 will cause the server to shut down (as if an EXIT was sent) whenever the
120 client does a QUIT command. When the servers shuts down, its prints its
121 statistics on STDOUT. Statistics returned are:
122
123 - number of succesful logins
124 - each command + frequency in alphabetical order
125
126 so a statistics list for one successful session could be:
127
128 1
129 DELE 102
130 EXIT 1
131 LIST 1
132 PASS 1
133 QUIT 1
134 RETR 102
135 STAT 1
136 UIDL 1
137 USER 1
138
139 =cut
140
141 # Make sure we do everything by the book
142 # Make sure we can do sockets
143 # Make sure we can do digests
144
145 use strict;
146 use IO::Socket;
147 use IO::Socket::IP;
148 use Digest::MD5 qw(md5_hex);
149
150 # Obtain the directory to work on
151 # Remove trailing slash if any
152 # Die now if there is no directory
153 # Die now if we can't work with it
154
155 my $directory = shift;
156 $directory =~ s#/$##;
157 die qq(Must specify directory to work with\n) unless $directory;
158 die qq(Trouble using directory "$directory": $!\n)
159 unless -d $directory and -w _;
160
161 # Initialize the flag settings
162
163 my $minimal = 0;
164 my $apoponly = 0;
165 my $autodelete = 0;
166 my $noextra = 0;
167 my $exitonquit = 0;
168 my $exitnow = 0;
169 my @port;
170
171 # While there are keywords specified
172 # Set appropriate flags if so specified
173
174 while (my $keyword = shift) {
175 $minimal = ($keyword eq 'minimal');
176 $apoponly = ($keyword eq 'apoponly');
177 $autodelete = ($keyword eq 'autodelete');
178 $noextra = ($keyword eq 'noextra');
179 @port = qw(LocalPort 110) if $keyword eq 'standardport';
180 }
181
182 # Make sure no buffering takes place
183 # Create a server that can only take one connection at a time
184
185 $| = 1;
186 my $server = IO::Socket::IP->new(
187 Type => SOCK_STREAM,
188 Listen => 1,
189 @port,
190 ) or die "Couldn't start a POP3 server:\n $@\n";
191
192 # Find out the port we're running on
193 # Let the caller know which port we're running on
194
195 my $port = $server->sockport;
196 print "$port\n";
197
198 # Initialize the connected flag
199 # Initialize the list of available messages
200 # Initialize the hash of message ordinal numbers to delete
201 # Initialize the hash of message ordinal numbers to delete automatically
202
203 my $connected = 0;
204 my @message;
205 my %delete;
206 my %autodelete;
207
208 # Initialize user
209 # Initialize digest password field (used by APOP only)
210 # Initialize the line ending on output
211
212 my $user = '';
213 my $digest;
214 my $lf = "\x0D\x0A"; # always CRLF
215
216 # Number of successful logins performed
217 # Hash with frequency of each command
218
219 my $logins = 0;
220 my %command;
221
222 # While the server is running and we got a new client
223 # Initialize the APOP initialization string
224 # If this is a minimal POP3 server
225 # Don't make it appear we can do POP3
226 # Else
227 # Create the APOP authentication string
228 # Let the client know we're there and we can do APOP
229
230 SERVER: while (my $client = $server->accept()) {
231 my $apop = '';
232 if ($minimal) {
233 print $client qq(+OK Welcome to the test-suite POP3 server$lf);
234 } else {
235 $apop = "<$$.".time().'@localhost>';
236 print $client qq(+OK $apop$lf);
237 }
238
239 # Obtain list of files in message directory
240 # Reset the messages to be (automatically) deleted hashes
241
242 @message = <$directory/*>;
243 %autodelete = %delete = ();
244
245 # While the client is asking us stuff to do
246 # Lose the line ending (whatever it is)
247 # Split into a command and parameters
248 # Make sure the command is always uppercase (easier checks later)
249 # Make sure the parameters are defined (if empty)
250
251 while (<$client>) {
252 s#\r?\n$##s;
253 my ($command,$parameters) = split( /\s+/,$_,2 );
254 $command = uc($command);
255 $parameters = '' unless defined($parameters);
256
257 # Count this command for the statistics
258 # Outloop if quitting this client
259
260 $command{$command}++;
261 last if $command eq 'BREAK';
262
263 # If we're connected
264 # Allow for variable references
265 # If there is a subroutine for this command
266 # Execute it with the given parameters and return result
267 # Send result to client if there is something to connect
268 # Stop server is so requested
269 # Outloop if we're no longer connected
270 # Else
271 # Indicate it's not implemented
272
273 if ($connected) {
274 no strict 'refs';
275 if (exists( &$command )) {
276 my @return = &{$command}( split( /\s+/,$parameters ) );
277 print $client @return if @return;
278 last SERVER if $exitnow;
279 last unless $connected;
280 } else {
281 print $client "-ERR unimplemented$lf";
282 }
283
284 # Elseif we're quitting without a connection
285 # Show that we agree
286 # And outloop
287
288 } elsif ($command eq 'QUIT') {
289 print $client "+OK$lf";
290 last;
291
292 # Elseif we're trying APOP authentication
293 # If we have a minimal POP3 server
294 # Show that this isn't implemented
295 # And reloop
296
297 } elsif ($command eq 'APOP') {
298 if ($minimal) {
299 print $client "-ERR unimplemented$lf";
300 next;
301 }
302
303 # Obtain the user name and the digest
304 # Log the user in if client gives the right credentials
305 # Send the result to the client
306
307 ($user,$digest) = split( /\s+/,$parameters );
308 my @return = login(
309 $user eq 'user' and
310 $digest eq md5_hex( $apop.'password')
311 );
312 print $client @return;
313
314 # Elseif we have a user name (and we're not connected yet)
315 # Log the user in if client gives the right credentials now and before
316 # Send the result to the client
317
318 } elsif ($user) {
319 my @return = login(
320 $command eq 'PASS' and
321 $user eq 'user' and
322 $parameters eq 'password'
323 );
324 print $client @return;
325
326 # Elseif the user name is passed (and none given before)
327 # If we only allow APOP
328 # Let the client know it's not ok
329 # Else
330 # Save the user name (for later checking with PASS)
331 # Let the client know it's ok so far
332
333 } elsif ($command eq 'USER') {
334 if ($apoponly) {
335 print $client "-ERR APOP authorization allowed only$lf";
336 } else {
337 $user = $parameters;
338 print $client "+OK$lf";
339 }
340
341 # Elseif the password is given (but no user name before)
342 # Let the client know it's wrong
343 # Else (attempting to do anything else without authorization)
344 # Let the client know it's wrong
345
346 } elsif ($command eq 'PASS') {
347 print $client "-ERR user first$lf";
348 } else {
349 print $client "-ERR authorization first$lf";
350 }
351 }
352
353 # Reset user name
354 # Reset connected flag
355 # Shut down the client connection
356
357 $user = '';
358 $connected = 0;
359 close( $client );
360 }
361
362 # Show number of successful logins
363 # For all the commands that were issued
364 # Return name and frequency of it
365 # And shut down the server
366
367 print "$logins\n";
368 foreach (sort keys %command) {
369 print "$_ $command{$_}\n";
370 }
371 close($server);
372
373 #------------------------------------------------------------------------
374 # OUT: 1 whatever needs to be sent to client
375
376 sub STAT {
377
378 # Initialize number of messages
379 # Initialize number of bytes they have
380 # Initialize ordinal number
381
382 my $messages = 0;
383 my $octets = 0;
384 my $ordinal = 0;
385
386 # For all of the messages
387 # Reloop if message marked as delete, incrementing ordina on the fly
388 # Increment number of messages
389 # Add number of bytes
390 # Return the result
391
392 foreach (@message) {
393 next if exists( $delete{$ordinal++} );
394 $messages++;
395 $octets += -s;
396 }
397 return "+OK $messages $octets$lf";
398 } #STAT
399
400 #------------------------------------------------------------------------
401 # OUT: 1 whatever needs to be sent to client
402
403 sub UIDL {
404
405 # Return now if running a minimal POP3 server
406
407 return "-ERR unimplemented$lf" if $minimal;
408
409 # Initialize message number
410 # If a number was specified
411 # Obtain ordinal number and possible error message
412 # Return error message if there is one
413 # Return the message number and the identifier of the message otherwise
414
415 my $number = shift;
416 if (defined($number)) {
417 my ($ordinal,$error) = ordinal( $number,1 );
418 return $error if $error;
419 return "+OK $number $message[$ordinal]$lf";
420 }
421
422 # Initialize ordinal number
423 # Initialize text to be returned
424 # For all of the messages
425 # Reloop if message marked as deleted, incrementing ordinal on the fly
426 # Add the ordinal number and the identifier (just use filename for that)
427 # Return the result with an extra . at the end to indicate end of list
428
429 my $ordinal = 0;
430 my $text = "+OK$lf";
431 foreach (@message) {
432 next if exists( $delete{$ordinal++} );
433 $text .= "$ordinal $_$lf"; # external numbers 1-based, internal 0-based
434 }
435 return "$text.$lf";
436 } #UIDL
437
438 #------------------------------------------------------------------------
439 # IN: 1 message to obtain (optionally)
440 # OUT: 1 whatever needs to be sent to client
441
442 sub LIST {
443
444 # Initialize message number
445 # If a number was specified
446 # Obtain ordinal number and possible error message
447 # Return error message if there is one
448 # Return the message number and size of message otherwise
449
450 my $number = shift;
451 if (defined($number)) {
452 my ($ordinal,$error) = ordinal( $number,1 );
453 return $error if $error;
454 return "+OK $number ".(-s $message[$ordinal]).$lf;
455 }
456
457 # Initialize ordinal number
458 # Initialize text to be returned
459 # For all of the messages
460 # Reloop if message marked as deleted, incrementing ordinal on the fly
461 # Add the ordinal number and the identifier (just use filename for that)
462 # Return the result with an extra . at the end to indicate end of list
463
464 my $ordinal = 0;
465 my $text = "+OK$lf";
466 foreach (@message) {
467 next if exists( $delete{$ordinal++} );
468 $text .= "$ordinal ".(-s).$lf; # external numbers 1-based, internal 0-based
469 }
470 return "$text.$lf";
471 } #LIST
472
473 #------------------------------------------------------------------------
474 # IN: 1 ordinal number of message to retrieve
475 # OUT: 1 whatever needs to be sent to client
476
477 sub RETR {
478
479 # Obtain ordinal number and possible error message
480 # Return now if there was an error message
481
482 my ($ordinal,$error) = ordinal( shift,1 );
483 return $error if $error;
484
485 # Open file for reading or return with empty message
486 # Initialize text to be returned
487 # While there are lines to be returned
488 # Make sure any period at the start of the line becomes a double period
489 # Add the line to the text to be returned
490
491 open( my $handle,'<',$message[$ordinal] ) or return "+OK$lf.$lf";
492 my $text = "+OK$lf";
493 while (<$handle>) {
494 s#^\.#..#;
495 $text .= $_;
496 }
497
498 # Mark this message to be deleted automatically if flag set
499 # Add the right marker to the text
500 # Return the finished text
501
502 $autodelete{$ordinal} = undef if $autodelete;
503 addmarker( \$text );
504 $text;
505 } #RETR
506
507 #------------------------------------------------------------------------
508 # IN: 1 ordinal number of message to retrieve
509 # 2 number of lines of the message to retrieve
510 # OUT: 1 whatever needs to be sent to client
511
512 sub TOP {
513
514 # Return now if running a minimal POP3 server
515 # Obtain ordinal number and possible error message
516 # Return now if there was an error message
517
518 return "-ERR unimplemented$lf" if $minimal;
519 my ($ordinal,$error) = ordinal( shift,1 );
520 return $error if $error;
521
522 # Open file for reading or return with empty message
523 # Initialize text to be returned
524
525 open( my $handle,'<',$message[$ordinal] ) or return "+OK$lf.$lf";
526 my $text = "+OK$lf";
527
528 # Obtain the number of lines
529 # If a number of lines was specified
530 # While there are lines to be returned
531 # Make sure any period at the start of the line becomes a double period
532 # Add the line to the text to be returned
533 # Outloop if we're reached the end of the headers
534
535 my $lines = shift;
536 if (defined($lines)) {
537 while (<$handle>) {
538 s#^\.#..#;
539 $text .= $_;
540 last if m#^\s+$#s;
541 }
542
543 # While there are lines to be fetched
544 # Outloop if no line left to be fetched
545 # Make sure any period at the start of the line becomes a double period
546 # Add the line to the text to be returned
547
548 while ($lines--) {
549 last unless defined($_ = <$handle>);
550 s#^\.#..#;
551 $text .= $_;
552 }
553
554 # Else (no limit)
555 # While there are lines to be returned
556 # Make sure any period at the start of the line becomes a double period
557 # Add the line to the text to be returned
558 # Mark this message to be deleted automatically if flag set
559
560 } else {
561 while (<$handle>) {
562 s#^\.#..#;
563 $text .= $_;
564 }
565 $autodelete{$ordinal} = undef if $autodelete;
566 }
567
568 # Add the right marker to the text
569 # Return the result with an extra . at the end to indicate end of list
570
571 addmarker( \$text );
572 $text;
573 } #TOP
574
575 #------------------------------------------------------------------------
576 # IN: 1 ordinal number of message to delete
577 # OUT: 1 whatever needs to be sent to client
578
579 sub DELE {
580
581 # Obtain ordinal number and possible error message
582 # Return now if there was an error message
583 # Mark this message as deletable
584 # Return the result with an extra . at the end to indicate end of list
585
586 my ($ordinal,$error) = ordinal( shift,1 );
587 return $error if $error;
588 $delete{$ordinal} = undef;
589 return "+OK$lf";
590 } #DELE
591
592 #------------------------------------------------------------------------
593 # IN: 1 ordinal number of message to undelete
594 # OUT: 1 whatever needs to be sent to client
595
596 sub RSET {
597
598 # Obtain ordinal number and possible error message
599 # Return now if there was an error message
600 # Unmark this message as deletable
601 # Return the result with an extra . at the end to indicate end of list
602
603 my ($ordinal,$error) = ordinal( shift );
604 return $error if $error;
605 delete( $delete{$ordinal} );
606 return "+OK$lf";
607 } #RSET
608
609 #------------------------------------------------------------------------
610 # OUT: 1 whatever needs to be sent to client
611
612 sub NOOP { "+OK$lf" } #NOOP
613
614 #------------------------------------------------------------------------
615
616 sub EXIT { $exitonquit = 1; return } #EXIT
617
618 #------------------------------------------------------------------------
619 # OUT: 1 whatever needs to be sent to client
620
621 sub QUIT {
622
623 # Remove all of the files that were supposed to be deleted
624 # Remove all of the files that were supposed to be deleted automatically
625 # Set exit now flag if QUIT is to operate as EXIT
626 # Mark the connection as ended
627 # Let the client now it was fun while it lasted
628
629 unlink( map {$message[$_]} keys %delete );
630 unlink( map {$message[$_]} keys %autodelete );
631 $exitnow = $exitonquit;
632 $connected = 0;
633 return "+OK$lf";
634 } #QUIT
635
636 #------------------------------------------------------------------------
637 # IN: 1 flag whether login successful
638 # OUT: 1 what needs to be returned to the client
639
640 sub login {
641
642 # If successful
643 # Increment number of successful logins
644 # Set connected flag
645 # Let the client know it's ok
646
647 if (shift) {
648 $logins++;
649 $connected = 1;
650 return "+OK$lf";
651 }
652
653 # Reset the user that was entered before
654 # Let the client know authorization has failed
655
656 $user = '';
657 return "-ERR authorization failed$lf";
658 } #login
659
660 #------------------------------------------------------------------------
661 # IN: 1 ordinal number of message
662 # 2 flag: check whether message deleted already
663 # OUT: 1 normalize message number
664 # 2 error message (if any)
665
666 sub ordinal {
667
668 # Obtain the message number
669 # Initialize error message
670 # Set error if too low
671 # Set error if zero
672 # Set error if too high
673
674 my $ordinal = shift;
675 my $error = '';
676 $error ||= "-ERR syntax error$lf" if $ordinal < 0;
677 $error ||= "-ERR messages are counted from 1$lf" if $ordinal == 0;
678 $error ||= "-ERR not that many messages$lf" if $ordinal > @message;
679
680 # Normalize for arrays
681 # Set error if checking for deletion and already deleted
682 # Return the result
683
684 $ordinal--;
685 $error ||= "-ERR already deleted$lf" if shift and exists( $delete{$ordinal} );
686 return ($ordinal,$error);
687 } #ordinal
688
689 #------------------------------------------------------------------------
690 # IN: 1 reference to text (to add the right end-of-data marker to)
691
692 sub addmarker {
693
694 # Obtain the reference to the text
695 # If we should check for extra newlines at the end
696 # Add the right stuff depending on the end of the text so far
697 # Else
698 # Add it as most POP3 servers do
699
700 my $textref = shift;
701 if ($noextra) {
702 $$textref .= ($$textref =~ m#\r\n$#so ? ".$lf" : "$lf.$lf");
703 } else {
704 $$textref .= "$lf.$lf";
705 }
706 }