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.ConnectionEstablished;
49 import net.pterodactylus.irc.event.ConnectionFailed;
50 import net.pterodactylus.irc.event.DccSendReceived;
51 import net.pterodactylus.irc.event.MotdReceived;
52 import net.pterodactylus.irc.event.NicknameInUseReceived;
53 import net.pterodactylus.irc.event.NoNicknameGivenReceived;
54 import net.pterodactylus.irc.event.PrivateMessageReceived;
55 import net.pterodactylus.irc.event.UnknownReplyReceived;
56 import net.pterodactylus.irc.util.RandomNickname;
58 import com.google.common.base.Optional;
59 import com.google.common.collect.Maps;
60 import com.google.common.collect.Sets;
61 import com.google.common.eventbus.EventBus;
62 import com.google.common.io.Closeables;
63 import com.google.common.primitives.Ints;
64 import com.google.common.primitives.Longs;
65 import com.google.common.util.concurrent.AbstractExecutionThreadService;
66 import com.google.common.util.concurrent.Service;
69 * A connection to an IRC server.
71 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
73 public class Connection extends AbstractExecutionThreadService implements Service {
76 private static final Logger logger = Logger.getLogger(Connection.class.getName());
79 private final EventBus eventBus;
81 /** The socket factory. */
82 private final SocketFactory socketFactory;
84 /** The hostname to connect to. */
85 private final String hostname;
87 /** The port to connect to. */
88 private final int port;
90 /** The nickname chooser. */
91 private NicknameChooser nicknameChooser = new NicknameChooser() {
94 public String getNickname() {
95 return RandomNickname.get();
100 private String nickname = null;
103 private Optional<String> username = Optional.absent();
105 /** The real name. */
106 private Optional<String> realName = Optional.absent();
108 /** The optional password for the connection. */
109 private Optional<String> password = Optional.absent();
111 /** The connection handler. */
112 private ConnectionHandler connectionHandler;
115 * Creates a new connection.
119 * @param socketFactory
122 * The hostname of the IRC server
124 * The port number of the IRC server
126 public Connection(EventBus eventBus, SocketFactory socketFactory, String hostname, int port) {
127 this.eventBus = eventBus;
128 this.socketFactory = socketFactory;
129 this.hostname = hostname;
138 * Returns the nickname that is currently in use by this connection. The
139 * nickname is only available once the connection has been {@link #start()}ed.
141 * @return The current nickname
143 public String nickname() {
152 * Sets the nickname chooser. The nickname chooser is only used during the
153 * creation of the connection.
155 * @param nicknameChooser
156 * The nickname chooser
157 * @return This connection
159 public Connection nicknameChooser(NicknameChooser nicknameChooser) {
160 this.nicknameChooser = nicknameChooser;
165 * Sets the username to use.
168 * The username to use
169 * @return This connection
171 public Connection username(String username) {
172 this.username = Optional.fromNullable(username);
177 * Sets the real name to use.
180 * The real name to use
181 * @return This connection
183 public Connection realName(String realName) {
184 this.realName = Optional.fromNullable(realName);
189 * Sets the optional password for the connection.
192 * The password for the connection
193 * @return This connection
195 public Connection password(String password) {
196 this.password = Optional.fromNullable(password);
205 * Checks whether the given source is the client represented by this
209 * The source to check
210 * @return {@code true} if this connection represents the given source, {@code
213 public boolean isSource(Source source) {
214 return source.nick().isPresent() && source.nick().get().equals(nickname);
218 * Joins the given channel.
221 * The channel to join
222 * @throws IOException
223 * if an I/O error occurs
225 public void joinChannel(final String channel) throws IOException {
226 connectionHandler.sendCommand("JOIN", channel);
230 * Sends a message to the given recipient, which may be a channel or another
234 * The recipient of the message
237 * @throws IOException
238 * if an I/O error occurs
240 public void sendMessage(String recipient, String message) throws IOException {
241 connectionHandler.sendCommand("PRIVMSG", recipient, message);
245 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
249 protected void startUp() throws IllegalStateException {
250 checkState(username.isPresent(), "username must be set");
251 checkState(realName.isPresent(), "realName must be set");
255 protected void run() {
257 /* connect to remote socket. */
259 Socket socket = socketFactory.createSocket(hostname, port);
260 connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
262 /* register connection. */
263 if (password.isPresent()) {
264 connectionHandler.sendCommand("PASSWORD", password.get());
266 connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
267 nickname = nicknameChooser.getNickname();
268 connectionHandler.sendCommand("NICK", nickname);
270 } catch (IOException ioe1) {
271 eventBus.post(new ConnectionFailed(this, ioe1));
275 /* now read replies and react. */
277 /* some status variables. */
278 int oldConnectionStatus = 0;
279 int connectionStatus = 0;
280 boolean connected = true;
281 StringBuilder motd = new StringBuilder();
282 Set<Nickname> nicks = Sets.newHashSet();
285 Map<String, String> nickPrefixes = Maps.newHashMap();
286 Set<Character> channelTypes = Sets.newHashSet();
289 Reply reply = connectionHandler.readReply();
290 logger.finest(String.format("<< %s", reply));
291 String command = reply.command();
292 List<String> parameters = reply.parameters();
294 /* most common events. */
295 if (command.equalsIgnoreCase("PRIVMSG")) {
296 String recipient = parameters.get(0);
297 String message = parameters.get(1);
298 if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
300 String[] messageWords = message.substring(1, message.length() - 1).split(" +");
301 String ctcpCommand = messageWords[0];
302 if (ctcpCommand.equalsIgnoreCase("DCC")) {
303 if (messageWords[1].equalsIgnoreCase("SEND")) {
304 Optional<InetAddress> inetAddress = parseInetAddress(messageWords[3]);
305 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[4]));
306 long fileSize = Optional.fromNullable(Longs.tryParse(messageWords[5])).or(-1L);
307 if (inetAddress.isPresent() && port.isPresent()) {
308 eventBus.post(new DccSendReceived(this, reply.source().get(), messageWords[2], inetAddress.get(), port.get(), fileSize));
310 logger.warning(String.format("Received malformed DCC SEND: “%s”", message));
314 } else if (!channelTypes.contains(recipient.charAt(0))) {
315 eventBus.post(new PrivateMessageReceived(this, reply.source().get(), message));
317 eventBus.post(new ChannelMessageReceived(this, recipient, reply.source().get(), message));
320 /* replies 001-004 don’t hold information but they have to be sent on a successful connection. */
321 } else if (command.equals("001")) {
322 connectionStatus |= 0x01;
323 } else if (command.equals("002")) {
324 connectionStatus |= 0x02;
325 } else if (command.equals("003")) {
326 connectionStatus |= 0x04;
327 } else if (command.equals("004")) {
328 connectionStatus |= 0x08;
330 /* 005 originally was a bounce message, now used to transmit useful information about the server. */
331 } else if (command.equals("005")) {
332 for (String parameter : parameters) {
333 if (parameter.startsWith("PREFIX=")) {
334 int openParen = parameter.indexOf('(');
335 int closeParen = parameter.indexOf(')');
336 if ((openParen != -1) && (closeParen != -1)) {
337 for (int modeCharacterIndex = 1; modeCharacterIndex < (closeParen - openParen); ++modeCharacterIndex) {
338 char modeCharacter = parameter.charAt(openParen + modeCharacterIndex);
339 char modeSymbol = parameter.charAt(closeParen + modeCharacterIndex);
340 nickPrefixes.put(String.valueOf(modeSymbol), String.valueOf(modeCharacter));
342 logger.fine(String.format("Parsed Prefixes: %s", nickPrefixes));
344 } else if (parameter.startsWith("CHANTYPES=")) {
345 for (int typeIndex = 10; typeIndex < parameter.length(); ++typeIndex) {
346 channelTypes.add(parameter.charAt(typeIndex));
348 logger.fine(String.format("Parsed Channel Types: %s", channelTypes));
352 /* 375, 372, and 376 handle the server’s MOTD. */
353 } else if (command.equals("375")) {
355 motd.append(parameters.get(1)).append('\n');
356 } else if (command.equals("372")) {
357 motd.append(parameters.get(1)).append('\n');
358 } else if (command.equals("376")) {
359 motd.append(parameters.get(1)).append('\n');
360 eventBus.post(new MotdReceived(this, motd.toString()));
363 /* 43x replies are for nick change errors. */
364 } else if (command.equals("431")) {
365 eventBus.post(new NoNicknameGivenReceived(this, reply));
366 } else if (command.equals("433")) {
367 if (connectionStatus == 0) {
368 nickname = nicknameChooser.getNickname();
369 connectionHandler.sendCommand("NICK", nickname);
371 eventBus.post(new NicknameInUseReceived(this, reply));
375 } else if (command.equalsIgnoreCase("JOIN")) {
376 eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
377 } else if (command.equals("331")) {
378 /* no topic is set. */
379 } else if (command.equals("332")) {
380 eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
381 } else if (command.equals("353")) {
382 for (String nickname : parameters.get(3).split(" ")) {
383 if (nickPrefixes.containsKey(nickname.substring(0, 1))) {
384 nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
386 nicks.add(new Nickname(nickname, ""));
389 } else if (command.equals("366")) {
390 eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
392 } else if (command.equalsIgnoreCase("PART")) {
393 eventBus.post(new ChannelLeft(this, parameters.get(0), reply.source().get(), parameters.get(1)));
395 /* common channel join errors. */
396 } else if (command.equals("474")) {
397 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.banned));
398 } else if (command.equals("473")) {
399 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.inviteOnly));
400 } else if (command.equals("475")) {
401 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.badChannelKey));
403 /* basic connection housekeeping. */
404 } else if (command.equalsIgnoreCase("PING")) {
405 connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
407 /* okay, everything else. */
409 eventBus.post(new UnknownReplyReceived(this, reply));
412 if ((connectionStatus == 0x0f) && (connectionStatus != oldConnectionStatus)) {
413 /* connection succeeded! */
414 eventBus.post(new ConnectionEstablished(this));
416 oldConnectionStatus = connectionStatus;
418 } catch (IOException ioe1) {
419 logger.log(Level.WARNING, "I/O error", ioe1);
421 logger.info("Closing Connection.");
423 Closeables.close(connectionHandler, true);
424 } catch (IOException ioe1) {
425 /* will not be thrown. */
436 * Returns an item from the list, or {@link Optional#absent()} if the list is
437 * shorter than required for the given index.
440 * The list to get an item from
442 * The index of the item
444 * The type of the list items
445 * @return This list item wrapped in an {@link Optional}, or {@link
446 * Optional#absent()} if the list is not long enough
448 private static <T> Optional<T> getOptional(List<T> list, int index) {
449 if (index < list.size()) {
450 return Optional.fromNullable(list.get(index));
452 return Optional.absent();
456 * Parses the given {@code ip} and returns an {@link InetAddress} from it.
460 * @return The parsed inet address, or {@link Optional#absent()} if no inet
461 * address could be parsed
463 private Optional<InetAddress> parseInetAddress(String ip) {
464 Long ipNumber = Longs.tryParse(ip);
465 if (ipNumber == null) {
466 return Optional.absent();
469 StringBuilder hostname = new StringBuilder(15);
470 hostname.append((ipNumber >>> 24) & 0xff).append('.');
471 hostname.append((ipNumber >>> 16) & 0xff).append('.');
472 hostname.append((ipNumber >>> 8) & 0xff).append('.');
473 hostname.append(ipNumber & 0xff);
475 return Optional.of(InetAddress.getByName(hostname.toString()));
476 } catch (UnknownHostException uhe1) {
477 return Optional.absent();
481 /** Handles input and output for the connection. */
482 private class ConnectionHandler implements Closeable {
484 /** The output stream of the connection. */
485 private final OutputStream outputStream;
487 /** The input stream of the connection. */
488 private final BufferedReader inputStreamReader;
491 * Creates a new connection handler for the given input stream and output
495 * The input stream of the connection
496 * @param outputStream
497 * The output stream of the connection
498 * @throws UnsupportedEncodingException
499 * if the encoding (currently “UTF-8”) is not valid
501 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
502 this.outputStream = outputStream;
503 inputStreamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
511 * Sends a command with the given parameters, skipping all {@link
512 * Optional#absent()} optionals.
515 * The command to send
518 * @throws IOException
519 * if an I/O error occurs
521 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
522 List<String> setParameters = new ArrayList<String>();
523 for (Optional<String> maybeSetParameter : parameters) {
524 if (maybeSetParameter.isPresent()) {
525 setParameters.add(maybeSetParameter.get());
528 sendCommand(command, setParameters.toArray(new String[setParameters.size()]));
532 * Sends a command with the given parameters.
535 * The command to send
537 * The parameters of the command
538 * @throws IOException
539 * if an I/O error occurs
540 * @throws IllegalArgumentException
541 * if any parameter but that last contains a space character
543 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
544 StringBuilder commandBuilder = new StringBuilder();
546 commandBuilder.append(command);
547 for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
548 String parameter = parameters[parameterIndex];
549 /* space is only allowed in the last parameter. */
550 commandBuilder.append(' ');
551 if (parameter.contains(" ")) {
552 if (parameterIndex == (parameters.length - 1)) {
553 commandBuilder.append(':');
555 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
558 commandBuilder.append(parameter);
561 logger.finest(String.format(">> %s", commandBuilder));
562 outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
563 outputStream.flush();
567 * Reads a line of reply from the connection.
570 * @throws IOException
571 * if an I/O error occurs
572 * @throws EOFException
575 public Reply readReply() throws IOException, EOFException {
576 String line = inputStreamReader.readLine();
578 throw new EOFException();
581 return Reply.parseLine(line);
589 public void close() throws IOException {
590 Closeables.close(outputStream, true);
591 Closeables.close(inputStreamReader, true);