src/org/sonews/daemon/command/PostCommand.java
author cli
Sun Sep 11 15:05:04 2011 +0200 (2011-09-11)
changeset 48 b78e77619152
parent 37 74139325d305
child 50 0bf10add82d9
permissions -rwxr-xr-x
Merge Channel and Group classes.
chris@1
     1
/*
chris@1
     2
 *   SONEWS News Server
chris@1
     3
 *   see AUTHORS for the list of contributors
chris@1
     4
 *
chris@1
     5
 *   This program is free software: you can redistribute it and/or modify
chris@1
     6
 *   it under the terms of the GNU General Public License as published by
chris@1
     7
 *   the Free Software Foundation, either version 3 of the License, or
chris@1
     8
 *   (at your option) any later version.
chris@1
     9
 *
chris@1
    10
 *   This program is distributed in the hope that it will be useful,
chris@1
    11
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
chris@1
    12
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
chris@1
    13
 *   GNU General Public License for more details.
chris@1
    14
 *
chris@1
    15
 *   You should have received a copy of the GNU General Public License
chris@1
    16
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
chris@1
    17
 */
chris@1
    18
package org.sonews.daemon.command;
chris@1
    19
chris@1
    20
import java.io.IOException;
chris@1
    21
import java.io.ByteArrayInputStream;
chris@3
    22
import java.io.ByteArrayOutputStream;
chris@1
    23
import java.sql.SQLException;
chris@3
    24
import java.util.Arrays;
chris@1
    25
import javax.mail.MessagingException;
chris@1
    26
import javax.mail.internet.AddressException;
chris@1
    27
import javax.mail.internet.InternetHeaders;
chris@3
    28
import org.sonews.config.Config;
chris@1
    29
import org.sonews.util.Log;
chris@1
    30
import org.sonews.mlgw.Dispatcher;
chris@3
    31
import org.sonews.storage.Article;
chris@3
    32
import org.sonews.storage.Group;
chris@1
    33
import org.sonews.daemon.NNTPConnection;
chris@3
    34
import org.sonews.storage.Headers;
chris@3
    35
import org.sonews.storage.StorageBackendException;
chris@3
    36
import org.sonews.storage.StorageManager;
chris@1
    37
import org.sonews.feed.FeedManager;
chris@1
    38
import org.sonews.util.Stats;
chris@1
    39
chris@1
    40
/**
chris@1
    41
 * Implementation of the POST command. This command requires multiple lines
chris@1
    42
 * from the client, so the handling of asynchronous reading is a little tricky
chris@1
    43
 * to handle.
chris@1
    44
 * @author Christian Lins
chris@1
    45
 * @since sonews/0.5.0
chris@1
    46
 */
cli@42
    47
