james-server-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From nor...@apache.org
Subject svn commit: r984159 - in /james/server/trunk: mailets/src/main/java/org/apache/james/transport/matchers/ spring-deployment/src/main/config/james/
Date Tue, 10 Aug 2010 18:41:38 GMT
Author: norman
Date: Tue Aug 10 18:41:38 2010
New Revision: 984159

URL: http://svn.apache.org/viewvc?rev=984159&view=rev
Log:
Add a NetworkIsinWhitelist matcher which match networks against a database. I think it make
more sense to put it in a extra matcher(JAMES-1034)

Added:
    james/server/trunk/mailets/src/main/java/org/apache/james/transport/matchers/AbstractSQLWhitelistMatcher.java
    james/server/trunk/mailets/src/main/java/org/apache/james/transport/matchers/NetworkIsInWhitelist.java
Modified:
    james/server/trunk/mailets/src/main/java/org/apache/james/transport/matchers/IsInWhiteList.java
    james/server/trunk/spring-deployment/src/main/config/james/sqlResources.xml

Added: james/server/trunk/mailets/src/main/java/org/apache/james/transport/matchers/AbstractSQLWhitelistMatcher.java
URL: http://svn.apache.org/viewvc/james/server/trunk/mailets/src/main/java/org/apache/james/transport/matchers/AbstractSQLWhitelistMatcher.java?rev=984159&view=auto
==============================================================================
--- james/server/trunk/mailets/src/main/java/org/apache/james/transport/matchers/AbstractSQLWhitelistMatcher.java
(added)
+++ james/server/trunk/mailets/src/main/java/org/apache/james/transport/matchers/AbstractSQLWhitelistMatcher.java
Tue Aug 10 18:41:38 2010
@@ -0,0 +1,284 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you under the Apache License, Version 2.0 (the            *
+ * "License"); you may not use this file except in compliance   *
+ * with the License.  You may obtain a copy of the License at   *
+ *                                                              *
+ *   http://www.apache.org/licenses/LICENSE-2.0                 *
+ *                                                              *
+ * Unless required by applicable law or agreed to in writing,   *
+ * software distributed under the License is distributed on an  *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
+ * KIND, either express or implied.  See the License for the    *
+ * specific language governing permissions and limitations      *
+ * under the License.                                           *
+ ****************************************************************/
+
+package org.apache.james.transport.matchers;
+
+import java.io.File;
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.PreparedStatement;
+import java.sql.SQLException;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Locale;
+import java.util.Map;
+import java.util.StringTokenizer;
+
+import javax.annotation.Resource;
+import javax.mail.MessagingException;
+import javax.sql.DataSource;
+
+import org.apache.james.api.user.JamesUser;
+import org.apache.james.api.user.UsersRepository;
+import org.apache.james.services.DataSourceSelector;
+import org.apache.james.transport.mailets.WhiteListManager;
+import org.apache.james.util.sql.JDBCUtil;
+import org.apache.james.util.sql.SqlResources;
+import org.apache.mailet.Mail;
+import org.apache.mailet.MailAddress;
+import org.apache.mailet.base.GenericMatcher;
+
+public abstract class AbstractSQLWhitelistMatcher extends GenericMatcher {
+
+
+    /** The user repository for this mail server.  Contains all the users with inboxes
+     * on this server.
+     */
+    private UsersRepository localusers;
+
+    protected DataSourceSelector selector;
+
+    protected DataSource datasource;
+    
+
+    /**
+     * Holds value of property sqlFile.
+     */
+    private File sqlFile;
+
+     /**
+     * Holds value of property sqlParameters.
+     */
+    private Map<String,String> sqlParameters = new HashMap<String,String>();
+
+
+    
+    @Resource(name="database-connections")
+    public void setDataSourceSelector(DataSourceSelector selector) {
+        this.selector = selector;
+    }
+    
+    @Resource(name="localusersrepository")
+    public void setUsersRepository(UsersRepository localusers) {
+        this.localusers = localusers;
+    }
+    
+    /**
+     * Getter for property sqlParameters.
+     * @return Value of property sqlParameters.
+     */
+    private Map<String,String> getSqlParameters() {
+        return this.sqlParameters;
+    }
+    
+    /**
+     * The JDBCUtil helper class
+     */
+    protected final JDBCUtil theJDBCUtil = new JDBCUtil() {
+        protected void delegatedLog(String logString) {
+            log(getMatcherName() +": " + logString);
+        }
+    };
+    
+    /**
+     * Contains all of the sql strings for this component.
+     */
+    protected SqlResources sqlQueries = new SqlResources();
+
+    
+    @Override
+    public void init() throws MessagingException {
+        String repositoryPath = null;
+        StringTokenizer st = new StringTokenizer(getCondition(), ", \t", false);
+        if (st.hasMoreTokens()) {
+            repositoryPath = st.nextToken().trim();
+        }
+        if (repositoryPath != null) {
+            log("repositoryPath: " + repositoryPath);
+        }
+        else {
+            throw new MessagingException("repositoryPath is null");
+        }
+
+      
+        try {
+            // Get the data-source required.
+            int stindex =   repositoryPath.indexOf("://") + 3;
+            String datasourceName = repositoryPath.substring(stindex);
+            datasource = selector.getDataSource(datasourceName);
+        } catch (Exception e) {
+            throw new MessagingException("Can't get datasource", e);
+        }
+
+        try {
+            initSqlQueries(datasource.getConnection(), getMailetContext());
+        } catch (Exception e) {
+            throw new MessagingException("Exception initializing queries", e);
+        }        
+        
+        super.init();
+	}
+
+    public Collection<MailAddress> match(Mail mail) throws MessagingException {
+        // check if it's a local sender
+        MailAddress senderMailAddress = mail.getSender();
+        if (senderMailAddress == null) {
+            return null;
+        }
+        if (getMailetContext().isLocalEmail(senderMailAddress)) {
+            // is a local sender, so return
+            return null;
+        }
+
+        String senderUser = senderMailAddress.getLocalPart();
+        String senderHost = senderMailAddress.getDomain();
+
+        senderUser = senderUser.toLowerCase(Locale.US);
+        senderHost = senderHost.toLowerCase(Locale.US);
+
+        Collection<MailAddress> recipients = mail.getRecipients();
+
+        Collection<MailAddress> inWhiteList = new java.util.HashSet<MailAddress>();
+
+        for (Iterator<MailAddress> i = recipients.iterator(); i.hasNext();) {
+            MailAddress recipientMailAddress = i.next();
+            String recipientUser = recipientMailAddress.getLocalPart().toLowerCase(Locale.US);
+            String recipientHost = recipientMailAddress.getDomain().toLowerCase(Locale.US);
+
+            if (!getMailetContext().isLocalServer(recipientHost)) {
+                // not a local recipient, so skip
+                continue;
+            }
+
+            recipientUser = getPrimaryName(recipientUser);
+
+            if (matchedWhitelist(recipientMailAddress, mail)) {
+                // This address was already in the list
+                inWhiteList.add(recipientMailAddress);
+            }
+
+        }
+
+        return inWhiteList;
+
+    }
+    
+    protected abstract boolean matchedWhitelist(MailAddress recipient, Mail mail) throws
MessagingException;
+    
+	/** Gets the main name of a local customer, handling alias */
+    protected String getPrimaryName(String originalUsername) {
+        String username;
+        try {
+            username = localusers.getRealName(originalUsername);
+            JamesUser user = (JamesUser) localusers.getUserByName(username);
+            if (user.getAliasing()) {
+                username = user.getAlias();
+            }
+        }
+        catch (Exception e) {
+            username = originalUsername;
+        }
+        return username;
+    }
+    
+    /**
+     * Initializes the sql query environment from the SqlResources file.
+     * Will look for conf/sqlResources.xml.
+     * Will <I>not</I> create the database resources, if missing
+     * (this task is done, if needed, in the {@link WhiteListManager}
+     * initialization routine).
+     * @param conn The connection for accessing the database
+     * @param mailetContext The current mailet context,
+     * for finding the conf/sqlResources.xml file
+     * @throws Exception If any error occurs
+     */
+    protected void initSqlQueries(Connection conn, org.apache.mailet.MailetContext mailetContext)
throws Exception {
+        try {
+            if (conn.getAutoCommit()) {
+                conn.setAutoCommit(false);
+            }
+            
+            this.sqlFile = new File((String) mailetContext.getAttribute("confDir"), "sqlResources.xml").getCanonicalFile();
+            sqlQueries.init(this.sqlFile, getSQLSectionName(), conn, getSqlParameters());
+            checkTables(conn);
+        } finally {
+            theJDBCUtil.closeJDBCConnection(conn);
+        }
+    }
+    
+
+    protected abstract String getTableName();
+    
+    protected abstract String getTableCreateQueryName();
+    
+    private void checkTables(Connection conn) throws SQLException {
+
+        // Need to ask in the case that identifiers are stored, ask the DatabaseMetaInfo.
+        // Try UPPER, lower, and MixedCase, to see if the table is there.
+        
+        boolean dbUpdated = false;
+        
+        dbUpdated = createTable(conn, getTableName(), getTableCreateQueryName());
+        
+        //Commit our changes if necessary.
+        if (conn != null && dbUpdated && !conn.getAutoCommit()) {
+            conn.commit();
+            dbUpdated = false;
+        }
+            
+    }
+    
+    private boolean createTable(Connection conn, String tableNameSqlStringName, String createSqlStringName)
throws SQLException {
+        String tableName = sqlQueries.getSqlString(tableNameSqlStringName, true);
+        
+        DatabaseMetaData dbMetaData = conn.getMetaData();
+
+        // Try UPPER, lower, and MixedCase, to see if the table is there.
+        if (theJDBCUtil.tableExists(dbMetaData, tableName)) {
+            return false;
+        }
+        
+        PreparedStatement createStatement = null;
+        
+        try {
+            createStatement =
+                    conn.prepareStatement(sqlQueries.getSqlString(createSqlStringName, true));
+            createStatement.execute();
+            
+            StringBuffer logBuffer = null;
+            logBuffer =
+                    new StringBuffer(64)
+                    .append("Created table '")
+                    .append(tableName)
+                    .append("' using sqlResources string '")
+                    .append(createSqlStringName)
+                    .append("'.");
+            log(logBuffer.toString());
+            
+        } finally {
+            theJDBCUtil.closeJDBCStatement(createStatement);
+        }
+        
+        return true;
+    }
+    
+    
+    protected abstract String getSQLSectionName();
+}

