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.concurrent.atomic.AtomicBoolean;
41 import javax.net.SocketFactory;
43 import net.pterodactylus.irc.connection.ConnectionEstablishHandler;
44 import net.pterodactylus.irc.event.ChannelJoined;
45 import net.pterodactylus.irc.event.ChannelLeft;
46 import net.pterodactylus.irc.event.ChannelMessageReceived;
47 import net.pterodactylus.irc.event.ChannelNicknames;
48 import net.pterodactylus.irc.event.ChannelNotJoined;
49 import net.pterodactylus.irc.event.ChannelNotJoined.Reason;
50 import net.pterodactylus.irc.event.ChannelNoticeReceived;
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.DccAcceptReceived;
57 import net.pterodactylus.irc.event.DccSendReceived;
58 import net.pterodactylus.irc.event.KickedFromChannel;
59 import net.pterodactylus.irc.event.MotdReceived;
60 import net.pterodactylus.irc.event.NicknameChanged;
61 import net.pterodactylus.irc.event.NicknameInUseReceived;
62 import net.pterodactylus.irc.event.NoNicknameGivenReceived;
63 import net.pterodactylus.irc.event.PrivateMessageReceived;
64 import net.pterodactylus.irc.event.PrivateNoticeReceived;
65 import net.pterodactylus.irc.event.ReplyReceived;
66 import net.pterodactylus.irc.event.UnknownReplyReceived;
67 import net.pterodactylus.irc.util.RandomNickname;
68 import net.pterodactylus.xdcc.util.io.BandwidthCountingInputStream;
69 import net.pterodactylus.xdcc.util.io.BandwidthCountingOutputStream;
71 import com.google.common.base.Optional;
72 import com.google.common.collect.Maps;
73 import com.google.common.collect.Sets;
74 import com.google.common.eventbus.EventBus;
75 import com.google.common.eventbus.Subscribe;
76 import com.google.common.io.Closeables;
77 import com.google.common.primitives.Ints;
78 import com.google.common.primitives.Longs;
79 import com.google.common.util.concurrent.AbstractExecutionThreadService;
80 import com.google.common.util.concurrent.Service;
81 import org.apache.log4j.Logger;
84 * A connection to an IRC server.
86 * @author <a href="mailto:bombe@pterodactylus.net">David āBombeā Roden</a>
88 public class Connection extends AbstractExecutionThreadService implements Service {
91 private static final Logger logger = Logger.getLogger(Connection.class.getName());
94 private final EventBus eventBus;
96 /** The socket factory. */
97 private final SocketFactory socketFactory;
99 /** The hostname to connect to. */
100 private final String hostname;
102 /** The port to connect to. */
103 private final int port;
105 /** The nickname chooser. */
106 private NicknameChooser nicknameChooser = new NicknameChooser() {
109 public String getNickname() {
110 return RandomNickname.get();
115 private String nickname = null;
118 private Optional<String> username = Optional.absent();
120 /** The real name. */
121 private Optional<String> realName = Optional.absent();
123 /** The optional password for the connection. */
124 private Optional<String> password = Optional.absent();
126 /** The connection handler. */
127 private ConnectionHandler connectionHandler;
129 /** Whether the connection has already been established. */
130 private final AtomicBoolean established = new AtomicBoolean();
133 * Creates a new connection.
137 * @param socketFactory
140 * The hostname of the IRC server
142 * The port number of the IRC server
144 public Connection(EventBus eventBus, SocketFactory socketFactory, String hostname, int port) {
145 this.eventBus = eventBus;
146 this.socketFactory = socketFactory;
147 this.hostname = hostname;
156 * Returns the hostname of the remote end of the connection.
158 * @return The remoteās hostname
160 public String hostname() {
165 * Returns the port number of the remote end of the connection.
167 * @return The remoteās port number
174 * Returns whether this connection has already been established.
176 * @return {@code true} as long as this connection is established, {@code
179 public boolean established() {
180 return established.get();
184 * Returns the nickname that is currently in use by this connection. The
185 * nickname is only available once the connection has been {@link #start()}ed.
187 * @return The current nickname
189 public String nickname() {
198 * Sets the nickname chooser. The nickname chooser is only used during the
199 * creation of the connection.
201 * @param nicknameChooser
202 * The nickname chooser
203 * @return This connection
205 public Connection nicknameChooser(NicknameChooser nicknameChooser) {
206 this.nicknameChooser = nicknameChooser;
211 * Sets the username to use.
214 * The username to use
215 * @return This connection
217 public Connection username(String username) {
218 this.username = Optional.fromNullable(username);
223 * Sets the real name to use.
226 * The real name to use
227 * @return This connection
229 public Connection realName(String realName) {
230 this.realName = Optional.fromNullable(realName);
235 * Sets the optional password for the connection.
238 * The password for the connection
239 * @return This connection
241 public Connection password(String password) {
242 this.password = Optional.fromNullable(password);
251 * Returns the current rate of the connectionās incoming side.
253 * @return The current input rate (in bytes per second)
255 public long getInputRate() {
256 return (connectionHandler != null) ? connectionHandler.getInputRate() : 0;
260 * Returns the current rate of the connectionās outgoing side.
262 * @return The current output rate (in bytes per second)
264 public long getOutputRate() {
265 return (connectionHandler != null) ? connectionHandler.getOutputRate() : 0;
269 * Checks whether the given source is the client represented by this
273 * The source to check
274 * @return {@code true} if this connection represents the given source, {@code
277 public boolean isSource(Source source) {
278 return source.nick().isPresent() && source.nick().get().equals(nickname);
282 * Joins the given channel.
285 * The channel to join
286 * @throws IOException
287 * if an I/O error occurs
289 public void joinChannel(final String channel) throws IOException {
290 connectionHandler.sendCommand("JOIN", channel);
294 * Sends a message to the given recipient, which may be a channel or another
298 * The recipient of the message
301 * @throws IOException
302 * if an I/O error occurs
304 public void sendMessage(String recipient, String message) throws IOException {
305 connectionHandler.sendCommand("PRIVMSG", recipient, message);
309 * Sends a DCC RESUME request to the given recipient.
312 * The recipient of the request
314 * The name of the file to resume
316 * The port number from the original DCC SEND request
318 * The position at which to resume the transfer
319 * @throws IOException
320 * if an I/O error occurs
322 public void sendDccResume(String recipient, String filename, int port, long position) throws IOException {
323 connectionHandler.sendCommand("PRIVMSG", recipient, String.format("\u0001DCC RESUME %s %d %d\u0001", filename, port, position));
327 * Closes this connection.
329 * @throws IOException
330 * if an I/O error occurs
332 public void close() throws IOException {
333 if (connectionHandler != null) {
334 connectionHandler.close();
339 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
343 protected void startUp() throws IllegalStateException {
344 checkState(username.isPresent(), "username must be set");
345 checkState(realName.isPresent(), "realName must be set");
349 protected void run() {
351 /* connect to remote socket. */
353 Socket socket = socketFactory.createSocket(hostname, port);
354 socket.setSoTimeout((int) TimeUnit.MINUTES.toMillis(3));
355 connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
357 /* register connection. */
358 if (password.isPresent()) {
359 connectionHandler.sendCommand("PASSWORD", password.get());
361 connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
362 nickname = nicknameChooser.getNickname();
363 connectionHandler.sendCommand("NICK", nickname);
365 } catch (IOException ioe1) {
366 eventBus.post(new ConnectionFailed(this, ioe1));
370 eventBus.register(this);
371 /* now read replies and react. */
373 /* some status variables. */
374 int oldConnectionStatus = 0;
375 int connectionStatus = 0;
376 boolean connected = true;
377 StringBuilder motd = new StringBuilder();
378 Set<Nickname> nicks = Sets.newHashSet();
381 Map<String, String> nickPrefixes = Maps.newHashMap();
382 Set<Character> channelTypes = Sets.newHashSet();
384 ConnectionEstablishHandler connectionEstablishHandler = new ConnectionEstablishHandler(eventBus, this);
387 Reply reply = connectionHandler.readReply();
388 eventBus.post(new ReplyReceived(this, reply));
389 logger.trace(String.format("<< %s", reply));
390 String command = reply.command();
391 List<String> parameters = reply.parameters();
393 /* most common events. */
394 if (command.equalsIgnoreCase("PRIVMSG")) {
395 String recipient = parameters.get(0);
396 String message = parameters.get(1);
397 if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
399 handleCtcp(reply.source().get(), message);
400 } else if (!channelTypes.contains(recipient.charAt(0))) {
401 eventBus.post(new PrivateMessageReceived(this, reply.source().get(), message));
403 eventBus.post(new ChannelMessageReceived(this, recipient, reply.source().get(), message));
406 } else if (command.equalsIgnoreCase("NOTICE")) {
407 String recipient = parameters.get(0);
408 String message = parameters.get(1);
409 if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
411 handleCtcp(reply.source().get(), message);
412 } else if (!channelTypes.contains(recipient.charAt(0))) {
413 eventBus.post(new PrivateNoticeReceived(this, reply));
415 eventBus.post(new ChannelNoticeReceived(this, reply.source().get(), recipient, message));
418 /* 43x replies are for nick change errors. */
419 } else if (command.equals("431")) {
420 eventBus.post(new NoNicknameGivenReceived(this, reply));
421 } else if (command.equals("433")) {
422 if (connectionStatus == 0) {
423 nickname = nicknameChooser.getNickname();
424 connectionHandler.sendCommand("NICK", nickname);
426 eventBus.post(new NicknameInUseReceived(this, reply));
430 } else if (command.equalsIgnoreCase("NICK")) {
431 eventBus.post(new NicknameChanged(this, reply.source().get(), parameters.get(0)));
434 } else if (command.equalsIgnoreCase("JOIN")) {
435 eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
436 } else if (command.equals("331")) {
437 /* no topic is set. */
438 } else if (command.equals("332")) {
439 eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
440 } else if (command.equals("353")) {
441 for (String nickname : parameters.get(3).split(" ")) {
442 if (nickPrefixes.containsKey(nickname.substring(0, 1))) {
443 nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
445 nicks.add(new Nickname(nickname, ""));
448 } else if (command.equals("366")) {
449 eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
451 } else if (command.equalsIgnoreCase("PART")) {
452 eventBus.post(new ChannelLeft(this, parameters.get(0), reply.source().get(), getOptional(parameters, 1)));
453 } else if (command.equalsIgnoreCase("QUIT")) {
454 eventBus.post(new ClientQuit(this, reply.source().get(), parameters.get(0)));
456 /* common channel join errors. */
457 } else if (command.equals("474")) {
458 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.banned));
459 } else if (command.equals("473")) {
460 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.inviteOnly));
461 } else if (command.equals("475")) {
462 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.badChannelKey));
463 } else if (command.equals("477")) {
464 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.registeredNicknamesOnly));
466 /* basic connection housekeeping. */
467 } else if (command.equalsIgnoreCase("PING")) {
468 connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
470 } else if (connectionEstablishHandler.willHandle(reply)) {
471 connectionEstablishHandler.handleReply(reply);
473 /* 005 originally was a bounce message, now used to transmit useful information about the server. */
474 } else if (command.equals("005")) {
475 for (String parameter : parameters) {
476 if (parameter.startsWith("PREFIX=")) {
477 int openParen = parameter.indexOf('(');
478 int closeParen = parameter.indexOf(')');
479 if ((openParen != -1) && (closeParen != -1)) {
480 for (int modeCharacterIndex = 1; modeCharacterIndex < (closeParen - openParen); ++modeCharacterIndex) {
481 char modeCharacter = parameter.charAt(openParen + modeCharacterIndex);
482 char modeSymbol = parameter.charAt(closeParen + modeCharacterIndex);
483 nickPrefixes.put(String.valueOf(modeSymbol), String.valueOf(modeCharacter));
485 logger.debug(String.format("Parsed Prefixes: %s", nickPrefixes));
487 } else if (parameter.startsWith("CHANTYPES=")) {
488 for (int typeIndex = 10; typeIndex < parameter.length(); ++typeIndex) {
489 channelTypes.add(parameter.charAt(typeIndex));
491 logger.debug(String.format("Parsed Channel Types: %s", channelTypes));
495 /* 375, 372, and 376 handle the serverās MOTD. */
496 } else if (command.equals("375")) {
498 motd.append(parameters.get(1)).append('\n');
499 } else if (command.equals("372")) {
500 motd.append(parameters.get(1)).append('\n');
501 } else if (command.equals("376")) {
502 motd.append(parameters.get(1)).append('\n');
503 eventBus.post(new MotdReceived(this, motd.toString()));
506 } else if (command.equalsIgnoreCase("KICK")) {
507 eventBus.post(new KickedFromChannel(this, parameters.get(0), reply.source().get(), parameters.get(1), getOptional(parameters, 2)));
509 /* okay, everything else. */
511 eventBus.post(new UnknownReplyReceived(this, reply));
514 eventBus.post(new ConnectionClosed(this));
515 } catch (IOException ioe1) {
516 logger.warn("I/O error", ioe1);
517 eventBus.post(new ConnectionClosed(this, ioe1));
518 } catch (RuntimeException re1) {
519 logger.error("Runtime error", re1);
520 eventBus.post(new ConnectionClosed(this, re1));
522 established.set(false);
523 eventBus.unregister(this);
524 logger.info("Closing Connection.");
526 Closeables.close(connectionHandler, true);
527 } catch (IOException ioe1) {
528 /* will not be thrown. */
535 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
536 if (connectionEstablished.connection() == this) {
537 established.set(true);
546 * Handles a CTCP message.
549 * The client sending the message
553 private void handleCtcp(Source client, String message) {
554 String[] messageWords = message.substring(1, message.length() - 1).split(" +");
555 String ctcpCommand = messageWords[0];
556 if (ctcpCommand.equalsIgnoreCase("DCC")) {
557 if (messageWords[1].equalsIgnoreCase("SEND")) {
558 Optional<InetAddress> inetAddress = parseInetAddress(messageWords[3]);
559 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[4]));
560 long fileSize = Optional.fromNullable(Longs.tryParse(messageWords[5])).or(-1L);
561 if (inetAddress.isPresent() && port.isPresent()) {
562 eventBus.post(new DccSendReceived(this, client, messageWords[2], inetAddress.get(), port.get(), fileSize));
564 logger.warn(String.format("Received malformed DCC SEND: ā%sā", message));
566 } else if (messageWords[1].equalsIgnoreCase("ACCEPT")) {
567 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[3]));
568 long position = (messageWords.length > 4) ? Optional.fromNullable(Longs.tryParse(messageWords[4])).or(-1L) : -1;
569 if (port.isPresent()) {
570 eventBus.post(new DccAcceptReceived(this, client, messageWords[2], port.get(), position));
572 logger.warn(String.format("Received malformed DCC ACCEPT: ā%sā", message));
579 * Returns an item from the list, or {@link Optional#absent()} if the list is
580 * shorter than required for the given index.
583 * The list to get an item from
585 * The index of the item
587 * The type of the list items
588 * @return This list item wrapped in an {@link Optional}, or {@link
589 * Optional#absent()} if the list is not long enough
591 private static <T> Optional<T> getOptional(List<T> list, int index) {
592 if (index < list.size()) {
593 return Optional.fromNullable(list.get(index));
595 return Optional.absent();
599 * Parses the given {@code ip} and returns an {@link InetAddress} from it.
603 * @return The parsed inet address, or {@link Optional#absent()} if no inet
604 * address could be parsed
606 private Optional<InetAddress> parseInetAddress(String ip) {
607 Long ipNumber = Longs.tryParse(ip);
608 if (ipNumber == null) {
609 return Optional.absent();
612 StringBuilder hostname = new StringBuilder(15);
613 hostname.append((ipNumber >>> 24) & 0xff).append('.');
614 hostname.append((ipNumber >>> 16) & 0xff).append('.');
615 hostname.append((ipNumber >>> 8) & 0xff).append('.');
616 hostname.append(ipNumber & 0xff);
618 return Optional.of(InetAddress.getByName(hostname.toString()));
619 } catch (UnknownHostException uhe1) {
620 return Optional.absent();
624 /** Handles input and output for the connection. */
625 private class ConnectionHandler implements Closeable {
627 /** The output stream of the connection. */
628 private final BandwidthCountingOutputStream outputStream;
630 /** The input stream. */
631 private final BandwidthCountingInputStream inputStream;
633 /** The input stream of the connection. */
634 private final BufferedReader inputStreamReader;
637 * Creates a new connection handler for the given input stream and output
641 * The input stream of the connection
642 * @param outputStream
643 * The output stream of the connection
644 * @throws UnsupportedEncodingException
645 * if the encoding (currently āUTF-8ā) is not valid
647 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
648 this.outputStream = new BandwidthCountingOutputStream(outputStream, 5, SECONDS);
649 this.inputStream = new BandwidthCountingInputStream(inputStream, 5, SECONDS);
650 inputStreamReader = new BufferedReader(new InputStreamReader(this.inputStream, "UTF-8"));
658 * Returns the current rate of the connectionās incoming side.
660 * @return The current input rate (in bytes per second)
662 public long getInputRate() {
663 return inputStream.getCurrentRate();
667 * Returns the current rate of the connectionās outgoing side.
669 * @return The current output rate (in bytes per second)
671 public long getOutputRate() {
672 return outputStream.getCurrentRate();
676 * Sends a command with the given parameters, skipping all {@link
677 * Optional#absent()} optionals.
680 * The command to send
683 * @throws IOException
684 * if an I/O error occurs
686 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
687 List<String> setParameters = new ArrayList<String>();
688 for (Optional<String> maybeSetParameter : parameters) {
689 if (maybeSetParameter.isPresent()) {
690 setParameters.add(maybeSetParameter.get());
693 sendCommand(command, setParameters.toArray(new String[setParameters.size()]));
697 * Sends a command with the given parameters.
700 * The command to send
702 * The parameters of the command
703 * @throws IOException
704 * if an I/O error occurs
705 * @throws IllegalArgumentException
706 * if any parameter but that last contains a space character
708 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
709 StringBuilder commandBuilder = new StringBuilder();
711 commandBuilder.append(command);
712 for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
713 String parameter = parameters[parameterIndex];
714 /* space is only allowed in the last parameter. */
715 commandBuilder.append(' ');
716 if (parameter.contains(" ")) {
717 if (parameterIndex == (parameters.length - 1)) {
718 commandBuilder.append(':');
720 throw new IllegalArgumentException(String.format("parameter ā%sā must not contain space!", parameter));
723 commandBuilder.append(parameter);
726 logger.trace(String.format(">> %s", commandBuilder));
727 outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
728 outputStream.flush();
732 * Reads a line of reply from the connection.
735 * @throws IOException
736 * if an I/O error occurs
737 * @throws EOFException
740 public Reply readReply() throws IOException, EOFException {
741 String line = inputStreamReader.readLine();
743 throw new EOFException();
746 return Reply.parseLine(line);
754 public void close() throws IOException {
755 Closeables.close(outputStream, true);
756 Closeables.close(inputStreamReader, true);
757 Closeables.close(inputStream, true);