3 * see AUTHORS for the list of contributors
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package org.sonews.daemon.command;
20 import java.io.IOException;
21 import java.io.ByteArrayInputStream;
22 import java.io.ByteArrayOutputStream;
23 import java.sql.SQLException;
24 import java.util.Arrays;
25 import java.util.logging.Level;
26 import javax.mail.MessagingException;
27 import javax.mail.internet.AddressException;
28 import javax.mail.internet.InternetHeaders;
29 import org.sonews.config.Config;
30 import org.sonews.util.Log;
31 import org.sonews.mlgw.Dispatcher;
32 import org.sonews.storage.Article;
33 import org.sonews.storage.Group;
34 import org.sonews.daemon.NNTPConnection;
35 import org.sonews.storage.Headers;
36 import org.sonews.storage.StorageBackendException;
37 import org.sonews.storage.StorageManager;
38 import org.sonews.feed.FeedManager;
39 import org.sonews.util.Stats;
40 import org.sonews.util.io.SMTPInputStream;
43 * Implementation of the POST command. This command requires multiple lines
44 * from the client, so the handling of asynchronous reading is a little tricky
46 * @author Christian Lins
49 public class PostCommand implements Command {
51 private final Article article = new Article();
52 private int lineCount = 0;
53 private long bodySize = 0;
54 private InternetHeaders headers = null;
55 private long maxBodySize =
56 Config.inst().get(Config.ARTICLE_MAXSIZE, 128) * 1024L; // Size in bytes
57 private PostState state = PostState.WaitForLineOne;
58 private final ByteArrayOutputStream bufBody = new ByteArrayOutputStream();
59 private final StringBuilder strHead = new StringBuilder();
62 public String[] getSupportedCommandStrings() {
63 return new String[]{"POST"};
67 public boolean hasFinished() {
68 return this.state == PostState.Finished;
72 public String impliedCapability() {
77 public boolean isStateful() {
82 * Process the given line String. line.trim() was called by NNTPConnection.
84 * @throws java.io.IOException
85 * @throws java.sql.SQLException
87 @Override // TODO: Refactor this method to reduce complexity!
88 public void processLine(NNTPConnection conn, String line, byte[] raw)
89 throws IOException, StorageBackendException {
91 case WaitForLineOne: {
92 if (line.equalsIgnoreCase("POST")) {
93 conn.println("340 send article to be posted. End with <CR-LF>.<CR-LF>");
94 state = PostState.ReadingHeaders;
96 conn.println("500 invalid command usage");
100 case ReadingHeaders: {
101 strHead.append(line);
102 strHead.append(NNTPConnection.NEWLINE);
104 if ("".equals(line) || ".".equals(line)) {
105 // we finally met the blank line
106 // separating headers from body
110 // Parse the header using the InternetHeader class from JavaMail API
111 headers = new InternetHeaders(
112 new ByteArrayInputStream(strHead.toString().trim().getBytes(conn.getCurrentCharset())));
114 // add the header entries for the article
115 article.setHeaders(headers);
116 } catch (MessagingException ex) {
117 Log.get().log(Level.INFO, ex.getLocalizedMessage(), ex);
118 conn.println("500 posting failed - invalid header");
119 state = PostState.Finished;
123 // Change charset for reading body;
124 // for multipart messages UTF-8 is returned
125 //conn.setCurrentCharset(article.getBodyCharset());
127 state = PostState.ReadingBody;
129 // WTF: do we need articles without bodies?
130 if (".".equals(line)) {
131 // Post an article without body
132 postArticle(conn, article);
133 state = PostState.Finished;
139 if (".".equals(line)) {
140 // Set some headers needed for Over command
141 headers.setHeader(Headers.LINES, Integer.toString(lineCount));
142 headers.setHeader(Headers.BYTES, Long.toString(bodySize));
144 byte[] body = unescapeDots(bufBody.toByteArray());
145 if (body.length >= 2) {
146 // Remove trailing CRLF
147 body = Arrays.copyOf(body, body.length - 2);
149 article.setBody(body); // set the article body
151 postArticle(conn, article);
152 state = PostState.Finished;
154 bodySize += line.length() + 1;
157 // Add line to body buffer
158 bufBody.write(raw, 0, raw.length);
159 bufBody.write(NNTPConnection.NEWLINE.getBytes());
161 if (bodySize > maxBodySize) {
162 conn.println("500 article is too long");
163 state = PostState.Finished;
170 // Should never happen
171 Log.get().severe("PostCommand::processLine(): already finished...");
177 * Article is a control message and needs special handling.
180 private void controlMessage(NNTPConnection conn, Article article)
182 String[] ctrl = article.getHeader(Headers.CONTROL)[0].split(" ");
183 if (ctrl.length == 2) // "cancel <mid>"
186 StorageManager.current().delete(ctrl[1]);
188 // Move cancel message to "control" group
189 article.setHeader(Headers.NEWSGROUPS, "control");
190 StorageManager.current().addArticle(article);
191 conn.println("240 article cancelled");
192 } catch (StorageBackendException ex) {
193 Log.get().severe(ex.toString());
194 conn.println("500 internal server error");
197 conn.println("441 unknown control header");
201 private void supersedeMessage(NNTPConnection conn, Article article)
204 String oldMsg = article.getHeader(Headers.SUPERSEDES)[0];
205 StorageManager.current().delete(oldMsg);
206 StorageManager.current().addArticle(article);
207 conn.println("240 article replaced");
208 } catch (StorageBackendException ex) {
209 Log.get().severe(ex.toString());
210 conn.println("500 internal server error");
214 private void postArticle(NNTPConnection conn, Article article)
216 article.setUser(conn.getUser());
218 if (article.getHeader(Headers.CONTROL)[0].length() > 0) {
219 controlMessage(conn, article);
220 } else if (article.getHeader(Headers.SUPERSEDES)[0].length() > 0) {
221 supersedeMessage(conn, article);
222 } else { // Post the article regularily
223 // Circle check; note that Path can already contain the hostname here
224 String host = Config.inst().get(Config.HOSTNAME, "localhost");
225 if (article.getHeader(Headers.PATH)[0].indexOf(host + "!", 1) > 0) {
226 Log.get().log(Level.INFO, "{0} skipped for host {1}", new Object[]{article.getMessageID(), host});
227 conn.println("441 I know this article already");
231 // Try to create the article in the database or post it to
232 // appropriate mailing list
234 boolean success = false;
235 String[] groupnames = article.getHeader(Headers.NEWSGROUPS)[0].split(",");
236 for (String groupname : groupnames) {
237 Group group = StorageManager.current().getGroup(groupname);
238 if (group != null && !group.isDeleted()) {
239 if (group.isMailingList() && !conn.isLocalConnection()) {
240 // Send to mailing list; the Dispatcher writes
241 // statistics to database
242 success = Dispatcher.toList(article, group.getName());
245 if (!StorageManager.current().isArticleExisting(article.getMessageID())) {
246 StorageManager.current().addArticle(article);
248 // Log this posting to statistics
249 Stats.getInstance().mailPosted(
250 article.getHeader(Headers.NEWSGROUPS)[0]);
258 conn.println("240 article posted ok");
259 FeedManager.queueForPush(article);
261 conn.println("441 newsgroup not found or configuration error");
263 } catch (AddressException ex) {
264 Log.get().warning(ex.getMessage());
265 conn.println("441 invalid sender address");
266 } catch (MessagingException ex) {
267 // A MessageException is thrown when the sender email address is
268 // invalid or something is wrong with the SMTP server.
269 System.err.println(ex.getLocalizedMessage());
270 conn.println("441 " + ex.getClass().getCanonicalName() + ": " + ex.getLocalizedMessage());
271 } catch (StorageBackendException ex) {
272 ex.printStackTrace();
273 conn.println("500 internal server error");
279 * TODO: rework, integrate into NNTPConnection
281 * @param body message body with doubled dots
282 * @return message body with unescaped dots (.. → .)
284 private static byte[] unescapeDots(byte[] body) throws IOException {
285 byte[] result = new byte[body.length];
286 int resultLength = 0;
288 ByteArrayInputStream escapedInput = new ByteArrayInputStream(body);
289 SMTPInputStream unescapedInput = new SMTPInputStream(escapedInput);
291 int ch = unescapedInput.read();
293 result[resultLength] = (byte) ch;
295 ch = unescapedInput.read();
298 return Arrays.copyOfRange(result, 0, resultLength);