WebMailServlet.java
上传用户:huihesys
上传日期:2007-01-04
资源大小:3877k
文件大小:12k
- /* CVS ID: $Id: WebMailServlet.java,v 1.4 2000/04/18 13:13:24 wastl Exp $ */
- package net.wastl.webmail.servlet;
- import java.net.*;
- import java.io.*;
- import java.util.*;
- import java.lang.reflect.*;
- import javax.mail.Session;
- import javax.mail.Provider;
- //import net.wastl.webmail.debug.LogFile;
- import net.wastl.webmail.server.http.*;
- import net.wastl.webmail.server.*;
- import net.wastl.webmail.ui.*;
- import net.wastl.webmail.ui.html.*;
- import javax.servlet.*;
- import javax.servlet.http.*;
- /*
- * WebMailServer.java
- *
- * Created: Oct 1999
- *
- * Copyright (C) 1999-2000 Sebastian Schaffert
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
- */
- /**
- * This is WebMails main server. From here most parts will be administered.
- * This is the servlet implementation of WebMail (introduced in 0.6.1)
- *
- * Created: Tue Feb 2 12:07:25 1999
- *
- * @author Sebastian Schaffert
- * @version $Revision: 1.4 $
- */
- public class WebMailServlet extends net.wastl.webmail.server.WebMailServer implements Servlet {
-
- ServletConfig srvlt_config;
-
- /** Size of the chunks that are sent. Must not be greater than 65536 */
- private static final int chunk_size=8192;
-
- protected String basepath;
- protected String imgbase;
-
- public WebMailServlet() {
- }
-
- public void init(ServletConfig config) throws ServletException {
- System.err.println("Init");
- srvlt_config=config;
- this.config=new Properties();
- Enumeration enum=config.getInitParameterNames();
- while(enum.hasMoreElements()) {
- String s=(String)enum.nextElement();
- this.config.put(s,config.getInitParameter(s));
- System.err.println(s+": "+config.getInitParameter(s));
- }
- try {
- doInit();
- } catch(Exception e) {
- e.printStackTrace();
- throw new ServletException("Could not intialize.");
- }
- if(config.getInitParameter("webmail.basepath")==null) {
- config.getServletContext().log("Warning: webmail.basepath initArg should be set to the WebMail Servlet's base path");
- basepath="";
- } else {
- basepath = config.getInitParameter("webmail.basepath");
- }
- if(config.getInitParameter("webmail.imagebase") == null) {
- config.getServletContext().log("Error: webmail.basepath initArg should be set to the WebMail Servlet's base path");
- imgbase="";
- } else {
- imgbase = config.getInitParameter("webmail.imagebase");
- }
- }
-
- public ServletConfig getServletConfig() {
- return srvlt_config;
- }
-
- public String getServletInfo() {
- return getVersion()+"n(c)2000 by Sebastian SchaffertnThis software is distributed under the GNU Lesser General Public License";
- }
-
- public void destroy() {
- shutdown();
- }
-
- public void service(ServletRequest req1, ServletResponse res1) throws ServletException {
- HttpServletRequest req=(HttpServletRequest)req1;
- HttpServletResponse res=(HttpServletResponse)res1;
-
- HTTPRequestHeader http_header=new HTTPRequestHeader();
- // Unfortunately, the servlet engine doesn't support multipart/form-data.
- // Our HTTPRequestHeader does, however.:-)
- // Enumeration test=req.getParameterNames();
- // while(test.hasMoreElements()) {
- // String param=(String)test.nextElement();
- // http_header.setContent(param,req.getParameter(param));
- // System.err.println("Content "+param+"="+req.getParameter(param));
- // }
-
- Enumeration en=req.getHeaderNames();
- while(en.hasMoreElements()) {
- String s=(String)en.nextElement();
- http_header.setHeader(s,req.getHeader(s));
- }
-
- if(req.getPathInfo()!=null) {
- http_header.setPath(req.getPathInfo());
- } else {
- http_header.setPath("/");
- }
- InetAddress addr;
- try {
- addr=InetAddress.getByName(req.getRemoteHost());
- } catch(UnknownHostException e) {
- try {
- addr=InetAddress.getByName(req.getRemoteAddr());
- } catch(Exception ex) {
- throw new ServletException("Remote host must identify!");
- }
- }
-
-
- HTMLDocument content=null;
- int err_code=400;
- HTTPSession sess=null;
-
- try {
- BufferedReader in=new BufferedReader(req.getReader());
-
- PrintWriter out=new PrintWriter(res.getOutputStream());
-
- StringBuffer str=new StringBuffer();
- int total=0;
- try {
- char[] buf=new char[8192];
- int read=1;
- int cl=req.getContentLength();
- while(in.ready() && read > 0 && (cl==-1 ||total < cl)) {
- read=in.read(buf,0,8192);
- if(read > 0) {
- total+=read;
- str.append(buf,0,read);
- }
- }
- } catch(Exception ex) {
- ex.printStackTrace();
- }
-
- if(total > 0) {
- http_header.setEncodedContent(str.toString(),req.getContentType());
- }
- if(req.getQueryString() != null) {
- http_header.setEncodedContent(req.getQueryString(),"application/x-www-form-urlencoded");
- }
- try {
- String url=http_header.getPath();
-
-
- try {
- /* Find out about the session id */
- sess=req.getSession(false)==null?null:(HTTPSession)req.getSession(false).getValue("webmail.session");
- if(sess == null && url.startsWith("/login")) {
- sess=newSession(req,http_header);
- } else if(sess == null && url.startsWith("/admin/login")) {
- http_header.setHeader("LOGIN","Administrator");
- sess=newAdminSession(req,http_header);
- }
- if(sess != null) sess.setEnv();
- /* Let the URLHandler determine the document to use */
- content=getURLHandler().handleURL(url,sess,http_header);
-
-
- } catch(InvalidPasswordException e) {
- getStorage().log(Storage.LOG_ERR,"Connection to "+addr.toString()+
- ": Authentication failed!");
- if(url.startsWith("/admin/login")) {
- content=getURLHandler().handleURL("/admin",null,http_header);
- } else if(url.startsWith("/login")) {
- // content=new HTMLLoginScreen(this,getStorage(),true);
- content=getURLHandler().handleURL("/",null,http_header);
- } else {
- content=new HTMLErrorMessage(getStorage(),e.getMessage());
- }
- } catch(InvalidDataException ex) {
- content=new HTMLErrorMessage(getStorage(),ex.getMessage());
- }
-
- res.setDateHeader("Date:",System.currentTimeMillis());
- res.setDateHeader("Expires",System.currentTimeMillis()+300000);
- res.setHeader("Pragma","no-cache");
- res.setHeader("Cache-Control","must-revalidate");
-
-
- synchronized(out) {
- //r=new HTTPResponseHeader(content.getReturnCode(),content.getReturnStatus());
- res.setStatus(content.getReturnCode());
-
- if(content.hasHTTPHeader()) {
- Enumeration enum=content.getHTTPHeaderKeys();
- while(enum.hasMoreElements()) {
- String s=(String)enum.nextElement();
- //r.putHeader(s,content.getHTTPHeader(s));
- res.setHeader(s,content.getHTTPHeader(s));
- }
- }
-
- if(content instanceof HTMLImage) {
- HTMLImage img=(HTMLImage)content;
- res.setHeader("Content-Type",img.getContentType());
- res.setHeader("Content-Transfer-Encoding",img.getContentEncoding());
- res.setHeader("Content-Length",""+img.size());
- res.setHeader("Connection","Keep-Alive");
-
- BufferedOutputStream iout=new BufferedOutputStream(res.getOutputStream());
-
- /* Send 8k junks */
- int offset=0;
- while(offset + chunk_size < img.size()) {
- iout.write(img.toBinary(),offset,chunk_size);
- offset+=chunk_size;
- }
- iout.write(img.toBinary(),offset,img.size()-offset);
- iout.flush();
-
- out.flush();
- res.getOutputStream().close();
- } else {
- res.setHeader("Content-Length",""+(content.length()+11));
- res.setHeader("Connection","Keep-Alive");
- res.setHeader("Content-Type","text/html");
-
- out.print(content+"rn");
- out.print("</HTML>rn");
- out.flush();
- out.close();
- }
- }
- } catch(DocumentNotFoundException e) {
- getStorage().log(Storage.LOG_INFO,"Connection to "+addr.toString()+
- ": Could not handle request ("+err_code+") (Reason: "+e.getMessage()+")");
- res.setStatus(err_code);
- res.setHeader("Content-type","text/html");
- res.setHeader("Connection","close");
-
- content=new HTMLErrorMessage(getStorage(),e.getMessage());
- out.print(content+"rn");
- out.print("</HTML>rn");
- out.flush();
- out.close();
- }
- } catch(Exception e) {
- e.printStackTrace();
- getStorage().log(Storage.LOG_INFO,"Connection to "+addr.toString()+" closed");
- throw new ServletException("Error: "+e.getMessage());
- }
- }
-
- /**
- * Init possible servers of this main class
- */
- protected void initServers() {
- }
-
- protected void shutdownServers() {
- }
-
- public String getBasePath() {
- return basepath;
- }
- public String getImageBasePath() {
- return imgbase;
- }
-
- public WebMailSession newSession(HttpServletRequest req, HTTPRequestHeader h) throws InvalidPasswordException {
- HttpSession sess=req.getSession(true);
-
- if(sess.getValue("webmail.session") == null) {
- WebMailSession n=new WebMailSession(this,req,h);
- timer.addTimeableConnection(n);
- n.login(h);
- sess.putValue("webmail.session",n);
- sessions.put(sess.getId(),n);
- System.err.println("Created new Session: "+sess.getId());
- return n;
- } else {
- Object tmp=sess.getValue("webmail.session");
- if(tmp instanceof WebMailSession) {
- WebMailSession n=(WebMailSession)tmp;
- n.login(h);
- System.err.println("Using old Session: "+sess.getId());
- return n;
- } else {
- sess.putValue("webmail.session",null);
- System.err.println("Reusing old AdminSession: "+sess.getId());
- return newSession(req,h);
- }
- }
- }
-
- public AdminSession newAdminSession(HttpServletRequest req, HTTPRequestHeader h) throws InvalidPasswordException {
- HttpSession sess=req.getSession(true);
-
- if(sess.getValue("webmail.session") == null) {
- AdminSession n=new AdminSession(this,req,h);
- timer.addTimeableConnection(n);
- n.login(h);
- sess.putValue("webmail.session",n);
- sessions.put(sess.getId(),n);
- System.err.println("Created new Session: "+sess.getId());
- return n;
- } else {
- Object tmp=sess.getValue("webmail.session");
- if(tmp instanceof AdminSession) {
- AdminSession n=(AdminSession)tmp;
- n.login(h);
- System.err.println("Using old Session: "+sess.getId());
- return n;
- } else {
- sess.putValue("webmail.session",null);
- System.err.println("Reusing old UserSession: "+sess.getId());
- return newAdminSession(req,h);
- }
- }
- }
-
-
- public WebMailSession newSession(InetAddress a,HTTPRequestHeader h) throws InvalidPasswordException {
- System.err.println("newSession invalid call");
- return null;
- }
-
- public AdminSession newAdminSession(InetAddress a,HTTPRequestHeader h) throws InvalidPasswordException {
- System.err.println("newAdminSession invalid call");
- return null;
- }
-
-
- public HTTPSession getSession(String sessionid, InetAddress a,HTTPRequestHeader h) throws InvalidPasswordException {
- System.err.println("getSession invalid call");
- return null;
- }
-
- public Enumeration getServers() {
- return new Enumeration() {
- public boolean hasMoreElements() {
- return false;
- }
- public Object nextElement() {
- return null;
- }
- };
- }
-
- public String toString() {
- String s="";
- s+="Server: "+srvlt_config.getServletContext().getServerInfo()+"n";
- s+="Mount Point: "+getBasePath()+"n";
- s+=getServletInfo();
- return s;
- }
-
- public Object getServer(String ID) {
- return null;
- }
-
- public void reinitServer(String ID) {
- }
-
- public static String getVersion() {
- return "WebMail/Java Servlet v"+VERSION;
- }
-
- } // WebMailServer