Modified: james/server/trunk/mailets/src/main/java/org/apache/james/transport/matchers/IsInWhiteList.java
URL: http://svn.apache.org/viewvc/james/server/trunk/mailets/src/main/java/org/apache/james/transport/matchers/IsInWhiteList.java?rev=984159&r1=984158&r2=984159&view=diff
==============================================================================
--- james/server/trunk/mailets/src/main/java/org/apache/james/transport/matchers/IsInWhiteList.java
(original)
+++ james/server/trunk/mailets/src/main/java/org/apache/james/transport/matchers/IsInWhiteList.java
Tue Aug 10 18:41:38 2010
@@ -17,208 +17,104 @@
  * under the License.                                           *
  ****************************************************************/
 
-
-
 package org.apache.james.transport.matchers;
 
-import org.apache.james.api.user.JamesUser;
-import org.apache.james.api.user.UsersRepository;
-import org.apache.james.services.DataSourceSelector;
-import org.apache.james.transport.mailets.WhiteListManager;
-import org.apache.james.util.sql.JDBCUtil;
-import org.apache.james.util.sql.SqlResources;
-import org.apache.mailet.base.GenericMatcher;
-import org.apache.mailet.Mail;
-import org.apache.mailet.MailAddress;
-
-import javax.annotation.Resource;
-import javax.mail.MessagingException;
-import javax.sql.DataSource;
-
-import java.io.File;
 import java.sql.Connection;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
 import java.util.Locale;
