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;
36 import java.util.concurrent.TimeUnit;
37 import java.util.concurrent.atomic.AtomicBoolean;
39 import javax.net.SocketFactory;
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.event.ChannelJoined;
49 import net.pterodactylus.irc.event.ChannelLeft;
50 import net.pterodactylus.irc.event.ChannelNicknames;
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.collect.Sets;
68 import com.google.common.eventbus.EventBus;
69 import com.google.common.eventbus.Subscribe;
70 import com.google.common.io.Closeables;
71 import com.google.common.util.concurrent.AbstractExecutionThreadService;
72 import com.google.common.util.concurrent.Service;
73 import org.apache.log4j.Logger;
76 * A connection to an IRC server.
78 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
80 public class Connection extends AbstractExecutionThreadService implements Service {
83 private static final Logger logger = Logger.getLogger(Connection.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 Connection(EventBus eventBus, SocketFactory socketFactory, String hostname, int port) {
137 this.eventBus = eventBus;
138 this.socketFactory = socketFactory;
139 this.hostname = hostname;
148 * Returns the hostname of the remote end of the connection.
150 * @return The remote’s hostname
152 public String hostname() {
157 * Returns the port number of the remote end of the connection.
159 * @return The remote’s port number
166 * Returns whether this connection has already been established.
168 * @return {@code true} as long as this connection is established, {@code
171 public boolean established() {
172 return established.get();
176 * Returns the nickname that is currently in use by this connection. The
177 * nickname is only available once the connection has been {@link #start()}ed.
179 * @return The current nickname
181 public String nickname() {
190 * Sets the nickname chooser. The nickname chooser is only used during the
191 * creation of the connection.
193 * @param nicknameChooser
194 * The nickname chooser
195 * @return This connection
197 public Connection nicknameChooser(NicknameChooser nicknameChooser) {
198 this.nicknameChooser = nicknameChooser;
203 * Sets the username to use.
206 * The username to use
207 * @return This connection
209 public Connection username(String username) {
210 this.username = Optional.fromNullable(username);
215 * Sets the real name to use.
218 * The real name to use
219 * @return This connection
221 public Connection realName(String realName) {
222 this.realName = Optional.fromNullable(realName);
227 * Sets the optional password for the connection.
230 * The password for the connection
231 * @return This connection
233 public Connection password(String password) {
234 this.password = Optional.fromNullable(password);
243 * Returns the current rate of the connection’s incoming side.
245 * @return The current input rate (in bytes per second)
247 public long getInputRate() {
248 return (connectionHandler != null) ? connectionHandler.getInputRate() : 0;
252 * Returns the current rate of the connection’s outgoing side.
254 * @return The current output rate (in bytes per second)
256 public long getOutputRate() {
257 return (connectionHandler != null) ? connectionHandler.getOutputRate() : 0;
261 * Checks whether the given source is the client represented by this
265 * The source to check
266 * @return {@code true} if this connection represents the given source, {@code
269 public boolean isSource(Source source) {
270 return source.nick().isPresent() && source.nick().get().equals(nickname);
274 * Joins the given channel.
277 * The channel to join
278 * @throws IOException
279 * if an I/O error occurs
281 public void joinChannel(final String channel) throws IOException {
282 connectionHandler.sendCommand("JOIN", channel);
286 * Sends a message to the given recipient, which may be a channel or another
290 * The recipient of the message
293 * @throws IOException
294 * if an I/O error occurs
296 public void sendMessage(String recipient, String message) throws IOException {
297 connectionHandler.sendCommand("PRIVMSG", recipient, message);
301 * Sends a DCC RESUME request to the given recipient.
304 * The recipient of the request
306 * The name of the file to resume
308 * The port number from the original DCC SEND request
310 * The position at which to resume the transfer
311 * @throws IOException
312 * if an I/O error occurs
314 public void sendDccResume(String recipient, String filename, int port, long position) throws IOException {
315 connectionHandler.sendCommand("PRIVMSG", recipient, String.format("\u0001DCC RESUME %s %d %d\u0001", filename, port, position));
319 * Closes this connection.
321 * @throws IOException
322 * if an I/O error occurs
324 public void close() throws IOException {
325 if (connectionHandler != null) {
326 connectionHandler.close();
331 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
335 protected void startUp() throws IllegalStateException {
336 checkState(username.isPresent(), "username must be set");
337 checkState(realName.isPresent(), "realName must be set");
341 protected void run() {
343 /* connect to remote socket. */
345 Socket socket = socketFactory.createSocket(hostname, port);
346 socket.setSoTimeout((int) TimeUnit.MINUTES.toMillis(3));
347 connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
349 /* register connection. */
350 if (password.isPresent()) {
351 connectionHandler.sendCommand("PASSWORD", password.get());
353 connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
354 nickname = nicknameChooser.getNickname();
355 connectionHandler.sendCommand("NICK", nickname);
357 } catch (IOException ioe1) {
358 eventBus.post(new ConnectionFailed(this, ioe1));
362 eventBus.register(this);
363 /* now read replies and react. */
365 /* some status variables. */
366 boolean connected = true;
367 Set<Nickname> nicks = Sets.newHashSet();
369 PrefixHandler prefixHandler = new PrefixHandler();
370 List<Handler> handlers = asList(
371 new MessageHandler(eventBus, this, prefixHandler),
372 new CtcpHandler(eventBus, this),
373 new MotdHandler(eventBus, this),
374 new ChannelNotJoinedHandler(eventBus, this),
375 new ConnectionEstablishHandler(eventBus, this),
380 Reply reply = connectionHandler.readReply();
381 eventBus.post(new ReplyReceived(this, reply));
382 logger.trace(String.format("<< %s", reply));
383 String command = reply.command();
384 List<String> parameters = reply.parameters();
386 for (Handler handler : handlers) {
387 if (handler.willHandle(reply)) {
388 handler.handleReply(reply);
393 /* 43x replies are for nick change errors. */
394 if (command.equals("431")) {
395 eventBus.post(new NoNicknameGivenReceived(this, reply));
396 } else if (command.equals("433")) {
397 if (!established.get()) {
398 nickname = nicknameChooser.getNickname();
399 connectionHandler.sendCommand("NICK", nickname);
401 eventBus.post(new NicknameInUseReceived(this, reply));
405 } else if (command.equalsIgnoreCase("NICK")) {
406 eventBus.post(new NicknameChanged(this, reply.source().get(), parameters.get(0)));
409 } else if (command.equalsIgnoreCase("JOIN")) {
410 eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
411 } else if (command.equals("331")) {
412 /* no topic is set. */
413 } else if (command.equals("332")) {
414 eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
415 } else if (command.equals("353")) {
416 for (String nickname : parameters.get(3).split(" ")) {
417 if (prefixHandler.isNickPrefixed(nickname)) {
418 nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
420 nicks.add(new Nickname(nickname, ""));
423 } else if (command.equals("366")) {
424 eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
426 } else if (command.equalsIgnoreCase("PART")) {
427 eventBus.post(new ChannelLeft(this, parameters.get(0), reply.source().get(), getOptional(parameters, 1)));
428 } else if (command.equalsIgnoreCase("QUIT")) {
429 eventBus.post(new ClientQuit(this, reply.source().get(), parameters.get(0)));
431 /* basic connection housekeeping. */
432 } else if (command.equalsIgnoreCase("PING")) {
433 connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
435 } else if (command.equalsIgnoreCase("KICK")) {
436 eventBus.post(new KickedFromChannel(this, parameters.get(0), reply.source().get(), parameters.get(1), getOptional(parameters, 2)));
438 /* okay, everything else. */
440 eventBus.post(new UnknownReplyReceived(this, reply));
443 eventBus.post(new ConnectionClosed(this));
444 } catch (IOException ioe1) {
445 logger.warn("I/O error", ioe1);
446 eventBus.post(new ConnectionClosed(this, ioe1));
447 } catch (RuntimeException re1) {
448 logger.error("Runtime error", re1);
449 eventBus.post(new ConnectionClosed(this, re1));
451 established.set(false);
452 eventBus.unregister(this);
453 logger.info("Closing Connection.");
455 Closeables.close(connectionHandler, true);
456 } catch (IOException ioe1) {
457 /* will not be thrown. */
464 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
465 if (connectionEstablished.connection() == this) {
466 established.set(true);
475 * Returns an item from the list, or {@link Optional#absent()} if the list is
476 * shorter than required for the given index.
479 * The list to get an item from
481 * The index of the item
483 * The type of the list items
484 * @return This list item wrapped in an {@link Optional}, or {@link
485 * Optional#absent()} if the list is not long enough
487 private static <T> Optional<T> getOptional(List<T> list, int index) {
488 if (index < list.size()) {
489 return Optional.fromNullable(list.get(index));
491 return Optional.absent();
494 /** Handles input and output for the connection. */
495 private class ConnectionHandler implements Closeable {
497 /** The output stream of the connection. */
498 private final BandwidthCountingOutputStream outputStream;
500 /** The input stream. */
501 private final BandwidthCountingInputStream inputStream;
503 /** The input stream of the connection. */
504 private final BufferedReader inputStreamReader;
507 * Creates a new connection handler for the given input stream and output
511 * The input stream of the connection
512 * @param outputStream
513 * The output stream of the connection
514 * @throws UnsupportedEncodingException
515 * if the encoding (currently “UTF-8”) is not valid
517 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
518 this.outputStream = new BandwidthCountingOutputStream(outputStream, 5, SECONDS);
519 this.inputStream = new BandwidthCountingInputStream(inputStream, 5, SECONDS);
520 inputStreamReader = new BufferedReader(new InputStreamReader(this.inputStream, "UTF-8"));
528 * Returns the current rate of the connection’s incoming side.
530 * @return The current input rate (in bytes per second)
532 public long getInputRate() {
533 return inputStream.getCurrentRate();
537 * Returns the current rate of the connection’s outgoing side.
539 * @return The current output rate (in bytes per second)
541 public long getOutputRate() {
542 return outputStream.getCurrentRate();
546 * Sends a command with the given parameters, skipping all {@link
547 * Optional#absent()} optionals.
550 * The command to send
553 * @throws IOException
554 * if an I/O error occurs
556 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
557 List<String> setParameters = new ArrayList<String>();
558 for (Optional<String> maybeSetParameter : parameters) {
559 if (maybeSetParameter.isPresent()) {
560 setParameters.add(maybeSetParameter.get());
563 sendCommand(command, setParameters.toArray(new String[setParameters.size()]));
567 * Sends a command with the given parameters.
570 * The command to send
572 * The parameters of the command
573 * @throws IOException
574 * if an I/O error occurs
575 * @throws IllegalArgumentException
576 * if any parameter but that last contains a space character
578 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
579 StringBuilder commandBuilder = new StringBuilder();
581 commandBuilder.append(command);
582 for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
583 String parameter = parameters[parameterIndex];
584 /* space is only allowed in the last parameter. */
585 commandBuilder.append(' ');
586 if (parameter.contains(" ")) {
587 if (parameterIndex == (parameters.length - 1)) {
588 commandBuilder.append(':');
590 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
593 commandBuilder.append(parameter);
596 logger.trace(String.format(">> %s", commandBuilder));
597 outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
598 outputStream.flush();
602 * Reads a line of reply from the connection.
605 * @throws IOException
606 * if an I/O error occurs
607 * @throws EOFException
610 public Reply readReply() throws IOException, EOFException {
611 String line = inputStreamReader.readLine();
613 throw new EOFException();
616 return Reply.parseLine(line);
624 public void close() throws IOException {
625 Closeables.close(outputStream, true);
626 Closeables.close(inputStreamReader, true);
627 Closeables.close(inputStream, true);