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.ConnectionEstablished;
50 import net.pterodactylus.irc.event.ConnectionFailed;
51 import net.pterodactylus.irc.event.DccSendReceived;
52 import net.pterodactylus.irc.event.MotdReceived;
53 import net.pterodactylus.irc.event.NicknameInUseReceived;
54 import net.pterodactylus.irc.event.NoNicknameGivenReceived;
55 import net.pterodactylus.irc.event.PrivateMessageReceived;
56 import net.pterodactylus.irc.event.UnknownReplyReceived;
57 import net.pterodactylus.irc.util.RandomNickname;
59 import com.google.common.base.Optional;
60 import com.google.common.collect.Maps;
61 import com.google.common.collect.Sets;
62 import com.google.common.eventbus.EventBus;
63 import com.google.common.io.Closeables;
64 import com.google.common.primitives.Ints;
65 import com.google.common.primitives.Longs;
66 import com.google.common.util.concurrent.AbstractExecutionThreadService;
67 import com.google.common.util.concurrent.Service;
70 * A connection to an IRC server.
72 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
74 public class Connection extends AbstractExecutionThreadService implements Service {
77 private static final Logger logger = Logger.getLogger(Connection.class.getName());
80 private final EventBus eventBus;
82 /** The socket factory. */
83 private final SocketFactory socketFactory;
85 /** The hostname to connect to. */
86 private final String hostname;
88 /** The port to connect to. */
89 private final int port;
91 /** The nickname chooser. */
92 private NicknameChooser nicknameChooser = new NicknameChooser() {
95 public String getNickname() {
96 return RandomNickname.get();
101 private String nickname = null;
104 private Optional<String> username = Optional.absent();
106 /** The real name. */
107 private Optional<String> realName = Optional.absent();
109 /** The optional password for the connection. */
110 private Optional<String> password = Optional.absent();
112 /** The connection handler. */
113 private ConnectionHandler connectionHandler;
116 * Creates a new connection.
120 * @param socketFactory
123 * The hostname of the IRC server
125 * The port number of the IRC server
127 public Connection(EventBus eventBus, SocketFactory socketFactory, String hostname, int port) {
128 this.eventBus = eventBus;
129 this.socketFactory = socketFactory;
130 this.hostname = hostname;
139 * Returns the nickname that is currently in use by this connection. The
140 * nickname is only available once the connection has been {@link #start()}ed.
142 * @return The current nickname
144 public String nickname() {
153 * Sets the nickname chooser. The nickname chooser is only used during the
154 * creation of the connection.
156 * @param nicknameChooser
157 * The nickname chooser
158 * @return This connection
160 public Connection nicknameChooser(NicknameChooser nicknameChooser) {
161 this.nicknameChooser = nicknameChooser;
166 * Sets the username to use.
169 * The username to use
170 * @return This connection
172 public Connection username(String username) {
173 this.username = Optional.fromNullable(username);
178 * Sets the real name to use.
181 * The real name to use
182 * @return This connection
184 public Connection realName(String realName) {
185 this.realName = Optional.fromNullable(realName);
190 * Sets the optional password for the connection.
193 * The password for the connection
194 * @return This connection
196 public Connection password(String password) {
197 this.password = Optional.fromNullable(password);
206 * Checks whether the given source is the client represented by this
210 * The source to check
211 * @return {@code true} if this connection represents the given source, {@code
214 public boolean isSource(Source source) {
215 return source.nick().isPresent() && source.nick().get().equals(nickname);
219 * Joins the given channel.
222 * The channel to join
223 * @throws IOException
224 * if an I/O error occurs
226 public void joinChannel(final String channel) throws IOException {
227 connectionHandler.sendCommand("JOIN", channel);
231 * Sends a message to the given recipient, which may be a channel or another
235 * The recipient of the message
238 * @throws IOException
239 * if an I/O error occurs
241 public void sendMessage(String recipient, String message) throws IOException {
242 connectionHandler.sendCommand("PRIVMSG", recipient, message);
246 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
250 protected void startUp() throws IllegalStateException {
251 checkState(username.isPresent(), "username must be set");
252 checkState(realName.isPresent(), "realName must be set");
256 protected void run() {
258 /* connect to remote socket. */
260 Socket socket = socketFactory.createSocket(hostname, port);
261 connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
263 /* register connection. */
264 if (password.isPresent()) {
265 connectionHandler.sendCommand("PASSWORD", password.get());
267 connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
268 nickname = nicknameChooser.getNickname();
269 connectionHandler.sendCommand("NICK", nickname);
271 } catch (IOException ioe1) {
272 eventBus.post(new ConnectionFailed(this, ioe1));
276 /* now read replies and react. */
278 /* some status variables. */
279 int oldConnectionStatus = 0;
280 int connectionStatus = 0;
281 boolean connected = true;
282 StringBuilder motd = new StringBuilder();
283 Set<Nickname> nicks = Sets.newHashSet();
286 Map<String, String> nickPrefixes = Maps.newHashMap();
287 Set<Character> channelTypes = Sets.newHashSet();
290 Reply reply = connectionHandler.readReply();
291 logger.finest(String.format("<< %s", reply));
292 String command = reply.command();
293 List<String> parameters = reply.parameters();
295 /* most common events. */
296 if (command.equalsIgnoreCase("PRIVMSG")) {
297 String recipient = parameters.get(0);
298 String message = parameters.get(1);
299 if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
301 String[] messageWords = message.substring(1, message.length() - 1).split(" +");
302 String ctcpCommand = messageWords[0];
303 if (ctcpCommand.equalsIgnoreCase("DCC")) {
304 if (messageWords[1].equalsIgnoreCase("SEND")) {
305 Optional<InetAddress> inetAddress = parseInetAddress(messageWords[3]);
306 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[4]));
307 long fileSize = Optional.fromNullable(Longs.tryParse(messageWords[5])).or(-1L);
308 if (inetAddress.isPresent() && port.isPresent()) {
309 eventBus.post(new DccSendReceived(this, reply.source().get(), messageWords[2], inetAddress.get(), port.get(), fileSize));
311 logger.warning(String.format("Received malformed DCC SEND: “%s”", message));
315 } else if (!channelTypes.contains(recipient.charAt(0))) {
316 eventBus.post(new PrivateMessageReceived(this, reply.source().get(), message));
318 eventBus.post(new ChannelMessageReceived(this, recipient, reply.source().get(), message));
321 /* replies 001-004 don’t hold information but they have to be sent on a successful connection. */
322 } else if (command.equals("001")) {
323 connectionStatus |= 0x01;
324 } else if (command.equals("002")) {
325 connectionStatus |= 0x02;
326 } else if (command.equals("003")) {
327 connectionStatus |= 0x04;
328 } else if (command.equals("004")) {
329 connectionStatus |= 0x08;
331 /* 005 originally was a bounce message, now used to transmit useful information about the server. */
332 } else if (command.equals("005")) {
333 for (String parameter : parameters) {
334 if (parameter.startsWith("PREFIX=")) {
335 int openParen = parameter.indexOf('(');
336 int closeParen = parameter.indexOf(')');
337 if ((openParen != -1) && (closeParen != -1)) {
338 for (int modeCharacterIndex = 1; modeCharacterIndex < (closeParen - openParen); ++modeCharacterIndex) {
339 char modeCharacter = parameter.charAt(openParen + modeCharacterIndex);
340 char modeSymbol = parameter.charAt(closeParen + modeCharacterIndex);
341 nickPrefixes.put(String.valueOf(modeSymbol), String.valueOf(modeCharacter));
343 logger.fine(String.format("Parsed Prefixes: %s", nickPrefixes));
345 } else if (parameter.startsWith("CHANTYPES=")) {
346 for (int typeIndex = 10; typeIndex < parameter.length(); ++typeIndex) {
347 channelTypes.add(parameter.charAt(typeIndex));
349 logger.fine(String.format("Parsed Channel Types: %s", channelTypes));
353 /* 375, 372, and 376 handle the server’s MOTD. */
354 } else if (command.equals("375")) {
356 motd.append(parameters.get(1)).append('\n');
357 } else if (command.equals("372")) {
358 motd.append(parameters.get(1)).append('\n');
359 } else if (command.equals("376")) {
360 motd.append(parameters.get(1)).append('\n');
361 eventBus.post(new MotdReceived(this, motd.toString()));
364 /* 43x replies are for nick change errors. */
365 } else if (command.equals("431")) {
366 eventBus.post(new NoNicknameGivenReceived(this, reply));
367 } else if (command.equals("433")) {
368 if (connectionStatus == 0) {
369 nickname = nicknameChooser.getNickname();
370 connectionHandler.sendCommand("NICK", nickname);
372 eventBus.post(new NicknameInUseReceived(this, reply));
376 } else if (command.equalsIgnoreCase("JOIN")) {
377 eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
378 } else if (command.equals("331")) {
379 /* no topic is set. */
380 } else if (command.equals("332")) {
381 eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
382 } else if (command.equals("353")) {
383 for (String nickname : parameters.get(3).split(" ")) {
384 if (nickPrefixes.containsKey(nickname.substring(0, 1))) {
385 nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
387 nicks.add(new Nickname(nickname, ""));
390 } else if (command.equals("366")) {
391 eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
393 } else if (command.equalsIgnoreCase("PART")) {
394 eventBus.post(new ChannelLeft(this, parameters.get(0), reply.source().get(), parameters.get(1)));
395 } else if (command.equalsIgnoreCase("QUIT")) {
396 eventBus.post(new ClientQuit(this, reply.source().get(), parameters.get(0)));
398 /* common channel join errors. */
399 } else if (command.equals("474")) {
400 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.banned));
401 } else if (command.equals("473")) {
402 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.inviteOnly));
403 } else if (command.equals("475")) {
404 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.badChannelKey));
406 /* basic connection housekeeping. */
407 } else if (command.equalsIgnoreCase("PING")) {
408 connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
410 /* okay, everything else. */
412 eventBus.post(new UnknownReplyReceived(this, reply));
415 if ((connectionStatus == 0x0f) && (connectionStatus != oldConnectionStatus)) {
416 /* connection succeeded! */
417 eventBus.post(new ConnectionEstablished(this));
419 oldConnectionStatus = connectionStatus;
421 } catch (IOException ioe1) {
422 logger.log(Level.WARNING, "I/O error", ioe1);
424 logger.info("Closing Connection.");
426 Closeables.close(connectionHandler, true);
427 } catch (IOException ioe1) {
428 /* will not be thrown. */
439 * Returns an item from the list, or {@link Optional#absent()} if the list is
440 * shorter than required for the given index.
443 * The list to get an item from
445 * The index of the item
447 * The type of the list items
448 * @return This list item wrapped in an {@link Optional}, or {@link
449 * Optional#absent()} if the list is not long enough
451 private static <T> Optional<T> getOptional(List<T> list, int index) {
452 if (index < list.size()) {
453 return Optional.fromNullable(list.get(index));
455 return Optional.absent();
459 * Parses the given {@code ip} and returns an {@link InetAddress} from it.
463 * @return The parsed inet address, or {@link Optional#absent()} if no inet
464 * address could be parsed
466 private Optional<InetAddress> parseInetAddress(String ip) {
467 Long ipNumber = Longs.tryParse(ip);
468 if (ipNumber == null) {
469 return Optional.absent();
472 StringBuilder hostname = new StringBuilder(15);
473 hostname.append((ipNumber >>> 24) & 0xff).append('.');
474 hostname.append((ipNumber >>> 16) & 0xff).append('.');
475 hostname.append((ipNumber >>> 8) & 0xff).append('.');
476 hostname.append(ipNumber & 0xff);
478 return Optional.of(InetAddress.getByName(hostname.toString()));
479 } catch (UnknownHostException uhe1) {
480 return Optional.absent();
484 /** Handles input and output for the connection. */
485 private class ConnectionHandler implements Closeable {
487 /** The output stream of the connection. */
488 private final OutputStream outputStream;
490 /** The input stream of the connection. */
491 private final BufferedReader inputStreamReader;
494 * Creates a new connection handler for the given input stream and output
498 * The input stream of the connection
499 * @param outputStream
500 * The output stream of the connection
501 * @throws UnsupportedEncodingException
502 * if the encoding (currently “UTF-8”) is not valid
504 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
505 this.outputStream = outputStream;
506 inputStreamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
514 * Sends a command with the given parameters, skipping all {@link
515 * Optional#absent()} optionals.
518 * The command to send
521 * @throws IOException
522 * if an I/O error occurs
524 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
525 List<String> setParameters = new ArrayList<String>();
526 for (Optional<String> maybeSetParameter : parameters) {
527 if (maybeSetParameter.isPresent()) {
528 setParameters.add(maybeSetParameter.get());
531 sendCommand(command, setParameters.toArray(new String[setParameters.size()]));
535 * Sends a command with the given parameters.
538 * The command to send
540 * The parameters of the command
541 * @throws IOException
542 * if an I/O error occurs
543 * @throws IllegalArgumentException
544 * if any parameter but that last contains a space character
546 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
547 StringBuilder commandBuilder = new StringBuilder();
549 commandBuilder.append(command);
550 for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
551 String parameter = parameters[parameterIndex];
552 /* space is only allowed in the last parameter. */
553 commandBuilder.append(' ');
554 if (parameter.contains(" ")) {
555 if (parameterIndex == (parameters.length - 1)) {
556 commandBuilder.append(':');
558 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
561 commandBuilder.append(parameter);
564 logger.finest(String.format(">> %s", commandBuilder));
565 outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
566 outputStream.flush();
570 * Reads a line of reply from the connection.
573 * @throws IOException
574 * if an I/O error occurs
575 * @throws EOFException
578 public Reply readReply() throws IOException, EOFException {
579 String line = inputStreamReader.readLine();
581 throw new EOFException();
584 return Reply.parseLine(line);
592 public void close() throws IOException {
593 Closeables.close(outputStream, true);
594 Closeables.close(inputStreamReader, true);