-import java.util.Map;
-import java.util.StringTokenizer;
+
+import javax.mail.MessagingException;
+
+import org.apache.mailet.Mail;
+import org.apache.mailet.MailAddress;
 
 /**
- * <P>Matches recipients having the mail sender in the recipient's private whitelist
.</P>
- * <P> The recipient name is always converted to its primary name (handling aliases).</P>
- * <P>Configuration string: The database name containing the white list table.</P>
- * <P>Example:</P>
- * <PRE><CODE>
- *    &lt;mailet match="IsInWhiteList=db://maildb" class="ToProcessor"&gt;
+ * <P>
+ * Matches recipients having the mail sender in the recipient's private
+ * whitelist .
+ * </P>
+ * <P>
+ * The recipient name is always converted to its primary name (handling
+ * aliases).
+ * </P>
+ * <P>
+ * Configuration string: The database name containing the white list table.
+ * </P>
+ * <P>
+ * Example:
+ * </P>
+ * 
+ * <PRE>
+ * &lt;CODE&gt;
+ *    &lt;mailet match=&quot;IsInWhiteList=db://maildb&quot; class=&quot;ToProcessor&quot;&gt;
  *       &lt;processor&gt; transport &lt;/processor&gt;
  *    &lt;/mailet&gt;
- * </CODE></PRE>
+ * &lt;/CODE&gt;
+ * </PRE>
+ * 
  * @see org.apache.james.transport.mailets.WhiteListManager
  * @version SVN $Revision: $ $Date: $
  * @since 2.3.0
  */
