Moving source files into src/-subdir.
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/>.
19 package org.sonews.daemon;
21 import java.io.IOException;
22 import java.net.InetSocketAddress;
23 import java.net.SocketException;
24 import java.nio.ByteBuffer;
25 import java.nio.CharBuffer;
26 import java.nio.channels.ClosedChannelException;
27 import java.nio.channels.SelectionKey;
28 import java.nio.channels.SocketChannel;
29 import java.nio.charset.Charset;
30 import java.util.Arrays;
31 import java.util.Timer;
32 import java.util.TimerTask;
33 import org.sonews.daemon.command.Command;
34 import org.sonews.storage.Article;
35 import org.sonews.storage.Channel;
36 import org.sonews.storage.StorageBackendException;
37 import org.sonews.util.Log;
38 import org.sonews.util.Stats;
41 * For every SocketChannel (so TCP/IP connection) there is an instance of
43 * @author Christian Lins
46 public final class NNTPConnection
49 public static final String NEWLINE = "\r\n"; // RFC defines this as newline
50 public static final String MESSAGE_ID_PATTERN = "<[^>]+>";
52 private static final Timer cancelTimer = new Timer(true); // Thread-safe? True for run as daemon
54 /** SocketChannel is generally thread-safe */
55 private SocketChannel channel = null;
56 private Charset charset = Charset.forName("UTF-8");
57 private Command command = null;
58 private Article currentArticle = null;
59 private Channel currentGroup = null;
60 private volatile long lastActivity = System.currentTimeMillis();
61 private ChannelLineBuffers lineBuffers = new ChannelLineBuffers();
62 private int readLock = 0;
63 private final Object readLockGate = new Object();
64 private SelectionKey writeSelKey = null;
66 public NNTPConnection(final SocketChannel channel)
71 throw new IllegalArgumentException("channel is null");
74 this.channel = channel;
75 Stats.getInstance().clientConnect();
79 * Tries to get the read lock for this NNTPConnection. This method is Thread-
80 * safe and returns true of the read lock was successfully set. If the lock
81 * is still hold by another Thread the method returns false.
85 // As synchronizing simple types may cause deadlocks,
86 // we use a gate object.
87 synchronized(readLockGate)
95 readLock = Thread.currentThread().hashCode();
102 * Releases the read lock in a Thread-safe way.
103 * @throws IllegalMonitorStateException if a Thread not holding the lock
104 * tries to release it.
106 void unlockReadLock()
108 synchronized(readLockGate)
110 if(readLock == Thread.currentThread().hashCode())
116 throw new IllegalMonitorStateException();
122 * @return Current input buffer of this NNTPConnection instance.
124 public ByteBuffer getInputBuffer()
126 return this.lineBuffers.getInputBuffer();
130 * @return Output buffer of this NNTPConnection which has at least one byte
133 public ByteBuffer getOutputBuffer()
135 return this.lineBuffers.getOutputBuffer();
139 * @return ChannelLineBuffers instance associated with this NNTPConnection.
141 public ChannelLineBuffers getBuffers()
143 return this.lineBuffers;
147 * @return true if this connection comes from a local remote address.
149 public boolean isLocalConnection()
151 return ((InetSocketAddress)this.channel.socket().getRemoteSocketAddress())
152 .getHostName().equalsIgnoreCase("localhost");
155 void setWriteSelectionKey(SelectionKey selKey)
157 this.writeSelKey = selKey;
160 public void shutdownInput()
164 // Closes the input line of the channel's socket, so no new data
165 // will be received and a timeout can be triggered.
166 this.channel.socket().shutdownInput();
168 catch(IOException ex)
170 Log.get().warning("Exception in NNTPConnection.shutdownInput(): " + ex);
174 public void shutdownOutput()
176 cancelTimer.schedule(new TimerTask()
183 // Closes the output line of the channel's socket.
184 channel.socket().shutdownOutput();
187 catch(SocketException ex)
189 // Socket was already disconnected
190 Log.get().info("NNTPConnection.shutdownOutput(): " + ex);
194 Log.get().warning("NNTPConnection.shutdownOutput(): " + ex);
200 public SocketChannel getSocketChannel()
205 public Article getCurrentArticle()
207 return this.currentArticle;
210 public Charset getCurrentCharset()
216 * @return The currently selected communication channel (not SocketChannel)
218 public Channel getCurrentChannel()
220 return this.currentGroup;
223 public void setCurrentArticle(final Article article)
225 this.currentArticle = article;
228 public void setCurrentGroup(final Channel group)
230 this.currentGroup = group;
233 public long getLastActivity()
235 return this.lastActivity;
239 * Due to the readLockGate there is no need to synchronize this method.
241 * @throws IllegalArgumentException if raw is null.
242 * @throws IllegalStateException if calling thread does not own the readLock.
244 void lineReceived(byte[] raw)
248 throw new IllegalArgumentException("raw is null");
251 if(readLock == 0 || readLock != Thread.currentThread().hashCode())
253 throw new IllegalStateException("readLock not properly set");
256 this.lastActivity = System.currentTimeMillis();
258 String line = new String(raw, this.charset);
260 // There might be a trailing \r, but trim() is a bad idea
261 // as it removes also leading spaces from long header lines.
262 if(line.endsWith("\r"))
264 line = line.substring(0, line.length() - 1);
265 raw = Arrays.copyOf(raw, raw.length - 1);
268 Log.get().fine("<< " + line);
272 command = parseCommandLine(line);
273 assert command != null;
278 // The command object will process the line we just received
281 command.processLine(this, line, raw);
283 catch(StorageBackendException ex)
285 Log.get().info("Retry command processing after StorageBackendException");
287 // Try it a second time, so that the backend has time to recover
288 command.processLine(this, line, raw);
291 catch(ClosedChannelException ex0)
295 Log.get().info("Connection to " + channel.socket().getRemoteSocketAddress()
296 + " closed: " + ex0);
298 catch(Exception ex0a)
300 ex0a.printStackTrace();
303 catch(Exception ex1) // This will catch a second StorageBackendException
308 ex1.printStackTrace();
309 println("500 Internal server error");
313 ex2.printStackTrace();
317 if(command == null || command.hasFinished())
320 charset = Charset.forName("UTF-8"); // Reset to default
325 * This method determines the fitting command processing class.
329 private Command parseCommandLine(String line)
331 String cmdStr = line.split(" ")[0];
332 return CommandSelector.getInstance().get(cmdStr);
336 * Puts the given line into the output buffer, adds a newline character
337 * and returns. The method returns immediately and does not block until
338 * the line was sent. If line is longer than 510 octets it is split up in
339 * several lines. Each line is terminated by \r\n (NNTPConnection.NEWLINE).
342 public void println(final CharSequence line, final Charset charset)
345 writeToChannel(CharBuffer.wrap(line), charset, line);
346 writeToChannel(CharBuffer.wrap(NEWLINE), charset, null);
350 * Writes the given raw lines to the output buffers and finishes with
351 * a newline character (\r\n).
354 public void println(final byte[] rawLines)
357 this.lineBuffers.addOutputBuffer(ByteBuffer.wrap(rawLines));
358 writeToChannel(CharBuffer.wrap(NEWLINE), charset, null);
362 * Encodes the given CharBuffer using the given Charset to a bunch of
363 * ByteBuffers (each 512 bytes large) and enqueues them for writing at the
364 * connected SocketChannel.
365 * @throws java.io.IOException
367 private void writeToChannel(CharBuffer characters, final Charset charset,
368 CharSequence debugLine)
371 if(!charset.canEncode())
373 Log.get().severe("FATAL: Charset " + charset + " cannot encode!");
377 // Write characters to output buffers
378 LineEncoder lenc = new LineEncoder(characters, charset);
379 lenc.encode(lineBuffers);
381 enableWriteEvents(debugLine);
384 private void enableWriteEvents(CharSequence debugLine)
386 // Enable OP_WRITE events so that the buffers are processed
389 this.writeSelKey.interestOps(SelectionKey.OP_WRITE);
390 ChannelWriter.getInstance().getSelector().wakeup();
392 catch(Exception ex) // CancelledKeyException and ChannelCloseException
394 Log.get().warning("NNTPConnection.writeToChannel(): " + ex);
398 // Update last activity timestamp
399 this.lastActivity = System.currentTimeMillis();
400 if(debugLine != null)
402 Log.get().fine(">> " + debugLine);
406 public void println(final CharSequence line)
409 println(line, charset);
412 public void print(final String line)
415 writeToChannel(CharBuffer.wrap(line), charset, line);
418 public void setCurrentCharset(final Charset charset)
420 this.charset = charset;
423 void setLastActivity(long timestamp)
425 this.lastActivity = timestamp;