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 whether this connection has already been established.
149 * @return {@code true} as long as this connection is established, {@code
152 public boolean established() {
157 * Returns the nickname that is currently in use by this connection. The
158 * nickname is only available once the connection has been {@link #start()}ed.
160 * @return The current nickname
162 public String nickname() {
171 * Sets the nickname chooser. The nickname chooser is only used during the
172 * creation of the connection.
174 * @param nicknameChooser
175 * The nickname chooser
176 * @return This connection
178 public Connection nicknameChooser(NicknameChooser nicknameChooser) {
179 this.nicknameChooser = nicknameChooser;
184 * Sets the username to use.
187 * The username to use
188 * @return This connection
190 public Connection username(String username) {
191 this.username = Optional.fromNullable(username);
196 * Sets the real name to use.
199 * The real name to use
200 * @return This connection
202 public Connection realName(String realName) {
203 this.realName = Optional.fromNullable(realName);
208 * Sets the optional password for the connection.
211 * The password for the connection
212 * @return This connection
214 public Connection password(String password) {
215 this.password = Optional.fromNullable(password);
224 * Checks whether the given source is the client represented by this
228 * The source to check
229 * @return {@code true} if this connection represents the given source, {@code
232 public boolean isSource(Source source) {
233 return source.nick().isPresent() && source.nick().get().equals(nickname);
237 * Joins the given channel.
240 * The channel to join
241 * @throws IOException
242 * if an I/O error occurs
244 public void joinChannel(final String channel) throws IOException {
245 connectionHandler.sendCommand("JOIN", channel);
249 * Sends a message to the given recipient, which may be a channel or another
253 * The recipient of the message
256 * @throws IOException
257 * if an I/O error occurs
259 public void sendMessage(String recipient, String message) throws IOException {
260 connectionHandler.sendCommand("PRIVMSG", recipient, message);
264 * Sends a DCC RESUME request to the given recipient.
267 * The recipient of the request
269 * The name of the file to resume
271 * The port number from the original DCC SEND request
273 * The position at which to resume the transfer
274 * @throws IOException
275 * if an I/O error occurs
277 public void sendDccResume(String recipient, String filename, int port, long position) throws IOException {
278 connectionHandler.sendCommand("PRIVMSG", recipient, String.format("\u0001DCC RESUME %s %d %d\u0001", filename, port, position));
282 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
286 protected void startUp() throws IllegalStateException {
287 checkState(username.isPresent(), "username must be set");
288 checkState(realName.isPresent(), "realName must be set");
292 protected void run() {
294 /* connect to remote socket. */
296 Socket socket = socketFactory.createSocket(hostname, port);
297 connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
299 /* register connection. */
300 if (password.isPresent()) {
301 connectionHandler.sendCommand("PASSWORD", password.get());
303 connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
304 nickname = nicknameChooser.getNickname();
305 connectionHandler.sendCommand("NICK", nickname);
307 } catch (IOException ioe1) {
308 eventBus.post(new ConnectionFailed(this, ioe1));
312 /* now read replies and react. */
314 /* some status variables. */
315 int oldConnectionStatus = 0;
316 int connectionStatus = 0;
317 boolean connected = true;
318 StringBuilder motd = new StringBuilder();
319 Set<Nickname> nicks = Sets.newHashSet();
322 Map<String, String> nickPrefixes = Maps.newHashMap();
323 Set<Character> channelTypes = Sets.newHashSet();
326 Reply reply = connectionHandler.readReply();
327 logger.finest(String.format("<< %s", reply));
328 String command = reply.command();
329 List<String> parameters = reply.parameters();
331 /* most common events. */
332 if (command.equalsIgnoreCase("PRIVMSG")) {
333 String recipient = parameters.get(0);
334 String message = parameters.get(1);
335 if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
337 handleCtcp(reply.source().get(), message);
338 } else if (!channelTypes.contains(recipient.charAt(0))) {
339 eventBus.post(new PrivateMessageReceived(this, reply.source().get(), message));
341 eventBus.post(new ChannelMessageReceived(this, recipient, reply.source().get(), message));
344 } else if (command.equalsIgnoreCase("NOTICE")) {
345 String recipient = parameters.get(0);
346 String message = parameters.get(1);
347 if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
349 handleCtcp(reply.source().get(), message);
350 } else if (!channelTypes.contains(recipient.charAt(0))) {
351 eventBus.post(new PrivateNoticeReceived(this, reply));
353 eventBus.post(new ChannelNoticeReceived(this, reply.source().get(), recipient, message));
356 /* 43x replies are for nick change errors. */
357 } else if (command.equals("431")) {
358 eventBus.post(new NoNicknameGivenReceived(this, reply));
359 } else if (command.equals("433")) {
360 if (connectionStatus == 0) {
361 nickname = nicknameChooser.getNickname();
362 connectionHandler.sendCommand("NICK", nickname);
364 eventBus.post(new NicknameInUseReceived(this, reply));
368 } else if (command.equalsIgnoreCase("NICK")) {
369 eventBus.post(new NicknameChanged(this, reply.source().get(), parameters.get(0)));
372 } else if (command.equalsIgnoreCase("JOIN")) {
373 eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
374 } else if (command.equals("331")) {
375 /* no topic is set. */
376 } else if (command.equals("332")) {
377 eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
378 } else if (command.equals("353")) {
379 for (String nickname : parameters.get(3).split(" ")) {
380 if (nickPrefixes.containsKey(nickname.substring(0, 1))) {
381 nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
383 nicks.add(new Nickname(nickname, ""));
386 } else if (command.equals("366")) {
387 eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
389 } else if (command.equalsIgnoreCase("PART")) {
390 eventBus.post(new ChannelLeft(this, parameters.get(0), reply.source().get(), getOptional(parameters, 1)));
391 } else if (command.equalsIgnoreCase("QUIT")) {
392 eventBus.post(new ClientQuit(this, reply.source().get(), parameters.get(0)));
394 /* common channel join errors. */
395 } else if (command.equals("474")) {
396 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.banned));
397 } else if (command.equals("473")) {
398 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.inviteOnly));
399 } else if (command.equals("475")) {
400 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.badChannelKey));
402 /* basic connection housekeeping. */
403 } else if (command.equalsIgnoreCase("PING")) {
404 connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
406 /* replies 001-004 don’t hold information but they have to be sent on a successful connection. */
407 } else if (command.equals("001")) {
408 connectionStatus |= 0x01;
409 } else if (command.equals("002")) {
410 connectionStatus |= 0x02;
411 } else if (command.equals("003")) {
412 connectionStatus |= 0x04;
413 } else if (command.equals("004")) {
414 connectionStatus |= 0x08;
416 /* 005 originally was a bounce message, now used to transmit useful information about the server. */
417 } else if (command.equals("005")) {
418 for (String parameter : parameters) {
419 if (parameter.startsWith("PREFIX=")) {
420 int openParen = parameter.indexOf('(');
421 int closeParen = parameter.indexOf(')');
422 if ((openParen != -1) && (closeParen != -1)) {
423 for (int modeCharacterIndex = 1; modeCharacterIndex < (closeParen - openParen); ++modeCharacterIndex) {
424 char modeCharacter = parameter.charAt(openParen + modeCharacterIndex);
425 char modeSymbol = parameter.charAt(closeParen + modeCharacterIndex);
426 nickPrefixes.put(String.valueOf(modeSymbol), String.valueOf(modeCharacter));
428 logger.fine(String.format("Parsed Prefixes: %s", nickPrefixes));
430 } else if (parameter.startsWith("CHANTYPES=")) {
431 for (int typeIndex = 10; typeIndex < parameter.length(); ++typeIndex) {
432 channelTypes.add(parameter.charAt(typeIndex));
434 logger.fine(String.format("Parsed Channel Types: %s", channelTypes));
438 /* 375, 372, and 376 handle the server’s MOTD. */
439 } else if (command.equals("375")) {
441 motd.append(parameters.get(1)).append('\n');
442 } else if (command.equals("372")) {
443 motd.append(parameters.get(1)).append('\n');
444 } else if (command.equals("376")) {
445 motd.append(parameters.get(1)).append('\n');
446 eventBus.post(new MotdReceived(this, motd.toString()));
449 /* okay, everything else. */
451 eventBus.post(new UnknownReplyReceived(this, reply));
454 if ((connectionStatus == 0x0f) && (connectionStatus != oldConnectionStatus)) {
455 /* connection succeeded! */
457 eventBus.post(new ConnectionEstablished(this));
459 oldConnectionStatus = connectionStatus;
461 eventBus.post(new ConnectionClosed(this));
462 } catch (IOException ioe1) {
463 logger.log(Level.WARNING, "I/O error", ioe1);
464 eventBus.post(new ConnectionClosed(this, ioe1));
467 logger.info("Closing Connection.");
469 Closeables.close(connectionHandler, true);
470 } catch (IOException ioe1) {
471 /* will not be thrown. */
482 * Handles a CTCP message.
485 * The client sending the message
489 private void handleCtcp(Source client, String message) {
490 String[] messageWords = message.substring(1, message.length() - 1).split(" +");
491 String ctcpCommand = messageWords[0];
492 if (ctcpCommand.equalsIgnoreCase("DCC")) {
493 if (messageWords[1].equalsIgnoreCase("SEND")) {
494 Optional<InetAddress> inetAddress = parseInetAddress(messageWords[3]);
495 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[4]));
496 long fileSize = Optional.fromNullable(Longs.tryParse(messageWords[5])).or(-1L);
497 if (inetAddress.isPresent() && port.isPresent()) {
498 eventBus.post(new DccSendReceived(this, client, messageWords[2], inetAddress.get(), port.get(), fileSize));
500 logger.warning(String.format("Received malformed DCC SEND: “%s”", message));
502 } else if (messageWords[1].equalsIgnoreCase("ACCEPT")) {
503 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[3]));
504 long position = Optional.fromNullable(Longs.tryParse(messageWords[4])).or(-1L);
505 if (port.isPresent()) {
506 eventBus.post(new DccAcceptReceived(this, client, messageWords[2], port.get(), position));
508 logger.warning(String.format("Received malformed DCC ACCEPT: “%s”", message));
515 * Returns an item from the list, or {@link Optional#absent()} if the list is
516 * shorter than required for the given index.
519 * The list to get an item from
521 * The index of the item
523 * The type of the list items
524 * @return This list item wrapped in an {@link Optional}, or {@link
525 * Optional#absent()} if the list is not long enough
527 private static <T> Optional<T> getOptional(List<T> list, int index) {
528 if (index < list.size()) {
529 return Optional.fromNullable(list.get(index));
531 return Optional.absent();
535 * Parses the given {@code ip} and returns an {@link InetAddress} from it.
539 * @return The parsed inet address, or {@link Optional#absent()} if no inet
540 * address could be parsed
542 private Optional<InetAddress> parseInetAddress(String ip) {
543 Long ipNumber = Longs.tryParse(ip);
544 if (ipNumber == null) {
545 return Optional.absent();
548 StringBuilder hostname = new StringBuilder(15);
549 hostname.append((ipNumber >>> 24) & 0xff).append('.');
550 hostname.append((ipNumber >>> 16) & 0xff).append('.');
551 hostname.append((ipNumber >>> 8) & 0xff).append('.');
552 hostname.append(ipNumber & 0xff);
554 return Optional.of(InetAddress.getByName(hostname.toString()));
555 } catch (UnknownHostException uhe1) {
556 return Optional.absent();
560 /** Handles input and output for the connection. */
561 private class ConnectionHandler implements Closeable {
563 /** The output stream of the connection. */
564 private final OutputStream outputStream;
566 /** The input stream of the connection. */
567 private final BufferedReader inputStreamReader;
570 * Creates a new connection handler for the given input stream and output
574 * The input stream of the connection
575 * @param outputStream
576 * The output stream of the connection
577 * @throws UnsupportedEncodingException
578 * if the encoding (currently “UTF-8”) is not valid
580 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
581 this.outputStream = outputStream;
582 inputStreamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
590 * Sends a command with the given parameters, skipping all {@link
591 * Optional#absent()} optionals.
594 * The command to send
597 * @throws IOException
598 * if an I/O error occurs
600 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
601 List<String> setParameters = new ArrayList<String>();
602 for (Optional<String> maybeSetParameter : parameters) {
603 if (maybeSetParameter.isPresent()) {
604 setParameters.add(maybeSetParameter.get());
607 sendCommand(command, setParameters.toArray(new String[setParameters.size()]));
611 * Sends a command with the given parameters.
614 * The command to send
616 * The parameters of the command
617 * @throws IOException
618 * if an I/O error occurs
619 * @throws IllegalArgumentException
620 * if any parameter but that last contains a space character
622 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
623 StringBuilder commandBuilder = new StringBuilder();
625 commandBuilder.append(command);
626 for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
627 String parameter = parameters[parameterIndex];
628 /* space is only allowed in the last parameter. */
629 commandBuilder.append(' ');
630 if (parameter.contains(" ")) {
631 if (parameterIndex == (parameters.length - 1)) {
632 commandBuilder.append(':');
634 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
637 commandBuilder.append(parameter);
640 logger.finest(String.format(">> %s", commandBuilder));
641 outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
642 outputStream.flush();
646 * Reads a line of reply from the connection.
649 * @throws IOException
650 * if an I/O error occurs
651 * @throws EOFException
654 public Reply readReply() throws IOException, EOFException {
655 String line = inputStreamReader.readLine();
657 throw new EOFException();
660 return Reply.parseLine(line);
668 public void close() throws IOException {
669 Closeables.close(outputStream, true);
670 Closeables.close(inputStreamReader, true);