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 * Joins the given channel.
207 * The channel to join
208 * @throws IOException
209 * if an I/O error occurs
211 public void joinChannel(final String channel) throws IOException {
212 connectionHandler.sendCommand("JOIN", channel);
216 * Sends a message to the given recipient, which may be a channel or another
220 * The recipient of the message
223 * @throws IOException
224 * if an I/O error occurs
226 public void sendMessage(String recipient, String message) throws IOException {
227 connectionHandler.sendCommand("PRIVMSG", recipient, message);
231 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
235 protected void startUp() throws IllegalStateException {
236 checkState(username.isPresent(), "username must be set");
237 checkState(realName.isPresent(), "realName must be set");
241 protected void run() {
243 /* connect to remote socket. */
245 Socket socket = socketFactory.createSocket(hostname, port);
246 connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
248 /* register connection. */
249 if (password.isPresent()) {
250 connectionHandler.sendCommand("PASSWORD", password.get());
252 connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
253 nickname = nicknameChooser.getNickname();
254 connectionHandler.sendCommand("NICK", nickname);
256 } catch (IOException ioe1) {
257 eventBus.post(new ConnectionFailed(this, ioe1));
261 /* now read replies and react. */
263 /* some status variables. */
264 int oldConnectionStatus = 0;
265 int connectionStatus = 0;
266 boolean connected = true;
267 StringBuilder motd = new StringBuilder();
268 Set<Nickname> nicks = Sets.newHashSet();
271 Map<String, String> nickPrefixes = Maps.newHashMap();
272 Set<Character> channelTypes = Sets.newHashSet();
275 Reply reply = connectionHandler.readReply();
276 logger.finest(String.format("<< %s", reply));
277 String command = reply.command();
278 List<String> parameters = reply.parameters();
280 /* most common events. */
281 if (command.equalsIgnoreCase("PRIVMSG")) {
282 String recipient = parameters.get(0);
283 String message = parameters.get(1);
284 if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
286 String[] messageWords = message.substring(1, message.length() - 1).split(" +");
287 String ctcpCommand = messageWords[0];
288 if (ctcpCommand.equalsIgnoreCase("DCC")) {
289 if (messageWords[1].equalsIgnoreCase("SEND")) {
290 Optional<InetAddress> inetAddress = parseInetAddress(messageWords[3]);
291 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[4]));
292 long fileSize = Optional.fromNullable(Longs.tryParse(messageWords[5])).or(-1L);
293 if (inetAddress.isPresent() && port.isPresent()) {
294 eventBus.post(new DccSendReceived(this, reply.source().get(), messageWords[2], inetAddress.get(), port.get(), fileSize));
296 logger.warning(String.format("Received malformed DCC SEND: “%s”", message));
300 } else if (!channelTypes.contains(recipient.charAt(0))) {
301 eventBus.post(new PrivateMessageReceived(this, reply.source().get(), message));
303 eventBus.post(new ChannelMessageReceived(this, recipient, reply.source().get(), message));
306 /* replies 001-004 don’t hold information but they have to be sent on a successful connection. */
307 } else if (command.equals("001")) {
308 connectionStatus |= 0x01;
309 } else if (command.equals("002")) {
310 connectionStatus |= 0x02;
311 } else if (command.equals("003")) {
312 connectionStatus |= 0x04;
313 } else if (command.equals("004")) {
314 connectionStatus |= 0x08;
316 /* 005 originally was a bounce message, now used to transmit useful information about the server. */
317 } else if (command.equals("005")) {
318 for (String parameter : parameters) {
319 if (parameter.startsWith("PREFIX=")) {
320 int openParen = parameter.indexOf('(');
321 int closeParen = parameter.indexOf(')');
322 if ((openParen != -1) && (closeParen != -1)) {
323 for (int modeCharacterIndex = 1; modeCharacterIndex < (closeParen - openParen); ++modeCharacterIndex) {
324 char modeCharacter = parameter.charAt(openParen + modeCharacterIndex);
325 char modeSymbol = parameter.charAt(closeParen + modeCharacterIndex);
326 nickPrefixes.put(String.valueOf(modeSymbol), String.valueOf(modeCharacter));
328 logger.fine(String.format("Parsed Prefixes: %s", nickPrefixes));
330 } else if (parameter.startsWith("CHANTYPES=")) {
331 for (int typeIndex = 10; typeIndex < parameter.length(); ++typeIndex) {
332 channelTypes.add(parameter.charAt(typeIndex));
334 logger.fine(String.format("Parsed Channel Types: %s", channelTypes));
338 /* 375, 372, and 376 handle the server’s MOTD. */
339 } else if (command.equals("375")) {
341 motd.append(parameters.get(1)).append('\n');
342 } else if (command.equals("372")) {
343 motd.append(parameters.get(1)).append('\n');
344 } else if (command.equals("376")) {
345 motd.append(parameters.get(1)).append('\n');
346 eventBus.post(new MotdReceived(this, motd.toString()));
349 /* 43x replies are for nick change errors. */
350 } else if (command.equals("431")) {
351 eventBus.post(new NoNicknameGivenReceived(this, reply));
352 } else if (command.equals("433")) {
353 if (connectionStatus == 0) {
354 nickname = nicknameChooser.getNickname();
355 connectionHandler.sendCommand("NICK", nickname);
357 eventBus.post(new NicknameInUseReceived(this, reply));
361 } else if (command.equalsIgnoreCase("JOIN")) {
362 eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
363 } else if (command.equals("331")) {
364 /* no topic is set. */
365 } else if (command.equals("332")) {
366 eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
367 } else if (command.equals("353")) {
368 for (String nickname : parameters.get(3).split(" ")) {
369 if (nickPrefixes.containsKey(nickname.substring(0, 1))) {
370 nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
372 nicks.add(new Nickname(nickname, ""));
375 } else if (command.equals("366")) {
376 eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
379 /* common channel join errors. */
380 } else if (command.equals("474")) {
381 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.banned));
382 } else if (command.equals("473")) {
383 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.inviteOnly));
384 } else if (command.equals("475")) {
385 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.badChannelKey));
387 /* basic connection housekeeping. */
388 } else if (command.equalsIgnoreCase("PING")) {
389 connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
391 /* okay, everything else. */
393 eventBus.post(new UnknownReplyReceived(this, reply));
396 if ((connectionStatus == 0x0f) && (connectionStatus != oldConnectionStatus)) {
397 /* connection succeeded! */
398 eventBus.post(new ConnectionEstablished(this));
400 oldConnectionStatus = connectionStatus;
402 } catch (IOException ioe1) {
403 logger.log(Level.WARNING, "I/O error", ioe1);
405 logger.info("Closing Connection.");
407 Closeables.close(connectionHandler, true);
408 } catch (IOException ioe1) {
409 /* will not be thrown. */
420 * Returns an item from the list, or {@link Optional#absent()} if the list is
421 * shorter than required for the given index.
424 * The list to get an item from
426 * The index of the item
428 * The type of the list items
429 * @return This list item wrapped in an {@link Optional}, or {@link
430 * Optional#absent()} if the list is not long enough
432 private static <T> Optional<T> getOptional(List<T> list, int index) {
433 if (index < list.size()) {
434 return Optional.fromNullable(list.get(index));
436 return Optional.absent();
440 * Parses the given {@code ip} and returns an {@link InetAddress} from it.
444 * @return The parsed inet address, or {@link Optional#absent()} if no inet
445 * address could be parsed
447 private Optional<InetAddress> parseInetAddress(String ip) {
448 Long ipNumber = Longs.tryParse(ip);
449 if (ipNumber == null) {
450 return Optional.absent();
453 StringBuilder hostname = new StringBuilder(15);
454 hostname.append((ipNumber >>> 24) & 0xff).append('.');
455 hostname.append((ipNumber >>> 16) & 0xff).append('.');
456 hostname.append((ipNumber >>> 8) & 0xff).append('.');
457 hostname.append(ipNumber & 0xff);
459 return Optional.of(InetAddress.getByName(hostname.toString()));
460 } catch (UnknownHostException uhe1) {
461 return Optional.absent();
465 /** Handles input and output for the connection. */
466 private class ConnectionHandler implements Closeable {
468 /** The output stream of the connection. */
469 private final OutputStream outputStream;
471 /** The input stream of the connection. */
472 private final BufferedReader inputStreamReader;
475 * Creates a new connection handler for the given input stream and output
479 * The input stream of the connection
480 * @param outputStream
481 * The output stream of the connection
482 * @throws UnsupportedEncodingException
483 * if the encoding (currently “UTF-8”) is not valid
485 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
486 this.outputStream = outputStream;
487 inputStreamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
495 * Sends a command with the given parameters, skipping all {@link
496 * Optional#absent()} optionals.
499 * The command to send
502 * @throws IOException
503 * if an I/O error occurs
505 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
506 List<String> setParameters = new ArrayList<String>();
507 for (Optional<String> maybeSetParameter : parameters) {
508 if (maybeSetParameter.isPresent()) {
509 setParameters.add(maybeSetParameter.get());
512 sendCommand(command, setParameters.toArray(new String[setParameters.size()]));
516 * Sends a command with the given parameters.
519 * The command to send
521 * The parameters of the command
522 * @throws IOException
523 * if an I/O error occurs
524 * @throws IllegalArgumentException
525 * if any parameter but that last contains a space character
527 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
528 StringBuilder commandBuilder = new StringBuilder();
530 commandBuilder.append(command);
531 for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
532 String parameter = parameters[parameterIndex];
533 /* space is only allowed in the last parameter. */
534 commandBuilder.append(' ');
535 if (parameter.contains(" ")) {
536 if (parameterIndex == (parameters.length - 1)) {
537 commandBuilder.append(':');
539 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
542 commandBuilder.append(parameter);
545 logger.finest(String.format(">> %s", commandBuilder));
546 outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
547 outputStream.flush();
551 * Reads a line of reply from the connection.
554 * @throws IOException
555 * if an I/O error occurs
556 * @throws EOFException
559 public Reply readReply() throws IOException, EOFException {
560 String line = inputStreamReader.readLine();
562 throw new EOFException();
565 return Reply.parseLine(line);
573 public void close() throws IOException {
574 Closeables.close(outputStream, true);
575 Closeables.close(inputStreamReader, true);