src/org/sonews/daemon/NNTPConnection.java
author František Kučera <franta-hg@frantovo.cz>
Tue Oct 11 16:17:51 2011 +0200 (2011-10-11)
changeset 70 2177f9b14688
parent 48 b78e77619152
child 101 d54786065fa3
permissions -rwxr-xr-x
Drupal: hlavičky, poměrně funkční čtení příspěvků (vlánka).
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;
chris@1
    19
chris@1
    20
import java.io.IOException;
chris@1
    21
import java.net.InetSocketAddress;
chris@3
    22
import java.net.SocketException;
chris@1
    23
import java.nio.ByteBuffer;
chris@1
    24
import java.nio.CharBuffer;
chris@1
    25
import java.nio.channels.ClosedChannelException;
chris@1
    26
import java.nio.channels.SelectionKey;
chris@1
    27
import java.nio.channels.SocketChannel;
chris@1
    28
import java.nio.charset.Charset;
chris@3
    29
import java.util.Arrays;
chris@1
    30
import java.util.Timer;
chris@1
    31
import java.util.TimerTask;
cli@49
    32
import java.util.logging.Level;
chris@3
    33
import org.sonews.daemon.command.Command;
chris@3
    34
import org.sonews.storage.Article;
cli@48
    35
import org.sonews.storage.Group;
cli@30
    36
import org.sonews.storage.StorageBackendException;
cli@25
    37
import org.sonews.util.Log;
chris@1
    38
import org.sonews.util.Stats;
chris@1
    39
chris@1
    40
/**
chris@1
    41
 * For every SocketChannel (so TCP/IP connection) there is an instance of
chris@1
    42
 * this class.
chris@1
    43
 * @author Christian Lins
chris@1
    44
 * @since sonews/0.5.0
chris@1
    45
 */
cli@49
    46
