2 * XdccDownloader - Connection.java - Copyright © 2013 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.irc;
20 import static com.google.common.base.Preconditions.checkState;
21 import static java.util.Arrays.asList;
22 import static java.util.concurrent.TimeUnit.SECONDS;
24 import java.io.BufferedReader;
25 import java.io.Closeable;
26 import java.io.EOFException;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.io.InputStreamReader;
30 import java.io.OutputStream;
31 import java.io.UnsupportedEncodingException;
32 import java.net.Socket;
33 import java.util.ArrayList;
34 import java.util.List;
35 import java.util.concurrent.TimeUnit;
36 import java.util.concurrent.atomic.AtomicBoolean;
38 import javax.net.SocketFactory;
40 import net.pterodactylus.irc.connection.ChannelNickHandler;
41 import net.pterodactylus.irc.connection.ChannelNotJoinedHandler;
42 import net.pterodactylus.irc.connection.ConnectionEstablishHandler;
43 import net.pterodactylus.irc.connection.CtcpHandler;
44 import net.pterodactylus.irc.connection.Handler;
45 import net.pterodactylus.irc.connection.MessageHandler;
46 import net.pterodactylus.irc.connection.MotdHandler;
47 import net.pterodactylus.irc.connection.PrefixHandler;
48 import net.pterodactylus.irc.connection.SimpleCommandHandler;
49 import net.pterodactylus.irc.event.ChannelJoined;
50 import net.pterodactylus.irc.event.ChannelLeft;
51 import net.pterodactylus.irc.event.ChannelTopic;
52 import net.pterodactylus.irc.event.ClientQuit;
53 import net.pterodactylus.irc.event.ConnectionClosed;
54 import net.pterodactylus.irc.event.ConnectionEstablished;
55 import net.pterodactylus.irc.event.ConnectionFailed;
56 import net.pterodactylus.irc.event.KickedFromChannel;
57 import net.pterodactylus.irc.event.NicknameChanged;
58 import net.pterodactylus.irc.event.NicknameInUseReceived;
59 import net.pterodactylus.irc.event.NoNicknameGivenReceived;
60 import net.pterodactylus.irc.event.ReplyReceived;
61 import net.pterodactylus.irc.event.UnknownReplyReceived;
62 import net.pterodactylus.irc.util.RandomNickname;
63 import net.pterodactylus.xdcc.util.io.BandwidthCountingInputStream;
64 import net.pterodactylus.xdcc.util.io.BandwidthCountingOutputStream;
66 import com.google.common.base.Optional;
67 import com.google.common.eventbus.EventBus;
68 import com.google.common.eventbus.Subscribe;
69 import com.google.common.io.Closeables;
70 import com.google.common.util.concurrent.AbstractExecutionThreadService;
71 import com.google.common.util.concurrent.Service;
72 import org.apache.log4j.Logger;
75 * A connection to an IRC server.
77 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
79 public class DefaultConnection extends AbstractExecutionThreadService implements Service,
83 private static final Logger logger = Logger.getLogger(DefaultConnection.class.getName());
86 private final EventBus eventBus;
88 /** The socket factory. */
89 private final SocketFactory socketFactory;
91 /** The hostname to connect to. */
92 private final String hostname;
94 /** The port to connect to. */
95 private final int port;
97 /** The nickname chooser. */
98 private NicknameChooser nicknameChooser = new NicknameChooser() {
101 public String getNickname() {
102 return RandomNickname.get();
107 private String nickname = null;
110 private Optional<String> username = Optional.absent();
112 /** The real name. */
113 private Optional<String> realName = Optional.absent();
115 /** The optional password for the connection. */
116 private Optional<String> password = Optional.absent();
118 /** The connection handler. */
119 private ConnectionHandler connectionHandler;
121 /** Whether the connection has already been established. */
122 private final AtomicBoolean established = new AtomicBoolean();
125 * Creates a new connection.
129 * @param socketFactory
132 * The hostname of the IRC server
134 * The port number of the IRC server
136 public DefaultConnection(EventBus eventBus, SocketFactory socketFactory, String hostname,
138 this.eventBus = eventBus;
139 this.socketFactory = socketFactory;
140 this.hostname = hostname;
149 public String hostname() {
159 public boolean established() {
160 return established.get();
164 public String nickname() {
169 public Connection username(String username) {
170 this.username = Optional.fromNullable(username);
175 public Connection realName(String realName) {
176 this.realName = Optional.fromNullable(realName);
181 public Connection password(String password) {
182 this.password = Optional.fromNullable(password);
191 public long getInputRate() {
192 return (connectionHandler != null) ? connectionHandler.getInputRate() : 0;
196 public long getOutputRate() {
197 return (connectionHandler != null) ? connectionHandler.getOutputRate() : 0;
201 public boolean isSource(Source source) {
202 return source.nick().isPresent() && source.nick().get().equals(nickname);
206 public void joinChannel(final String channel) throws IOException {
207 connectionHandler.sendCommand("JOIN", channel);
211 public void sendMessage(String recipient, String message) throws IOException {
212 connectionHandler.sendCommand("PRIVMSG", recipient, message);
216 public void sendDccResume(String recipient, String filename, int port, long position) throws IOException {
217 connectionHandler.sendCommand("PRIVMSG", recipient,
218 String.format("\u0001DCC RESUME %s %d %d\u0001", filename, port, position));
227 public void close() throws IOException {
228 if (connectionHandler != null) {
229 connectionHandler.close();
234 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
238 protected void startUp() throws IllegalStateException {
239 checkState(username.isPresent(), "username must be set");
240 checkState(realName.isPresent(), "realName must be set");
244 protected void run() {
246 /* connect to remote socket. */
248 Socket socket = socketFactory.createSocket(hostname, port);
249 socket.setSoTimeout((int) TimeUnit.MINUTES.toMillis(3));
250 connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
252 /* register connection. */
253 if (password.isPresent()) {
254 connectionHandler.sendCommand("PASSWORD", password.get());
256 connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
257 nickname = nicknameChooser.getNickname();
258 connectionHandler.sendCommand("NICK", nickname);
260 } catch (IOException ioe1) {
261 eventBus.post(new ConnectionFailed(this, ioe1));
265 eventBus.register(this);
266 /* now read replies and react. */
268 /* some status variables. */
269 boolean connected = true;
271 PrefixHandler prefixHandler = new PrefixHandler();
272 List<Handler> handlers = asList(
273 new MessageHandler(eventBus, this, prefixHandler),
274 new CtcpHandler(eventBus, this),
275 new ChannelNickHandler(eventBus, this, prefixHandler),
276 new SimpleCommandHandler(eventBus)
278 (s, p) -> new NoNicknameGivenReceived(
281 (s, p) -> new NicknameChanged(this,
284 (s, p) -> new ChannelJoined(this,
287 (s, p) -> new ChannelTopic(this, p.get(1),
290 (s, p) -> new ChannelLeft(this, p.get(0),
291 s.get(), getOptional(p, 1)))
293 (s, p) -> new ClientQuit(this, s.get(),
296 (s, p) -> new KickedFromChannel(this,
297 p.get(0), s.get(), p.get(1),
299 new MotdHandler(eventBus, this),
300 new ChannelNotJoinedHandler(eventBus, this),
301 new ConnectionEstablishHandler(eventBus, this),
306 Reply reply = connectionHandler.readReply();
307 eventBus.post(new ReplyReceived(this, reply));
308 logger.trace(String.format("<< %s", reply));
309 String command = reply.command();
310 List<String> parameters = reply.parameters();
312 for (Handler handler : handlers) {
313 if (handler.willHandle(reply)) {
314 handler.handleReply(reply);
319 /* 43x replies are for nick change errors. */
320 if (command.equals("433")) {
321 if (!established.get()) {
322 nickname = nicknameChooser.getNickname();
323 connectionHandler.sendCommand("NICK", nickname);
325 eventBus.post(new NicknameInUseReceived(this, reply));
329 /* basic connection housekeeping. */
330 } else if (command.equalsIgnoreCase("PING")) {
331 connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
333 /* okay, everything else. */
335 eventBus.post(new UnknownReplyReceived(this, reply));
338 eventBus.post(new ConnectionClosed(this));
339 } catch (IOException ioe1) {
340 logger.warn("I/O error", ioe1);
341 eventBus.post(new ConnectionClosed(this, ioe1));
342 } catch (RuntimeException re1) {
343 logger.error("Runtime error", re1);
344 eventBus.post(new ConnectionClosed(this, re1));
346 established.set(false);
347 eventBus.unregister(this);
348 logger.info("Closing Connection.");
350 Closeables.close(connectionHandler, true);
351 } catch (IOException ioe1) {
352 /* will not be thrown. */
359 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
360 if (connectionEstablished.connection() == this) {
361 established.set(true);
370 * Returns an item from the list, or {@link Optional#absent()} if the list is
371 * shorter than required for the given index.
374 * The list to get an item from
376 * The index of the item
378 * The type of the list items
379 * @return This list item wrapped in an {@link Optional}, or {@link
380 * Optional#absent()} if the list is not long enough
382 private static <T> Optional<T> getOptional(List<T> list, int index) {
383 if (index < list.size()) {
384 return Optional.fromNullable(list.get(index));
386 return Optional.absent();
389 /** Handles input and output for the connection. */
390 private class ConnectionHandler implements Closeable {
392 /** The output stream of the connection. */
393 private final BandwidthCountingOutputStream outputStream;
395 /** The input stream. */
396 private final BandwidthCountingInputStream inputStream;
398 /** The input stream of the connection. */
399 private final BufferedReader inputStreamReader;
402 * Creates a new connection handler for the given input stream and output
406 * The input stream of the connection
407 * @param outputStream
408 * The output stream of the connection
409 * @throws UnsupportedEncodingException
410 * if the encoding (currently “UTF-8”) is not valid
412 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
413 this.outputStream = new BandwidthCountingOutputStream(outputStream, 5, SECONDS);
414 this.inputStream = new BandwidthCountingInputStream(inputStream, 5, SECONDS);
415 inputStreamReader = new BufferedReader(new InputStreamReader(this.inputStream, "UTF-8"));
423 * Returns the current rate of the connection’s incoming side.
425 * @return The current input rate (in bytes per second)
427 public long getInputRate() {
428 return inputStream.getCurrentRate();
432 * Returns the current rate of the connection’s outgoing side.
434 * @return The current output rate (in bytes per second)
436 public long getOutputRate() {
437 return outputStream.getCurrentRate();
441 * Sends a command with the given parameters, skipping all {@link
442 * Optional#absent()} optionals.
445 * The command to send
448 * @throws IOException
449 * if an I/O error occurs
451 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
452 List<String> setParameters = new ArrayList<String>();
453 for (Optional<String> maybeSetParameter : parameters) {
454 if (maybeSetParameter.isPresent()) {
455 setParameters.add(maybeSetParameter.get());
458 sendCommand(command, setParameters.toArray(new String[setParameters.size()]));
462 * Sends a command with the given parameters.
465 * The command to send
467 * The parameters of the command
468 * @throws IOException
469 * if an I/O error occurs
470 * @throws IllegalArgumentException
471 * if any parameter but that last contains a space character
473 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
474 StringBuilder commandBuilder = new StringBuilder();
476 commandBuilder.append(command);
477 for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
478 String parameter = parameters[parameterIndex];
479 /* space is only allowed in the last parameter. */
480 commandBuilder.append(' ');
481 if (parameter.contains(" ")) {
482 if (parameterIndex == (parameters.length - 1)) {
483 commandBuilder.append(':');
485 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
488 commandBuilder.append(parameter);
491 logger.trace(String.format(">> %s", commandBuilder));
492 outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
493 outputStream.flush();
497 * Reads a line of reply from the connection.
500 * @throws IOException
501 * if an I/O error occurs
502 * @throws EOFException
505 public Reply readReply() throws IOException, EOFException {
506 String line = inputStreamReader.readLine();
508 throw new EOFException();
511 return Reply.parseLine(line);
519 public void close() throws IOException {
520 Closeables.close(outputStream, true);
521 Closeables.close(inputStreamReader, true);
522 Closeables.close(inputStream, true);