-public class IsInWhiteList extends GenericMatcher {
+public class IsInWhiteList extends AbstractSQLWhitelistMatcher {
 
     private String selectByPK;
-    
-    private DataSource datasource;
-    
-    /** The user repository for this mail server.  Contains all the users with inboxes
-     * on this server.
-     */
-    private UsersRepository localusers;
-
-    /**
-     * The JDBCUtil helper class
-     */
-    private final JDBCUtil theJDBCUtil = new JDBCUtil() {
-        protected void delegatedLog(String logString) {
-            log("IsInWhiteList: " + logString);
-        }
-    };
-    
-    /**
-     * Contains all of the sql strings for this component.
-     */
-    private SqlResources sqlQueries = new SqlResources();
-
-    /**
-     * Holds value of property sqlFile.
-     */
-    private File sqlFile;
-
-     /**
-     * Holds value of property sqlParameters.
-     */
-    private Map<String,String> sqlParameters = new HashMap<String,String>();
-
-    private DataSourceSelector selector;
-
-    @Resource(name="database-connections")
-    public void setDataSourceSelector(DataSourceSelector selector) {
-        this.selector = selector;
-    }
-    
-    @Resource(name="localusersrepository")
-    public void setUsersRepository(UsersRepository localusers) {
-        this.localusers = localusers;
-    }
-    
-    /**
-     * Getter for property sqlParameters.
-     * @return Value of property sqlParameters.
-     */
-    private Map<String,String> getSqlParameters() {
 
-        return this.sqlParameters;
+    @Override
+    public void init() throws javax.mail.MessagingException {
+        super.init();
+        selectByPK = sqlQueries.getSqlString("selectByPK", true);
     }
 
-    /**
-     * @see org.apache.mailet.GenericMailet#init()
+    /*
+     * (non-Javadoc)
+     * @see org.apache.james.transport.matchers.AbstractSQLWhitelistMatcher#getSQLSectionName()
      */
-    public void init() throws javax.mail.MessagingException {
-        String repositoryPath = null;
-        StringTokenizer st = new StringTokenizer(getCondition(), ", \t", false);
-        if (st.hasMoreTokens()) {
-            repositoryPath = st.nextToken().trim();
-        }
-        if (repositoryPath != null) {
-            log("repositoryPath: " + repositoryPath);
-        }
-        else {
-            throw new MessagingException("repositoryPath is null");
-        }
-
-      
-        try {
-            // Get the data-source required.
-            int stindex =   repositoryPath.indexOf("://") + 3;
-            String datasourceName = repositoryPath.substring(stindex);
-            datasource = selector.getDataSource(datasourceName);
-        } catch (Exception e) {
-            throw new MessagingException("Can't get datasource", e);
-        }
-
-        try {
-            initSqlQueries(datasource.getConnection(), getMailetContext());
-        } catch (Exception e) {
-            throw new MessagingException("Exception initializing queries", e);
-        }        
-        
-        selectByPK = sqlQueries.getSqlString("selectByPK", true);
+    protected String getSQLSectionName() {
+        return "Whitelist";
     }
 
-    /**
-     * @see org.apache.mailet.GenericMatcher#match(Mail)
+    /*
+     * (non-Javadoc)
+     * @see org.apache.james.transport.matchers.AbstractSQLWhitelistMatcher#matchedWhitelist(org.apache.mailet.MailAddress,
org.apache.mailet.Mail)
      */
-    public Collection<MailAddress> match(Mail mail) throws MessagingException {
-        // check if it's a local sender
+    protected boolean matchedWhitelist(MailAddress recipientMailAddress, Mail mail) throws
MessagingException {
         MailAddress senderMailAddress = mail.getSender();
-        if (senderMailAddress == null) {
-            return null;
-        }
-        if (getMailetContext().isLocalEmail(senderMailAddress)) {
-            // is a local sender, so return
-            return null;
-        }
-        
-        String senderUser = senderMailAddress.getLocalPart();
-        String senderHost = senderMailAddress.getDomain();
-        
-        senderUser = senderUser.toLowerCase(Locale.US);
-        senderHost = senderHost.toLowerCase(Locale.US);
-        
-        Collection<MailAddress> recipients = mail.getRecipients();
-                
-        Collection<MailAddress> inWhiteList = new java.util.HashSet<MailAddress>();
+        String senderUser = senderMailAddress.getLocalPart().toLowerCase(Locale.US);
+        String senderHost = senderMailAddress.getDomain().toLowerCase(Locale.US);
         
         Connection conn = null;
         PreparedStatement selectStmt = null;
         ResultSet selectRS = null;
         try {
-            
-            for (Iterator<MailAddress> i = recipients.iterator(); i.hasNext(); ) {
-                try {
-                    MailAddress recipientMailAddress = i.next();
-                    String recipientUser = recipientMailAddress.getLocalPart().toLowerCase(Locale.US);
-                    String recipientHost = recipientMailAddress.getDomain().toLowerCase(Locale.US);
-                    
-                    if (!getMailetContext().isLocalServer(recipientHost)) {
-                        // not a local recipient, so skip
-                        continue;
-                    }
-                    
-                    recipientUser = getPrimaryName(recipientUser);
-                    
-                    if (conn == null) {
-                        conn = datasource.getConnection();
-                    }
-                    
-                    if (selectStmt == null) {
-                        selectStmt = conn.prepareStatement(selectByPK);
-                    }
-                    selectStmt.setString(1, recipientUser);
-                    selectStmt.setString(2, recipientHost);
-                    selectStmt.setString(3, senderUser);
-                    selectStmt.setString(4, senderHost);
-                    selectRS = selectStmt.executeQuery();
-                    if (selectRS.next()) {
-                        //This address was already in the list
-                        inWhiteList.add(recipientMailAddress);
-                    }
-                                        
-                } finally {
-                    theJDBCUtil.closeJDBCResultSet(selectRS);
+
+            try {
+                String recipientUser = recipientMailAddress.getLocalPart().toLowerCase(Locale.US);
+                String recipientHost = recipientMailAddress.getDomain().toLowerCase(Locale.US);
+
+                if (conn == null) {
+                    conn = datasource.getConnection();
+                }
+
+                if (selectStmt == null) {
+                    selectStmt = conn.prepareStatement(selectByPK);
                 }
-                
+                selectStmt.setString(1, recipientUser);
+                selectStmt.setString(2, recipientHost);
+                selectStmt.setString(3, senderUser);
+                selectStmt.setString(4, senderHost);
+                selectRS = selectStmt.executeQuery();
+                if (selectRS.next()) {
+                    // This address was already in the list
+                    return true;
+                }
+
+            } finally {
+                theJDBCUtil.closeJDBCResultSet(selectRS);
             }
-            
-            return inWhiteList;
-            
+
         } catch (SQLException sqle) {
             log("Error accessing database", sqle);
             throw new MessagingException("Exception thrown", sqle);
@@ -226,47 +122,23 @@ public class IsInWhiteList extends Gener
             theJDBCUtil.closeJDBCStatement(selectStmt);
             theJDBCUtil.closeJDBCConnection(conn);
         }
+        return false;
     }
 
-    /** Gets the main name of a local customer, handling alias */
-    private String getPrimaryName(String originalUsername) {
-        String username;
-        try {
-            username = localusers.getRealName(originalUsername);
-            JamesUser user = (JamesUser) localusers.getUserByName(username);
-            if (user.getAliasing()) {
-                username = user.getAlias();
-            }
-        }
-        catch (Exception e) {
-            username = originalUsername;
-        }
-        return username;
+    /*
+     * (non-Javadoc)
+     * @see org.apache.james.transport.matchers.AbstractSQLWhitelistMatcher#getTableCreateQueryName()
+     */
+    protected String getTableCreateQueryName() {
+        return "createWhiteListTable";
     }
-    
-    /**
-     * Initializes the sql query environment from the SqlResources file.
-     * Will look for conf/sqlResources.xml.
-     * Will <I>not</I> create the database resources, if missing
-     * (this task is done, if needed, in the {@link WhiteListManager}
-     * initialization routine).
-     * @param conn The connection for accessing the database
-     * @param mailetContext The current mailet context,
-     * for finding the conf/sqlResources.xml file
-     * @throws Exception If any error occurs
+
+    /*
+     * (non-Javadoc)
+     * @see org.apache.james.transport.matchers.AbstractSQLWhitelistMatcher#getTableName()
      */
-    private void initSqlQueries(Connection conn, org.apache.mailet.MailetContext mailetContext)
throws Exception {
-        try {
-            if (conn.getAutoCommit()) {
-                conn.setAutoCommit(false);
-            }
-            
-            this.sqlFile = new File((String) mailetContext.getAttribute("confDir"), "sqlResources.xml").getCanonicalFile();
-            sqlQueries.init(this.sqlFile, "WhiteList" , conn, getSqlParameters());
-            
-        } finally {
-            theJDBCUtil.closeJDBCConnection(conn);
-        }
+    protected String getTableName() {
+        return "whiteListTableName";
     }
-    
+
 }

Added: james/server/trunk/mailets/src/main/java/org/apache/james/transport/matchers/NetworkIsInWhitelist.java
URL: http://svn.apache.org/viewvc/james/server/trunk/mailets/src/main/java/org/apache/james/transport/matchers/NetworkIsInWhitelist.java?rev=984159&view=auto
==============================================================================
--- james/server/trunk/mailets/src/main/java/org/apache/james/transport/matchers/NetworkIsInWhitelist.java
(added)
+++ james/server/trunk/mailets/src/main/java/org/apache/james/transport/matchers/NetworkIsInWhitelist.java
Tue Aug 10 18:41:38 2010
@@ -0,0 +1,147 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you under the Apache License, Version 2.0 (the            *
+ * "License"); you may not use this file except in compliance   *
+ * with the License.  You may obtain a copy of the License at   *
+ *                                                              *
+ *   http://www.apache.org/licenses/LICENSE-2.0                 *
+ *                                                              *
+ * Unless required by applicable law or agreed to in writing,   *
+ * software distributed under the License is distributed on an  *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
+ * KIND, either express or implied.  See the License for the    *
+ * specific language governing permissions and limitations      *
+ * under the License.                                           *
+ ****************************************************************/
+package org.apache.james.transport.matchers;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+
+import javax.annotation.Resource;
+import javax.mail.MessagingException;
+
+import org.apache.james.api.dnsservice.DNSService;
+import org.apache.james.api.dnsservice.util.NetMatcher;
+import org.apache.mailet.Mail;
+import org.apache.mailet.MailAddress;
+
+/**
+ * Matcher which lookup whitelisted networks in a database. The networks can be specified
via netmask. 
+ * 
+ * For example:
+ * 192.168.0.0/24
+ * 
+ * Th whitelisting is done per recipient
+ *
+ */
+public class NetworkIsInWhitelist extends AbstractSQLWhitelistMatcher {
+
+    private DNSService dns;
+    private String selectNetworks;
+
+    /**
+     * Injection setter for the DNSService.
+     * 
+     * @param dnsService
+     */
+    @Resource(name="dnsserver")
+    public void setDNSService(DNSService dns) {
+        this.dns = dns;
+    }
+    
+
+    /*
+     * (non-Javadoc)
+     * @see org.apache.james.transport.matchers.AbstractSQLWhitelistMatcher#getSQLSectionName()
+     */
+    protected String getSQLSectionName() {
+        return "NetworkWhitelist";
+    }
+
+    @Override
+    public void init() throws MessagingException {
+        super.init();
+        selectNetworks = sqlQueries.getSqlString("selectNetwork", true);
+
+    }
+
+
+    /*
+     * (non-Javadoc)
+     * @see org.apache.james.transport.matchers.AbstractSQLWhitelistMatcher#matchedWhitelist(org.apache.mailet.MailAddress,
org.apache.mailet.Mail)
+     */
+    protected boolean matchedWhitelist(MailAddress recipientMailAddress, Mail mail) throws
MessagingException {
+        // check if it's a local sender
+        MailAddress senderMailAddress = mail.getSender();
+        String senderUser = senderMailAddress.getLocalPart().toLowerCase(Locale.US);
+        String senderHost = senderMailAddress.getDomain().toLowerCase(Locale.US);
+        
+        Connection conn = null;
+        PreparedStatement selectStmt = null;
+        ResultSet selectRS = null;
+        try {
+
+            try {
+                String recipientUser = recipientMailAddress.getLocalPart().toLowerCase(Locale.US);
+                String recipientHost = recipientMailAddress.getDomain().toLowerCase(Locale.US);
+
+                if (conn == null) {
+                    conn = datasource.getConnection();
+                }
+
+                if (selectStmt == null) {
+                    selectStmt = conn.prepareStatement(selectNetworks);
+                }
+                selectStmt.setString(1, recipientUser);
+                selectStmt.setString(2, recipientHost);
+                selectStmt.setString(3, senderUser);
+                selectStmt.setString(4, senderHost);
+                selectRS = selectStmt.executeQuery();
+                List<String> nets = new ArrayList<String>();
+                while (selectRS.next()) {
+                    nets.add(selectRS.getString(1));
+                }
+                NetMatcher matcher = new NetMatcher(nets, dns);
+                return matcher.matchInetNetwork(mail.getRemoteAddr());
+
+            } finally {
+                theJDBCUtil.closeJDBCResultSet(selectRS);
+            }
+
+        } catch (SQLException sqle) {
+            log("Error accessing database", sqle);
+            throw new MessagingException("Exception thrown", sqle);
+        } finally {
+            theJDBCUtil.closeJDBCStatement(selectStmt);
+            theJDBCUtil.closeJDBCConnection(conn);
+        }        
+    }
+
+
+    /*
+     * (non-Javadoc)
+     * @see org.apache.james.transport.matchers.AbstractSQLWhitelistMatcher#getTableCreateQueryName()
+     */
+    protected String getTableCreateQueryName() {
+        return "createNetworkWhiteListTable";
+    }
+
+
+    /*
+     * (non-Javadoc)
+     * @see org.apache.james.transport.matchers.AbstractSQLWhitelistMatcher#getTableName()
+     */
+    protected String getTableName() {
+        return "networkWhiteListTableName";
+    }
+
+}

Modified: james/server/trunk/spring-deployment/src/main/config/james/sqlResources.xml
URL: http://svn.apache.org/viewvc/james/server/trunk/spring-deployment/src/main/config/james/sqlResources.xml?rev=984159&r1=984158&r2=984159&view=diff
==============================================================================
--- james/server/trunk/spring-deployment/src/main/config/james/sqlResources.xml (original)
+++ james/server/trunk/spring-deployment/src/main/config/james/sqlResources.xml Tue Aug 10
18:41:38 2010
@@ -689,6 +689,86 @@
 
 </sqlDefs>
 
+<sqlDefs name="NetworkWhiteList">
+
+    <sql name="networkWhiteListTableName">networkWhitelist</sql>
+
+    <!-- Statements used to retrieve a single entry. -->
+    <sql name="selectNetwork">SELECT network FROM networkWhitelist where (localUser=?
AND localHost=?)</sql>
+
+    <!-- Statements used to create the "whitelist" table. -->
+    <sql name="createNetworkWhiteListTable" db="hypersonic">
+        CREATE TABLE networkWhitelist (
+            localUser varchar (64) NOT NULL,
+            localHost varchar (255) NOT NULL,
+            network varchar (255) NOT NULL,
+            PRIMARY KEY (localUser, localHost)
+        )    </sql>
+    <sql name="createNetworkWhiteListTable" db="hsqldb">
+        CREATE CACHED TABLE ${table} (
+        CREATE TABLE networkWhitelist (
+            localUser varchar (64) NOT NULL,
+            localHost varchar (255) NOT NULL,
+            network varchar (255) NOT NULL
+        )    </sql>
+    <sql name="createNetworkWhiteListTable" db="mysql">
+        CREATE TABLE networkWhitelist (
+            localUser varchar (64) NOT NULL,
+            localHost varchar (255) character set latin1 NOT NULL,
+            network varchar (255) NOT NULL
+        ) TYPE=InnoDB
+    </sql>
+    <sql name="createNetworkWhiteListTable" db="mssql">
+        CREATE TABLE [networkWhitelist] (
+            [localUser] [varchar] (64) NOT NULL,
+            [localHost] [varchar] (255) NOT NULL,
+            [network] [varchar] (255) NOT NULL
+        )
+    </sql>
+    <sql name="createNetworkWhiteListTable" db="oracle">
+        CREATE TABLE networkWhitelist (
+            localUser varchar (64) NOT NULL,
+            localHost varchar (255) NOT NULL,
+            network varchar (255) NOT NULL
+        )
+    </sql>
+    <sql name="createNetworkWhiteListTable" db="postgresql">
+        CREATE TABLE networkWhitelist (
+            localUser varchar (64) NOT NULL,
+            localHost varchar (255) NOT NULL,
+            network varchar (255) NOT NULL
+        )
+    </sql>
+    <sql name="createNetworkWhiteListTable" db="sapdb">
+        CREATE TABLE networkWhitelist (
+            localUser varchar (64) NOT NULL,
+            localHost varchar (255) NOT NULL,
+            network varchar (255) NOT NULL
+        )
+    </sql>
+    <sql name="createNetworkWhiteListTable" db="db2">
+        CREATE TABLE networkWhitelist (
+            localUser varchar (64) NOT NULL,
+            localHost varchar (255) NOT NULL,
+            network varchar (255) NOT NULL
+        )
+    </sql>
+    <sql name="createNetworkWhiteListTable" db="ingres">
+        CREATE TABLE networkWhitelist (
+            localUser varchar (64) NOT NULL,
+            localHost varchar (255) NOT NULL,
+            network varchar (255) NOT NULL
+        )
+    </sql>
+    <sql name="createNetworkWhiteListTable" db="derby">
+        CREATE TABLE networkWhitelist (
+            localUser varchar (64) NOT NULL,
+            localHost varchar (255) NOT NULL,
+            network varchar (255) NOT NULL
+        )
+    </sql>
+
+</sqlDefs>
 <!-- SQL statements to support the GreyList Handler-->
 <!-- -->
 <sqlDefs name="GreyList">



---------------------------------------------------------------------
To unsubscribe, e-mail: server-dev-unsubscribe@james.apache.org
For additional commands, e-mail: server-dev-help@james.apache.org


Mime
View raw message