src/org/sonews/daemon/command/PostCommand.java
author František Kučera <franta-hg@frantovo.cz>
Wed Dec 31 12:07:40 2014 +0100 (2014-12-31)
changeset 120 bb1c8a7b774c
parent 115 e5bfc969d41f
permissions -rwxr-xr-x
XSLT: licence – GNU GPLv3
     1 /*
     2  *   SONEWS News Server
     3  *   see AUTHORS for the list of contributors
     4  *
     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.
     9  *
    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.
    14  *
    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/>.
    17  */
    18 package org.sonews.daemon.command;
    19 
    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;
    41 
    42 /**
    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
    45  * to handle.
    46  * @author Christian Lins
    47  * @since sonews/0.5.0
    48  */
    49 public class PostCommand implements Command {
    50 
    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();
    60 
    61 	@Override
    62 	public String[] getSupportedCommandStrings() {
    63 		return new String[]{"POST"};
    64 	}
    65 
    66 	@Override
    67 	public boolean hasFinished() {
    68 		return this.state == PostState.Finished;
    69 	}
    70 
    71 	@Override
    72 	public String impliedCapability() {
    73 		return null;
    74 	}
    75 
    76 	@Override
    77 	public boolean isStateful() {
    78 		return true;
    79 	}
    80 
    81 	/**
    82 	 * Process the given line String. line.trim() was called by NNTPConnection.
    83 	 * @param line
    84 	 * @throws java.io.IOException
    85 	 * @throws java.sql.SQLException
    86 	 */
    87 	@Override // TODO: Refactor this method to reduce complexity!
    88 	public void processLine(NNTPConnection conn, String line, byte[] raw)
    89 			throws IOException, StorageBackendException {
    90 		switch (state) {
    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;
    95 				} else {
    96 					conn.println("500 invalid command usage");
    97 				}
    98 				break;
    99 			}
   100 			case ReadingHeaders: {
   101 				strHead.append(line);
   102 				strHead.append(NNTPConnection.NEWLINE);
   103 
   104 				if ("".equals(line) || ".".equals(line)) {
   105 					// we finally met the blank line
   106 					// separating headers from body
   107 					// WTF: "."
   108 
   109 					try {
   110 						// Parse the header using the InternetHeader class from JavaMail API
   111 						headers = new InternetHeaders(
   112 								new ByteArrayInputStream(strHead.toString().trim().getBytes(conn.getCurrentCharset())));
   113 
   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;
   120 						break;
   121 					}
   122 
   123 					// Change charset for reading body;
   124 					// for multipart messages UTF-8 is returned
   125 					//conn.setCurrentCharset(article.getBodyCharset());
   126 
   127 					state = PostState.ReadingBody;
   128 
   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;
   134 					}
   135 				}
   136 				break;
   137 			}
   138 			case ReadingBody: {
   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));
   143 
   144 					byte[] body = unescapeDots(bufBody.toByteArray());
   145 					if (body.length >= 2) {
   146 						// Remove trailing CRLF
   147 						body = Arrays.copyOf(body, body.length - 2);
   148 					}
   149 					article.setBody(body); // set the article body
   150 
   151 					postArticle(conn, article);
   152 					state = PostState.Finished;
   153 				} else {
   154 					bodySize += line.length() + 1;
   155 					lineCount++;
   156 
   157 					// Add line to body buffer
   158 					bufBody.write(raw, 0, raw.length);
   159 					bufBody.write(NNTPConnection.NEWLINE.getBytes());
   160 
   161 					if (bodySize > maxBodySize) {
   162 						conn.println("500 article is too long");
   163 						state = PostState.Finished;
   164 						break;
   165 					}
   166 				}
   167 				break;
   168 			}
   169 			default: {
   170 				// Should never happen
   171 				Log.get().severe("PostCommand::processLine(): already finished...");
   172 			}
   173 		}
   174 	}
   175 
   176 	/**
   177 	 * Article is a control message and needs special handling.
   178 	 * @param article
   179 	 */
   180 	private void controlMessage(NNTPConnection conn, Article article)
   181 			throws IOException {
   182 		String[] ctrl = article.getHeader(Headers.CONTROL)[0].split(" ");
   183 		if (ctrl.length == 2) // "cancel <mid>"
   184 		{
   185 			try {
   186 				StorageManager.current().delete(ctrl[1]);
   187 
   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");
   195 			}
   196 		} else {
   197 			conn.println("441 unknown control header");
   198 		}
   199 	}
   200 
   201 	private void supersedeMessage(NNTPConnection conn, Article article)
   202 			throws IOException {
   203 		try {
   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");
   211 		}
   212 	}
   213 
   214 	private void postArticle(NNTPConnection conn, Article article)
   215 			throws IOException {
   216 		article.setUser(conn.getUser());
   217 
   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");
   228 				return;
   229 			}
   230 
   231 			// Try to create the article in the database or post it to
   232 			// appropriate mailing list
   233 			try {
   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());
   243 						} else {
   244 							// Store in database
   245 							if (!StorageManager.current().isArticleExisting(article.getMessageID())) {
   246 								StorageManager.current().addArticle(article);
   247 
   248 								// Log this posting to statistics
   249 								Stats.getInstance().mailPosted(
   250 										article.getHeader(Headers.NEWSGROUPS)[0]);
   251 							}
   252 							success = true;
   253 						}
   254 					}
   255 				} // end for
   256 
   257 				if (success) {
   258 					conn.println("240 article posted ok");
   259 					FeedManager.queueForPush(article);
   260 				} else {
   261 					conn.println("441 newsgroup not found or configuration error");
   262 				}
   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");
   274 			}
   275 		}
   276 	}
   277 
   278 	/**
   279 	 * TODO: rework, integrate into NNTPConnection
   280 	 * 
   281 	 * @param body message body with doubled dots
   282 	 * @return message body with unescaped dots (.. → .)
   283 	 */
   284 	private static byte[] unescapeDots(byte[] body) throws IOException {
   285 		byte[] result = new byte[body.length];
   286 		int resultLength = 0;
   287 
   288 		ByteArrayInputStream escapedInput = new ByteArrayInputStream(body);
   289 		SMTPInputStream unescapedInput = new SMTPInputStream(escapedInput);
   290 
   291 		int ch = unescapedInput.read();
   292 		while (ch >= 0) {
   293 			result[resultLength] = (byte) ch;
   294 			resultLength++;
   295 			ch = unescapedInput.read();
   296 		}
   297 
   298 		return Arrays.copyOfRange(result, 0, resultLength);
   299 	}
   300 }