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