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 * Closes this connection.
284 * @throws IOException
285 * if an I/O error occurs
287 public void close() throws IOException {
288 connectionHandler.close();
292 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
296 protected void startUp() throws IllegalStateException {
297 checkState(username.isPresent(), "username must be set");
298 checkState(realName.isPresent(), "realName must be set");
302 protected void run() {
304 /* connect to remote socket. */
306 Socket socket = socketFactory.createSocket(hostname, port);
307 connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
309 /* register connection. */
310 if (password.isPresent()) {
311 connectionHandler.sendCommand("PASSWORD", password.get());
313 connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
314 nickname = nicknameChooser.getNickname();
315 connectionHandler.sendCommand("NICK", nickname);
317 } catch (IOException ioe1) {
318 eventBus.post(new ConnectionFailed(this, ioe1));
322 /* now read replies and react. */
324 /* some status variables. */
325 int oldConnectionStatus = 0;
326 int connectionStatus = 0;
327 boolean connected = true;
328 StringBuilder motd = new StringBuilder();
329 Set<Nickname> nicks = Sets.newHashSet();
332 Map<String, String> nickPrefixes = Maps.newHashMap();
333 Set<Character> channelTypes = Sets.newHashSet();
336 Reply reply = connectionHandler.readReply();
337 logger.finest(String.format("<< %s", reply));
338 String command = reply.command();
339 List<String> parameters = reply.parameters();
341 /* most common events. */
342 if (command.equalsIgnoreCase("PRIVMSG")) {
343 String recipient = parameters.get(0);
344 String message = parameters.get(1);
345 if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
347 handleCtcp(reply.source().get(), message);
348 } else if (!channelTypes.contains(recipient.charAt(0))) {
349 eventBus.post(new PrivateMessageReceived(this, reply.source().get(), message));
351 eventBus.post(new ChannelMessageReceived(this, recipient, reply.source().get(), message));
354 } else if (command.equalsIgnoreCase("NOTICE")) {
355 String recipient = parameters.get(0);
356 String message = parameters.get(1);
357 if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
359 handleCtcp(reply.source().get(), message);
360 } else if (!channelTypes.contains(recipient.charAt(0))) {
361 eventBus.post(new PrivateNoticeReceived(this, reply));
363 eventBus.post(new ChannelNoticeReceived(this, reply.source().get(), recipient, message));
366 /* 43x replies are for nick change errors. */
367 } else if (command.equals("431")) {
368 eventBus.post(new NoNicknameGivenReceived(this, reply));
369 } else if (command.equals("433")) {
370 if (connectionStatus == 0) {
371 nickname = nicknameChooser.getNickname();
372 connectionHandler.sendCommand("NICK", nickname);
374 eventBus.post(new NicknameInUseReceived(this, reply));
378 } else if (command.equalsIgnoreCase("NICK")) {
379 eventBus.post(new NicknameChanged(this, reply.source().get(), parameters.get(0)));
382 } else if (command.equalsIgnoreCase("JOIN")) {
383 eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
384 } else if (command.equals("331")) {
385 /* no topic is set. */
386 } else if (command.equals("332")) {
387 eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
388 } else if (command.equals("353")) {
389 for (String nickname : parameters.get(3).split(" ")) {
390 if (nickPrefixes.containsKey(nickname.substring(0, 1))) {
391 nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
393 nicks.add(new Nickname(nickname, ""));
396 } else if (command.equals("366")) {
397 eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
399 } else if (command.equalsIgnoreCase("PART")) {
400 eventBus.post(new ChannelLeft(this, parameters.get(0), reply.source().get(), getOptional(parameters, 1)));
401 } else if (command.equalsIgnoreCase("QUIT")) {
402 eventBus.post(new ClientQuit(this, reply.source().get(), parameters.get(0)));
404 /* common channel join errors. */
405 } else if (command.equals("474")) {
406 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.banned));
407 } else if (command.equals("473")) {
408 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.inviteOnly));
409 } else if (command.equals("475")) {
410 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.badChannelKey));
412 /* basic connection housekeeping. */
413 } else if (command.equalsIgnoreCase("PING")) {
414 connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
416 /* replies 001-004 don’t hold information but they have to be sent on a successful connection. */
417 } else if (command.equals("001")) {
418 connectionStatus |= 0x01;
419 } else if (command.equals("002")) {
420 connectionStatus |= 0x02;
421 } else if (command.equals("003")) {
422 connectionStatus |= 0x04;
423 } else if (command.equals("004")) {
424 connectionStatus |= 0x08;
426 /* 005 originally was a bounce message, now used to transmit useful information about the server. */
427 } else if (command.equals("005")) {
428 for (String parameter : parameters) {
429 if (parameter.startsWith("PREFIX=")) {
430 int openParen = parameter.indexOf('(');
431 int closeParen = parameter.indexOf(')');
432 if ((openParen != -1) && (closeParen != -1)) {
433 for (int modeCharacterIndex = 1; modeCharacterIndex < (closeParen - openParen); ++modeCharacterIndex) {
434 char modeCharacter = parameter.charAt(openParen + modeCharacterIndex);
435 char modeSymbol = parameter.charAt(closeParen + modeCharacterIndex);
436 nickPrefixes.put(String.valueOf(modeSymbol), String.valueOf(modeCharacter));
438 logger.fine(String.format("Parsed Prefixes: %s", nickPrefixes));
440 } else if (parameter.startsWith("CHANTYPES=")) {
441 for (int typeIndex = 10; typeIndex < parameter.length(); ++typeIndex) {
442 channelTypes.add(parameter.charAt(typeIndex));
444 logger.fine(String.format("Parsed Channel Types: %s", channelTypes));
448 /* 375, 372, and 376 handle the server’s MOTD. */
449 } else if (command.equals("375")) {
451 motd.append(parameters.get(1)).append('\n');
452 } else if (command.equals("372")) {
453 motd.append(parameters.get(1)).append('\n');
454 } else if (command.equals("376")) {
455 motd.append(parameters.get(1)).append('\n');
456 eventBus.post(new MotdReceived(this, motd.toString()));
459 /* okay, everything else. */
461 eventBus.post(new UnknownReplyReceived(this, reply));
464 if ((connectionStatus == 0x0f) && (connectionStatus != oldConnectionStatus)) {
465 /* connection succeeded! */
467 eventBus.post(new ConnectionEstablished(this));
469 oldConnectionStatus = connectionStatus;
471 eventBus.post(new ConnectionClosed(this));
472 } catch (IOException ioe1) {
473 logger.log(Level.WARNING, "I/O error", ioe1);
474 eventBus.post(new ConnectionClosed(this, ioe1));
477 logger.info("Closing Connection.");
479 Closeables.close(connectionHandler, true);
480 } catch (IOException ioe1) {
481 /* will not be thrown. */
492 * Handles a CTCP message.
495 * The client sending the message
499 private void handleCtcp(Source client, String message) {
500 String[] messageWords = message.substring(1, message.length() - 1).split(" +");
501 String ctcpCommand = messageWords[0];
502 if (ctcpCommand.equalsIgnoreCase("DCC")) {
503 if (messageWords[1].equalsIgnoreCase("SEND")) {
504 Optional<InetAddress> inetAddress = parseInetAddress(messageWords[3]);
505 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[4]));
506 long fileSize = Optional.fromNullable(Longs.tryParse(messageWords[5])).or(-1L);
507 if (inetAddress.isPresent() && port.isPresent()) {
508 eventBus.post(new DccSendReceived(this, client, messageWords[2], inetAddress.get(), port.get(), fileSize));
510 logger.warning(String.format("Received malformed DCC SEND: “%s”", message));
512 } else if (messageWords[1].equalsIgnoreCase("ACCEPT")) {
513 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[3]));
514 long position = Optional.fromNullable(Longs.tryParse(messageWords[4])).or(-1L);
515 if (port.isPresent()) {
516 eventBus.post(new DccAcceptReceived(this, client, messageWords[2], port.get(), position));
518 logger.warning(String.format("Received malformed DCC ACCEPT: “%s”", message));
525 * Returns an item from the list, or {@link Optional#absent()} if the list is
526 * shorter than required for the given index.
529 * The list to get an item from
531 * The index of the item
533 * The type of the list items
534 * @return This list item wrapped in an {@link Optional}, or {@link
535 * Optional#absent()} if the list is not long enough
537 private static <T> Optional<T> getOptional(List<T> list, int index) {
538 if (index < list.size()) {
539 return Optional.fromNullable(list.get(index));
541 return Optional.absent();
545 * Parses the given {@code ip} and returns an {@link InetAddress} from it.
549 * @return The parsed inet address, or {@link Optional#absent()} if no inet
550 * address could be parsed
552 private Optional<InetAddress> parseInetAddress(String ip) {
553 Long ipNumber = Longs.tryParse(ip);
554 if (ipNumber == null) {
555 return Optional.absent();
558 StringBuilder hostname = new StringBuilder(15);
559 hostname.append((ipNumber >>> 24) & 0xff).append('.');
560 hostname.append((ipNumber >>> 16) & 0xff).append('.');
561 hostname.append((ipNumber >>> 8) & 0xff).append('.');
562 hostname.append(ipNumber & 0xff);
564 return Optional.of(InetAddress.getByName(hostname.toString()));
565 } catch (UnknownHostException uhe1) {
566 return Optional.absent();
570 /** Handles input and output for the connection. */
571 private class ConnectionHandler implements Closeable {
573 /** The output stream of the connection. */
574 private final OutputStream outputStream;
576 /** The input stream of the connection. */
577 private final BufferedReader inputStreamReader;
580 * Creates a new connection handler for the given input stream and output
584 * The input stream of the connection
585 * @param outputStream
586 * The output stream of the connection
587 * @throws UnsupportedEncodingException
588 * if the encoding (currently “UTF-8”) is not valid
590 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
591 this.outputStream = outputStream;
592 inputStreamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
600 * Sends a command with the given parameters, skipping all {@link
601 * Optional#absent()} optionals.
604 * The command to send
607 * @throws IOException
608 * if an I/O error occurs
610 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
611 List<String> setParameters = new ArrayList<String>();
612 for (Optional<String> maybeSetParameter : parameters) {
613 if (maybeSetParameter.isPresent()) {
614 setParameters.add(maybeSetParameter.get());
617 sendCommand(command, setParameters.toArray(new String[setParameters.size()]));
621 * Sends a command with the given parameters.
624 * The command to send
626 * The parameters of the command
627 * @throws IOException
628 * if an I/O error occurs
629 * @throws IllegalArgumentException
630 * if any parameter but that last contains a space character
632 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
633 StringBuilder commandBuilder = new StringBuilder();
635 commandBuilder.append(command);
636 for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
637 String parameter = parameters[parameterIndex];
638 /* space is only allowed in the last parameter. */
639 commandBuilder.append(' ');
640 if (parameter.contains(" ")) {
641 if (parameterIndex == (parameters.length - 1)) {
642 commandBuilder.append(':');
644 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
647 commandBuilder.append(parameter);
650 logger.finest(String.format(">> %s", commandBuilder));
651 outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
652 outputStream.flush();
656 * Reads a line of reply from the connection.
659 * @throws IOException
660 * if an I/O error occurs
661 * @throws EOFException
664 public Reply readReply() throws IOException, EOFException {
665 String line = inputStreamReader.readLine();
667 throw new EOFException();
670 return Reply.parseLine(line);
678 public void close() throws IOException {
679 Closeables.close(outputStream, true);
680 Closeables.close(inputStreamReader, true);