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.ChannelMessageReceived;
43 import net.pterodactylus.irc.event.ChannelNicknames;
44 import net.pterodactylus.irc.event.ChannelNotJoined;
45 import net.pterodactylus.irc.event.ChannelNotJoined.Reason;
46 import net.pterodactylus.irc.event.ChannelTopic;
47 import net.pterodactylus.irc.event.ConnectionEstablished;
48 import net.pterodactylus.irc.event.ConnectionFailed;
49 import net.pterodactylus.irc.event.DccSendReceived;
50 import net.pterodactylus.irc.event.MotdReceived;
51 import net.pterodactylus.irc.event.NicknameInUseReceived;
52 import net.pterodactylus.irc.event.NoNicknameGivenReceived;
53 import net.pterodactylus.irc.event.PrivateMessageReceived;
54 import net.pterodactylus.irc.event.UnknownReplyReceived;
55 import net.pterodactylus.irc.util.RandomNickname;
57 import com.google.common.base.Optional;
58 import com.google.common.collect.Maps;
59 import com.google.common.collect.Sets;
60 import com.google.common.eventbus.EventBus;
61 import com.google.common.io.Closeables;
62 import com.google.common.primitives.Ints;
63 import com.google.common.primitives.Longs;
64 import com.google.common.util.concurrent.AbstractExecutionThreadService;
65 import com.google.common.util.concurrent.Service;
68 * A connection to an IRC server.
70 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
72 public class Connection extends AbstractExecutionThreadService implements Service {
75 private static final Logger logger = Logger.getLogger(Connection.class.getName());
78 private final EventBus eventBus;
80 /** The socket factory. */
81 private final SocketFactory socketFactory;
83 /** The hostname to connect to. */
84 private final String hostname;
86 /** The port to connect to. */
87 private final int port;
89 /** The nickname chooser. */
90 private NicknameChooser nicknameChooser = new NicknameChooser() {
93 public String getNickname() {
94 return RandomNickname.get();
99 private String nickname = null;
102 private Optional<String> username = Optional.absent();
104 /** The real name. */
105 private Optional<String> realName = Optional.absent();
107 /** The optional password for the connection. */
108 private Optional<String> password = Optional.absent();
110 /** The connection handler. */
111 private ConnectionHandler connectionHandler;
114 * Creates a new connection.
118 * @param socketFactory
121 * The hostname of the IRC server
123 * The port number of the IRC server
125 public Connection(EventBus eventBus, SocketFactory socketFactory, String hostname, int port) {
126 this.eventBus = eventBus;
127 this.socketFactory = socketFactory;
128 this.hostname = hostname;
137 * Returns the nickname that is currently in use by this connection. The
138 * nickname is only available once the connection has been {@link #start()}ed.
140 * @return The current nickname
142 public String nickname() {
151 * Sets the nickname chooser. The nickname chooser is only used during the
152 * creation of the connection.
154 * @param nicknameChooser
155 * The nickname chooser
156 * @return This connection
158 public Connection nicknameChooser(NicknameChooser nicknameChooser) {
159 this.nicknameChooser = nicknameChooser;
164 * Sets the username to use.
167 * The username to use
168 * @return This connection
170 public Connection username(String username) {
171 this.username = Optional.fromNullable(username);
176 * Sets the real name to use.
179 * The real name to use
180 * @return This connection
182 public Connection realName(String realName) {
183 this.realName = Optional.fromNullable(realName);
188 * Sets the optional password for the connection.
191 * The password for the connection
192 * @return This connection
194 public Connection password(String password) {
195 this.password = Optional.fromNullable(password);
204 * Checks whether the given source is the client represented by this
208 * The source to check
209 * @return {@code true} if this connection represents the given source, {@code
212 public boolean isSource(Source source) {
213 return source.nick().isPresent() && source.nick().get().equals(nickname);
217 * Joins the given channel.
220 * The channel to join
221 * @throws IOException
222 * if an I/O error occurs
224 public void joinChannel(final String channel) throws IOException {
225 connectionHandler.sendCommand("JOIN", channel);
229 * Sends a message to the given recipient, which may be a channel or another
233 * The recipient of the message
236 * @throws IOException
237 * if an I/O error occurs
239 public void sendMessage(String recipient, String message) throws IOException {
240 connectionHandler.sendCommand("PRIVMSG", recipient, message);
244 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
248 protected void startUp() throws IllegalStateException {
249 checkState(username.isPresent(), "username must be set");
250 checkState(realName.isPresent(), "realName must be set");
254 protected void run() {
256 /* connect to remote socket. */
258 Socket socket = socketFactory.createSocket(hostname, port);
259 connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
261 /* register connection. */
262 if (password.isPresent()) {
263 connectionHandler.sendCommand("PASSWORD", password.get());
265 connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
266 nickname = nicknameChooser.getNickname();
267 connectionHandler.sendCommand("NICK", nickname);
269 } catch (IOException ioe1) {
270 eventBus.post(new ConnectionFailed(this, ioe1));
274 /* now read replies and react. */
276 /* some status variables. */
277 int oldConnectionStatus = 0;
278 int connectionStatus = 0;
279 boolean connected = true;
280 StringBuilder motd = new StringBuilder();
281 Set<Nickname> nicks = Sets.newHashSet();
284 Map<String, String> nickPrefixes = Maps.newHashMap();
285 Set<Character> channelTypes = Sets.newHashSet();
288 Reply reply = connectionHandler.readReply();
289 logger.finest(String.format("<< %s", reply));
290 String command = reply.command();
291 List<String> parameters = reply.parameters();
293 /* most common events. */
294 if (command.equalsIgnoreCase("PRIVMSG")) {
295 String recipient = parameters.get(0);
296 String message = parameters.get(1);
297 if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
299 String[] messageWords = message.substring(1, message.length() - 1).split(" +");
300 String ctcpCommand = messageWords[0];
301 if (ctcpCommand.equalsIgnoreCase("DCC")) {
302 if (messageWords[1].equalsIgnoreCase("SEND")) {
303 Optional<InetAddress> inetAddress = parseInetAddress(messageWords[3]);
304 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[4]));
305 long fileSize = Optional.fromNullable(Longs.tryParse(messageWords[5])).or(-1L);
306 if (inetAddress.isPresent() && port.isPresent()) {
307 eventBus.post(new DccSendReceived(this, reply.source().get(), messageWords[2], inetAddress.get(), port.get(), fileSize));
309 logger.warning(String.format("Received malformed DCC SEND: “%s”", message));
313 } else if (!channelTypes.contains(recipient.charAt(0))) {
314 eventBus.post(new PrivateMessageReceived(this, reply.source().get(), message));
316 eventBus.post(new ChannelMessageReceived(this, recipient, reply.source().get(), message));
319 /* replies 001-004 don’t hold information but they have to be sent on a successful connection. */
320 } else if (command.equals("001")) {
321 connectionStatus |= 0x01;
322 } else if (command.equals("002")) {
323 connectionStatus |= 0x02;
324 } else if (command.equals("003")) {
325 connectionStatus |= 0x04;
326 } else if (command.equals("004")) {
327 connectionStatus |= 0x08;
329 /* 005 originally was a bounce message, now used to transmit useful information about the server. */
330 } else if (command.equals("005")) {
331 for (String parameter : parameters) {
332 if (parameter.startsWith("PREFIX=")) {
333 int openParen = parameter.indexOf('(');
334 int closeParen = parameter.indexOf(')');
335 if ((openParen != -1) && (closeParen != -1)) {
336 for (int modeCharacterIndex = 1; modeCharacterIndex < (closeParen - openParen); ++modeCharacterIndex) {
337 char modeCharacter = parameter.charAt(openParen + modeCharacterIndex);
338 char modeSymbol = parameter.charAt(closeParen + modeCharacterIndex);
339 nickPrefixes.put(String.valueOf(modeSymbol), String.valueOf(modeCharacter));
341 logger.fine(String.format("Parsed Prefixes: %s", nickPrefixes));
343 } else if (parameter.startsWith("CHANTYPES=")) {
344 for (int typeIndex = 10; typeIndex < parameter.length(); ++typeIndex) {
345 channelTypes.add(parameter.charAt(typeIndex));
347 logger.fine(String.format("Parsed Channel Types: %s", channelTypes));
351 /* 375, 372, and 376 handle the server’s MOTD. */
352 } else if (command.equals("375")) {
354 motd.append(parameters.get(1)).append('\n');
355 } else if (command.equals("372")) {
356 motd.append(parameters.get(1)).append('\n');
357 } else if (command.equals("376")) {
358 motd.append(parameters.get(1)).append('\n');
359 eventBus.post(new MotdReceived(this, motd.toString()));
362 /* 43x replies are for nick change errors. */
363 } else if (command.equals("431")) {
364 eventBus.post(new NoNicknameGivenReceived(this, reply));
365 } else if (command.equals("433")) {
366 if (connectionStatus == 0) {
367 nickname = nicknameChooser.getNickname();
368 connectionHandler.sendCommand("NICK", nickname);
370 eventBus.post(new NicknameInUseReceived(this, reply));
374 } else if (command.equalsIgnoreCase("JOIN")) {
375 eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
376 } else if (command.equals("331")) {
377 /* no topic is set. */
378 } else if (command.equals("332")) {
379 eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
380 } else if (command.equals("353")) {
381 for (String nickname : parameters.get(3).split(" ")) {
382 if (nickPrefixes.containsKey(nickname.substring(0, 1))) {
383 nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
385 nicks.add(new Nickname(nickname, ""));
388 } else if (command.equals("366")) {
389 eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
392 /* common channel join errors. */
393 } else if (command.equals("474")) {
394 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.banned));
395 } else if (command.equals("473")) {
396 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.inviteOnly));
397 } else if (command.equals("475")) {
398 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.badChannelKey));
400 /* basic connection housekeeping. */
401 } else if (command.equalsIgnoreCase("PING")) {
402 connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
404 /* okay, everything else. */
406 eventBus.post(new UnknownReplyReceived(this, reply));
409 if ((connectionStatus == 0x0f) && (connectionStatus != oldConnectionStatus)) {
410 /* connection succeeded! */
411 eventBus.post(new ConnectionEstablished(this));
413 oldConnectionStatus = connectionStatus;
415 } catch (IOException ioe1) {
416 logger.log(Level.WARNING, "I/O error", ioe1);
418 logger.info("Closing Connection.");
420 Closeables.close(connectionHandler, true);
421 } catch (IOException ioe1) {
422 /* will not be thrown. */
433 * Returns an item from the list, or {@link Optional#absent()} if the list is
434 * shorter than required for the given index.
437 * The list to get an item from
439 * The index of the item
441 * The type of the list items
442 * @return This list item wrapped in an {@link Optional}, or {@link
443 * Optional#absent()} if the list is not long enough
445 private static <T> Optional<T> getOptional(List<T> list, int index) {
446 if (index < list.size()) {
447 return Optional.fromNullable(list.get(index));
449 return Optional.absent();
453 * Parses the given {@code ip} and returns an {@link InetAddress} from it.
457 * @return The parsed inet address, or {@link Optional#absent()} if no inet
458 * address could be parsed
460 private Optional<InetAddress> parseInetAddress(String ip) {
461 Long ipNumber = Longs.tryParse(ip);
462 if (ipNumber == null) {
463 return Optional.absent();
466 StringBuilder hostname = new StringBuilder(15);
467 hostname.append((ipNumber >>> 24) & 0xff).append('.');
468 hostname.append((ipNumber >>> 16) & 0xff).append('.');
469 hostname.append((ipNumber >>> 8) & 0xff).append('.');
470 hostname.append(ipNumber & 0xff);
472 return Optional.of(InetAddress.getByName(hostname.toString()));
473 } catch (UnknownHostException uhe1) {
474 return Optional.absent();
478 /** Handles input and output for the connection. */
479 private class ConnectionHandler implements Closeable {
481 /** The output stream of the connection. */
482 private final OutputStream outputStream;
484 /** The input stream of the connection. */
485 private final BufferedReader inputStreamReader;
488 * Creates a new connection handler for the given input stream and output
492 * The input stream of the connection
493 * @param outputStream
494 * The output stream of the connection
495 * @throws UnsupportedEncodingException
496 * if the encoding (currently “UTF-8”) is not valid
498 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
499 this.outputStream = outputStream;
500 inputStreamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
508 * Sends a command with the given parameters, skipping all {@link
509 * Optional#absent()} optionals.
512 * The command to send
515 * @throws IOException
516 * if an I/O error occurs
518 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
519 List<String> setParameters = new ArrayList<String>();
520 for (Optional<String> maybeSetParameter : parameters) {
521 if (maybeSetParameter.isPresent()) {
522 setParameters.add(maybeSetParameter.get());
525 sendCommand(command, setParameters.toArray(new String[setParameters.size()]));
529 * Sends a command with the given parameters.
532 * The command to send
534 * The parameters of the command
535 * @throws IOException
536 * if an I/O error occurs
537 * @throws IllegalArgumentException
538 * if any parameter but that last contains a space character
540 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
541 StringBuilder commandBuilder = new StringBuilder();
543 commandBuilder.append(command);
544 for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
545 String parameter = parameters[parameterIndex];
546 /* space is only allowed in the last parameter. */
547 commandBuilder.append(' ');
548 if (parameter.contains(" ")) {
549 if (parameterIndex == (parameters.length - 1)) {
550 commandBuilder.append(':');
552 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
555 commandBuilder.append(parameter);
558 logger.finest(String.format(">> %s", commandBuilder));
559 outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
560 outputStream.flush();
564 * Reads a line of reply from the connection.
567 * @throws IOException
568 * if an I/O error occurs
569 * @throws EOFException
572 public Reply readReply() throws IOException, EOFException {
573 String line = inputStreamReader.readLine();
575 throw new EOFException();
578 return Reply.parseLine(line);
586 public void close() throws IOException {
587 Closeables.close(outputStream, true);
588 Closeables.close(inputStreamReader, true);