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;
21 import static java.util.Arrays.asList;
22 import static java.util.concurrent.TimeUnit.SECONDS;
24 import java.io.BufferedReader;
25 import java.io.Closeable;
26 import java.io.EOFException;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.io.InputStreamReader;
30 import java.io.OutputStream;
31 import java.io.UnsupportedEncodingException;
32 import java.net.Socket;
33 import java.util.ArrayList;
34 import java.util.List;
35 import java.util.concurrent.TimeUnit;
36 import java.util.concurrent.atomic.AtomicBoolean;
38 import javax.net.SocketFactory;
40 import net.pterodactylus.irc.connection.ChannelNickHandler;
41 import net.pterodactylus.irc.connection.ChannelNotJoinedHandler;
42 import net.pterodactylus.irc.connection.ConnectionEstablishHandler;
43 import net.pterodactylus.irc.connection.CtcpHandler;
44 import net.pterodactylus.irc.connection.Handler;
45 import net.pterodactylus.irc.connection.MessageHandler;
46 import net.pterodactylus.irc.connection.MotdHandler;
47 import net.pterodactylus.irc.connection.PrefixHandler;
48 import net.pterodactylus.irc.connection.SimpleCommandHandler;
49 import net.pterodactylus.irc.event.ChannelJoined;
50 import net.pterodactylus.irc.event.ChannelLeft;
51 import net.pterodactylus.irc.event.ChannelTopic;
52 import net.pterodactylus.irc.event.ClientQuit;
53 import net.pterodactylus.irc.event.ConnectionClosed;
54 import net.pterodactylus.irc.event.ConnectionEstablished;
55 import net.pterodactylus.irc.event.ConnectionFailed;
56 import net.pterodactylus.irc.event.KickedFromChannel;
57 import net.pterodactylus.irc.event.NicknameChanged;
58 import net.pterodactylus.irc.event.NicknameInUseReceived;
59 import net.pterodactylus.irc.event.NoNicknameGivenReceived;
60 import net.pterodactylus.irc.event.ReplyReceived;
61 import net.pterodactylus.irc.event.UnknownReplyReceived;
62 import net.pterodactylus.irc.util.RandomNickname;
63 import net.pterodactylus.xdcc.util.io.BandwidthCountingInputStream;
64 import net.pterodactylus.xdcc.util.io.BandwidthCountingOutputStream;
66 import com.google.common.base.Optional;
67 import com.google.common.eventbus.EventBus;
68 import com.google.common.eventbus.Subscribe;
69 import com.google.common.io.Closeables;
70 import com.google.common.util.concurrent.AbstractExecutionThreadService;
71 import com.google.common.util.concurrent.Service;
72 import org.apache.log4j.Logger;
75 * A connection to an IRC server.
77 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
79 public class Connection extends AbstractExecutionThreadService implements Service {
82 private static final Logger logger = Logger.getLogger(Connection.class.getName());
85 private final EventBus eventBus;
87 /** The socket factory. */
88 private final SocketFactory socketFactory;
90 /** The hostname to connect to. */
91 private final String hostname;
93 /** The port to connect to. */
94 private final int port;
96 /** The nickname chooser. */
97 private NicknameChooser nicknameChooser = new NicknameChooser() {
100 public String getNickname() {
101 return RandomNickname.get();
106 private String nickname = null;
109 private Optional<String> username = Optional.absent();
111 /** The real name. */
112 private Optional<String> realName = Optional.absent();
114 /** The optional password for the connection. */
115 private Optional<String> password = Optional.absent();
117 /** The connection handler. */
118 private ConnectionHandler connectionHandler;
120 /** Whether the connection has already been established. */
121 private final AtomicBoolean established = new AtomicBoolean();
124 * Creates a new connection.
128 * @param socketFactory
131 * The hostname of the IRC server
133 * The port number of the IRC server
135 public Connection(EventBus eventBus, SocketFactory socketFactory, String hostname, int port) {
136 this.eventBus = eventBus;
137 this.socketFactory = socketFactory;
138 this.hostname = hostname;
147 * Returns the hostname of the remote end of the connection.
149 * @return The remote’s hostname
151 public String hostname() {
156 * Returns the port number of the remote end of the connection.
158 * @return The remote’s port number
165 * Returns whether this connection has already been established.
167 * @return {@code true} as long as this connection is established, {@code
170 public boolean established() {
171 return established.get();
175 * Returns the nickname that is currently in use by this connection. The
176 * nickname is only available once the connection has been {@link #start()}ed.
178 * @return The current nickname
180 public String nickname() {
189 * Sets the nickname chooser. The nickname chooser is only used during the
190 * creation of the connection.
192 * @param nicknameChooser
193 * The nickname chooser
194 * @return This connection
196 public Connection nicknameChooser(NicknameChooser nicknameChooser) {
197 this.nicknameChooser = nicknameChooser;
202 * Sets the username to use.
205 * The username to use
206 * @return This connection
208 public Connection username(String username) {
209 this.username = Optional.fromNullable(username);
214 * Sets the real name to use.
217 * The real name to use
218 * @return This connection
220 public Connection realName(String realName) {
221 this.realName = Optional.fromNullable(realName);
226 * Sets the optional password for the connection.
229 * The password for the connection
230 * @return This connection
232 public Connection password(String password) {
233 this.password = Optional.fromNullable(password);
242 * Returns the current rate of the connection’s incoming side.
244 * @return The current input rate (in bytes per second)
246 public long getInputRate() {
247 return (connectionHandler != null) ? connectionHandler.getInputRate() : 0;
251 * Returns the current rate of the connection’s outgoing side.
253 * @return The current output rate (in bytes per second)
255 public long getOutputRate() {
256 return (connectionHandler != null) ? connectionHandler.getOutputRate() : 0;
260 * Checks whether the given source is the client represented by this
264 * The source to check
265 * @return {@code true} if this connection represents the given source, {@code
268 public boolean isSource(Source source) {
269 return source.nick().isPresent() && source.nick().get().equals(nickname);
273 * Joins the given channel.
276 * The channel to join
277 * @throws IOException
278 * if an I/O error occurs
280 public void joinChannel(final String channel) throws IOException {
281 connectionHandler.sendCommand("JOIN", channel);
285 * Sends a message to the given recipient, which may be a channel or another
289 * The recipient of the message
292 * @throws IOException
293 * if an I/O error occurs
295 public void sendMessage(String recipient, String message) throws IOException {
296 connectionHandler.sendCommand("PRIVMSG", recipient, message);
300 * Sends a DCC RESUME request to the given recipient.
303 * The recipient of the request
305 * The name of the file to resume
307 * The port number from the original DCC SEND request
309 * The position at which to resume the transfer
310 * @throws IOException
311 * if an I/O error occurs
313 public void sendDccResume(String recipient, String filename, int port, long position) throws IOException {
314 connectionHandler.sendCommand("PRIVMSG", recipient, String.format("\u0001DCC RESUME %s %d %d\u0001", filename, port, position));
318 * Closes this connection.
320 * @throws IOException
321 * if an I/O error occurs
323 public void close() throws IOException {
324 if (connectionHandler != null) {
325 connectionHandler.close();
330 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
334 protected void startUp() throws IllegalStateException {
335 checkState(username.isPresent(), "username must be set");
336 checkState(realName.isPresent(), "realName must be set");
340 protected void run() {
342 /* connect to remote socket. */
344 Socket socket = socketFactory.createSocket(hostname, port);
345 socket.setSoTimeout((int) TimeUnit.MINUTES.toMillis(3));
346 connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
348 /* register connection. */
349 if (password.isPresent()) {
350 connectionHandler.sendCommand("PASSWORD", password.get());
352 connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
353 nickname = nicknameChooser.getNickname();
354 connectionHandler.sendCommand("NICK", nickname);
356 } catch (IOException ioe1) {
357 eventBus.post(new ConnectionFailed(this, ioe1));
361 eventBus.register(this);
362 /* now read replies and react. */
364 /* some status variables. */
365 boolean connected = true;
367 PrefixHandler prefixHandler = new PrefixHandler();
368 List<Handler> handlers = asList(
369 new MessageHandler(eventBus, this, prefixHandler),
370 new CtcpHandler(eventBus, this),
371 new ChannelNickHandler(eventBus, this, prefixHandler),
372 new SimpleCommandHandler()
373 .addCommand("431", (parameters) -> eventBus.post(
374 new NoNicknameGivenReceived(this))),
375 new MotdHandler(eventBus, this),
376 new ChannelNotJoinedHandler(eventBus, this),
377 new ConnectionEstablishHandler(eventBus, this),
382 Reply reply = connectionHandler.readReply();
383 eventBus.post(new ReplyReceived(this, reply));
384 logger.trace(String.format("<< %s", reply));
385 String command = reply.command();
386 List<String> parameters = reply.parameters();
388 for (Handler handler : handlers) {
389 if (handler.willHandle(reply)) {
390 handler.handleReply(reply);
395 /* 43x replies are for nick change errors. */
396 if (command.equals("433")) {
397 if (!established.get()) {
398 nickname = nicknameChooser.getNickname();
399 connectionHandler.sendCommand("NICK", nickname);
401 eventBus.post(new NicknameInUseReceived(this, reply));
405 } else if (command.equalsIgnoreCase("NICK")) {
406 eventBus.post(new NicknameChanged(this, reply.source().get(), parameters.get(0)));
409 } else if (command.equalsIgnoreCase("JOIN")) {
410 eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
411 } else if (command.equals("331")) {
412 /* no topic is set. */
413 } else if (command.equals("332")) {
414 eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
415 } else if (command.equalsIgnoreCase("PART")) {
416 eventBus.post(new ChannelLeft(this, parameters.get(0), reply.source().get(), getOptional(parameters, 1)));
417 } else if (command.equalsIgnoreCase("QUIT")) {
418 eventBus.post(new ClientQuit(this, reply.source().get(), parameters.get(0)));
420 /* basic connection housekeeping. */
421 } else if (command.equalsIgnoreCase("PING")) {
422 connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
424 } else if (command.equalsIgnoreCase("KICK")) {
425 eventBus.post(new KickedFromChannel(this, parameters.get(0), reply.source().get(), parameters.get(1), getOptional(parameters, 2)));
427 /* okay, everything else. */
429 eventBus.post(new UnknownReplyReceived(this, reply));
432 eventBus.post(new ConnectionClosed(this));
433 } catch (IOException ioe1) {
434 logger.warn("I/O error", ioe1);
435 eventBus.post(new ConnectionClosed(this, ioe1));
436 } catch (RuntimeException re1) {
437 logger.error("Runtime error", re1);
438 eventBus.post(new ConnectionClosed(this, re1));
440 established.set(false);
441 eventBus.unregister(this);
442 logger.info("Closing Connection.");
444 Closeables.close(connectionHandler, true);
445 } catch (IOException ioe1) {
446 /* will not be thrown. */
453 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
454 if (connectionEstablished.connection() == this) {
455 established.set(true);
464 * Returns an item from the list, or {@link Optional#absent()} if the list is
465 * shorter than required for the given index.
468 * The list to get an item from
470 * The index of the item
472 * The type of the list items
473 * @return This list item wrapped in an {@link Optional}, or {@link
474 * Optional#absent()} if the list is not long enough
476 private static <T> Optional<T> getOptional(List<T> list, int index) {
477 if (index < list.size()) {
478 return Optional.fromNullable(list.get(index));
480 return Optional.absent();
483 /** Handles input and output for the connection. */
484 private class ConnectionHandler implements Closeable {
486 /** The output stream of the connection. */
487 private final BandwidthCountingOutputStream outputStream;
489 /** The input stream. */
490 private final BandwidthCountingInputStream inputStream;
492 /** The input stream of the connection. */
493 private final BufferedReader inputStreamReader;
496 * Creates a new connection handler for the given input stream and output
500 * The input stream of the connection
501 * @param outputStream
502 * The output stream of the connection
503 * @throws UnsupportedEncodingException
504 * if the encoding (currently “UTF-8”) is not valid
506 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
507 this.outputStream = new BandwidthCountingOutputStream(outputStream, 5, SECONDS);
508 this.inputStream = new BandwidthCountingInputStream(inputStream, 5, SECONDS);
509 inputStreamReader = new BufferedReader(new InputStreamReader(this.inputStream, "UTF-8"));
517 * Returns the current rate of the connection’s incoming side.
519 * @return The current input rate (in bytes per second)
521 public long getInputRate() {
522 return inputStream.getCurrentRate();
526 * Returns the current rate of the connection’s outgoing side.
528 * @return The current output rate (in bytes per second)
530 public long getOutputRate() {
531 return outputStream.getCurrentRate();
535 * Sends a command with the given parameters, skipping all {@link
536 * Optional#absent()} optionals.
539 * The command to send
542 * @throws IOException
543 * if an I/O error occurs
545 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
546 List<String> setParameters = new ArrayList<String>();
547 for (Optional<String> maybeSetParameter : parameters) {
548 if (maybeSetParameter.isPresent()) {
549 setParameters.add(maybeSetParameter.get());
552 sendCommand(command, setParameters.toArray(new String[setParameters.size()]));
556 * Sends a command with the given parameters.
559 * The command to send
561 * The parameters of the command
562 * @throws IOException
563 * if an I/O error occurs
564 * @throws IllegalArgumentException
565 * if any parameter but that last contains a space character
567 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
568 StringBuilder commandBuilder = new StringBuilder();
570 commandBuilder.append(command);
571 for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
572 String parameter = parameters[parameterIndex];
573 /* space is only allowed in the last parameter. */
574 commandBuilder.append(' ');
575 if (parameter.contains(" ")) {
576 if (parameterIndex == (parameters.length - 1)) {
577 commandBuilder.append(':');
579 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
582 commandBuilder.append(parameter);
585 logger.trace(String.format(">> %s", commandBuilder));
586 outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
587 outputStream.flush();
591 * Reads a line of reply from the connection.
594 * @throws IOException
595 * if an I/O error occurs
596 * @throws EOFException
599 public Reply readReply() throws IOException, EOFException {
600 String line = inputStreamReader.readLine();
602 throw new EOFException();
605 return Reply.parseLine(line);
613 public void close() throws IOException {
614 Closeables.close(outputStream, true);
615 Closeables.close(inputStreamReader, true);
616 Closeables.close(inputStream, true);