Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.net.*;
- import java.util.regex.*;
- import java.util.*;
- public class SmtpSink
- {
- boolean finished = false;
- public static void main( String[] args )
- {
- new SmtpSink( 2000 );
- }
- SmtpSink( int port )
- {
- int count = 0;
- try
- {
- ServerSocket listener = new ServerSocket( port );
- while ( ! finished )
- {
- Socket client = listener.accept();
- new Connection( client, ++count );
- }
- }
- catch (Exception e)
- {
- }
- }
- }
- class Connection
- {
- Socket client;
- int id;
- BufferedReader in;
- PrintWriter out;
- Pattern p_DATA;
- Pattern p_QUIT;
- Connection( Socket client, int id ) throws IOException
- {
- try
- {
- p_DATA = Pattern.compile( "data", Pattern.CASE_INSENSITIVE );
- p_QUIT = Pattern.compile( "quit", Pattern.CASE_INSENSITIVE );
- }
- catch (Exception e)
- {
- System.out.println( "Error compiling pattern: " + e );
- }
- this.client = client;
- this.id = id;
- InputStream in_stream = client.getInputStream();
- InputStreamReader in_stream_reader = new InputStreamReader( in_stream );
- in = new BufferedReader( in_stream_reader );
- OutputStream out_stream = client.getOutputStream();
- OutputStreamWriter out_stream_writer = new OutputStreamWriter( out_stream );
- out = new PrintWriter( out_stream_writer, true );
- new Thread(
- new Runnable()
- {
- public void run()
- {
- handle_message();
- }
- }
- ).start();
- }
- void handle_message()
- {
- int state = 0; // 0 == processing commands
- // 1 == processing DATA
- String remote = client.getInetAddress().getHostAddress();
- Calendar now = new GregorianCalendar();
- File msgfile = new File( "msgs", "msg." + now.get(Calendar.YEAR) + "."
- + now.get(Calendar.MONTH) + "."
- + now.get(Calendar.DAY_OF_MONTH) + "-"
- + now.get(Calendar.HOUR_OF_DAY) + "."
- + now.get(Calendar.MINUTE) + "."
- + now.get(Calendar.SECOND) + "-"
- + id + "-" + remote );
- try
- {
- FileOutputStream fileout = new FileOutputStream( msgfile );
- PrintWriter file = new PrintWriter( fileout );
- String line;
- out.println( "220 hello " + remote );
- while ( (line = in.readLine()) != null )
- {
- file.println( line );
- if ( state == 0 )
- {
- Matcher m = p_QUIT.matcher( line );
- if ( m.lookingAt() )
- {
- out.println( "221 bye" );
- client.close();
- client = null;
- break;
- }
- m = p_DATA.matcher( line );
- if ( m.lookingAt() )
- {
- state = 1;
- out.println( "354 send the message" );
- }
- else
- out.println( "250 OK" );
- }
- else
- {
- if ( line.equals( "." ) )
- {
- out.println( "250 OK" );
- state = 0;
- }
- }
- }
- if ( client != null )
- client.close();
- file.close();
- }
- catch (Exception e)
- {
- System.out.println( "handle_message exception: " + e );
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment