001 /* 002 * Copyright 2010 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 package com.hs.mail.smtp.server; 017 018 import java.io.IOException; 019 import java.io.PrintStream; 020 import java.net.Socket; 021 import java.util.StringTokenizer; 022 023 import com.hs.mail.container.config.Config; 024 import com.hs.mail.container.server.ConnectionHandler; 025 import com.hs.mail.container.server.socket.TcpSocketChannel; 026 import com.hs.mail.container.server.socket.TcpTransport; 027 import com.hs.mail.exception.LookupException; 028 import com.hs.mail.smtp.SmtpSession; 029 import com.hs.mail.smtp.processor.SmtpProcessor; 030 import com.hs.mail.smtp.processor.SmtpProcessorFactory; 031 032 /** 033 * 034 * @author Won Chul Doh 035 * @since May 3, 2010 036 * 037 */ 038 public class SmtpConnectionHandler implements ConnectionHandler { 039 040 private boolean debug = false; 041 042 private PrintStream out; // debug output stream 043 044 public void setDebug(boolean debug) { 045 this.debug = debug; 046 } 047 048 public synchronized void setDebugOut(PrintStream out) { 049 this.out = out; 050 } 051 052 public void handleConnection(Socket soc) throws IOException { 053 TcpTransport trans = new TcpTransport(); 054 trans.setChannel(new TcpSocketChannel(soc)); 055 SmtpSession session = new SmtpSession(trans); 056 session.setDebug(debug); 057 if (debug && out != null) { 058 session.setDebugOut(out); 059 } 060 061 String greetings = new StringBuilder() 062 .append("220 ") 063 .append(Config.getHelloName()) 064 .append(" Service ready") 065 .toString(); 066 session.writeResponse(greetings); 067 068 while (!trans.isSessionEnded()) { 069 String line = trans.readLine(); 070 if (line != null) { 071 if (debug) 072 session.getDebugOut().println(line); 073 StringTokenizer st = new StringTokenizer(line); 074 if (!st.hasMoreTokens()) { 075 break; 076 } 077 String command = st.nextToken().trim(); 078 try { 079 SmtpProcessor processor = SmtpProcessorFactory 080 .createSmtpProcessor(command); 081 processor.process(session, trans, st); 082 } catch (LookupException e) { 083 session.writeResponse("500 5.5.1 Unknown command \"" + command 084 + "\""); 085 } 086 } 087 } 088 } 089 090 }