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;
22 import java.io.BufferedReader;
23 import java.io.Closeable;
24 import java.io.EOFException;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.io.InputStreamReader;
28 import java.io.OutputStream;
29 import java.io.UnsupportedEncodingException;
30 import java.net.InetAddress;
31 import java.net.Socket;
32 import java.net.UnknownHostException;
33 import java.util.ArrayList;
34 import java.util.List;
37 import java.util.logging.Level;
38 import java.util.logging.Logger;
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.UnknownReplyReceived;
62 import net.pterodactylus.irc.util.RandomNickname;
64 import com.google.common.base.Optional;
65 import com.google.common.collect.Maps;
66 import com.google.common.collect.Sets;
67 import com.google.common.eventbus.EventBus;
68 import com.google.common.io.Closeables;
69 import com.google.common.primitives.Ints;
70 import com.google.common.primitives.Longs;
71 import com.google.common.util.concurrent.AbstractExecutionThreadService;
72 import com.google.common.util.concurrent.Service;
75 * A connection to an IRC server.
77 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
79 public class Connection extends AbstractExecutionThreadService implements Service {
82 private static final Logger logger = Logger.getLogger(Connection.class.getName());
85 private final EventBus eventBus;
87 /** The socket factory. */
88 private final SocketFactory socketFactory;
90 /** The hostname to connect to. */
91 private final String hostname;
93 /** The port to connect to. */
94 private final int port;
96 /** The nickname chooser. */
97 private NicknameChooser nicknameChooser = new NicknameChooser() {
100 public String getNickname() {
101 return RandomNickname.get();
106 private String nickname = null;
109 private Optional<String> username = Optional.absent();
111 /** The real name. */
112 private Optional<String> realName = Optional.absent();
114 /** The optional password for the connection. */
115 private Optional<String> password = Optional.absent();
117 /** The connection handler. */
118 private ConnectionHandler connectionHandler;
120 /** Whether the connection has already been established. */
121 private boolean established;
124 * Creates a new connection.
128 * @param socketFactory
131 * The hostname of the IRC server
133 * The port number of the IRC server
135 public Connection(EventBus eventBus, SocketFactory socketFactory, String hostname, int port) {
136 this.eventBus = eventBus;
137 this.socketFactory = socketFactory;
138 this.hostname = hostname;
147 * Returns the hostname of the remote end of the connection.
148 * @return The remote’s hostname
150 public String hostname() {
155 * Returns the port number of the remote end of the connection.
156 * @return The remote’s port number
163 * Returns whether this connection has already been established.
165 * @return {@code true} as long as this connection is established, {@code
168 public boolean established() {
173 * Returns the nickname that is currently in use by this connection. The
174 * nickname is only available once the connection has been {@link #start()}ed.
176 * @return The current nickname
178 public String nickname() {
187 * Sets the nickname chooser. The nickname chooser is only used during the
188 * creation of the connection.
190 * @param nicknameChooser
191 * The nickname chooser
192 * @return This connection
194 public Connection nicknameChooser(NicknameChooser nicknameChooser) {
195 this.nicknameChooser = nicknameChooser;
200 * Sets the username to use.
203 * The username to use
204 * @return This connection
206 public Connection username(String username) {
207 this.username = Optional.fromNullable(username);
212 * Sets the real name to use.
215 * The real name to use
216 * @return This connection
218 public Connection realName(String realName) {
219 this.realName = Optional.fromNullable(realName);
224 * Sets the optional password for the connection.
227 * The password for the connection
228 * @return This connection
230 public Connection password(String password) {
231 this.password = Optional.fromNullable(password);
240 * Checks whether the given source is the client represented by this
244 * The source to check
245 * @return {@code true} if this connection represents the given source, {@code
248 public boolean isSource(Source source) {
249 return source.nick().isPresent() && source.nick().get().equals(nickname);
253 * Joins the given channel.
256 * The channel to join
257 * @throws IOException
258 * if an I/O error occurs
260 public void joinChannel(final String channel) throws IOException {
261 connectionHandler.sendCommand("JOIN", channel);
265 * Sends a message to the given recipient, which may be a channel or another
269 * The recipient of the message
272 * @throws IOException
273 * if an I/O error occurs
275 public void sendMessage(String recipient, String message) throws IOException {
276 connectionHandler.sendCommand("PRIVMSG", recipient, message);
280 * Sends a DCC RESUME request to the given recipient.
283 * The recipient of the request
285 * The name of the file to resume
287 * The port number from the original DCC SEND request
289 * The position at which to resume the transfer
290 * @throws IOException
291 * if an I/O error occurs
293 public void sendDccResume(String recipient, String filename, int port, long position) throws IOException {
294 connectionHandler.sendCommand("PRIVMSG", recipient, String.format("\u0001DCC RESUME %s %d %d\u0001", filename, port, position));
298 * Closes this connection.
300 * @throws IOException
301 * if an I/O error occurs
303 public void close() throws IOException {
304 connectionHandler.close();
308 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
312 protected void startUp() throws IllegalStateException {
313 checkState(username.isPresent(), "username must be set");
314 checkState(realName.isPresent(), "realName must be set");
318 protected void run() {
320 /* connect to remote socket. */
322 Socket socket = socketFactory.createSocket(hostname, port);
323 connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
325 /* register connection. */
326 if (password.isPresent()) {
327 connectionHandler.sendCommand("PASSWORD", password.get());
329 connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
330 nickname = nicknameChooser.getNickname();
331 connectionHandler.sendCommand("NICK", nickname);
333 } catch (IOException ioe1) {
334 eventBus.post(new ConnectionFailed(this, ioe1));
338 /* now read replies and react. */
340 /* some status variables. */
341 int oldConnectionStatus = 0;
342 int connectionStatus = 0;
343 boolean connected = true;
344 StringBuilder motd = new StringBuilder();
345 Set<Nickname> nicks = Sets.newHashSet();
348 Map<String, String> nickPrefixes = Maps.newHashMap();
349 Set<Character> channelTypes = Sets.newHashSet();
352 Reply reply = connectionHandler.readReply();
353 logger.finest(String.format("<< %s", reply));
354 String command = reply.command();
355 List<String> parameters = reply.parameters();
357 /* most common events. */
358 if (command.equalsIgnoreCase("PRIVMSG")) {
359 String recipient = parameters.get(0);
360 String message = parameters.get(1);
361 if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
363 handleCtcp(reply.source().get(), message);
364 } else if (!channelTypes.contains(recipient.charAt(0))) {
365 eventBus.post(new PrivateMessageReceived(this, reply.source().get(), message));
367 eventBus.post(new ChannelMessageReceived(this, recipient, reply.source().get(), message));
370 } else if (command.equalsIgnoreCase("NOTICE")) {
371 String recipient = parameters.get(0);
372 String message = parameters.get(1);
373 if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
375 handleCtcp(reply.source().get(), message);
376 } else if (!channelTypes.contains(recipient.charAt(0))) {
377 eventBus.post(new PrivateNoticeReceived(this, reply));
379 eventBus.post(new ChannelNoticeReceived(this, reply.source().get(), recipient, message));
382 /* 43x replies are for nick change errors. */
383 } else if (command.equals("431")) {
384 eventBus.post(new NoNicknameGivenReceived(this, reply));
385 } else if (command.equals("433")) {
386 if (connectionStatus == 0) {
387 nickname = nicknameChooser.getNickname();
388 connectionHandler.sendCommand("NICK", nickname);
390 eventBus.post(new NicknameInUseReceived(this, reply));
394 } else if (command.equalsIgnoreCase("NICK")) {
395 eventBus.post(new NicknameChanged(this, reply.source().get(), parameters.get(0)));
398 } else if (command.equalsIgnoreCase("JOIN")) {
399 eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
400 } else if (command.equals("331")) {
401 /* no topic is set. */
402 } else if (command.equals("332")) {
403 eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
404 } else if (command.equals("353")) {
405 for (String nickname : parameters.get(3).split(" ")) {
406 if (nickPrefixes.containsKey(nickname.substring(0, 1))) {
407 nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
409 nicks.add(new Nickname(nickname, ""));
412 } else if (command.equals("366")) {
413 eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
415 } else if (command.equalsIgnoreCase("PART")) {
416 eventBus.post(new ChannelLeft(this, parameters.get(0), reply.source().get(), getOptional(parameters, 1)));
417 } else if (command.equalsIgnoreCase("QUIT")) {
418 eventBus.post(new ClientQuit(this, reply.source().get(), parameters.get(0)));
420 /* common channel join errors. */
421 } else if (command.equals("474")) {
422 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.banned));
423 } else if (command.equals("473")) {
424 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.inviteOnly));
425 } else if (command.equals("475")) {
426 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.badChannelKey));
428 /* basic connection housekeeping. */
429 } else if (command.equalsIgnoreCase("PING")) {
430 connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
432 /* replies 001-004 don’t hold information but they have to be sent on a successful connection. */
433 } else if (command.equals("001")) {
434 connectionStatus |= 0x01;
435 } else if (command.equals("002")) {
436 connectionStatus |= 0x02;
437 } else if (command.equals("003")) {
438 connectionStatus |= 0x04;
439 } else if (command.equals("004")) {
440 connectionStatus |= 0x08;
442 /* 005 originally was a bounce message, now used to transmit useful information about the server. */
443 } else if (command.equals("005")) {
444 for (String parameter : parameters) {
445 if (parameter.startsWith("PREFIX=")) {
446 int openParen = parameter.indexOf('(');
447 int closeParen = parameter.indexOf(')');
448 if ((openParen != -1) && (closeParen != -1)) {
449 for (int modeCharacterIndex = 1; modeCharacterIndex < (closeParen - openParen); ++modeCharacterIndex) {
450 char modeCharacter = parameter.charAt(openParen + modeCharacterIndex);
451 char modeSymbol = parameter.charAt(closeParen + modeCharacterIndex);
452 nickPrefixes.put(String.valueOf(modeSymbol), String.valueOf(modeCharacter));
454 logger.fine(String.format("Parsed Prefixes: %s", nickPrefixes));
456 } else if (parameter.startsWith("CHANTYPES=")) {
457 for (int typeIndex = 10; typeIndex < parameter.length(); ++typeIndex) {
458 channelTypes.add(parameter.charAt(typeIndex));
460 logger.fine(String.format("Parsed Channel Types: %s", channelTypes));
464 /* 375, 372, and 376 handle the server’s MOTD. */
465 } else if (command.equals("375")) {
467 motd.append(parameters.get(1)).append('\n');
468 } else if (command.equals("372")) {
469 motd.append(parameters.get(1)).append('\n');
470 } else if (command.equals("376")) {
471 motd.append(parameters.get(1)).append('\n');
472 eventBus.post(new MotdReceived(this, motd.toString()));
475 /* okay, everything else. */
477 eventBus.post(new UnknownReplyReceived(this, reply));
480 if ((connectionStatus == 0x0f) && (connectionStatus != oldConnectionStatus)) {
481 /* connection succeeded! */
483 eventBus.post(new ConnectionEstablished(this));
485 oldConnectionStatus = connectionStatus;
487 eventBus.post(new ConnectionClosed(this));
488 } catch (IOException ioe1) {
489 logger.log(Level.WARNING, "I/O error", ioe1);
490 eventBus.post(new ConnectionClosed(this, ioe1));
493 logger.info("Closing Connection.");
495 Closeables.close(connectionHandler, true);
496 } catch (IOException ioe1) {
497 /* will not be thrown. */
508 * Handles a CTCP message.
511 * The client sending the message
515 private void handleCtcp(Source client, String message) {
516 String[] messageWords = message.substring(1, message.length() - 1).split(" +");
517 String ctcpCommand = messageWords[0];
518 if (ctcpCommand.equalsIgnoreCase("DCC")) {
519 if (messageWords[1].equalsIgnoreCase("SEND")) {
520 Optional<InetAddress> inetAddress = parseInetAddress(messageWords[3]);
521 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[4]));
522 long fileSize = Optional.fromNullable(Longs.tryParse(messageWords[5])).or(-1L);
523 if (inetAddress.isPresent() && port.isPresent()) {
524 eventBus.post(new DccSendReceived(this, client, messageWords[2], inetAddress.get(), port.get(), fileSize));
526 logger.warning(String.format("Received malformed DCC SEND: “%s”", message));
528 } else if (messageWords[1].equalsIgnoreCase("ACCEPT")) {
529 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[3]));
530 long position = Optional.fromNullable(Longs.tryParse(messageWords[4])).or(-1L);
531 if (port.isPresent()) {
532 eventBus.post(new DccAcceptReceived(this, client, messageWords[2], port.get(), position));
534 logger.warning(String.format("Received malformed DCC ACCEPT: “%s”", message));
541 * Returns an item from the list, or {@link Optional#absent()} if the list is
542 * shorter than required for the given index.
545 * The list to get an item from
547 * The index of the item
549 * The type of the list items
550 * @return This list item wrapped in an {@link Optional}, or {@link
551 * Optional#absent()} if the list is not long enough
553 private static <T> Optional<T> getOptional(List<T> list, int index) {
554 if (index < list.size()) {
555 return Optional.fromNullable(list.get(index));
557 return Optional.absent();
561 * Parses the given {@code ip} and returns an {@link InetAddress} from it.
565 * @return The parsed inet address, or {@link Optional#absent()} if no inet
566 * address could be parsed
568 private Optional<InetAddress> parseInetAddress(String ip) {
569 Long ipNumber = Longs.tryParse(ip);
570 if (ipNumber == null) {
571 return Optional.absent();
574 StringBuilder hostname = new StringBuilder(15);
575 hostname.append((ipNumber >>> 24) & 0xff).append('.');
576 hostname.append((ipNumber >>> 16) & 0xff).append('.');
577 hostname.append((ipNumber >>> 8) & 0xff).append('.');
578 hostname.append(ipNumber & 0xff);
580 return Optional.of(InetAddress.getByName(hostname.toString()));
581 } catch (UnknownHostException uhe1) {
582 return Optional.absent();
586 /** Handles input and output for the connection. */
587 private class ConnectionHandler implements Closeable {
589 /** The output stream of the connection. */
590 private final OutputStream outputStream;
592 /** The input stream of the connection. */
593 private final BufferedReader inputStreamReader;
596 * Creates a new connection handler for the given input stream and output
600 * The input stream of the connection
601 * @param outputStream
602 * The output stream of the connection
603 * @throws UnsupportedEncodingException
604 * if the encoding (currently “UTF-8”) is not valid
606 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
607 this.outputStream = outputStream;
608 inputStreamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
616 * Sends a command with the given parameters, skipping all {@link
617 * Optional#absent()} optionals.
620 * The command to send
623 * @throws IOException
624 * if an I/O error occurs
626 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
627 List<String> setParameters = new ArrayList<String>();
628 for (Optional<String> maybeSetParameter : parameters) {
629 if (maybeSetParameter.isPresent()) {
630 setParameters.add(maybeSetParameter.get());
633 sendCommand(command, setParameters.toArray(new String[setParameters.size()]));
637 * Sends a command with the given parameters.
640 * The command to send
642 * The parameters of the command
643 * @throws IOException
644 * if an I/O error occurs
645 * @throws IllegalArgumentException
646 * if any parameter but that last contains a space character
648 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
649 StringBuilder commandBuilder = new StringBuilder();
651 commandBuilder.append(command);
652 for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
653 String parameter = parameters[parameterIndex];
654 /* space is only allowed in the last parameter. */
655 commandBuilder.append(' ');
656 if (parameter.contains(" ")) {
657 if (parameterIndex == (parameters.length - 1)) {
658 commandBuilder.append(':');
660 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
663 commandBuilder.append(parameter);
666 logger.finest(String.format(">> %s", commandBuilder));
667 outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
668 outputStream.flush();
672 * Reads a line of reply from the connection.
675 * @throws IOException
676 * if an I/O error occurs
677 * @throws EOFException
680 public Reply readReply() throws IOException, EOFException {
681 String line = inputStreamReader.readLine();
683 throw new EOFException();
686 return Reply.parseLine(line);
694 public void close() throws IOException {
695 Closeables.close(outputStream, true);
696 Closeables.close(inputStreamReader, true);