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.logging.Level;
39 import java.util.logging.Logger;
40 import javax.net.SocketFactory;
42 import net.pterodactylus.irc.event.ChannelJoined;
43 import net.pterodactylus.irc.event.ChannelLeft;
44 import net.pterodactylus.irc.event.ChannelMessageReceived;
45 import net.pterodactylus.irc.event.ChannelNicknames;
46 import net.pterodactylus.irc.event.ChannelNotJoined;
47 import net.pterodactylus.irc.event.ChannelNotJoined.Reason;
48 import net.pterodactylus.irc.event.ChannelNoticeReceived;
49 import net.pterodactylus.irc.event.ChannelTopic;
50 import net.pterodactylus.irc.event.ClientQuit;
51 import net.pterodactylus.irc.event.ConnectionClosed;
52 import net.pterodactylus.irc.event.ConnectionEstablished;
53 import net.pterodactylus.irc.event.ConnectionFailed;
54 import net.pterodactylus.irc.event.DccAcceptReceived;
55 import net.pterodactylus.irc.event.DccSendReceived;
56 import net.pterodactylus.irc.event.MotdReceived;
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.PrivateMessageReceived;
61 import net.pterodactylus.irc.event.PrivateNoticeReceived;
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;
78 * A connection to an IRC server.
80 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
82 public class Connection extends AbstractExecutionThreadService implements Service {
85 private static final Logger logger = Logger.getLogger(Connection.class.getName());
88 private final EventBus eventBus;
90 /** The socket factory. */
91 private final SocketFactory socketFactory;
93 /** The hostname to connect to. */
94 private final String hostname;
96 /** The port to connect to. */
97 private final int port;
99 /** The nickname chooser. */
100 private NicknameChooser nicknameChooser = new NicknameChooser() {
103 public String getNickname() {
104 return RandomNickname.get();
109 private String nickname = null;
112 private Optional<String> username = Optional.absent();
114 /** The real name. */
115 private Optional<String> realName = Optional.absent();
117 /** The optional password for the connection. */
118 private Optional<String> password = Optional.absent();
120 /** The connection handler. */
121 private ConnectionHandler connectionHandler;
123 /** Whether the connection has already been established. */
124 private boolean established;
127 * Creates a new connection.
131 * @param socketFactory
134 * The hostname of the IRC server
136 * The port number of the IRC server
138 public Connection(EventBus eventBus, SocketFactory socketFactory, String hostname, int port) {
139 this.eventBus = eventBus;
140 this.socketFactory = socketFactory;
141 this.hostname = hostname;
150 * Returns the hostname of the remote end of the connection.
151 * @return The remote’s hostname
153 public String hostname() {
158 * 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() {
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 connectionHandler.close();
329 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
333 protected void startUp() throws IllegalStateException {
334 checkState(username.isPresent(), "username must be set");
335 checkState(realName.isPresent(), "realName must be set");
339 protected void run() {
341 /* connect to remote socket. */
343 Socket socket = socketFactory.createSocket(hostname, port);
344 connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
346 /* register connection. */
347 if (password.isPresent()) {
348 connectionHandler.sendCommand("PASSWORD", password.get());
350 connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
351 nickname = nicknameChooser.getNickname();
352 connectionHandler.sendCommand("NICK", nickname);
354 } catch (IOException ioe1) {
355 eventBus.post(new ConnectionFailed(this, ioe1));
359 /* now read replies and react. */
361 /* some status variables. */
362 int oldConnectionStatus = 0;
363 int connectionStatus = 0;
364 boolean connected = true;
365 StringBuilder motd = new StringBuilder();
366 Set<Nickname> nicks = Sets.newHashSet();
369 Map<String, String> nickPrefixes = Maps.newHashMap();
370 Set<Character> channelTypes = Sets.newHashSet();
373 Reply reply = connectionHandler.readReply();
374 logger.finest(String.format("<< %s", reply));
375 String command = reply.command();
376 List<String> parameters = reply.parameters();
378 /* most common events. */
379 if (command.equalsIgnoreCase("PRIVMSG")) {
380 String recipient = parameters.get(0);
381 String message = parameters.get(1);
382 if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
384 handleCtcp(reply.source().get(), message);
385 } else if (!channelTypes.contains(recipient.charAt(0))) {
386 eventBus.post(new PrivateMessageReceived(this, reply.source().get(), message));
388 eventBus.post(new ChannelMessageReceived(this, recipient, reply.source().get(), message));
391 } else if (command.equalsIgnoreCase("NOTICE")) {
392 String recipient = parameters.get(0);
393 String message = parameters.get(1);
394 if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
396 handleCtcp(reply.source().get(), message);
397 } else if (!channelTypes.contains(recipient.charAt(0))) {
398 eventBus.post(new PrivateNoticeReceived(this, reply));
400 eventBus.post(new ChannelNoticeReceived(this, reply.source().get(), recipient, message));
403 /* 43x replies are for nick change errors. */
404 } else if (command.equals("431")) {
405 eventBus.post(new NoNicknameGivenReceived(this, reply));
406 } else if (command.equals("433")) {
407 if (connectionStatus == 0) {
408 nickname = nicknameChooser.getNickname();
409 connectionHandler.sendCommand("NICK", nickname);
411 eventBus.post(new NicknameInUseReceived(this, reply));
415 } else if (command.equalsIgnoreCase("NICK")) {
416 eventBus.post(new NicknameChanged(this, reply.source().get(), parameters.get(0)));
419 } else if (command.equalsIgnoreCase("JOIN")) {
420 eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
421 } else if (command.equals("331")) {
422 /* no topic is set. */
423 } else if (command.equals("332")) {
424 eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
425 } else if (command.equals("353")) {
426 for (String nickname : parameters.get(3).split(" ")) {
427 if (nickPrefixes.containsKey(nickname.substring(0, 1))) {
428 nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
430 nicks.add(new Nickname(nickname, ""));
433 } else if (command.equals("366")) {
434 eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
436 } else if (command.equalsIgnoreCase("PART")) {
437 eventBus.post(new ChannelLeft(this, parameters.get(0), reply.source().get(), getOptional(parameters, 1)));
438 } else if (command.equalsIgnoreCase("QUIT")) {
439 eventBus.post(new ClientQuit(this, reply.source().get(), parameters.get(0)));
441 /* common channel join errors. */
442 } else if (command.equals("474")) {
443 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.banned));
444 } else if (command.equals("473")) {
445 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.inviteOnly));
446 } else if (command.equals("475")) {
447 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.badChannelKey));
449 /* basic connection housekeeping. */
450 } else if (command.equalsIgnoreCase("PING")) {
451 connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
453 /* replies 001-004 don’t hold information but they have to be sent on a successful connection. */
454 } else if (command.equals("001")) {
455 connectionStatus |= 0x01;
456 } else if (command.equals("002")) {
457 connectionStatus |= 0x02;
458 } else if (command.equals("003")) {
459 connectionStatus |= 0x04;
460 } else if (command.equals("004")) {
461 connectionStatus |= 0x08;
463 /* 005 originally was a bounce message, now used to transmit useful information about the server. */
464 } else if (command.equals("005")) {
465 for (String parameter : parameters) {
466 if (parameter.startsWith("PREFIX=")) {
467 int openParen = parameter.indexOf('(');
468 int closeParen = parameter.indexOf(')');
469 if ((openParen != -1) && (closeParen != -1)) {
470 for (int modeCharacterIndex = 1; modeCharacterIndex < (closeParen - openParen); ++modeCharacterIndex) {
471 char modeCharacter = parameter.charAt(openParen + modeCharacterIndex);
472 char modeSymbol = parameter.charAt(closeParen + modeCharacterIndex);
473 nickPrefixes.put(String.valueOf(modeSymbol), String.valueOf(modeCharacter));
475 logger.fine(String.format("Parsed Prefixes: %s", nickPrefixes));
477 } else if (parameter.startsWith("CHANTYPES=")) {
478 for (int typeIndex = 10; typeIndex < parameter.length(); ++typeIndex) {
479 channelTypes.add(parameter.charAt(typeIndex));
481 logger.fine(String.format("Parsed Channel Types: %s", channelTypes));
485 /* 375, 372, and 376 handle the server’s MOTD. */
486 } else if (command.equals("375")) {
488 motd.append(parameters.get(1)).append('\n');
489 } else if (command.equals("372")) {
490 motd.append(parameters.get(1)).append('\n');
491 } else if (command.equals("376")) {
492 motd.append(parameters.get(1)).append('\n');
493 eventBus.post(new MotdReceived(this, motd.toString()));
496 /* okay, everything else. */
498 eventBus.post(new UnknownReplyReceived(this, reply));
501 if ((connectionStatus == 0x0f) && (connectionStatus != oldConnectionStatus)) {
502 /* connection succeeded! */
504 eventBus.post(new ConnectionEstablished(this));
506 oldConnectionStatus = connectionStatus;
508 eventBus.post(new ConnectionClosed(this));
509 } catch (IOException ioe1) {
510 logger.log(Level.WARNING, "I/O error", ioe1);
511 eventBus.post(new ConnectionClosed(this, ioe1));
514 logger.info("Closing Connection.");
516 Closeables.close(connectionHandler, true);
517 } catch (IOException ioe1) {
518 /* will not be thrown. */
529 * Handles a CTCP message.
532 * The client sending the message
536 private void handleCtcp(Source client, String message) {
537 String[] messageWords = message.substring(1, message.length() - 1).split(" +");
538 String ctcpCommand = messageWords[0];
539 if (ctcpCommand.equalsIgnoreCase("DCC")) {
540 if (messageWords[1].equalsIgnoreCase("SEND")) {
541 Optional<InetAddress> inetAddress = parseInetAddress(messageWords[3]);
542 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[4]));
543 long fileSize = Optional.fromNullable(Longs.tryParse(messageWords[5])).or(-1L);
544 if (inetAddress.isPresent() && port.isPresent()) {
545 eventBus.post(new DccSendReceived(this, client, messageWords[2], inetAddress.get(), port.get(), fileSize));
547 logger.warning(String.format("Received malformed DCC SEND: “%s”", message));
549 } else if (messageWords[1].equalsIgnoreCase("ACCEPT")) {
550 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[3]));
551 long position = Optional.fromNullable(Longs.tryParse(messageWords[4])).or(-1L);
552 if (port.isPresent()) {
553 eventBus.post(new DccAcceptReceived(this, client, messageWords[2], port.get(), position));
555 logger.warning(String.format("Received malformed DCC ACCEPT: “%s”", message));
562 * Returns an item from the list, or {@link Optional#absent()} if the list is
563 * shorter than required for the given index.
566 * The list to get an item from
568 * The index of the item
570 * The type of the list items
571 * @return This list item wrapped in an {@link Optional}, or {@link
572 * Optional#absent()} if the list is not long enough
574 private static <T> Optional<T> getOptional(List<T> list, int index) {
575 if (index < list.size()) {
576 return Optional.fromNullable(list.get(index));
578 return Optional.absent();
582 * Parses the given {@code ip} and returns an {@link InetAddress} from it.
586 * @return The parsed inet address, or {@link Optional#absent()} if no inet
587 * address could be parsed
589 private Optional<InetAddress> parseInetAddress(String ip) {
590 Long ipNumber = Longs.tryParse(ip);
591 if (ipNumber == null) {
592 return Optional.absent();
595 StringBuilder hostname = new StringBuilder(15);
596 hostname.append((ipNumber >>> 24) & 0xff).append('.');
597 hostname.append((ipNumber >>> 16) & 0xff).append('.');
598 hostname.append((ipNumber >>> 8) & 0xff).append('.');
599 hostname.append(ipNumber & 0xff);
601 return Optional.of(InetAddress.getByName(hostname.toString()));
602 } catch (UnknownHostException uhe1) {
603 return Optional.absent();
607 /** Handles input and output for the connection. */
608 private class ConnectionHandler implements Closeable {
610 /** The output stream of the connection. */
611 private final BandwidthCountingOutputStream outputStream;
613 /** The input stream. */
614 private final BandwidthCountingInputStream inputStream;
616 /** The input stream of the connection. */
617 private final BufferedReader inputStreamReader;
620 * Creates a new connection handler for the given input stream and output
624 * The input stream of the connection
625 * @param outputStream
626 * The output stream of the connection
627 * @throws UnsupportedEncodingException
628 * if the encoding (currently “UTF-8”) is not valid
630 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
631 this.outputStream = new BandwidthCountingOutputStream(outputStream, 5, SECONDS);
632 this.inputStream = new BandwidthCountingInputStream(inputStream, 5, SECONDS);
633 inputStreamReader = new BufferedReader(new InputStreamReader(this.inputStream, "UTF-8"));
641 * Returns the current rate of the connection’s incoming side.
643 * @return The current input rate (in bytes per second)
645 public long getInputRate() {
646 return inputStream.getCurrentRate();
650 * Returns the current rate of the connection’s outgoing side.
652 * @return The current output rate (in bytes per second)
654 public long getOutputRate() {
655 return outputStream.getCurrentRate();
659 * Sends a command with the given parameters, skipping all {@link
660 * Optional#absent()} optionals.
663 * The command to send
666 * @throws IOException
667 * if an I/O error occurs
669 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
670 List<String> setParameters = new ArrayList<String>();
671 for (Optional<String> maybeSetParameter : parameters) {
672 if (maybeSetParameter.isPresent()) {
673 setParameters.add(maybeSetParameter.get());
676 sendCommand(command, setParameters.toArray(new String[setParameters.size()]));
680 * Sends a command with the given parameters.
683 * The command to send
685 * The parameters of the command
686 * @throws IOException
687 * if an I/O error occurs
688 * @throws IllegalArgumentException
689 * if any parameter but that last contains a space character
691 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
692 StringBuilder commandBuilder = new StringBuilder();
694 commandBuilder.append(command);
695 for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
696 String parameter = parameters[parameterIndex];
697 /* space is only allowed in the last parameter. */
698 commandBuilder.append(' ');
699 if (parameter.contains(" ")) {
700 if (parameterIndex == (parameters.length - 1)) {
701 commandBuilder.append(':');
703 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
706 commandBuilder.append(parameter);
709 logger.finest(String.format(">> %s", commandBuilder));
710 outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
711 outputStream.flush();
715 * Reads a line of reply from the connection.
718 * @throws IOException
719 * if an I/O error occurs
720 * @throws EOFException
723 public Reply readReply() throws IOException, EOFException {
724 String line = inputStreamReader.readLine();
726 throw new EOFException();
729 return Reply.parseLine(line);
737 public void close() throws IOException {
738 Closeables.close(outputStream, true);
739 Closeables.close(inputStreamReader, true);