1 /*****************************************************************
2 * Licensed to the Apache Software Foundation (ASF) under one *
3 * or more contributor license agreements. See the NOTICE file *
4 * distributed with this work for additional information *
5 * regarding copyright ownership. The ASF licenses this file *
6 * to you under the Apache License, Version 2.0 (the *
7 * "License"); you may not use this file except in compliance *
8 * with the License. You may obtain a copy of the License at *
9 * *
10 * http://www.apache.org/licenses/LICENSE-2.0 *
11 * *
12 * Unless required by applicable law or agreed to in writing, *
13 * software distributed under the License is distributed on an *
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
15 * KIND, either express or implied. See the License for the *
16 * specific language governing permissions and limitations *
17 * under the License. *
18 ****************************************************************/
19
20 package org.apache.james.transport.mailets;
21
22 import org.apache.avalon.cornerstone.services.datasources.DataSourceSelector;
23 import org.apache.avalon.excalibur.datasource.DataSourceComponent;
24 import org.apache.avalon.framework.service.ServiceManager;
25 import org.apache.james.Constants;
26 import org.apache.james.util.JDBCUtil;
27 import org.apache.mailet.MailAddress;
28 import org.apache.mailet.MailetException;
29
30 import javax.mail.MessagingException;
31
32 import java.sql.Connection;
33 import java.sql.DatabaseMetaData;
34 import java.sql.PreparedStatement;
35 import java.sql.ResultSet;
36 import java.sql.SQLException;
37 import java.util.Collection;
38 import java.util.Iterator;
39 import java.util.Map;
40
41 /***
42 * Implements a Virtual User Table for JAMES. Derived from the
43 * JDBCAlias mailet, but whereas that mailet uses a simple map from a
44 * source address to a destination address, this handles simple
45 * wildcard selection, verifies that a catchall address is for a domain
46 * in the Virtual User Table, and handles forwarding.
47 *
48 * JDBCVirtualUserTable does not provide any administation tools.
49 * You'll have to create the VirtualUserTable yourself. The standard
50 * configuration is as follows:
51 *
52 * CREATE TABLE VirtualUserTable
53 * (
54 * user varchar(64) NOT NULL default '',
55 * domain varchar(255) NOT NULL default '',
56 * target_address varchar(255) NOT NULL default '',
57 * PRIMARY KEY (user,domain)
58 * );
59 *
60 * The user column specifies the username of the virtual recipient, the domain
61 * column the domain of the virtual recipient, and the target_address column
62 * the email address of the real recipient. The target_address column can contain
63 * just the username in the case of a local user, and multiple recipients can be
64 * specified in a list separated by commas, semi-colons or colons.
65 *
66 * The standard query used with VirtualUserTable is:
67 *
68 * select VirtualUserTable.target_address from VirtualUserTable, VirtualUserTable as VUTDomains
69 * where (VirtualUserTable.user like ? or VirtualUserTable.user like "\%")
70 * and (VirtualUserTable.domain like ?
71 * or (VirtualUserTable.domain like "\%" and VUTDomains.domain like ?))
72 * order by concat(VirtualUserTable.user,'@',VirtualUserTable.domain) desc limit 1
73 *
74 * For a given [user, domain, domain] used with the query, this will
75 * match as follows (in precedence order):
76 *
77 * 1. user@domain - explicit mapping for user@domain
78 * 2. user@% - catchall mapping for user anywhere
79 * 3. %@domain - catchall mapping for anyone at domain
80 * 4. null - no valid mapping
81 *
82 * You need to set the connection. At the moment, there is a limit to
83 * what you can change regarding the SQL Query, because there isn't a
84 * means to specify where in the query to replace parameters. [TODO]
85 *
86 * <mailet match="All" class="JDBCVirtualUserTable">
87 * <table>db://maildb/VirtualUserTable</table>
88 * <sqlquery>sqlquery</sqlquery>
89 * </mailet>
90 */
91 public class JDBCVirtualUserTable extends AbstractVirtualUserTable
92 {
93 protected DataSourceComponent datasource;
94
95 /***
96 * The query used by the mailet to get the alias mapping
97 */
98 protected String query = null;
99
100 /***
101 * The JDBCUtil helper class
102 */
103 private final JDBCUtil theJDBCUtil = new JDBCUtil() {
104 protected void delegatedLog(String logString) {
105 log("JDBCVirtualUserTable: " + logString);
106 }
107 };
108
109 /***
110 * Initialize the mailet
111 */
112 public void init() throws MessagingException {
113 if (getInitParameter("table") == null) {
114 throw new MailetException("Table location not specified for JDBCVirtualUserTable");
115 }
116
117 String tableURL = getInitParameter("table");
118
119 String datasourceName = tableURL.substring(5);
120 int pos = datasourceName.indexOf("/");
121 String tableName = datasourceName.substring(pos + 1);
122 datasourceName = datasourceName.substring(0, pos);
123 Connection conn = null;
124
125 try {
126 ServiceManager componentManager = (ServiceManager)getMailetContext().getAttribute(Constants.AVALON_COMPONENT_MANAGER);
127
128 DataSourceSelector datasources = (DataSourceSelector)componentManager.lookup(DataSourceSelector.ROLE);
129
130 datasource = (DataSourceComponent)datasources.select(datasourceName);
131
132 conn = datasource.getConnection();
133
134
135 DatabaseMetaData dbMetaData = conn.getMetaData();
136
137
138 if (!(theJDBCUtil.tableExists(dbMetaData, tableName))) {
139 StringBuffer exceptionBuffer =
140 new StringBuffer(128)
141 .append("Could not find table '")
142 .append(tableName)
143 .append("' in datasource '")
144 .append(datasourceName)
145 .append("'");
146 throw new MailetException(exceptionBuffer.toString());
147 }
148
149
150 query = getInitParameter("sqlquery","select VirtualUserTable.target_address from VirtualUserTable, VirtualUserTable as VUTDomains where (VirtualUserTable.user like ? or VirtualUserTable.user like '//%') and (VirtualUserTable.domain like ? or (VirtualUserTable.domain like '//%' and VUTDomains.domain like ?)) order by concat(VirtualUserTable.user,'@',VirtualUserTable.domain) desc limit 1");
151 } catch (MailetException me) {
152 throw me;
153 } catch (Exception e) {
154 throw new MessagingException("Error initializing JDBCVirtualUserTable", e);
155 } finally {
156 theJDBCUtil.closeJDBCConnection(conn);
157 }
158 }
159
160 /***
161 * Map any virtual recipients to real recipients using the configured
162 * JDBC connection, table and query.
163 *
164 * @param recipientsMap the mapping of virtual to real recipients
165 */
166 protected void mapRecipients(Map recipientsMap) throws MessagingException {
167 Connection conn = null;
168 PreparedStatement mappingStmt = null;
169
170 Collection recipients = recipientsMap.keySet();
171
172 try {
173 conn = datasource.getConnection();
174 mappingStmt = conn.prepareStatement(query);
175
176 for (Iterator i = recipients.iterator(); i.hasNext(); ) {
177 ResultSet mappingRS = null;
178 try {
179 MailAddress source = (MailAddress)i.next();
180 mappingStmt.setString(1, source.getUser());
181 mappingStmt.setString(2, source.getHost());
182 mappingStmt.setString(3, source.getHost());
183 mappingRS = mappingStmt.executeQuery();
184 if (mappingRS.next()) {
185 String targetString = mappingRS.getString(1);
186 recipientsMap.put(source, targetString);
187 }
188 } finally {
189 theJDBCUtil.closeJDBCResultSet(mappingRS);
190 }
191 }
192 } catch (SQLException sqle) {
193 throw new MessagingException("Error accessing database", sqle);
194 } finally {
195 theJDBCUtil.closeJDBCStatement(mappingStmt);
196 theJDBCUtil.closeJDBCConnection(conn);
197 }
198 }
199
200 public String getMailetInfo() {
201 return "JDBC Virtual User Table mailet";
202 }
203 }