public class PostCommand implements Command {
chris@3
    48
cli@37
    49
	private final Article article = new Article();
cli@37
    50
	private int lineCount = 0;
cli@37
    51
	private long bodySize = 0;
cli@37
    52
	private InternetHeaders headers = null;
cli@37
    53
	private long maxBodySize =
cli@42
    54
			Config.inst().get(Config.ARTICLE_MAXSIZE, 128) * 1024L; // Size in bytes
cli@37
    55
	private PostState state = PostState.WaitForLineOne;
cli@37
    56
	private final ByteArrayOutputStream bufBody = new ByteArrayOutputStream();
cli@37
    57
	private final StringBuilder strHead = new StringBuilder();
chris@1
    58
cli@37
    59
	@Override
cli@42
    60
	public String[] getSupportedCommandStrings() {
cli@42
    61
		return new String[]{"POST"};
cli@37
    62
	}
chris@1
    63
cli@37
    64
	@Override
cli@42
    65
	public boolean hasFinished() {
cli@37
    66
		return this.state == PostState.Finished;
cli@37
    67
	}
cli@20
    68
cli@37
    69
	@Override
cli@42
    70
	public String impliedCapability() {
cli@37
    71
		return null;
cli@37
    72
	}
chris@3
    73
cli@37
    74
	@Override
cli@42
    75
	public boolean isStateful() {
cli@37
    76
		return true;
cli@37
    77
	}
chris@1
    78
cli@37
    79
	/**
cli@37
    80
	 * Process the given line String. line.trim() was called by NNTPConnection.
cli@37
    81
	 * @param line
cli@37
    82
	 * @throws java.io.IOException
cli@37
    83
	 * @throws java.sql.SQLException
cli@37
    84
	 */
cli@37
    85
	@Override // TODO: Refactor this method to reduce complexity!
cli@37
    86
	public void processLine(NNTPConnection conn, String line, byte[] raw)
cli@42
    87
			throws IOException, StorageBackendException {
cli@37
    88
		switch (state) {
cli@37
    89
			case WaitForLineOne: {
cli@37
    90
				if (line.equalsIgnoreCase("POST")) {
cli@37
    91
					conn.println("340 send article to be posted. End with <CR-LF>.<CR-LF>");
cli@37
    92
					state = PostState.ReadingHeaders;
cli@37
    93
				} else {
cli@37
    94
					conn.println("500 invalid command usage");
cli@37
    95
				}
cli@37
    96
				break;
cli@37
    97
			}
cli@37
    98
			case ReadingHeaders: {
cli@37
    99
				strHead.append(line);
cli@37
   100
				strHead.append(NNTPConnection.NEWLINE);
chris@1
   101
cli@37
   102
				if ("".equals(line) || ".".equals(line)) {
cli@37
   103
					// we finally met the blank line
cli@37
   104
					// separating headers from body
chris@3
   105
cli@37
   106
					try {
cli@37
   107
						// Parse the header using the InternetHeader class from JavaMail API
cli@37
   108
						headers = new InternetHeaders(
cli@42
   109
								new ByteArrayInputStream(strHead.toString().trim().getBytes(conn.getCurrentCharset())));
cli@18
   110
cli@37
   111
						// add the header entries for the article
cli@37
   112
						article.setHeaders(headers);
cli@37
   113
					} catch (MessagingException e) {
cli@37
   114
						e.printStackTrace();
cli@37
   115
						conn.println("500 posting failed - invalid header");
cli@37
   116
						state = PostState.Finished;
cli@37
   117
						break;
cli@37
   118
					}
chris@1
   119
cli@37
   120
					// Change charset for reading body;
cli@37
   121
					// for multipart messages UTF-8 is returned
cli@37
   122
					//conn.setCurrentCharset(article.getBodyCharset());
chris@1
   123
cli@37
   124
					state = PostState.ReadingBody;
chris@1
   125
cli@37
   126
					if (".".equals(line)) {
cli@37
   127
						// Post an article without body
cli@37
   128
						postArticle(conn, article);
cli@37
   129
						state = PostState.Finished;
cli@37
   130
					}
cli@37
   131
				}
cli@37
   132
				break;
cli@37
   133
			}
cli@37
   134
			case ReadingBody: {
cli@37
   135
				if (".".equals(line)) {
cli@37
   136
					// Set some headers needed for Over command
cli@37
   137
					headers.setHeader(Headers.LINES, Integer.toString(lineCount));
cli@37
   138
					headers.setHeader(Headers.BYTES, Long.toString(bodySize));
cli@37
   139
cli@37
   140
					byte[] body = bufBody.toByteArray();
cli@37
   141
					if (body.length >= 2) {
cli@37
   142
						// Remove trailing CRLF
cli@37
   143
						body = Arrays.copyOf(body, body.length - 2);
cli@37
   144
					}
cli@37
   145
					article.setBody(body); // set the article body
cli@37
   146
cli@37
   147
					postArticle(conn, article);
cli@37
   148
					state = PostState.Finished;
cli@37
   149
				} else {
cli@37
   150
					bodySize += line.length() + 1;
cli@37
   151
					lineCount++;
cli@37
   152
cli@37
   153
					// Add line to body buffer
cli@37
   154
					bufBody.write(raw, 0, raw.length);
cli@37
   155
					bufBody.write(NNTPConnection.NEWLINE.getBytes());
cli@37
   156
cli@37
   157
					if (bodySize > maxBodySize) {
cli@37
   158
						conn.println("500 article is too long");
cli@37
   159
						state = PostState.Finished;
cli@37
   160
						break;
cli@37
   161
					}
cli@37
   162
				}
cli@37
   163
				break;
cli@37
   164
			}
cli@37
   165
			default: {
cli@37
   166
				// Should never happen
cli@37
   167
				Log.get().severe("PostCommand::processLine(): already finished...");
cli@37
   168
			}
cli@37
   169
		}
cli@37
   170
	}
cli@37
   171
cli@37
   172
	/**
cli@37
   173
	 * Article is a control message and needs special handling.
cli@37
   174
	 * @param article
cli@37
   175
	 */
cli@37
   176
	private void controlMessage(NNTPConnection conn, Article article)
cli@42
   177
			throws IOException {
cli@37
   178
		String[] ctrl = article.getHeader(Headers.CONTROL)[0].split(" ");
cli@37
   179
		if (ctrl.length == 2) // "cancel <mid>"
cli@37
   180
		{
cli@37
   181
			try {
cli@37
   182
				StorageManager.current().delete(ctrl[1]);
cli@37
   183
cli@37
   184
				// Move cancel message to "control" group
cli@37
   185
				article.setHeader(Headers.NEWSGROUPS, "control");
cli@37
   186
				StorageManager.current().addArticle(article);
cli@37
   187
				conn.println("240 article cancelled");
cli@37
   188
			} catch (StorageBackendException ex) {
cli@37
   189
				Log.get().severe(ex.toString());
cli@37
   190
				conn.println("500 internal server error");
cli@37
   191
			}
cli@37
   192
		} else {
cli@37
   193
			conn.println("441 unknown control header");
cli@37
   194
		}
cli@37
   195
	}
cli@37
   196
cli@37
   197
	private void supersedeMessage(NNTPConnection conn, Article article)
cli@42
   198
			throws IOException {
cli@37
   199
		try {
cli@37
   200
			String oldMsg = article.getHeader(Headers.SUPERSEDES)[0];
cli@37
   201
			StorageManager.current().delete(oldMsg);
cli@37
   202
			StorageManager.current().addArticle(article);
cli@37
   203
			conn.println("240 article replaced");
cli@37
   204
		} catch (StorageBackendException ex) {
cli@37
   205
			Log.get().severe(ex.toString());
cli@37
   206
			conn.println("500 internal server error");
cli@37
   207
		}
cli@37
   208
	}
cli@37
   209
cli@37
   210
	private void postArticle(NNTPConnection conn, Article article)
cli@42
   211
			throws IOException {
cli@37
   212
		if (article.getHeader(Headers.CONTROL)[0].length() > 0) {
cli@37
   213
			controlMessage(conn, article);
cli@37
   214
		} else if (article.getHeader(Headers.SUPERSEDES)[0].length() > 0) {
cli@37
   215
			supersedeMessage(conn, article);
cli@37
   216
		} else // Post the article regularily
cli@37
   217
		{
cli@37
   218
			// Circle check; note that Path can already contain the hostname here
cli@37
   219
			String host = Config.inst().get(Config.HOSTNAME, "localhost");
cli@37
   220
			if (article.getHeader(Headers.PATH)[0].indexOf(host + "!", 1) > 0) {
cli@37
   221
				Log.get().info(article.getMessageID() + " skipped for host " + host);
cli@37
   222
				conn.println("441 I know this article already");
cli@37
   223
				return;
cli@37
   224
			}
cli@37
   225
cli@37
   226
			// Try to create the article in the database or post it to
cli@37
   227
			// appropriate mailing list
cli@37
   228
			try {
cli@37
   229
				boolean success = false;
cli@37
   230
				String[] groupnames = article.getHeader(Headers.NEWSGROUPS)[0].split(",");
cli@37
   231
				for (String groupname : groupnames) {
cli@37
   232
					Group group = StorageManager.current().getGroup(groupname);
cli@37
   233
					if (group != null && !group.isDeleted()) {
cli@37
   234
						if (group.isMailingList() && !conn.isLocalConnection()) {
cli@37
   235
							// Send to mailing list; the Dispatcher writes
cli@37
   236
							// statistics to database
cli@37
   237
							Dispatcher.toList(article, group.getName());
cli@37
   238
							success = true;
cli@37
   239
						} else {
cli@37
   240
							// Store in database
cli@37
   241
							if (!StorageManager.current().isArticleExisting(article.getMessageID())) {
cli@37
   242
								StorageManager.current().addArticle(article);
cli@37
   243
cli@37
   244
								// Log this posting to statistics
cli@37
   245
								Stats.getInstance().mailPosted(
cli@42
   246
										article.getHeader(Headers.NEWSGROUPS)[0]);
cli@37
   247
							}
cli@37
   248
							success = true;
cli@37
   249
						}
cli@37
   250
					}
cli@37
   251
				} // end for
cli@37
   252
cli@37
   253
				if (success) {
cli@37
   254
					conn.println("240 article posted ok");
cli@37
   255
					FeedManager.queueForPush(article);
cli@37
   256
				} else {
cli@37
   257
					conn.println("441 newsgroup not found");
cli@37
   258
				}
cli@37
   259
			} catch (AddressException ex) {
cli@37
   260
				Log.get().warning(ex.getMessage());
cli@37
   261
				conn.println("441 invalid sender address");
cli@37
   262
			} catch (MessagingException ex) {
cli@37
   263
				// A MessageException is thrown when the sender email address is
cli@37
   264
				// invalid or something is wrong with the SMTP server.
cli@37
   265
				System.err.println(ex.getLocalizedMessage());
cli@37
   266
				conn.println("441 " + ex.getClass().getCanonicalName() + ": " + ex.getLocalizedMessage());
cli@37
   267
			} catch (StorageBackendException ex) {
cli@37
   268
				ex.printStackTrace();
cli@37
   269
				conn.println("500 internal server error");
cli@37
   270
			}
cli@37
   271
		}
cli@37
   272
	}
chris@1
   273
}