public final class NNTPConnection {
chris@1
    47
cli@37
    48
	public static final String NEWLINE = "\r\n";    // RFC defines this as newline
cli@37
    49
	public static final String MESSAGE_ID_PATTERN = "<[^>]+>";
cli@37
    50
	private static final Timer cancelTimer = new Timer(true); // Thread-safe? True for run as daemon
cli@37
    51
	/** SocketChannel is generally thread-safe */
cli@37
    52
	private SocketChannel channel = null;
cli@37
    53
	private Charset charset = Charset.forName("UTF-8");
cli@37
    54
	private Command command = null;
cli@37
    55
	private Article currentArticle = null;
cli@48
    56
	private Group currentGroup = null;
cli@37
    57
	private volatile long lastActivity = System.currentTimeMillis();
cli@37
    58
	private ChannelLineBuffers lineBuffers = new ChannelLineBuffers();
cli@37
    59
	private int readLock = 0;
cli@37
    60
	private final Object readLockGate = new Object();
cli@37
    61
	private SelectionKey writeSelKey = null;
chris@1
    62
cli@37
    63
	public NNTPConnection(final SocketChannel channel)
cli@49
    64
			throws IOException {
cli@37
    65
		if (channel == null) {
cli@37
    66
			throw new IllegalArgumentException("channel is null");
cli@37
    67
		}
chris@1
    68
cli@37
    69
		this.channel = channel;
cli@37
    70
		Stats.getInstance().clientConnect();
cli@37
    71
	}
chris@1
    72
cli@37
    73
	/**
cli@37
    74
	 * Tries to get the read lock for this NNTPConnection. This method is Thread-
cli@37
    75
	 * safe and returns true of the read lock was successfully set. If the lock
cli@37
    76
	 * is still hold by another Thread the method returns false.
cli@37
    77
	 */
cli@49
    78
	boolean tryReadLock() {
cli@37
    79
		// As synchronizing simple types may cause deadlocks,
cli@37
    80
		// we use a gate object.
cli@37
    81
		synchronized (readLockGate) {
cli@37
    82
			if (readLock != 0) {
cli@37
    83
				return false;
cli@37
    84
			} else {
cli@37
    85
				readLock = Thread.currentThread().hashCode();
cli@37
    86
				return true;
cli@37
    87
			}
cli@37
    88
		}
cli@37
    89
	}
chris@3
    90
cli@37
    91
	/**
cli@37
    92
	 * Releases the read lock in a Thread-safe way.
cli@37
    93
	 * @throws IllegalMonitorStateException if a Thread not holding the lock
cli@37
    94
	 * tries to release it.
cli@37
    95
	 */
cli@49
    96
	void unlockReadLock() {
cli@37
    97
		synchronized (readLockGate) {
cli@37
    98
			if (readLock == Thread.currentThread().hashCode()) {
cli@37
    99
				readLock = 0;
cli@37
   100
			} else {
cli@37
   101
				throw new IllegalMonitorStateException();
cli@37
   102
			}
cli@37
   103
		}
cli@37
   104
	}
chris@1
   105
cli@37
   106
	/**
cli@37
   107
	 * @return Current input buffer of this NNTPConnection instance.
cli@37
   108
	 */
cli@49
   109
	public ByteBuffer getInputBuffer() {
cli@37
   110
		return this.lineBuffers.getInputBuffer();
cli@37
   111
	}
chris@1
   112
cli@37
   113
	/**
cli@37
   114
	 * @return Output buffer of this NNTPConnection which has at least one byte
cli@37
   115
	 * free storage.
cli@37
   116
	 */
cli@49
   117
	public ByteBuffer getOutputBuffer() {
cli@37
   118
		return this.lineBuffers.getOutputBuffer();
cli@37
   119
	}
cli@30
   120
cli@37
   121
	/**
cli@37
   122
	 * @return ChannelLineBuffers instance associated with this NNTPConnection.
cli@37
   123
	 */
cli@49
   124
	public ChannelLineBuffers getBuffers() {
cli@37
   125
		return this.lineBuffers;
cli@37
   126
	}
chris@1
   127
cli@37
   128
	/**
cli@37
   129
	 * @return true if this connection comes from a local remote address.
cli@37
   130
	 */
cli@49
   131
	public boolean isLocalConnection() {
cli@37
   132
		return ((InetSocketAddress) this.channel.socket().getRemoteSocketAddress()).getHostName().equalsIgnoreCase("localhost");
cli@37
   133
	}
chris@3
   134
cli@49
   135
	void setWriteSelectionKey(SelectionKey selKey) {
cli@37
   136
		this.writeSelKey = selKey;
cli@37
   137
	}
chris@3
   138
cli@49
   139
	public void shutdownInput() {
cli@37
   140
		try {
cli@37
   141
			// Closes the input line of the channel's socket, so no new data
cli@37
   142
			// will be received and a timeout can be triggered.
cli@37
   143
			this.channel.socket().shutdownInput();
cli@37
   144
		} catch (IOException ex) {
cli@37
   145
			Log.get().warning("Exception in NNTPConnection.shutdownInput(): " + ex);
cli@37
   146
		}
cli@37
   147
	}
chris@1
   148
cli@49
   149
	public void shutdownOutput() {
cli@49
   150
		cancelTimer.schedule(new TimerTask() {
cli@37
   151
			@Override
cli@49
   152
			public void run() {
cli@37
   153
				try {
cli@37
   154
					// Closes the output line of the channel's socket.
cli@37
   155
					channel.socket().shutdownOutput();
cli@37
   156
					channel.close();
cli@37
   157
				} catch (SocketException ex) {
cli@37
   158
					// Socket was already disconnected
cli@37
   159
					Log.get().info("NNTPConnection.shutdownOutput(): " + ex);
cli@37
   160
				} catch (Exception ex) {
cli@37
   161
					Log.get().warning("NNTPConnection.shutdownOutput(): " + ex);
cli@37
   162
				}
cli@37
   163
			}
cli@37
   164
		}, 3000);
cli@37
   165
	}
cli@37
   166
cli@49
   167
	public SocketChannel getSocketChannel() {
cli@37
   168
		return this.channel;
cli@37
   169
	}
cli@37
   170
cli@49
   171
	public Article getCurrentArticle() {
cli@37
   172
		return this.currentArticle;
cli@37
   173
	}
cli@37
   174
cli@49
   175
	public Charset getCurrentCharset() {
cli@37
   176
		return this.charset;
cli@37
   177
	}
cli@37
   178
cli@37
   179
	/**
cli@37
   180
	 * @return The currently selected communication channel (not SocketChannel)
cli@37
   181
	 */
cli@49
   182
	public Group getCurrentChannel() {
cli@37
   183
		return this.currentGroup;
cli@37
   184
	}
cli@37
   185
cli@49
   186
	public void setCurrentArticle(final Article article) {
cli@37
   187
		this.currentArticle = article;
cli@37
   188
	}
cli@37
   189
cli@49
   190
	public void setCurrentGroup(final Group group) {
cli@37
   191
		this.currentGroup = group;
cli@37
   192
	}
cli@37
   193
cli@49
   194
	public long getLastActivity() {
cli@37
   195
		return this.lastActivity;
cli@37
   196
	}
cli@37
   197
cli@37
   198
	/**
cli@37
   199
	 * Due to the readLockGate there is no need to synchronize this method.
cli@37
   200
	 * @param raw
cli@37
   201
	 * @throws IllegalArgumentException if raw is null.
cli@37
   202
	 * @throws IllegalStateException if calling thread does not own the readLock.
cli@37
   203
	 */
cli@49
   204
	void lineReceived(byte[] raw) {
cli@37
   205
		if (raw == null) {
cli@37
   206
			throw new IllegalArgumentException("raw is null");
cli@37
   207
		}
cli@37
   208
cli@37
   209
		if (readLock == 0 || readLock != Thread.currentThread().hashCode()) {
cli@37
   210
			throw new IllegalStateException("readLock not properly set");
cli@37
   211
		}
cli@37
   212
cli@37
   213
		this.lastActivity = System.currentTimeMillis();
cli@37
   214
cli@37
   215
		String line = new String(raw, this.charset);
cli@37
   216
cli@37
   217
		// There might be a trailing \r, but trim() is a bad idea
cli@37
   218
		// as it removes also leading spaces from long header lines.
cli@37
   219
		if (line.endsWith("\r")) {
cli@37
   220
			line = line.substring(0, line.length() - 1);
cli@37
   221
			raw = Arrays.copyOf(raw, raw.length - 1);
cli@37
   222
		}
cli@37
   223
cli@37
   224
		Log.get().fine("<< " + line);
cli@37
   225
cli@37
   226
		if (command == null) {
cli@37
   227
			command = parseCommandLine(line);
cli@37
   228
			assert command != null;
cli@37
   229
		}
cli@37
   230
cli@37
   231
		try {
cli@37
   232
			// The command object will process the line we just received
cli@37
   233
			try {
cli@37
   234
				command.processLine(this, line, raw);
cli@37
   235
			} catch (StorageBackendException ex) {
cli@37
   236
				Log.get().info("Retry command processing after StorageBackendException");
cli@37
   237
cli@37
   238
				// Try it a second time, so that the backend has time to recover
cli@37
   239
				command.processLine(this, line, raw);
cli@37
   240
			}
cli@37
   241
		} catch (ClosedChannelException ex0) {
cli@37
   242
			try {
cli@49
   243
				StringBuilder strBuf = new StringBuilder();
cli@49
   244
				strBuf.append("Connection to ");
cli@49
   245
				strBuf.append(channel.socket().getRemoteSocketAddress());
cli@49
   246
				strBuf.append(" closed: ");
cli@49
   247
				strBuf.append(ex0);
cli@49
   248
				Log.get().info(strBuf.toString());
cli@37
   249
			} catch (Exception ex0a) {
cli@37
   250
				ex0a.printStackTrace();
cli@37
   251
			}
cli@49
   252
		} catch (Exception ex1) { // This will catch a second StorageBackendException
cli@37
   253
			try {
cli@37
   254
				command = null;
cli@49
   255
				Log.get().log(Level.WARNING, ex1.getLocalizedMessage(), ex1);
cli@49
   256
				println("403 Internal server error");
cli@49
   257
cli@49
   258
				// Should we end the connection here?
cli@49
   259
				// RFC says we MUST return 400 before closing the connection
cli@49
   260
				shutdownInput();
cli@49
   261
				shutdownOutput();
cli@37
   262
			} catch (Exception ex2) {
cli@37
   263
				ex2.printStackTrace();
cli@37
   264
			}
cli@37
   265
		}
cli@37
   266
cli@37
   267
		if (command == null || command.hasFinished()) {
cli@37
   268
			command = null;
cli@37
   269
			charset = Charset.forName("UTF-8"); // Reset to default
cli@37
   270
		}
cli@37
   271
	}
cli@37
   272
cli@37
   273
	/**
cli@37
   274
	 * This method determines the fitting command processing class.
cli@37
   275
	 * @param line
cli@37
   276
	 * @return
cli@37
   277
	 */
cli@49
   278
	private Command parseCommandLine(String line) {
cli@37
   279
		String cmdStr = line.split(" ")[0];
cli@37
   280
		return CommandSelector.getInstance().get(cmdStr);
cli@37
   281
	}
cli@37
   282
cli@37
   283
	/**
cli@37
   284
	 * Puts the given line into the output buffer, adds a newline character
cli@37
   285
	 * and returns. The method returns immediately and does not block until
cli@37
   286
	 * the line was sent. If line is longer than 510 octets it is split up in
cli@37
   287
	 * several lines. Each line is terminated by \r\n (NNTPConnection.NEWLINE).
cli@37
   288
	 * @param line
cli@37
   289
	 */
cli@37
   290
	public void println(final CharSequence line, final Charset charset)
cli@49
   291
			throws IOException {
cli@37
   292
		writeToChannel(CharBuffer.wrap(line), charset, line);
cli@37
   293
		writeToChannel(CharBuffer.wrap(NEWLINE), charset, null);
cli@37
   294
	}
cli@37
   295
cli@37
   296
	/**
cli@37
   297
	 * Writes the given raw lines to the output buffers and finishes with
cli@37
   298
	 * a newline character (\r\n).
cli@37
   299
	 * @param rawLines
cli@37
   300
	 */
cli@37
   301
	public void println(final byte[] rawLines)
cli@49
   302
			throws IOException {
cli@37
   303
		this.lineBuffers.addOutputBuffer(ByteBuffer.wrap(rawLines));
cli@37
   304
		writeToChannel(CharBuffer.wrap(NEWLINE), charset, null);
cli@37
   305
	}
cli@37
   306
cli@37
   307
	/**
cli@37
   308
	 * Encodes the given CharBuffer using the given Charset to a bunch of
cli@37
   309
	 * ByteBuffers (each 512 bytes large) and enqueues them for writing at the
cli@37
   310
	 * connected SocketChannel.
cli@37
   311
	 * @throws java.io.IOException
cli@37
   312
	 */
cli@37
   313
	private void writeToChannel(CharBuffer characters, final Charset charset,
cli@49
   314
			CharSequence debugLine)
cli@49
   315
			throws IOException {
cli@37
   316
		if (!charset.canEncode()) {
cli@37
   317
			Log.get().severe("FATAL: Charset " + charset + " cannot encode!");
cli@37
   318
			return;
cli@37
   319
		}
cli@37
   320
cli@37
   321
		// Write characters to output buffers
cli@37
   322
		LineEncoder lenc = new LineEncoder(characters, charset);
cli@37
   323
		lenc.encode(lineBuffers);
cli@37
   324
cli@37
   325
		enableWriteEvents(debugLine);
cli@37
   326
	}
cli@37
   327
cli@49
   328
	private void enableWriteEvents(CharSequence debugLine) {
cli@37
   329
		// Enable OP_WRITE events so that the buffers are processed
cli@37
   330
		try {
cli@37
   331
			this.writeSelKey.interestOps(SelectionKey.OP_WRITE);
cli@37
   332
			ChannelWriter.getInstance().getSelector().wakeup();
cli@37
   333
		} catch (Exception ex) // CancelledKeyException and ChannelCloseException
cli@37
   334
		{
cli@37
   335
			Log.get().warning("NNTPConnection.writeToChannel(): " + ex);
cli@37
   336
			return;
cli@37
   337
		}
cli@37
   338
cli@37
   339
		// Update last activity timestamp
cli@37
   340
		this.lastActivity = System.currentTimeMillis();
cli@37
   341
		if (debugLine != null) {
cli@37
   342
			Log.get().fine(">> " + debugLine);
cli@37
   343
		}
cli@37
   344
	}
cli@37
   345
cli@37
   346
	public void println(final CharSequence line)
cli@49
   347
			throws IOException {
cli@37
   348
		println(line, charset);
cli@37
   349
	}
cli@37
   350
cli@37
   351
	public void print(final String line)
cli@49
   352
			throws IOException {
cli@37
   353
		writeToChannel(CharBuffer.wrap(line), charset, line);
cli@37
   354
	}
cli@37
   355
cli@49
   356
	public void setCurrentCharset(final Charset charset) {
cli@37
   357
		this.charset = charset;
cli@37
   358
	}
cli@37
   359
cli@49
   360
	void setLastActivity(long timestamp) {
cli@37
   361
		this.lastActivity = timestamp;
cli@37
   362
	}
chris@1
   363
}