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.concurrent.TimeUnit.SECONDS;
23 import java.io.BufferedReader;
24 import java.io.Closeable;
25 import java.io.EOFException;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.InputStreamReader;
29 import java.io.OutputStream;
30 import java.io.UnsupportedEncodingException;
31 import java.net.InetAddress;
32 import java.net.Socket;
33 import java.net.UnknownHostException;
34 import java.util.ArrayList;
35 import java.util.List;
38 import java.util.concurrent.TimeUnit;
39 import java.util.logging.Level;
40 import java.util.logging.Logger;
41 import javax.net.SocketFactory;
43 import net.pterodactylus.irc.event.ChannelJoined;
44 import net.pterodactylus.irc.event.ChannelLeft;
45 import net.pterodactylus.irc.event.ChannelMessageReceived;
46 import net.pterodactylus.irc.event.ChannelNicknames;
47 import net.pterodactylus.irc.event.ChannelNotJoined;
48 import net.pterodactylus.irc.event.ChannelNotJoined.Reason;
49 import net.pterodactylus.irc.event.ChannelNoticeReceived;
50 import net.pterodactylus.irc.event.ChannelTopic;
51 import net.pterodactylus.irc.event.ClientQuit;
52 import net.pterodactylus.irc.event.ConnectionClosed;
53 import net.pterodactylus.irc.event.ConnectionEstablished;
54 import net.pterodactylus.irc.event.ConnectionFailed;
55 import net.pterodactylus.irc.event.DccAcceptReceived;
56 import net.pterodactylus.irc.event.DccSendReceived;
57 import net.pterodactylus.irc.event.MotdReceived;
58 import net.pterodactylus.irc.event.NicknameChanged;
59 import net.pterodactylus.irc.event.NicknameInUseReceived;
60 import net.pterodactylus.irc.event.NoNicknameGivenReceived;
61 import net.pterodactylus.irc.event.PrivateMessageReceived;
62 import net.pterodactylus.irc.event.PrivateNoticeReceived;
63 import net.pterodactylus.irc.event.ReplyReceived;
64 import net.pterodactylus.irc.event.UnknownReplyReceived;
65 import net.pterodactylus.irc.util.RandomNickname;
66 import net.pterodactylus.xdcc.util.io.BandwidthCountingInputStream;
67 import net.pterodactylus.xdcc.util.io.BandwidthCountingOutputStream;
69 import com.google.common.base.Optional;
70 import com.google.common.collect.Maps;
71 import com.google.common.collect.Sets;
72 import com.google.common.eventbus.EventBus;
73 import com.google.common.io.Closeables;
74 import com.google.common.primitives.Ints;
75 import com.google.common.primitives.Longs;
76 import com.google.common.util.concurrent.AbstractExecutionThreadService;
77 import com.google.common.util.concurrent.Service;
80 * A connection to an IRC server.
82 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
84 public class Connection extends AbstractExecutionThreadService implements Service {
87 private static final Logger logger = Logger.getLogger(Connection.class.getName());
90 private final EventBus eventBus;
92 /** The socket factory. */
93 private final SocketFactory socketFactory;
95 /** The hostname to connect to. */
96 private final String hostname;
98 /** The port to connect to. */
99 private final int port;
101 /** The nickname chooser. */
102 private NicknameChooser nicknameChooser = new NicknameChooser() {
105 public String getNickname() {
106 return RandomNickname.get();
111 private String nickname = null;
114 private Optional<String> username = Optional.absent();
116 /** The real name. */
117 private Optional<String> realName = Optional.absent();
119 /** The optional password for the connection. */
120 private Optional<String> password = Optional.absent();
122 /** The connection handler. */
123 private ConnectionHandler connectionHandler;
125 /** Whether the connection has already been established. */
126 private boolean established;
129 * Creates a new connection.
133 * @param socketFactory
136 * The hostname of the IRC server
138 * The port number of the IRC server
140 public Connection(EventBus eventBus, SocketFactory socketFactory, String hostname, int port) {
141 this.eventBus = eventBus;
142 this.socketFactory = socketFactory;
143 this.hostname = hostname;
152 * Returns the hostname of the remote end of the connection.
154 * @return The remote’s hostname
156 public String hostname() {
161 * Returns the port number of the remote end of the connection.
163 * @return The remote’s port number
170 * Returns whether this connection has already been established.
172 * @return {@code true} as long as this connection is established, {@code
175 public boolean established() {
180 * Returns the nickname that is currently in use by this connection. The
181 * nickname is only available once the connection has been {@link #start()}ed.
183 * @return The current nickname
185 public String nickname() {
194 * Sets the nickname chooser. The nickname chooser is only used during the
195 * creation of the connection.
197 * @param nicknameChooser
198 * The nickname chooser
199 * @return This connection
201 public Connection nicknameChooser(NicknameChooser nicknameChooser) {
202 this.nicknameChooser = nicknameChooser;
207 * Sets the username to use.
210 * The username to use
211 * @return This connection
213 public Connection username(String username) {
214 this.username = Optional.fromNullable(username);
219 * Sets the real name to use.
222 * The real name to use
223 * @return This connection
225 public Connection realName(String realName) {
226 this.realName = Optional.fromNullable(realName);
231 * Sets the optional password for the connection.
234 * The password for the connection
235 * @return This connection
237 public Connection password(String password) {
238 this.password = Optional.fromNullable(password);
247 * Returns the current rate of the connection’s incoming side.
249 * @return The current input rate (in bytes per second)
251 public long getInputRate() {
252 return (connectionHandler != null) ? connectionHandler.getInputRate() : 0;
256 * Returns the current rate of the connection’s outgoing side.
258 * @return The current output rate (in bytes per second)
260 public long getOutputRate() {
261 return (connectionHandler != null) ? connectionHandler.getOutputRate() : 0;
265 * Checks whether the given source is the client represented by this
269 * The source to check
270 * @return {@code true} if this connection represents the given source, {@code
273 public boolean isSource(Source source) {
274 return source.nick().isPresent() && source.nick().get().equals(nickname);
278 * Joins the given channel.
281 * The channel to join
282 * @throws IOException
283 * if an I/O error occurs
285 public void joinChannel(final String channel) throws IOException {
286 connectionHandler.sendCommand("JOIN", channel);
290 * Sends a message to the given recipient, which may be a channel or another
294 * The recipient of the message
297 * @throws IOException
298 * if an I/O error occurs
300 public void sendMessage(String recipient, String message) throws IOException {
301 connectionHandler.sendCommand("PRIVMSG", recipient, message);
305 * Sends a DCC RESUME request to the given recipient.
308 * The recipient of the request
310 * The name of the file to resume
312 * The port number from the original DCC SEND request
314 * The position at which to resume the transfer
315 * @throws IOException
316 * if an I/O error occurs
318 public void sendDccResume(String recipient, String filename, int port, long position) throws IOException {
319 connectionHandler.sendCommand("PRIVMSG", recipient, String.format("\u0001DCC RESUME %s %d %d\u0001", filename, port, position));
323 * Closes this connection.
325 * @throws IOException
326 * if an I/O error occurs
328 public void close() throws IOException {
329 if (connectionHandler != null) {
330 connectionHandler.close();
335 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
339 protected void startUp() throws IllegalStateException {
340 checkState(username.isPresent(), "username must be set");
341 checkState(realName.isPresent(), "realName must be set");
345 protected void run() {
347 /* connect to remote socket. */
349 Socket socket = socketFactory.createSocket(hostname, port);
350 socket.setSoTimeout((int) TimeUnit.MINUTES.toMillis(3));
351 connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
353 /* register connection. */
354 if (password.isPresent()) {
355 connectionHandler.sendCommand("PASSWORD", password.get());
357 connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
358 nickname = nicknameChooser.getNickname();
359 connectionHandler.sendCommand("NICK", nickname);
361 } catch (IOException ioe1) {
362 eventBus.post(new ConnectionFailed(this, ioe1));
366 /* now read replies and react. */
368 /* some status variables. */
369 int oldConnectionStatus = 0;
370 int connectionStatus = 0;
371 boolean connected = true;
372 StringBuilder motd = new StringBuilder();
373 Set<Nickname> nicks = Sets.newHashSet();
376 Map<String, String> nickPrefixes = Maps.newHashMap();
377 Set<Character> channelTypes = Sets.newHashSet();
380 Reply reply = connectionHandler.readReply();
381 eventBus.post(new ReplyReceived(this, reply));
382 logger.finest(String.format("<< %s", reply));
383 String command = reply.command();
384 List<String> parameters = reply.parameters();
386 /* most common events. */
387 if (command.equalsIgnoreCase("PRIVMSG")) {
388 String recipient = parameters.get(0);
389 String message = parameters.get(1);
390 if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
392 handleCtcp(reply.source().get(), message);
393 } else if (!channelTypes.contains(recipient.charAt(0))) {
394 eventBus.post(new PrivateMessageReceived(this, reply.source().get(), message));
396 eventBus.post(new ChannelMessageReceived(this, recipient, reply.source().get(), message));
399 } else if (command.equalsIgnoreCase("NOTICE")) {
400 String recipient = parameters.get(0);
401 String message = parameters.get(1);
402 if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
404 handleCtcp(reply.source().get(), message);
405 } else if (!channelTypes.contains(recipient.charAt(0))) {
406 eventBus.post(new PrivateNoticeReceived(this, reply));
408 eventBus.post(new ChannelNoticeReceived(this, reply.source().get(), recipient, message));
411 /* 43x replies are for nick change errors. */
412 } else if (command.equals("431")) {
413 eventBus.post(new NoNicknameGivenReceived(this, reply));
414 } else if (command.equals("433")) {
415 if (connectionStatus == 0) {
416 nickname = nicknameChooser.getNickname();
417 connectionHandler.sendCommand("NICK", nickname);
419 eventBus.post(new NicknameInUseReceived(this, reply));
423 } else if (command.equalsIgnoreCase("NICK")) {
424 eventBus.post(new NicknameChanged(this, reply.source().get(), parameters.get(0)));
427 } else if (command.equalsIgnoreCase("JOIN")) {
428 eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
429 } else if (command.equals("331")) {
430 /* no topic is set. */
431 } else if (command.equals("332")) {
432 eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
433 } else if (command.equals("353")) {
434 for (String nickname : parameters.get(3).split(" ")) {
435 if (nickPrefixes.containsKey(nickname.substring(0, 1))) {
436 nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
438 nicks.add(new Nickname(nickname, ""));
441 } else if (command.equals("366")) {
442 eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
444 } else if (command.equalsIgnoreCase("PART")) {
445 eventBus.post(new ChannelLeft(this, parameters.get(0), reply.source().get(), getOptional(parameters, 1)));
446 } else if (command.equalsIgnoreCase("QUIT")) {
447 eventBus.post(new ClientQuit(this, reply.source().get(), parameters.get(0)));
449 /* common channel join errors. */
450 } else if (command.equals("474")) {
451 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.banned));
452 } else if (command.equals("473")) {
453 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.inviteOnly));
454 } else if (command.equals("475")) {
455 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.badChannelKey));
457 /* basic connection housekeeping. */
458 } else if (command.equalsIgnoreCase("PING")) {
459 connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
461 /* replies 001-004 don’t hold information but they have to be sent on a successful connection. */
462 } else if (command.equals("001")) {
463 connectionStatus |= 0x01;
464 } else if (command.equals("002")) {
465 connectionStatus |= 0x02;
466 } else if (command.equals("003")) {
467 connectionStatus |= 0x04;
468 } else if (command.equals("004")) {
469 connectionStatus |= 0x08;
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.fine(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.fine(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 /* okay, everything else. */
506 eventBus.post(new UnknownReplyReceived(this, reply));
509 if ((connectionStatus == 0x0f) && (connectionStatus != oldConnectionStatus)) {
510 /* connection succeeded! */
512 eventBus.post(new ConnectionEstablished(this));
514 oldConnectionStatus = connectionStatus;
516 eventBus.post(new ConnectionClosed(this));
517 } catch (IOException ioe1) {
518 logger.log(Level.WARNING, "I/O error", ioe1);
519 eventBus.post(new ConnectionClosed(this, ioe1));
520 } catch (RuntimeException re1) {
521 logger.log(Level.SEVERE, "Runtime error", re1);
522 eventBus.post(new ConnectionClosed(this, re1));
525 logger.info("Closing Connection.");
527 Closeables.close(connectionHandler, true);
528 } catch (IOException ioe1) {
529 /* will not be thrown. */
540 * Handles a CTCP message.
543 * The client sending the message
547 private void handleCtcp(Source client, String message) {
548 String[] messageWords = message.substring(1, message.length() - 1).split(" +");
549 String ctcpCommand = messageWords[0];
550 if (ctcpCommand.equalsIgnoreCase("DCC")) {
551 if (messageWords[1].equalsIgnoreCase("SEND")) {
552 Optional<InetAddress> inetAddress = parseInetAddress(messageWords[3]);
553 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[4]));
554 long fileSize = Optional.fromNullable(Longs.tryParse(messageWords[5])).or(-1L);
555 if (inetAddress.isPresent() && port.isPresent()) {
556 eventBus.post(new DccSendReceived(this, client, messageWords[2], inetAddress.get(), port.get(), fileSize));
558 logger.warning(String.format("Received malformed DCC SEND: “%s”", message));
560 } else if (messageWords[1].equalsIgnoreCase("ACCEPT")) {
561 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[3]));
562 long position = (messageWords.length > 4) ? Optional.fromNullable(Longs.tryParse(messageWords[4])).or(-1L) : -1;
563 if (port.isPresent()) {
564 eventBus.post(new DccAcceptReceived(this, client, messageWords[2], port.get(), position));
566 logger.warning(String.format("Received malformed DCC ACCEPT: “%s”", message));
573 * Returns an item from the list, or {@link Optional#absent()} if the list is
574 * shorter than required for the given index.
577 * The list to get an item from
579 * The index of the item
581 * The type of the list items
582 * @return This list item wrapped in an {@link Optional}, or {@link
583 * Optional#absent()} if the list is not long enough
585 private static <T> Optional<T> getOptional(List<T> list, int index) {
586 if (index < list.size()) {
587 return Optional.fromNullable(list.get(index));
589 return Optional.absent();
593 * Parses the given {@code ip} and returns an {@link InetAddress} from it.
597 * @return The parsed inet address, or {@link Optional#absent()} if no inet
598 * address could be parsed
600 private Optional<InetAddress> parseInetAddress(String ip) {
601 Long ipNumber = Longs.tryParse(ip);
602 if (ipNumber == null) {
603 return Optional.absent();
606 StringBuilder hostname = new StringBuilder(15);
607 hostname.append((ipNumber >>> 24) & 0xff).append('.');
608 hostname.append((ipNumber >>> 16) & 0xff).append('.');
609 hostname.append((ipNumber >>> 8) & 0xff).append('.');
610 hostname.append(ipNumber & 0xff);
612 return Optional.of(InetAddress.getByName(hostname.toString()));
613 } catch (UnknownHostException uhe1) {
614 return Optional.absent();
618 /** Handles input and output for the connection. */
619 private class ConnectionHandler implements Closeable {
621 /** The output stream of the connection. */
622 private final BandwidthCountingOutputStream outputStream;
624 /** The input stream. */
625 private final BandwidthCountingInputStream inputStream;
627 /** The input stream of the connection. */
628 private final BufferedReader inputStreamReader;
631 * Creates a new connection handler for the given input stream and output
635 * The input stream of the connection
636 * @param outputStream
637 * The output stream of the connection
638 * @throws UnsupportedEncodingException
639 * if the encoding (currently “UTF-8”) is not valid
641 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
642 this.outputStream = new BandwidthCountingOutputStream(outputStream, 5, SECONDS);
643 this.inputStream = new BandwidthCountingInputStream(inputStream, 5, SECONDS);
644 inputStreamReader = new BufferedReader(new InputStreamReader(this.inputStream, "UTF-8"));
652 * Returns the current rate of the connection’s incoming side.
654 * @return The current input rate (in bytes per second)
656 public long getInputRate() {
657 return inputStream.getCurrentRate();
661 * Returns the current rate of the connection’s outgoing side.
663 * @return The current output rate (in bytes per second)
665 public long getOutputRate() {
666 return outputStream.getCurrentRate();
670 * Sends a command with the given parameters, skipping all {@link
671 * Optional#absent()} optionals.
674 * The command to send
677 * @throws IOException
678 * if an I/O error occurs
680 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
681 List<String> setParameters = new ArrayList<String>();
682 for (Optional<String> maybeSetParameter : parameters) {
683 if (maybeSetParameter.isPresent()) {
684 setParameters.add(maybeSetParameter.get());
687 sendCommand(command, setParameters.toArray(new String[setParameters.size()]));
691 * Sends a command with the given parameters.
694 * The command to send
696 * The parameters of the command
697 * @throws IOException
698 * if an I/O error occurs
699 * @throws IllegalArgumentException
700 * if any parameter but that last contains a space character
702 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
703 StringBuilder commandBuilder = new StringBuilder();
705 commandBuilder.append(command);
706 for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
707 String parameter = parameters[parameterIndex];
708 /* space is only allowed in the last parameter. */
709 commandBuilder.append(' ');
710 if (parameter.contains(" ")) {
711 if (parameterIndex == (parameters.length - 1)) {
712 commandBuilder.append(':');
714 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
717 commandBuilder.append(parameter);
720 logger.finest(String.format(">> %s", commandBuilder));
721 outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
722 outputStream.flush();
726 * Reads a line of reply from the connection.
729 * @throws IOException
730 * if an I/O error occurs
731 * @throws EOFException
734 public Reply readReply() throws IOException, EOFException {
735 String line = inputStreamReader.readLine();
737 throw new EOFException();
740 return Reply.parseLine(line);
748 public void close() throws IOException {
749 Closeables.close(outputStream, true);
750 Closeables.close(inputStreamReader, true);
751 Closeables.close(inputStream, true);