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.ChannelTopic;
48 import net.pterodactylus.irc.event.ClientQuit;
49 import net.pterodactylus.irc.event.ConnectionClosed;
50 import net.pterodactylus.irc.event.ConnectionEstablished;
51 import net.pterodactylus.irc.event.ConnectionFailed;
52 import net.pterodactylus.irc.event.DccAcceptReceived;
53 import net.pterodactylus.irc.event.DccSendReceived;
54 import net.pterodactylus.irc.event.MotdReceived;
55 import net.pterodactylus.irc.event.NicknameChanged;
56 import net.pterodactylus.irc.event.NicknameInUseReceived;
57 import net.pterodactylus.irc.event.NoNicknameGivenReceived;
58 import net.pterodactylus.irc.event.PrivateMessageReceived;
59 import net.pterodactylus.irc.event.UnknownReplyReceived;
60 import net.pterodactylus.irc.util.RandomNickname;
62 import com.google.common.base.Optional;
63 import com.google.common.collect.Maps;
64 import com.google.common.collect.Sets;
65 import com.google.common.eventbus.EventBus;
66 import com.google.common.io.Closeables;
67 import com.google.common.primitives.Ints;
68 import com.google.common.primitives.Longs;
69 import com.google.common.util.concurrent.AbstractExecutionThreadService;
70 import com.google.common.util.concurrent.Service;
73 * A connection to an IRC server.
75 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
77 public class Connection extends AbstractExecutionThreadService implements Service {
80 private static final Logger logger = Logger.getLogger(Connection.class.getName());
83 private final EventBus eventBus;
85 /** The socket factory. */
86 private final SocketFactory socketFactory;
88 /** The hostname to connect to. */
89 private final String hostname;
91 /** The port to connect to. */
92 private final int port;
94 /** The nickname chooser. */
95 private NicknameChooser nicknameChooser = new NicknameChooser() {
98 public String getNickname() {
99 return RandomNickname.get();
104 private String nickname = null;
107 private Optional<String> username = Optional.absent();
109 /** The real name. */
110 private Optional<String> realName = Optional.absent();
112 /** The optional password for the connection. */
113 private Optional<String> password = Optional.absent();
115 /** The connection handler. */
116 private ConnectionHandler connectionHandler;
118 /** Whether the connection has already been established. */
119 private boolean established;
122 * Creates a new connection.
126 * @param socketFactory
129 * The hostname of the IRC server
131 * The port number of the IRC server
133 public Connection(EventBus eventBus, SocketFactory socketFactory, String hostname, int port) {
134 this.eventBus = eventBus;
135 this.socketFactory = socketFactory;
136 this.hostname = hostname;
145 * Returns whether this connection has already been established.
147 * @return {@code true} as long as this connection is established, {@code
150 public boolean established() {
155 * Returns the nickname that is currently in use by this connection. The
156 * nickname is only available once the connection has been {@link #start()}ed.
158 * @return The current nickname
160 public String nickname() {
169 * Sets the nickname chooser. The nickname chooser is only used during the
170 * creation of the connection.
172 * @param nicknameChooser
173 * The nickname chooser
174 * @return This connection
176 public Connection nicknameChooser(NicknameChooser nicknameChooser) {
177 this.nicknameChooser = nicknameChooser;
182 * Sets the username to use.
185 * The username to use
186 * @return This connection
188 public Connection username(String username) {
189 this.username = Optional.fromNullable(username);
194 * Sets the real name to use.
197 * The real name to use
198 * @return This connection
200 public Connection realName(String realName) {
201 this.realName = Optional.fromNullable(realName);
206 * Sets the optional password for the connection.
209 * The password for the connection
210 * @return This connection
212 public Connection password(String password) {
213 this.password = Optional.fromNullable(password);
222 * Checks whether the given source is the client represented by this
226 * The source to check
227 * @return {@code true} if this connection represents the given source, {@code
230 public boolean isSource(Source source) {
231 return source.nick().isPresent() && source.nick().get().equals(nickname);
235 * Joins the given channel.
238 * The channel to join
239 * @throws IOException
240 * if an I/O error occurs
242 public void joinChannel(final String channel) throws IOException {
243 connectionHandler.sendCommand("JOIN", channel);
247 * Sends a message to the given recipient, which may be a channel or another
251 * The recipient of the message
254 * @throws IOException
255 * if an I/O error occurs
257 public void sendMessage(String recipient, String message) throws IOException {
258 connectionHandler.sendCommand("PRIVMSG", recipient, message);
262 * Sends a DCC RESUME request to the given recipient.
265 * The recipient of the request
267 * The name of the file to resume
269 * The port number from the original DCC SEND request
271 * The position at which to resume the transfer
272 * @throws IOException
273 * if an I/O error occurs
275 public void sendDccResume(String recipient, String filename, int port, long position) throws IOException {
276 connectionHandler.sendCommand("PRIVMSG", recipient, String.format("\u0001DCC RESUME %s %d %d\u0001", filename, port, position));
280 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
284 protected void startUp() throws IllegalStateException {
285 checkState(username.isPresent(), "username must be set");
286 checkState(realName.isPresent(), "realName must be set");
290 protected void run() {
292 /* connect to remote socket. */
294 Socket socket = socketFactory.createSocket(hostname, port);
295 connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
297 /* register connection. */
298 if (password.isPresent()) {
299 connectionHandler.sendCommand("PASSWORD", password.get());
301 connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
302 nickname = nicknameChooser.getNickname();
303 connectionHandler.sendCommand("NICK", nickname);
305 } catch (IOException ioe1) {
306 eventBus.post(new ConnectionFailed(this, ioe1));
310 /* now read replies and react. */
312 /* some status variables. */
313 int oldConnectionStatus = 0;
314 int connectionStatus = 0;
315 boolean connected = true;
316 StringBuilder motd = new StringBuilder();
317 Set<Nickname> nicks = Sets.newHashSet();
320 Map<String, String> nickPrefixes = Maps.newHashMap();
321 Set<Character> channelTypes = Sets.newHashSet();
324 Reply reply = connectionHandler.readReply();
325 logger.finest(String.format("<< %s", reply));
326 String command = reply.command();
327 List<String> parameters = reply.parameters();
329 /* most common events. */
330 if (command.equalsIgnoreCase("PRIVMSG")) {
331 String recipient = parameters.get(0);
332 String message = parameters.get(1);
333 if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
335 String[] messageWords = message.substring(1, message.length() - 1).split(" +");
336 String ctcpCommand = messageWords[0];
337 if (ctcpCommand.equalsIgnoreCase("DCC")) {
338 if (messageWords[1].equalsIgnoreCase("SEND")) {
339 Optional<InetAddress> inetAddress = parseInetAddress(messageWords[3]);
340 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[4]));
341 long fileSize = Optional.fromNullable(Longs.tryParse(messageWords[5])).or(-1L);
342 if (inetAddress.isPresent() && port.isPresent()) {
343 eventBus.post(new DccSendReceived(this, reply.source().get(), messageWords[2], inetAddress.get(), port.get(), fileSize));
345 logger.warning(String.format("Received malformed DCC SEND: “%s”", message));
347 } else if (messageWords[1].equalsIgnoreCase("ACCEPT")) {
348 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[3]));
349 long position = Optional.fromNullable(Longs.tryParse(messageWords[4])).or(-1L);
350 if (port.isPresent()) {
351 eventBus.post(new DccAcceptReceived(this, reply.source().get(), messageWords[2], port.get(), position));
353 logger.warning(String.format("Received malformed DCC ACCEPT: “%s”", message));
357 } else if (!channelTypes.contains(recipient.charAt(0))) {
358 eventBus.post(new PrivateMessageReceived(this, reply.source().get(), message));
360 eventBus.post(new ChannelMessageReceived(this, recipient, reply.source().get(), message));
363 /* replies 001-004 don’t hold information but they have to be sent on a successful connection. */
364 } else if (command.equals("001")) {
365 connectionStatus |= 0x01;
366 } else if (command.equals("002")) {
367 connectionStatus |= 0x02;
368 } else if (command.equals("003")) {
369 connectionStatus |= 0x04;
370 } else if (command.equals("004")) {
371 connectionStatus |= 0x08;
373 /* 005 originally was a bounce message, now used to transmit useful information about the server. */
374 } else if (command.equals("005")) {
375 for (String parameter : parameters) {
376 if (parameter.startsWith("PREFIX=")) {
377 int openParen = parameter.indexOf('(');
378 int closeParen = parameter.indexOf(')');
379 if ((openParen != -1) && (closeParen != -1)) {
380 for (int modeCharacterIndex = 1; modeCharacterIndex < (closeParen - openParen); ++modeCharacterIndex) {
381 char modeCharacter = parameter.charAt(openParen + modeCharacterIndex);
382 char modeSymbol = parameter.charAt(closeParen + modeCharacterIndex);
383 nickPrefixes.put(String.valueOf(modeSymbol), String.valueOf(modeCharacter));
385 logger.fine(String.format("Parsed Prefixes: %s", nickPrefixes));
387 } else if (parameter.startsWith("CHANTYPES=")) {
388 for (int typeIndex = 10; typeIndex < parameter.length(); ++typeIndex) {
389 channelTypes.add(parameter.charAt(typeIndex));
391 logger.fine(String.format("Parsed Channel Types: %s", channelTypes));
395 /* 375, 372, and 376 handle the server’s MOTD. */
396 } else if (command.equals("375")) {
398 motd.append(parameters.get(1)).append('\n');
399 } else if (command.equals("372")) {
400 motd.append(parameters.get(1)).append('\n');
401 } else if (command.equals("376")) {
402 motd.append(parameters.get(1)).append('\n');
403 eventBus.post(new MotdReceived(this, motd.toString()));
406 /* 43x replies are for nick change errors. */
407 } else if (command.equals("431")) {
408 eventBus.post(new NoNicknameGivenReceived(this, reply));
409 } else if (command.equals("433")) {
410 if (connectionStatus == 0) {
411 nickname = nicknameChooser.getNickname();
412 connectionHandler.sendCommand("NICK", nickname);
414 eventBus.post(new NicknameInUseReceived(this, reply));
418 } else if (command.equalsIgnoreCase("NICK")) {
419 eventBus.post(new NicknameChanged(this, reply.source().get(), parameters.get(0)));
422 } else if (command.equalsIgnoreCase("JOIN")) {
423 eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
424 } else if (command.equals("331")) {
425 /* no topic is set. */
426 } else if (command.equals("332")) {
427 eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
428 } else if (command.equals("353")) {
429 for (String nickname : parameters.get(3).split(" ")) {
430 if (nickPrefixes.containsKey(nickname.substring(0, 1))) {
431 nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
433 nicks.add(new Nickname(nickname, ""));
436 } else if (command.equals("366")) {
437 eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
439 } else if (command.equalsIgnoreCase("PART")) {
440 eventBus.post(new ChannelLeft(this, parameters.get(0), reply.source().get(), getOptional(parameters, 1)));
441 } else if (command.equalsIgnoreCase("QUIT")) {
442 eventBus.post(new ClientQuit(this, reply.source().get(), parameters.get(0)));
444 /* common channel join errors. */
445 } else if (command.equals("474")) {
446 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.banned));
447 } else if (command.equals("473")) {
448 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.inviteOnly));
449 } else if (command.equals("475")) {
450 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.badChannelKey));
452 /* basic connection housekeeping. */
453 } else if (command.equalsIgnoreCase("PING")) {
454 connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
456 /* okay, everything else. */
458 eventBus.post(new UnknownReplyReceived(this, reply));
461 if ((connectionStatus == 0x0f) && (connectionStatus != oldConnectionStatus)) {
462 /* connection succeeded! */
464 eventBus.post(new ConnectionEstablished(this));
466 oldConnectionStatus = connectionStatus;
468 eventBus.post(new ConnectionClosed(this));
469 } catch (IOException ioe1) {
470 logger.log(Level.WARNING, "I/O error", ioe1);
471 eventBus.post(new ConnectionClosed(this, ioe1));
474 logger.info("Closing Connection.");
476 Closeables.close(connectionHandler, true);
477 } catch (IOException ioe1) {
478 /* will not be thrown. */
489 * Returns an item from the list, or {@link Optional#absent()} if the list is
490 * shorter than required for the given index.
493 * The list to get an item from
495 * The index of the item
497 * The type of the list items
498 * @return This list item wrapped in an {@link Optional}, or {@link
499 * Optional#absent()} if the list is not long enough
501 private static <T> Optional<T> getOptional(List<T> list, int index) {
502 if (index < list.size()) {
503 return Optional.fromNullable(list.get(index));
505 return Optional.absent();
509 * Parses the given {@code ip} and returns an {@link InetAddress} from it.
513 * @return The parsed inet address, or {@link Optional#absent()} if no inet
514 * address could be parsed
516 private Optional<InetAddress> parseInetAddress(String ip) {
517 Long ipNumber = Longs.tryParse(ip);
518 if (ipNumber == null) {
519 return Optional.absent();
522 StringBuilder hostname = new StringBuilder(15);
523 hostname.append((ipNumber >>> 24) & 0xff).append('.');
524 hostname.append((ipNumber >>> 16) & 0xff).append('.');
525 hostname.append((ipNumber >>> 8) & 0xff).append('.');
526 hostname.append(ipNumber & 0xff);
528 return Optional.of(InetAddress.getByName(hostname.toString()));
529 } catch (UnknownHostException uhe1) {
530 return Optional.absent();
534 /** Handles input and output for the connection. */
535 private class ConnectionHandler implements Closeable {
537 /** The output stream of the connection. */
538 private final OutputStream outputStream;
540 /** The input stream of the connection. */
541 private final BufferedReader inputStreamReader;
544 * Creates a new connection handler for the given input stream and output
548 * The input stream of the connection
549 * @param outputStream
550 * The output stream of the connection
551 * @throws UnsupportedEncodingException
552 * if the encoding (currently “UTF-8”) is not valid
554 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
555 this.outputStream = outputStream;
556 inputStreamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
564 * Sends a command with the given parameters, skipping all {@link
565 * Optional#absent()} optionals.
568 * The command to send
571 * @throws IOException
572 * if an I/O error occurs
574 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
575 List<String> setParameters = new ArrayList<String>();
576 for (Optional<String> maybeSetParameter : parameters) {
577 if (maybeSetParameter.isPresent()) {
578 setParameters.add(maybeSetParameter.get());
581 sendCommand(command, setParameters.toArray(new String[setParameters.size()]));
585 * Sends a command with the given parameters.
588 * The command to send
590 * The parameters of the command
591 * @throws IOException
592 * if an I/O error occurs
593 * @throws IllegalArgumentException
594 * if any parameter but that last contains a space character
596 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
597 StringBuilder commandBuilder = new StringBuilder();
599 commandBuilder.append(command);
600 for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
601 String parameter = parameters[parameterIndex];
602 /* space is only allowed in the last parameter. */
603 commandBuilder.append(' ');
604 if (parameter.contains(" ")) {
605 if (parameterIndex == (parameters.length - 1)) {
606 commandBuilder.append(':');
608 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
611 commandBuilder.append(parameter);
614 logger.finest(String.format(">> %s", commandBuilder));
615 outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
616 outputStream.flush();
620 * Reads a line of reply from the connection.
623 * @throws IOException
624 * if an I/O error occurs
625 * @throws EOFException
628 public Reply readReply() throws IOException, EOFException {
629 String line = inputStreamReader.readLine();
631 throw new EOFException();
634 return Reply.parseLine(line);
642 public void close() throws IOException {
643 Closeables.close(outputStream, true);
644 Closeables.close(inputStreamReader, true);