WebMailServer.java
上传用户:huihesys
上传日期:2007-01-04
资源大小:3877k
文件大小:13k
- /* CVS ID: $Id: WebMailServer.java,v 1.4 2000/04/18 13:12:47 wastl Exp $ */
- package net.wastl.webmail.server;
- 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.standalone.*;
- import net.wastl.webmail.debug.ErrorHandler;
- import net.wastl.webmail.server.http.*;
- import net.wastl.webmail.ui.ContentBar;
- import net.wastl.webmail.config.ConfigScheme;
- import net.wastl.webmail.misc.Helper;
- /*
- * WebMailServer.java
- *
- * Created: Tue Feb 2 12:07:25 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.
- *
- * @author Sebastian Schaffert
- * @version $Revision: 1.4 $
- */
- public abstract class WebMailServer {
-
- protected ConnectionTimer timer;
- protected AuthenticatorHandler ahandler;
- protected PluginHandler phandler;
- protected ToplevelURLHandler uhandler;
- protected ContentBar contentbar;
- protected Hashtable sessions;
- protected static boolean debug=false;
- // private LogFile logfile;
- public static final String VERSION="0.7.0";
- protected static Provider[] possible_providers;
- protected static Provider[] store_providers;
- protected static Provider[] transport_providers;
- private long start_time;
- protected static Storage storage;
- protected ConfigScheme config_scheme;
- protected static WebMailServer server;
- protected Properties config;
- public WebMailServer() {
- }
- public static boolean getDebug() {
- return debug;
- }
- public static void setDebug(boolean b) {
- debug=b;
- }
-
- protected void doInit() throws WebMailException {
- server=this;
- System.err.println("nnWebMail/Java Server v"+VERSION+" going up...");
- System.err.println("=====================================n");
- System.err.println("Initalizing...");
- new SystemCheck(this);
-
- initConfig();
- ahandler=new AuthenticatorHandler(this);
-
- System.err.println("- Storage API ("+System.getProperty("webmail.storage")+
- ") and Configuration ... ");
- initStorage();
- timer=new ConnectionTimer();
- sessions=new Hashtable();
- System.err.println(" done!");
- uhandler=new ToplevelURLHandler(this);
- phandler=new PluginHandler(this);
- initProviders();
- initServers();
- storage.initConfigKeys();
- storage.log(Storage.LOG_CRIT,"=============================== cut ===============================");
- storage.log(Storage.LOG_CRIT,"WebMail/Java Server "+VERSION+" initialization completed.");
- System.err.println("Initalization complete.");
- start_time=System.currentTimeMillis();
- }
- protected void initStorage() {
- /* Storage API */
- try {
- Class storage_api=Class.forName(config.getProperty("webmail.storage"));
- Class[] tmp=new Class[1];
- tmp[0]=Class.forName("net.wastl.webmail.server.WebMailServer");
- Constructor cons=storage_api.getConstructor(tmp);
- Object[] sargs=new Object[1];
- sargs[0]=this;
- storage=(Storage)cons.newInstance(sargs);
- } catch(InvocationTargetException e) {
- Throwable t=e.getTargetException();
- System.err.println("Nested exception: ");
- t.printStackTrace();
- System.err.println("Fatal error. Could not initialize. Exiting now!");
- System.exit(1);
- } catch(Exception e) {
- e.printStackTrace();
- System.err.println("Fatal error. Could not initialize. Exiting now!");
- System.exit(1);
- }
- }
- protected void initConfig() {
- config_scheme=new ConfigScheme();
- config_scheme.configRegisterIntegerKey("SESSION TIMEOUT","3600000",
- "Timeout in milliseconds after which a WebMailSession is closed automatically.");
- config_scheme.configRegisterCryptedStringKey("ADMIN PASSWORD","Secret",
- "Password for administrator connections. Shown encrypted, but enter"+
- " plain password to change.");
- }
- protected void initProviders() {
- possible_providers=Session.getDefaultInstance(System.getProperties(),null).getProviders();
- System.err.println("- Mail providers:");
- config_scheme.configRegisterChoiceKey("DEFAULT PROTOCOL","Protocol to be used as default");
- config_scheme.getConfigParameter("DEFAULT PROTOCOL").setDefault("imap");
- int p_transport=0;
- int p_store=0;
- for(int i=0; i<possible_providers.length;i++) {
- System.err.println(" * "+possible_providers[i].getProtocol()+" from "+possible_providers[i].getVendor());
- if(possible_providers[i].getType() == Provider.Type.STORE) {
- p_store++;
- config_scheme.configAddChoice("DEFAULT PROTOCOL",possible_providers[i].getProtocol(),"Use "+
- possible_providers[i].getProtocol()+" from "+possible_providers[i].getVendor());
- config_scheme.configRegisterYesNoKey("ENABLE "+possible_providers[i].getProtocol().toUpperCase(),"Enable "+
- possible_providers[i].getProtocol()+" from "+possible_providers[i].getVendor());
- } else {
- p_transport++;
- }
- }
- store_providers=new Provider[p_store];
- transport_providers=new Provider[p_transport];
- p_store=0;
- p_transport=0;
- for(int i=0; i<possible_providers.length;i++) {
- if(possible_providers[i].getType() == Provider.Type.STORE) {
- store_providers[p_store]=possible_providers[i];
- p_store++;
- } else {
- transport_providers[p_transport]=possible_providers[i];
- p_transport++;
- }
- }
- }
-
- /**
- * Init possible servers of this main class
- */
- protected abstract void initServers();
-
- protected abstract void shutdownServers();
- public abstract Object getServer(String ID);
- public abstract Enumeration getServers();
- public String getBasePath() {
- return "";
- }
- public String getImageBasePath() {
- return "";
- }
- /*
- * @deprecated Use getServer("HTTP") instead
- */
- public HTTPServer getHTTPServer() {
- return (HTTPServer)getServer("HTTP");
- }
- /*
- * @deprecated Use getServer("SSL") instead
- */
- public SSLServer getSSLServer() {
- return (SSLServer)getServer("SSL");
- }
- public abstract void reinitServer(String ID);
-
- /*
- * @deprecated Use reinitServer("HTTP") instead
- */
- public void reinitHTTPServer() {
- reinitServer("HTTP");
- }
- /*
- * @deprecated Use reinitServer("SSL") instead
- */
- public void reinitSSLServer() {
- reinitServer("SSL");
- }
- public String getBaseURI(HTTPRequestHeader header) {
- String host=header.getHeader("Host");
- StringTokenizer tok=new StringTokenizer(host,":");
- String hostname=tok.nextToken();
- int port=80;
- if(tok.hasMoreElements()) {
- try {
- port=Integer.parseInt(tok.nextToken());
- } catch(NumberFormatException e) {}
- }
- int ssl_port=443;
- try {
- ssl_port=Integer.parseInt(storage.getConfig("ssl port"));
- } catch(NumberFormatException e) {}
- int http_port=80;
- try {
- http_port=Integer.parseInt(storage.getConfig("http port"));
- } catch(NumberFormatException e) {}
- String protocol="http";
- if(port==ssl_port) protocol="https"; else
- if(port==http_port) protocol="http";
- return protocol+"://"+host;
- }
- public Provider[] getStoreProviders() {
- Vector v=new Vector();
- for(int i=0;i<store_providers.length;i++) {
- if(storage.getConfig("ENABLE "+store_providers[i].getProtocol().toUpperCase()).equals("YES")) {
- v.addElement(store_providers[i]);
- }
- }
- Provider[] retval=new Provider[v.size()];
- v.copyInto(retval);
- return retval;
- }
- public Provider[] getTransportProviders() {
- return transport_providers;
- }
- public ConnectionTimer getConnectionTimer() {
- return timer;
- }
- public WebMailSession newSession(InetAddress a,HTTPRequestHeader h) throws InvalidPasswordException {
- if(sessions.get(Helper.calcSessionCode(a,h)) == null) {
- WebMailSession n=new WebMailSession(this,a,h);
- sessions.put(n.getSessionCode(),n);
- //System.err.println("New session: "+n.getSessionCode());
- timer.addTimeableConnection(n);
- n.login(h);
- return n;
- } else {
- WebMailSession n=(WebMailSession)sessions.get(Helper.calcSessionCode(a,h));
- n.login(h);
- return n;
- }
- }
- public AdminSession newAdminSession(InetAddress a,HTTPRequestHeader h) throws InvalidPasswordException {
- if(sessions.get(Helper.calcSessionCode(a,h)) == null) {
- AdminSession n=new AdminSession(this,a,h);
- sessions.put(n.getSessionCode(),n);
- //System.err.println("New admin session: "+n.getSessionCode());
- timer.addTimeableConnection(n);
- return n;
- } else {
- AdminSession n=(AdminSession)sessions.get(Helper.calcSessionCode(a,h));
- return n;
- }
- }
-
- public HTTPSession getSession(String sessionid, InetAddress a,HTTPRequestHeader h) throws InvalidPasswordException {
- String n=Helper.calcSessionCode(a,h);
- //System.err.print("Session requested: "+sessionid);
- if(!sessionid.startsWith(n)) {
- throw new InvalidPasswordException("Session-IDs didn't match. Please don't try to hack the server"+
- " by fiddling around with the URI's.");
- }
- if(sessions.get(sessionid) == null) {
- System.err.println(" not found!!!");
- throw new InvalidPasswordException("Mailbox without session or non-existant session-ID."+
- "Maybe the server was restarted or your session has expired. Please try to log in again");
- }
- //System.err.println(" found.");
- return (HTTPSession)sessions.get(sessionid);
- }
- public void removeSession(HTTPSession w) {
- storage.log(Storage.LOG_INFO,"Removing session: "+w.getSessionCode());
- timer.removeTimeableConnection(w);
- sessions.remove(w.getSessionCode());
- if(!w.isLoggedOut()) {
- w.logout();
- }
- }
- public HTTPSession getSession(String key) {
- return (HTTPSession)sessions.get(key);
- }
-
- public Enumeration getSessions() {
- return sessions.keys();
- }
- public static Storage getStorage() {
- return storage;
- }
- public PluginHandler getPluginHandler() {
- return phandler;
- }
-
- public AuthenticatorHandler getAuthenticatorHandler() {
- return ahandler;
- }
- public ToplevelURLHandler getURLHandler() {
- return uhandler;
- }
- public ConfigScheme getConfigScheme() {
- return config_scheme;
- }
- public void setContentBar(ContentBar c) {
- contentbar=c;
- }
- public ContentBar getContentBar() {
- return contentbar;
- }
- public String getProperty(String name) {
- return config.getProperty(name);
- }
- public void setProperty(String name, String value) {
- config.put(name,value);
- }
- /**
- @deprecated Use StorageAPI instead
- */
- public static String getConfig(String key) {
- return storage.getConfig(key);
- }
- public void restart() {
- System.err.println("Initiating shutdown for child processes:");
- Enumeration e=sessions.keys();
- System.err.print("- Removing active WebMail sessions ... ");
- while(e.hasMoreElements()) {
- HTTPSession w=(HTTPSession)sessions.get(e.nextElement());
- removeSession(w);
- }
- System.err.println("done!");
- shutdownServers();
- try {
- Thread.sleep(5000);
- } catch(Exception ex) {}
- storage.log(Storage.LOG_CRIT,"Shutdown completed successfully. Restarting.");
- storage.shutdown();
- System.err.println("Garbage collecting ...");
- System.gc();
- try {
- doInit();
- } catch(WebMailException ex) {
- ex.printStackTrace();
- System.exit(1);
- }
- }
- public void shutdown() {
- System.err.println("Initiating shutdown for child processes:");
- Enumeration e=sessions.keys();
- System.err.print("- Removing active WebMail sessions ... ");
- while(e.hasMoreElements()) {
- HTTPSession w=(HTTPSession)sessions.get(e.nextElement());
- removeSession(w);
- }
- System.err.println("done!");
- shutdownServers();
- storage.log(Storage.LOG_CRIT,"Shutdown completed successfully. Terminating.");
- storage.shutdown();
- System.err.println("Shutdown complete! Will return to console now.");
- System.exit(0);
- }
- public long getUptime() {
- return System.currentTimeMillis()-start_time;
- }
- public static String getVersion() {
- return "WebMail/Java v"+VERSION;
- }
- public static WebMailServer getServer() {
- return server;
- }
- public static String generateMessageID(String user) {
- long time=System.currentTimeMillis();
- String msgid=Long.toHexString(time)+".JavaWebMail."+VERSION+"."+user;
- try {
- msgid+="@"+InetAddress.getLocalHost().getHostName();
- } catch(Exception ex){}
- return msgid;
- }
- } // WebMailServer