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.MotdReceived;
50 import net.pterodactylus.irc.event.NicknameInUseReceived;
51 import net.pterodactylus.irc.event.NoNicknameGivenReceived;
52 import net.pterodactylus.irc.event.PrivateMessageReceived;
53 import net.pterodactylus.irc.event.UnknownReplyReceived;
54 import net.pterodactylus.irc.util.RandomNickname;
56 import com.google.common.base.Optional;
57 import com.google.common.collect.Maps;
58 import com.google.common.collect.Sets;
59 import com.google.common.eventbus.EventBus;
60 import com.google.common.io.Closeables;
61 import com.google.common.primitives.Longs;
62 import com.google.common.util.concurrent.AbstractExecutionThreadService;
63 import com.google.common.util.concurrent.Service;
66 * A connection to an IRC server.
68 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
70 public class Connection extends AbstractExecutionThreadService implements Service {
73 private static final Logger logger = Logger.getLogger(Connection.class.getName());
76 private final EventBus eventBus;
78 /** The socket factory. */
79 private final SocketFactory socketFactory;
81 /** The hostname to connect to. */
82 private final String hostname;
84 /** The port to connect to. */
85 private final int port;
87 /** The nickname chooser. */
88 private NicknameChooser nicknameChooser = new NicknameChooser() {
91 public String getNickname() {
92 return RandomNickname.get();
97 private String nickname = null;
100 private Optional<String> username = Optional.absent();
102 /** The real name. */
103 private Optional<String> realName = Optional.absent();
105 /** The optional password for the connection. */
106 private Optional<String> password = Optional.absent();
108 /** The connection handler. */
109 private ConnectionHandler connectionHandler;
112 * Creates a new connection.
116 * @param socketFactory
119 * The hostname of the IRC server
121 * The port number of the IRC server
123 public Connection(EventBus eventBus, SocketFactory socketFactory, String hostname, int port) {
124 this.eventBus = eventBus;
125 this.socketFactory = socketFactory;
126 this.hostname = hostname;
135 * Returns the nickname that is currently in use by this connection. The
136 * nickname is only available once the connection has been {@link #start()}ed.
138 * @return The current nickname
140 public String nickname() {
149 * Sets the nickname chooser. The nickname chooser is only used during the
150 * creation of the connection.
152 * @param nicknameChooser
153 * The nickname chooser
154 * @return This connection
156 public Connection nicknameChooser(NicknameChooser nicknameChooser) {
157 this.nicknameChooser = nicknameChooser;
162 * Sets the username to use.
165 * The username to use
166 * @return This connection
168 public Connection username(String username) {
169 this.username = Optional.fromNullable(username);
174 * Sets the real name to use.
177 * The real name to use
178 * @return This connection
180 public Connection realName(String realName) {
181 this.realName = Optional.fromNullable(realName);
186 * Sets the optional password for the connection.
189 * The password for the connection
190 * @return This connection
192 public Connection password(String password) {
193 this.password = Optional.fromNullable(password);
202 * Joins the given channel.
205 * The channel to join
206 * @throws IOException
207 * if an I/O error occurs
209 public void joinChannel(final String channel) throws IOException {
210 connectionHandler.sendCommand("JOIN", channel);
214 * Sends a message to the given recipient, which may be a channel or another
218 * The recipient of the message
221 * @throws IOException
222 * if an I/O error occurs
224 public void sendMessage(String recipient, String message) throws IOException {
225 connectionHandler.sendCommand("PRIVMSG", recipient, message);
229 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
233 protected void startUp() throws IllegalStateException {
234 checkState(username.isPresent(), "username must be set");
235 checkState(realName.isPresent(), "realName must be set");
239 protected void run() {
241 /* connect to remote socket. */
243 Socket socket = socketFactory.createSocket(hostname, port);
244 connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
246 /* register connection. */
247 if (password.isPresent()) {
248 connectionHandler.sendCommand("PASSWORD", password.get());
250 connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
251 nickname = nicknameChooser.getNickname();
252 connectionHandler.sendCommand("NICK", nickname);
254 } catch (IOException ioe1) {
255 eventBus.post(new ConnectionFailed(this, ioe1));
259 /* now read replies and react. */
261 /* some status variables. */
262 int oldConnectionStatus = 0;
263 int connectionStatus = 0;
264 boolean connected = true;
265 StringBuilder motd = new StringBuilder();
266 Set<Nickname> nicks = Sets.newHashSet();
269 Map<String, String> nickPrefixes = Maps.newHashMap();
270 Set<Character> channelTypes = Sets.newHashSet();
273 Reply reply = connectionHandler.readReply();
274 logger.finest(String.format("<< %s", reply));
275 String command = reply.command();
276 List<String> parameters = reply.parameters();
278 /* most common events. */
279 if (command.equalsIgnoreCase("PRIVMSG")) {
280 String recipient = parameters.get(0);
281 String message = parameters.get(1);
282 if (!channelTypes.contains(recipient.charAt(0))) {
283 eventBus.post(new PrivateMessageReceived(this, reply.source().get(), message));
285 eventBus.post(new ChannelMessageReceived(this, recipient, reply.source().get(), message));
288 /* replies 001-004 don’t hold information but they have to be sent on a successful connection. */
289 } else if (command.equals("001")) {
290 connectionStatus |= 0x01;
291 } else if (command.equals("002")) {
292 connectionStatus |= 0x02;
293 } else if (command.equals("003")) {
294 connectionStatus |= 0x04;
295 } else if (command.equals("004")) {
296 connectionStatus |= 0x08;
298 /* 005 originally was a bounce message, now used to transmit useful information about the server. */
299 } else if (command.equals("005")) {
300 for (String parameter : parameters) {
301 if (parameter.startsWith("PREFIX=")) {
302 int openParen = parameter.indexOf('(');
303 int closeParen = parameter.indexOf(')');
304 if ((openParen != -1) && (closeParen != -1)) {
305 for (int modeCharacterIndex = 1; modeCharacterIndex < (closeParen - openParen); ++modeCharacterIndex) {
306 char modeCharacter = parameter.charAt(openParen + modeCharacterIndex);
307 char modeSymbol = parameter.charAt(closeParen + modeCharacterIndex);
308 nickPrefixes.put(String.valueOf(modeSymbol), String.valueOf(modeCharacter));
310 logger.fine(String.format("Parsed Prefixes: %s", nickPrefixes));
312 } else if (parameter.startsWith("CHANTYPES=")) {
313 for (int typeIndex = 10; typeIndex < parameter.length(); ++typeIndex) {
314 channelTypes.add(parameter.charAt(typeIndex));
316 logger.fine(String.format("Parsed Channel Types: %s", channelTypes));
320 /* 375, 372, and 376 handle the server’s MOTD. */
321 } else if (command.equals("375")) {
323 motd.append(parameters.get(1)).append('\n');
324 } else if (command.equals("372")) {
325 motd.append(parameters.get(1)).append('\n');
326 } else if (command.equals("376")) {
327 motd.append(parameters.get(1)).append('\n');
328 eventBus.post(new MotdReceived(this, motd.toString()));
331 /* 43x replies are for nick change errors. */
332 } else if (command.equals("431")) {
333 eventBus.post(new NoNicknameGivenReceived(this, reply));
334 } else if (command.equals("433")) {
335 if (connectionStatus == 0) {
336 nickname = nicknameChooser.getNickname();
337 connectionHandler.sendCommand("NICK", nickname);
339 eventBus.post(new NicknameInUseReceived(this, reply));
343 } else if (command.equalsIgnoreCase("JOIN")) {
344 eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
345 } else if (command.equals("331")) {
346 /* no topic is set. */
347 } else if (command.equals("332")) {
348 eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
349 } else if (command.equals("353")) {
350 for (String nickname : parameters.get(3).split(" ")) {
351 if (nickPrefixes.containsKey(nickname.substring(0, 1))) {
352 nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
354 nicks.add(new Nickname(nickname, ""));
357 } else if (command.equals("366")) {
358 eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
361 /* common channel join errors. */
362 } else if (command.equals("474")) {
363 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.banned));
364 } else if (command.equals("473")) {
365 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.inviteOnly));
366 } else if (command.equals("475")) {
367 eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.badChannelKey));
369 /* basic connection housekeeping. */
370 } else if (command.equalsIgnoreCase("PING")) {
371 connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
373 /* okay, everything else. */
375 eventBus.post(new UnknownReplyReceived(this, reply));
378 if ((connectionStatus == 0x0f) && (connectionStatus != oldConnectionStatus)) {
379 /* connection succeeded! */
380 eventBus.post(new ConnectionEstablished(this));
382 oldConnectionStatus = connectionStatus;
384 } catch (IOException ioe1) {
385 logger.log(Level.WARNING, "I/O error", ioe1);
387 logger.info("Closing Connection.");
389 Closeables.close(connectionHandler, true);
390 } catch (IOException ioe1) {
391 /* will not be thrown. */
402 * Returns an item from the list, or {@link Optional#absent()} if the list is
403 * shorter than required for the given index.
406 * The list to get an item from
408 * The index of the item
410 * The type of the list items
411 * @return This list item wrapped in an {@link Optional}, or {@link
412 * Optional#absent()} if the list is not long enough
414 private static <T> Optional<T> getOptional(List<T> list, int index) {
415 if (index < list.size()) {
416 return Optional.fromNullable(list.get(index));
418 return Optional.absent();
422 * Parses the given {@code ip} and returns an {@link InetAddress} from it.
426 * @return The parsed inet address, or {@link Optional#absent()} if no inet
427 * address could be parsed
429 private Optional<InetAddress> parseInetAddress(String ip) {
430 Long ipNumber = Longs.tryParse(ip);
431 if (ipNumber == null) {
432 return Optional.absent();
435 StringBuilder hostname = new StringBuilder(15);
436 hostname.append((ipNumber >>> 24) & 0xff).append('.');
437 hostname.append((ipNumber >>> 16) & 0xff).append('.');
438 hostname.append((ipNumber >>> 8) & 0xff).append('.');
439 hostname.append(ipNumber & 0xff);
441 return Optional.of(InetAddress.getByName(hostname.toString()));
442 } catch (UnknownHostException uhe1) {
443 return Optional.absent();
447 /** Handles input and output for the connection. */
448 private class ConnectionHandler implements Closeable {
450 /** The output stream of the connection. */
451 private final OutputStream outputStream;
453 /** The input stream of the connection. */
454 private final BufferedReader inputStreamReader;
457 * Creates a new connection handler for the given input stream and output
461 * The input stream of the connection
462 * @param outputStream
463 * The output stream of the connection
464 * @throws UnsupportedEncodingException
465 * if the encoding (currently “UTF-8”) is not valid
467 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
468 this.outputStream = outputStream;
469 inputStreamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
477 * Sends a command with the given parameters, skipping all {@link
478 * Optional#absent()} optionals.
481 * The command to send
484 * @throws IOException
485 * if an I/O error occurs
487 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
488 List<String> setParameters = new ArrayList<String>();
489 for (Optional<String> maybeSetParameter : parameters) {
490 if (maybeSetParameter.isPresent()) {
491 setParameters.add(maybeSetParameter.get());
494 sendCommand(command, setParameters.toArray(new String[setParameters.size()]));
498 * Sends a command with the given parameters.
501 * The command to send
503 * The parameters of the command
504 * @throws IOException
505 * if an I/O error occurs
506 * @throws IllegalArgumentException
507 * if any parameter but that last contains a space character
509 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
510 StringBuilder commandBuilder = new StringBuilder();
512 commandBuilder.append(command);
513 for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
514 String parameter = parameters[parameterIndex];
515 /* space is only allowed in the last parameter. */
516 commandBuilder.append(' ');
517 if (parameter.contains(" ")) {
518 if (parameterIndex == (parameters.length - 1)) {
519 commandBuilder.append(':');
521 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
524 commandBuilder.append(parameter);
527 logger.finest(String.format(">> %s", commandBuilder));
528 outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
529 outputStream.flush();
533 * Reads a line of reply from the connection.
536 * @throws IOException
537 * if an I/O error occurs
538 * @throws EOFException
541 public Reply readReply() throws IOException, EOFException {
542 String line = inputStreamReader.readLine();
544 throw new EOFException();
547 return Reply.parseLine(line);
555 public void close() throws IOException {
556 Closeables.close(outputStream, true);
557 Closeables.close(inputStreamReader, true);