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 javax.net.SocketFactory;
41 import net.pterodactylus.irc.event.ChannelJoined;
42 import net.pterodactylus.irc.event.ChannelLeft;
43 import net.pterodactylus.irc.event.ChannelMessageReceived;
44 import net.pterodactylus.irc.event.ChannelNicknames;
45 import net.pterodactylus.irc.event.ChannelNotJoined;
46 import net.pterodactylus.irc.event.ChannelNotJoined.Reason;
47 import net.pterodactylus.irc.event.ChannelNoticeReceived;
48 import net.pterodactylus.irc.event.ChannelTopic;
49 import net.pterodactylus.irc.event.ClientQuit;
50 import net.pterodactylus.irc.event.ConnectionClosed;
51 import net.pterodactylus.irc.event.ConnectionEstablished;
52 import net.pterodactylus.irc.event.ConnectionFailed;
53 import net.pterodactylus.irc.event.DccAcceptReceived;
54 import net.pterodactylus.irc.event.DccSendReceived;
55 import net.pterodactylus.irc.event.MotdReceived;
56 import net.pterodactylus.irc.event.NicknameChanged;
57 import net.pterodactylus.irc.event.NicknameInUseReceived;
58 import net.pterodactylus.irc.event.NoNicknameGivenReceived;
59 import net.pterodactylus.irc.event.PrivateMessageReceived;
60 import net.pterodactylus.irc.event.PrivateNoticeReceived;
61 import net.pterodactylus.irc.event.ReplyReceived;
62 import net.pterodactylus.irc.event.UnknownReplyReceived;
63 import net.pterodactylus.irc.util.RandomNickname;
64 import net.pterodactylus.xdcc.util.io.BandwidthCountingInputStream;
65 import net.pterodactylus.xdcc.util.io.BandwidthCountingOutputStream;
67 import com.google.common.base.Optional;
68 import com.google.common.collect.Maps;
69 import com.google.common.collect.Sets;
70 import com.google.common.eventbus.EventBus;
71 import com.google.common.io.Closeables;
72 import com.google.common.primitives.Ints;
73 import com.google.common.primitives.Longs;
74 import com.google.common.util.concurrent.AbstractExecutionThreadService;
75 import com.google.common.util.concurrent.Service;
76 import org.apache.log4j.Logger;
79 * A connection to an IRC server.
81 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
83 public class Connection extends AbstractExecutionThreadService implements Service {
86 private static final Logger logger = Logger.getLogger(Connection.class.getName());
89 private final EventBus eventBus;
91 /** The socket factory. */
92 private final SocketFactory socketFactory;
94 /** The hostname to connect to. */
95 private final String hostname;
97 /** The port to connect to. */
98 private final int port;
100 /** The nickname chooser. */
101 private NicknameChooser nicknameChooser = new NicknameChooser() {
104 public String getNickname() {
105 return RandomNickname.get();
110 private String nickname = null;
113 private Optional<String> username = Optional.absent();
115 /** The real name. */
116 private Optional<String> realName = Optional.absent();
118 /** The optional password for the connection. */
119 private Optional<String> password = Optional.absent();
121 /** The connection handler. */
122 private ConnectionHandler connectionHandler;
124 /** Whether the connection has already been established. */
125 private boolean established;
128 * Creates a new connection.
132 * @param socketFactory
135 * The hostname of the IRC server
137 * The port number of the IRC server
139 public Connection(EventBus eventBus, SocketFactory socketFactory, String hostname, int port) {
140 this.eventBus = eventBus;
141 this.socketFactory = socketFactory;
142 this.hostname = hostname;
151 * Returns the hostname of the remote end of the connection.
153 * @return The remote’s hostname
155 public String hostname() {
160 * Returns the port number of the remote end of the connection.
162 * @return The remote’s port number
169 * Returns whether this connection has already been established.
171 * @return {@code true} as long as this connection is established, {@code
174 public boolean established() {
179 * Returns the nickname that is currently in use by this connection. The
180 * nickname is only available once the connection has been {@link #start()}ed.
182 * @return The current nickname
184 public String nickname() {
193 * Sets the nickname chooser. The nickname chooser is only used during the
194 * creation of the connection.
196 * @param nicknameChooser
197 * The nickname chooser
198 * @return This connection
200 public Connection nicknameChooser(NicknameChooser nicknameChooser) {
201 this.nicknameChooser = nicknameChooser;
206 * Sets the username to use.
209 * The username to use
210 * @return This connection
212 public Connection username(String username) {
213 this.username = Optional.fromNullable(username);
218 * Sets the real name to use.
221 * The real name to use
222 * @return This connection
224 public Connection realName(String realName) {
225 this.realName = Optional.fromNullable(realName);
230 * Sets the optional password for the connection.
233 * The password for the connection
234 * @return This connection
236 public Connection password(String password) {
237 this.password = Optional.fromNullable(password);
246 * Returns the current rate of the connection’s incoming side.
248 * @return The current input rate (in bytes per second)
250 public long getInputRate() {
251 return (connectionHandler != null) ? connectionHandler.getInputRate() : 0;
255 * Returns the current rate of the connection’s outgoing side.
257 * @return The current output rate (in bytes per second)
259 public long getOutputRate() {
260 return (connectionHandler != null) ? connectionHandler.getOutputRate() : 0;
264 * Checks whether the given source is the client represented by this
268 * The source to check
269 * @return {@code true} if this connection represents the given source, {@code
272 public boolean isSource(Source source) {
273 return source.nick().isPresent() && source.nick().get().equals(nickname);
277 * Joins the given channel.
280 * The channel to join
281 * @throws IOException
282 * if an I/O error occurs
284 public void joinChannel(final String channel) throws IOException {
285 connectionHandler.sendCommand("JOIN", channel);
289 * Sends a message to the given recipient, which may be a channel or another
293 * The recipient of the message
296 * @throws IOException
297 * if an I/O error occurs
299 public void sendMessage(String recipient, String message) throws IOException {
300 connectionHandler.sendCommand("PRIVMSG", recipient, message);
304 * Sends a DCC RESUME request to the given recipient.
307 * The recipient of the request
309 * The name of the file to resume
311 * The port number from the original DCC SEND request
313 * The position at which to resume the transfer
314 * @throws IOException
315 * if an I/O error occurs
317 public void sendDccResume(String recipient, String filename, int port, long position) throws IOException {
318 connectionHandler.sendCommand("PRIVMSG", recipient, String.format("\u0001DCC RESUME %s %d %d\u0001", filename, port, position));
322 * Closes this connection.
324 * @throws IOException
325 * if an I/O error occurs
327 public void close() throws IOException {
328 if (connectionHandler != null) {
329 connectionHandler.close();
334 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
338 protected void startUp() throws IllegalStateException {
339 checkState(username.isPresent(), "username must be set");
340 checkState(realName.isPresent(), "realName must be set");
344 protected void run() {
346 /* connect to remote socket. */
348 Socket socket = socketFactory.createSocket(hostname, port);
349 socket.setSoTimeout((int) TimeUnit.MINUTES.toMillis(3));
350 connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
352 /* register connection. */
353 if (password.isPresent()) {
354 connectionHandler.sendCommand("PASSWORD", password.get());
356 connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
357 nickname = nicknameChooser.getNickname();
358 connectionHandler.sendCommand("NICK", nickname);
360 } catch (IOException ioe1) {
361 eventBus.post(new ConnectionFailed(this, ioe1));
365 /* now read replies and react. */
367 /* some status variables. */
368 int oldConnectionStatus = 0;
369 int connectionStatus = 0;
370 boolean connected = true;
371 StringBuilder motd = new StringBuilder();
372 Set<Nickname> nicks = Sets.newHashSet();
375 Map<String, String> nickPrefixes = Maps.newHashMap();
376 Set<Character> channelTypes = Sets.newHashSet();
379 Reply reply = connectionHandler.readReply();
380 eventBus.post(new ReplyReceived(this, reply));
381 logger.trace(String.format("<< %s", reply));
382 String command = reply.command();
383 List<String> parameters = reply.parameters();
385 /* most common events. */
386 if (command.equalsIgnoreCase("PRIVMSG")) {
387 String recipient = parameters.get(0);
388 String message = parameters.get(1);
389 if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
391 handleCtcp(reply.source().get(), message);
392 } else if (!channelTypes.contains(recipient.charAt(0))) {
393 eventBus.post(new PrivateMessageReceived(this, reply.source().get(), message));
395 eventBus.post(new ChannelMessageReceived(this, recipient, reply.source().get(), message));
398 } else if (command.equalsIgnoreCase("NOTICE")) {
399 String recipient = parameters.get(0);
400 String message = parameters.get(1);
401 if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
403 handleCtcp(reply.source().get(), message);
404 } else if (!channelTypes.contains(recipient.charAt(0))) {
405 eventBus.post(new PrivateNoticeReceived(this, reply));
407 eventBus.post(new ChannelNoticeReceived(this, reply.source().get(), recipient, message));
410 /* 43x replies are for nick change errors. */
411 } else if (command.equals("431")) {
412 eventBus.post(new NoNicknameGivenReceived(this, reply));
413 } else if (command.equals("433")) {
414 if (connectionStatus == 0) {
415 nickname = nicknameChooser.getNickname();
416 connectionHandler.sendCommand("NICK", nickname);
418 eventBus.post(new NicknameInUseReceived(this, reply));
422 } else if (command.equalsIgnoreCase("NICK")) {
423 eventBus.post(new NicknameChanged(this, reply.source().get(), parameters.get(0)));
426 } else if (command.equalsIgnoreCase("JOIN")) {
427 eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
428 } else if (command.equals("331")) {
429 /* no topic is set. */
430 } else if (command.equals("332")) {
431 eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
432 } else if (command.equals("353")) {
433 for (String nickname : parameters.get(3).split(" ")) {
434 if (nickPrefixes.containsKey(nickname.substring(0, 1))) {
435 nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
437 nicks.add(new Nickname(nickname, ""));
440 } else if (command.equals("366")) {
441 eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
443 } else if (command.equalsIgnoreCase("PART")) {
444 eventBus.post(new ChannelLeft(this, parameters.get(0), reply.source().get(), getOptional(parameters, 1)));
445 } else if (command.equalsIgnoreCase("QUIT")) {
446 eventBus.post(new ClientQuit(this, reply.source().get(), parameters.get(0)));
448 /* common channel join errors. */
449 } else if (command.equals("474")) {
450 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.banned));
451 } else if (command.equals("473")) {
452 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.inviteOnly));
453 } else if (command.equals("475")) {
454 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.badChannelKey));
456 /* basic connection housekeeping. */
457 } else if (command.equalsIgnoreCase("PING")) {
458 connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
460 /* replies 001-004 don’t hold information but they have to be sent on a successful connection. */
461 } else if (command.equals("001")) {
462 connectionStatus |= 0x01;
463 } else if (command.equals("002")) {
464 connectionStatus |= 0x02;
465 } else if (command.equals("003")) {
466 connectionStatus |= 0x04;
467 } else if (command.equals("004")) {
468 connectionStatus |= 0x08;
470 /* 005 originally was a bounce message, now used to transmit useful information about the server. */
471 } else if (command.equals("005")) {
472 for (String parameter : parameters) {
473 if (parameter.startsWith("PREFIX=")) {
474 int openParen = parameter.indexOf('(');
475 int closeParen = parameter.indexOf(')');
476 if ((openParen != -1) && (closeParen != -1)) {
477 for (int modeCharacterIndex = 1; modeCharacterIndex < (closeParen - openParen); ++modeCharacterIndex) {
478 char modeCharacter = parameter.charAt(openParen + modeCharacterIndex);
479 char modeSymbol = parameter.charAt(closeParen + modeCharacterIndex);
480 nickPrefixes.put(String.valueOf(modeSymbol), String.valueOf(modeCharacter));
482 logger.debug(String.format("Parsed Prefixes: %s", nickPrefixes));
484 } else if (parameter.startsWith("CHANTYPES=")) {
485 for (int typeIndex = 10; typeIndex < parameter.length(); ++typeIndex) {
486 channelTypes.add(parameter.charAt(typeIndex));
488 logger.debug(String.format("Parsed Channel Types: %s", channelTypes));
492 /* 375, 372, and 376 handle the server’s MOTD. */
493 } else if (command.equals("375")) {
495 motd.append(parameters.get(1)).append('\n');
496 } else if (command.equals("372")) {
497 motd.append(parameters.get(1)).append('\n');
498 } else if (command.equals("376")) {
499 motd.append(parameters.get(1)).append('\n');
500 eventBus.post(new MotdReceived(this, motd.toString()));
503 /* okay, everything else. */
505 eventBus.post(new UnknownReplyReceived(this, reply));
508 if ((connectionStatus == 0x0f) && (connectionStatus != oldConnectionStatus)) {
509 /* connection succeeded! */
511 eventBus.post(new ConnectionEstablished(this));
513 oldConnectionStatus = connectionStatus;
515 eventBus.post(new ConnectionClosed(this));
516 } catch (IOException ioe1) {
517 logger.warn("I/O error", ioe1);
518 eventBus.post(new ConnectionClosed(this, ioe1));
519 } catch (RuntimeException re1) {
520 logger.error("Runtime error", re1);
521 eventBus.post(new ConnectionClosed(this, re1));
524 logger.info("Closing Connection.");
526 Closeables.close(connectionHandler, true);
527 } catch (IOException ioe1) {
528 /* will not be thrown. */
539 * Handles a CTCP message.
542 * The client sending the message
546 private void handleCtcp(Source client, String message) {
547 String[] messageWords = message.substring(1, message.length() - 1).split(" +");
548 String ctcpCommand = messageWords[0];
549 if (ctcpCommand.equalsIgnoreCase("DCC")) {
550 if (messageWords[1].equalsIgnoreCase("SEND")) {
551 Optional<InetAddress> inetAddress = parseInetAddress(messageWords[3]);
552 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[4]));
553 long fileSize = Optional.fromNullable(Longs.tryParse(messageWords[5])).or(-1L);
554 if (inetAddress.isPresent() && port.isPresent()) {
555 eventBus.post(new DccSendReceived(this, client, messageWords[2], inetAddress.get(), port.get(), fileSize));
557 logger.warn(String.format("Received malformed DCC SEND: “%s”", message));
559 } else if (messageWords[1].equalsIgnoreCase("ACCEPT")) {
560 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[3]));
561 long position = (messageWords.length > 4) ? Optional.fromNullable(Longs.tryParse(messageWords[4])).or(-1L) : -1;
562 if (port.isPresent()) {
563 eventBus.post(new DccAcceptReceived(this, client, messageWords[2], port.get(), position));
565 logger.warn(String.format("Received malformed DCC ACCEPT: “%s”", message));
572 * Returns an item from the list, or {@link Optional#absent()} if the list is
573 * shorter than required for the given index.
576 * The list to get an item from
578 * The index of the item
580 * The type of the list items
581 * @return This list item wrapped in an {@link Optional}, or {@link
582 * Optional#absent()} if the list is not long enough
584 private static <T> Optional<T> getOptional(List<T> list, int index) {
585 if (index < list.size()) {
586 return Optional.fromNullable(list.get(index));
588 return Optional.absent();
592 * Parses the given {@code ip} and returns an {@link InetAddress} from it.
596 * @return The parsed inet address, or {@link Optional#absent()} if no inet
597 * address could be parsed
599 private Optional<InetAddress> parseInetAddress(String ip) {
600 Long ipNumber = Longs.tryParse(ip);
601 if (ipNumber == null) {
602 return Optional.absent();
605 StringBuilder hostname = new StringBuilder(15);
606 hostname.append((ipNumber >>> 24) & 0xff).append('.');
607 hostname.append((ipNumber >>> 16) & 0xff).append('.');
608 hostname.append((ipNumber >>> 8) & 0xff).append('.');
609 hostname.append(ipNumber & 0xff);
611 return Optional.of(InetAddress.getByName(hostname.toString()));
612 } catch (UnknownHostException uhe1) {
613 return Optional.absent();
617 /** Handles input and output for the connection. */
618 private class ConnectionHandler implements Closeable {
620 /** The output stream of the connection. */
621 private final BandwidthCountingOutputStream outputStream;
623 /** The input stream. */
624 private final BandwidthCountingInputStream inputStream;
626 /** The input stream of the connection. */
627 private final BufferedReader inputStreamReader;
630 * Creates a new connection handler for the given input stream and output
634 * The input stream of the connection
635 * @param outputStream
636 * The output stream of the connection
637 * @throws UnsupportedEncodingException
638 * if the encoding (currently “UTF-8”) is not valid
640 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
641 this.outputStream = new BandwidthCountingOutputStream(outputStream, 5, SECONDS);
642 this.inputStream = new BandwidthCountingInputStream(inputStream, 5, SECONDS);
643 inputStreamReader = new BufferedReader(new InputStreamReader(this.inputStream, "UTF-8"));
651 * Returns the current rate of the connection’s incoming side.
653 * @return The current input rate (in bytes per second)
655 public long getInputRate() {
656 return inputStream.getCurrentRate();
660 * Returns the current rate of the connection’s outgoing side.
662 * @return The current output rate (in bytes per second)
664 public long getOutputRate() {
665 return outputStream.getCurrentRate();
669 * Sends a command with the given parameters, skipping all {@link
670 * Optional#absent()} optionals.
673 * The command to send
676 * @throws IOException
677 * if an I/O error occurs
679 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
680 List<String> setParameters = new ArrayList<String>();
681 for (Optional<String> maybeSetParameter : parameters) {
682 if (maybeSetParameter.isPresent()) {
683 setParameters.add(maybeSetParameter.get());
686 sendCommand(command, setParameters.toArray(new String[setParameters.size()]));
690 * Sends a command with the given parameters.
693 * The command to send
695 * The parameters of the command
696 * @throws IOException
697 * if an I/O error occurs
698 * @throws IllegalArgumentException
699 * if any parameter but that last contains a space character
701 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
702 StringBuilder commandBuilder = new StringBuilder();
704 commandBuilder.append(command);
705 for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
706 String parameter = parameters[parameterIndex];
707 /* space is only allowed in the last parameter. */
708 commandBuilder.append(' ');
709 if (parameter.contains(" ")) {
710 if (parameterIndex == (parameters.length - 1)) {
711 commandBuilder.append(':');
713 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
716 commandBuilder.append(parameter);
719 logger.trace(String.format(">> %s", commandBuilder));
720 outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
721 outputStream.flush();
725 * Reads a line of reply from the connection.
728 * @throws IOException
729 * if an I/O error occurs
730 * @throws EOFException
733 public Reply readReply() throws IOException, EOFException {
734 String line = inputStreamReader.readLine();
736 throw new EOFException();
739 return Reply.parseLine(line);
747 public void close() throws IOException {
748 Closeables.close(outputStream, true);
749 Closeables.close(inputStreamReader, true);
750 Closeables.close(inputStream, true);