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.InetAddress;
33 import java.net.Socket;
34 import java.net.UnknownHostException;
35 import java.util.ArrayList;
36 import java.util.List;
39 import java.util.concurrent.TimeUnit;
40 import java.util.concurrent.atomic.AtomicBoolean;
42 import javax.net.SocketFactory;
44 import net.pterodactylus.irc.connection.ChannelNotJoinedHandler;
45 import net.pterodactylus.irc.connection.ConnectionEstablishHandler;
46 import net.pterodactylus.irc.connection.Handler;
47 import net.pterodactylus.irc.event.ChannelJoined;
48 import net.pterodactylus.irc.event.ChannelLeft;
49 import net.pterodactylus.irc.event.ChannelMessageReceived;
50 import net.pterodactylus.irc.event.ChannelNicknames;
51 import net.pterodactylus.irc.event.ChannelNotJoined;
52 import net.pterodactylus.irc.event.ChannelNotJoined.Reason;
53 import net.pterodactylus.irc.event.ChannelNoticeReceived;
54 import net.pterodactylus.irc.event.ChannelTopic;
55 import net.pterodactylus.irc.event.ClientQuit;
56 import net.pterodactylus.irc.event.ConnectionClosed;
57 import net.pterodactylus.irc.event.ConnectionEstablished;
58 import net.pterodactylus.irc.event.ConnectionFailed;
59 import net.pterodactylus.irc.event.DccAcceptReceived;
60 import net.pterodactylus.irc.event.DccSendReceived;
61 import net.pterodactylus.irc.event.KickedFromChannel;
62 import net.pterodactylus.irc.event.MotdReceived;
63 import net.pterodactylus.irc.event.NicknameChanged;
64 import net.pterodactylus.irc.event.NicknameInUseReceived;
65 import net.pterodactylus.irc.event.NoNicknameGivenReceived;
66 import net.pterodactylus.irc.event.PrivateMessageReceived;
67 import net.pterodactylus.irc.event.PrivateNoticeReceived;
68 import net.pterodactylus.irc.event.ReplyReceived;
69 import net.pterodactylus.irc.event.UnknownReplyReceived;
70 import net.pterodactylus.irc.util.RandomNickname;
71 import net.pterodactylus.xdcc.util.io.BandwidthCountingInputStream;
72 import net.pterodactylus.xdcc.util.io.BandwidthCountingOutputStream;
74 import com.google.common.base.Optional;
75 import com.google.common.collect.Maps;
76 import com.google.common.collect.Sets;
77 import com.google.common.eventbus.EventBus;
78 import com.google.common.eventbus.Subscribe;
79 import com.google.common.io.Closeables;
80 import com.google.common.primitives.Ints;
81 import com.google.common.primitives.Longs;
82 import com.google.common.util.concurrent.AbstractExecutionThreadService;
83 import com.google.common.util.concurrent.Service;
84 import org.apache.log4j.Logger;
87 * A connection to an IRC server.
89 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
91 public class Connection extends AbstractExecutionThreadService implements Service {
94 private static final Logger logger = Logger.getLogger(Connection.class.getName());
97 private final EventBus eventBus;
99 /** The socket factory. */
100 private final SocketFactory socketFactory;
102 /** The hostname to connect to. */
103 private final String hostname;
105 /** The port to connect to. */
106 private final int port;
108 /** The nickname chooser. */
109 private NicknameChooser nicknameChooser = new NicknameChooser() {
112 public String getNickname() {
113 return RandomNickname.get();
118 private String nickname = null;
121 private Optional<String> username = Optional.absent();
123 /** The real name. */
124 private Optional<String> realName = Optional.absent();
126 /** The optional password for the connection. */
127 private Optional<String> password = Optional.absent();
129 /** The connection handler. */
130 private ConnectionHandler connectionHandler;
132 /** Whether the connection has already been established. */
133 private final AtomicBoolean established = new AtomicBoolean();
136 * Creates a new connection.
140 * @param socketFactory
143 * The hostname of the IRC server
145 * The port number of the IRC server
147 public Connection(EventBus eventBus, SocketFactory socketFactory, String hostname, int port) {
148 this.eventBus = eventBus;
149 this.socketFactory = socketFactory;
150 this.hostname = hostname;
159 * Returns the hostname of the remote end of the connection.
161 * @return The remote’s hostname
163 public String hostname() {
168 * Returns the port number of the remote end of the connection.
170 * @return The remote’s port number
177 * Returns whether this connection has already been established.
179 * @return {@code true} as long as this connection is established, {@code
182 public boolean established() {
183 return established.get();
187 * Returns the nickname that is currently in use by this connection. The
188 * nickname is only available once the connection has been {@link #start()}ed.
190 * @return The current nickname
192 public String nickname() {
201 * Sets the nickname chooser. The nickname chooser is only used during the
202 * creation of the connection.
204 * @param nicknameChooser
205 * The nickname chooser
206 * @return This connection
208 public Connection nicknameChooser(NicknameChooser nicknameChooser) {
209 this.nicknameChooser = nicknameChooser;
214 * Sets the username to use.
217 * The username to use
218 * @return This connection
220 public Connection username(String username) {
221 this.username = Optional.fromNullable(username);
226 * Sets the real name to use.
229 * The real name to use
230 * @return This connection
232 public Connection realName(String realName) {
233 this.realName = Optional.fromNullable(realName);
238 * Sets the optional password for the connection.
241 * The password for the connection
242 * @return This connection
244 public Connection password(String password) {
245 this.password = Optional.fromNullable(password);
254 * Returns the current rate of the connection’s incoming side.
256 * @return The current input rate (in bytes per second)
258 public long getInputRate() {
259 return (connectionHandler != null) ? connectionHandler.getInputRate() : 0;
263 * Returns the current rate of the connection’s outgoing side.
265 * @return The current output rate (in bytes per second)
267 public long getOutputRate() {
268 return (connectionHandler != null) ? connectionHandler.getOutputRate() : 0;
272 * Checks whether the given source is the client represented by this
276 * The source to check
277 * @return {@code true} if this connection represents the given source, {@code
280 public boolean isSource(Source source) {
281 return source.nick().isPresent() && source.nick().get().equals(nickname);
285 * Joins the given channel.
288 * The channel to join
289 * @throws IOException
290 * if an I/O error occurs
292 public void joinChannel(final String channel) throws IOException {
293 connectionHandler.sendCommand("JOIN", channel);
297 * Sends a message to the given recipient, which may be a channel or another
301 * The recipient of the message
304 * @throws IOException
305 * if an I/O error occurs
307 public void sendMessage(String recipient, String message) throws IOException {
308 connectionHandler.sendCommand("PRIVMSG", recipient, message);
312 * Sends a DCC RESUME request to the given recipient.
315 * The recipient of the request
317 * The name of the file to resume
319 * The port number from the original DCC SEND request
321 * The position at which to resume the transfer
322 * @throws IOException
323 * if an I/O error occurs
325 public void sendDccResume(String recipient, String filename, int port, long position) throws IOException {
326 connectionHandler.sendCommand("PRIVMSG", recipient, String.format("\u0001DCC RESUME %s %d %d\u0001", filename, port, position));
330 * Closes this connection.
332 * @throws IOException
333 * if an I/O error occurs
335 public void close() throws IOException {
336 if (connectionHandler != null) {
337 connectionHandler.close();
342 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
346 protected void startUp() throws IllegalStateException {
347 checkState(username.isPresent(), "username must be set");
348 checkState(realName.isPresent(), "realName must be set");
352 protected void run() {
354 /* connect to remote socket. */
356 Socket socket = socketFactory.createSocket(hostname, port);
357 socket.setSoTimeout((int) TimeUnit.MINUTES.toMillis(3));
358 connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
360 /* register connection. */
361 if (password.isPresent()) {
362 connectionHandler.sendCommand("PASSWORD", password.get());
364 connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
365 nickname = nicknameChooser.getNickname();
366 connectionHandler.sendCommand("NICK", nickname);
368 } catch (IOException ioe1) {
369 eventBus.post(new ConnectionFailed(this, ioe1));
373 eventBus.register(this);
374 /* now read replies and react. */
376 /* some status variables. */
377 boolean connected = true;
378 StringBuilder motd = new StringBuilder();
379 Set<Nickname> nicks = Sets.newHashSet();
382 Map<String, String> nickPrefixes = Maps.newHashMap();
383 Set<Character> channelTypes = Sets.newHashSet();
385 List<Handler> handlers = asList(
386 new ConnectionEstablishHandler(eventBus, this),
387 new ChannelNotJoinedHandler(eventBus, this)
391 Reply reply = connectionHandler.readReply();
392 eventBus.post(new ReplyReceived(this, reply));
393 logger.trace(String.format("<< %s", reply));
394 String command = reply.command();
395 List<String> parameters = reply.parameters();
397 for (Handler handler : handlers) {
398 if (handler.willHandle(reply)) {
399 handler.handleReply(reply);
404 /* most common events. */
405 if (command.equalsIgnoreCase("PRIVMSG")) {
406 String recipient = parameters.get(0);
407 String message = parameters.get(1);
408 if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
410 handleCtcp(reply.source().get(), message);
411 } else if (!channelTypes.contains(recipient.charAt(0))) {
412 eventBus.post(new PrivateMessageReceived(this, reply.source().get(), message));
414 eventBus.post(new ChannelMessageReceived(this, recipient, reply.source().get(), message));
417 } else if (command.equalsIgnoreCase("NOTICE")) {
418 String recipient = parameters.get(0);
419 String message = parameters.get(1);
420 if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
422 handleCtcp(reply.source().get(), message);
423 } else if (!channelTypes.contains(recipient.charAt(0))) {
424 eventBus.post(new PrivateNoticeReceived(this, reply));
426 eventBus.post(new ChannelNoticeReceived(this, reply.source().get(), recipient, message));
429 /* 43x replies are for nick change errors. */
430 } else if (command.equals("431")) {
431 eventBus.post(new NoNicknameGivenReceived(this, reply));
432 } else if (command.equals("433")) {
433 if (!established.get()) {
434 nickname = nicknameChooser.getNickname();
435 connectionHandler.sendCommand("NICK", nickname);
437 eventBus.post(new NicknameInUseReceived(this, reply));
441 } else if (command.equalsIgnoreCase("NICK")) {
442 eventBus.post(new NicknameChanged(this, reply.source().get(), parameters.get(0)));
445 } else if (command.equalsIgnoreCase("JOIN")) {
446 eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
447 } else if (command.equals("331")) {
448 /* no topic is set. */
449 } else if (command.equals("332")) {
450 eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
451 } else if (command.equals("353")) {
452 for (String nickname : parameters.get(3).split(" ")) {
453 if (nickPrefixes.containsKey(nickname.substring(0, 1))) {
454 nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
456 nicks.add(new Nickname(nickname, ""));
459 } else if (command.equals("366")) {
460 eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
462 } else if (command.equalsIgnoreCase("PART")) {
463 eventBus.post(new ChannelLeft(this, parameters.get(0), reply.source().get(), getOptional(parameters, 1)));
464 } else if (command.equalsIgnoreCase("QUIT")) {
465 eventBus.post(new ClientQuit(this, reply.source().get(), parameters.get(0)));
467 /* basic connection housekeeping. */
468 } else if (command.equalsIgnoreCase("PING")) {
469 connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
471 /* 005 originally was a bounce message, now used to transmit useful information about the server. */
472 } else if (command.equals("005")) {
473 for (String parameter : parameters) {
474 if (parameter.startsWith("PREFIX=")) {
475 int openParen = parameter.indexOf('(');
476 int closeParen = parameter.indexOf(')');
477 if ((openParen != -1) && (closeParen != -1)) {
478 for (int modeCharacterIndex = 1; modeCharacterIndex < (closeParen - openParen); ++modeCharacterIndex) {
479 char modeCharacter = parameter.charAt(openParen + modeCharacterIndex);
480 char modeSymbol = parameter.charAt(closeParen + modeCharacterIndex);
481 nickPrefixes.put(String.valueOf(modeSymbol), String.valueOf(modeCharacter));
483 logger.debug(String.format("Parsed Prefixes: %s", nickPrefixes));
485 } else if (parameter.startsWith("CHANTYPES=")) {
486 for (int typeIndex = 10; typeIndex < parameter.length(); ++typeIndex) {
487 channelTypes.add(parameter.charAt(typeIndex));
489 logger.debug(String.format("Parsed Channel Types: %s", channelTypes));
493 /* 375, 372, and 376 handle the server’s MOTD. */
494 } else if (command.equals("375")) {
496 motd.append(parameters.get(1)).append('\n');
497 } else if (command.equals("372")) {
498 motd.append(parameters.get(1)).append('\n');
499 } else if (command.equals("376")) {
500 motd.append(parameters.get(1)).append('\n');
501 eventBus.post(new MotdReceived(this, motd.toString()));
504 } else if (command.equalsIgnoreCase("KICK")) {
505 eventBus.post(new KickedFromChannel(this, parameters.get(0), reply.source().get(), parameters.get(1), getOptional(parameters, 2)));
507 /* okay, everything else. */
509 eventBus.post(new UnknownReplyReceived(this, reply));
512 eventBus.post(new ConnectionClosed(this));
513 } catch (IOException ioe1) {
514 logger.warn("I/O error", ioe1);
515 eventBus.post(new ConnectionClosed(this, ioe1));
516 } catch (RuntimeException re1) {
517 logger.error("Runtime error", re1);
518 eventBus.post(new ConnectionClosed(this, re1));
520 established.set(false);
521 eventBus.unregister(this);
522 logger.info("Closing Connection.");
524 Closeables.close(connectionHandler, true);
525 } catch (IOException ioe1) {
526 /* will not be thrown. */
533 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
534 if (connectionEstablished.connection() == this) {
535 established.set(true);
544 * Handles a CTCP message.
547 * The client sending the message
551 private void handleCtcp(Source client, String message) {
552 String[] messageWords = message.substring(1, message.length() - 1).split(" +");
553 String ctcpCommand = messageWords[0];
554 if (ctcpCommand.equalsIgnoreCase("DCC")) {
555 if (messageWords[1].equalsIgnoreCase("SEND")) {
556 Optional<InetAddress> inetAddress = parseInetAddress(messageWords[3]);
557 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[4]));
558 long fileSize = Optional.fromNullable(Longs.tryParse(messageWords[5])).or(-1L);
559 if (inetAddress.isPresent() && port.isPresent()) {
560 eventBus.post(new DccSendReceived(this, client, messageWords[2], inetAddress.get(), port.get(), fileSize));
562 logger.warn(String.format("Received malformed DCC SEND: “%s”", message));
564 } else if (messageWords[1].equalsIgnoreCase("ACCEPT")) {
565 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[3]));
566 long position = (messageWords.length > 4) ? Optional.fromNullable(Longs.tryParse(messageWords[4])).or(-1L) : -1;
567 if (port.isPresent()) {
568 eventBus.post(new DccAcceptReceived(this, client, messageWords[2], port.get(), position));
570 logger.warn(String.format("Received malformed DCC ACCEPT: “%s”", message));
577 * Returns an item from the list, or {@link Optional#absent()} if the list is
578 * shorter than required for the given index.
581 * The list to get an item from
583 * The index of the item
585 * The type of the list items
586 * @return This list item wrapped in an {@link Optional}, or {@link
587 * Optional#absent()} if the list is not long enough
589 private static <T> Optional<T> getOptional(List<T> list, int index) {
590 if (index < list.size()) {
591 return Optional.fromNullable(list.get(index));
593 return Optional.absent();
597 * Parses the given {@code ip} and returns an {@link InetAddress} from it.
601 * @return The parsed inet address, or {@link Optional#absent()} if no inet
602 * address could be parsed
604 private Optional<InetAddress> parseInetAddress(String ip) {
605 Long ipNumber = Longs.tryParse(ip);
606 if (ipNumber == null) {
607 return Optional.absent();
610 StringBuilder hostname = new StringBuilder(15);
611 hostname.append((ipNumber >>> 24) & 0xff).append('.');
612 hostname.append((ipNumber >>> 16) & 0xff).append('.');
613 hostname.append((ipNumber >>> 8) & 0xff).append('.');
614 hostname.append(ipNumber & 0xff);
616 return Optional.of(InetAddress.getByName(hostname.toString()));
617 } catch (UnknownHostException uhe1) {
618 return Optional.absent();
622 /** Handles input and output for the connection. */
623 private class ConnectionHandler implements Closeable {
625 /** The output stream of the connection. */
626 private final BandwidthCountingOutputStream outputStream;
628 /** The input stream. */
629 private final BandwidthCountingInputStream inputStream;
631 /** The input stream of the connection. */
632 private final BufferedReader inputStreamReader;
635 * Creates a new connection handler for the given input stream and output
639 * The input stream of the connection
640 * @param outputStream
641 * The output stream of the connection
642 * @throws UnsupportedEncodingException
643 * if the encoding (currently “UTF-8”) is not valid
645 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
646 this.outputStream = new BandwidthCountingOutputStream(outputStream, 5, SECONDS);
647 this.inputStream = new BandwidthCountingInputStream(inputStream, 5, SECONDS);
648 inputStreamReader = new BufferedReader(new InputStreamReader(this.inputStream, "UTF-8"));
656 * Returns the current rate of the connection’s incoming side.
658 * @return The current input rate (in bytes per second)
660 public long getInputRate() {
661 return inputStream.getCurrentRate();
665 * Returns the current rate of the connection’s outgoing side.
667 * @return The current output rate (in bytes per second)
669 public long getOutputRate() {
670 return outputStream.getCurrentRate();
674 * Sends a command with the given parameters, skipping all {@link
675 * Optional#absent()} optionals.
678 * The command to send
681 * @throws IOException
682 * if an I/O error occurs
684 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
685 List<String> setParameters = new ArrayList<String>();
686 for (Optional<String> maybeSetParameter : parameters) {
687 if (maybeSetParameter.isPresent()) {
688 setParameters.add(maybeSetParameter.get());
691 sendCommand(command, setParameters.toArray(new String[setParameters.size()]));
695 * Sends a command with the given parameters.
698 * The command to send
700 * The parameters of the command
701 * @throws IOException
702 * if an I/O error occurs
703 * @throws IllegalArgumentException
704 * if any parameter but that last contains a space character
706 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
707 StringBuilder commandBuilder = new StringBuilder();
709 commandBuilder.append(command);
710 for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
711 String parameter = parameters[parameterIndex];
712 /* space is only allowed in the last parameter. */
713 commandBuilder.append(' ');
714 if (parameter.contains(" ")) {
715 if (parameterIndex == (parameters.length - 1)) {
716 commandBuilder.append(':');
718 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
721 commandBuilder.append(parameter);
724 logger.trace(String.format(">> %s", commandBuilder));
725 outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
726 outputStream.flush();
730 * Reads a line of reply from the connection.
733 * @throws IOException
734 * if an I/O error occurs
735 * @throws EOFException
738 public Reply readReply() throws IOException, EOFException {
739 String line = inputStreamReader.readLine();
741 throw new EOFException();
744 return Reply.parseLine(line);
752 public void close() throws IOException {
753 Closeables.close(outputStream, true);
754 Closeables.close(inputStreamReader, true);
755 Closeables.close(inputStream, true);