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.event.ChannelJoined;
49 import net.pterodactylus.irc.event.ChannelLeft;
50 import net.pterodactylus.irc.event.ChannelTopic;
51 import net.pterodactylus.irc.event.ClientQuit;
52 import net.pterodactylus.irc.event.ConnectionClosed;
53 import net.pterodactylus.irc.event.ConnectionEstablished;
54 import net.pterodactylus.irc.event.ConnectionFailed;
55 import net.pterodactylus.irc.event.KickedFromChannel;
56 import net.pterodactylus.irc.event.NicknameChanged;
57 import net.pterodactylus.irc.event.NicknameInUseReceived;
58 import net.pterodactylus.irc.event.NoNicknameGivenReceived;
59 import net.pterodactylus.irc.event.ReplyReceived;
60 import net.pterodactylus.irc.event.UnknownReplyReceived;
61 import net.pterodactylus.irc.util.RandomNickname;
62 import net.pterodactylus.xdcc.util.io.BandwidthCountingInputStream;
63 import net.pterodactylus.xdcc.util.io.BandwidthCountingOutputStream;
65 import com.google.common.base.Optional;
66 import com.google.common.eventbus.EventBus;
67 import com.google.common.eventbus.Subscribe;
68 import com.google.common.io.Closeables;
69 import com.google.common.util.concurrent.AbstractExecutionThreadService;
70 import com.google.common.util.concurrent.Service;
71 import org.apache.log4j.Logger;
74 * A connection to an IRC server.
76 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
78 public class Connection extends AbstractExecutionThreadService implements Service {
81 private static final Logger logger = Logger.getLogger(Connection.class.getName());
84 private final EventBus eventBus;
86 /** The socket factory. */
87 private final SocketFactory socketFactory;
89 /** The hostname to connect to. */
90 private final String hostname;
92 /** The port to connect to. */
93 private final int port;
95 /** The nickname chooser. */
96 private NicknameChooser nicknameChooser = new NicknameChooser() {
99 public String getNickname() {
100 return RandomNickname.get();
105 private String nickname = null;
108 private Optional<String> username = Optional.absent();
110 /** The real name. */
111 private Optional<String> realName = Optional.absent();
113 /** The optional password for the connection. */
114 private Optional<String> password = Optional.absent();
116 /** The connection handler. */
117 private ConnectionHandler connectionHandler;
119 /** Whether the connection has already been established. */
120 private final AtomicBoolean established = new AtomicBoolean();
123 * Creates a new connection.
127 * @param socketFactory
130 * The hostname of the IRC server
132 * The port number of the IRC server
134 public Connection(EventBus eventBus, SocketFactory socketFactory, String hostname, int port) {
135 this.eventBus = eventBus;
136 this.socketFactory = socketFactory;
137 this.hostname = hostname;
146 * Returns the hostname of the remote end of the connection.
148 * @return The remote’s hostname
150 public String hostname() {
155 * Returns the port number of the remote end of the connection.
157 * @return The remote’s port number
164 * Returns whether this connection has already been established.
166 * @return {@code true} as long as this connection is established, {@code
169 public boolean established() {
170 return established.get();
174 * Returns the nickname that is currently in use by this connection. The
175 * nickname is only available once the connection has been {@link #start()}ed.
177 * @return The current nickname
179 public String nickname() {
188 * Sets the nickname chooser. The nickname chooser is only used during the
189 * creation of the connection.
191 * @param nicknameChooser
192 * The nickname chooser
193 * @return This connection
195 public Connection nicknameChooser(NicknameChooser nicknameChooser) {
196 this.nicknameChooser = nicknameChooser;
201 * Sets the username to use.
204 * The username to use
205 * @return This connection
207 public Connection username(String username) {
208 this.username = Optional.fromNullable(username);
213 * Sets the real name to use.
216 * The real name to use
217 * @return This connection
219 public Connection realName(String realName) {
220 this.realName = Optional.fromNullable(realName);
225 * Sets the optional password for the connection.
228 * The password for the connection
229 * @return This connection
231 public Connection password(String password) {
232 this.password = Optional.fromNullable(password);
241 * Returns the current rate of the connection’s incoming side.
243 * @return The current input rate (in bytes per second)
245 public long getInputRate() {
246 return (connectionHandler != null) ? connectionHandler.getInputRate() : 0;
250 * Returns the current rate of the connection’s outgoing side.
252 * @return The current output rate (in bytes per second)
254 public long getOutputRate() {
255 return (connectionHandler != null) ? connectionHandler.getOutputRate() : 0;
259 * Checks whether the given source is the client represented by this
263 * The source to check
264 * @return {@code true} if this connection represents the given source, {@code
267 public boolean isSource(Source source) {
268 return source.nick().isPresent() && source.nick().get().equals(nickname);
272 * Joins the given channel.
275 * The channel to join
276 * @throws IOException
277 * if an I/O error occurs
279 public void joinChannel(final String channel) throws IOException {
280 connectionHandler.sendCommand("JOIN", channel);
284 * Sends a message to the given recipient, which may be a channel or another
288 * The recipient of the message
291 * @throws IOException
292 * if an I/O error occurs
294 public void sendMessage(String recipient, String message) throws IOException {
295 connectionHandler.sendCommand("PRIVMSG", recipient, message);
299 * Sends a DCC RESUME request to the given recipient.
302 * The recipient of the request
304 * The name of the file to resume
306 * The port number from the original DCC SEND request
308 * The position at which to resume the transfer
309 * @throws IOException
310 * if an I/O error occurs
312 public void sendDccResume(String recipient, String filename, int port, long position) throws IOException {
313 connectionHandler.sendCommand("PRIVMSG", recipient, String.format("\u0001DCC RESUME %s %d %d\u0001", filename, port, position));
317 * Closes this connection.
319 * @throws IOException
320 * if an I/O error occurs
322 public void close() throws IOException {
323 if (connectionHandler != null) {
324 connectionHandler.close();
329 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
333 protected void startUp() throws IllegalStateException {
334 checkState(username.isPresent(), "username must be set");
335 checkState(realName.isPresent(), "realName must be set");
339 protected void run() {
341 /* connect to remote socket. */
343 Socket socket = socketFactory.createSocket(hostname, port);
344 socket.setSoTimeout((int) TimeUnit.MINUTES.toMillis(3));
345 connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
347 /* register connection. */
348 if (password.isPresent()) {
349 connectionHandler.sendCommand("PASSWORD", password.get());
351 connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
352 nickname = nicknameChooser.getNickname();
353 connectionHandler.sendCommand("NICK", nickname);
355 } catch (IOException ioe1) {
356 eventBus.post(new ConnectionFailed(this, ioe1));
360 eventBus.register(this);
361 /* now read replies and react. */
363 /* some status variables. */
364 boolean connected = true;
366 PrefixHandler prefixHandler = new PrefixHandler();
367 List<Handler> handlers = asList(
368 new MessageHandler(eventBus, this, prefixHandler),
369 new CtcpHandler(eventBus, this),
370 new ChannelNickHandler(eventBus, this, prefixHandler),
371 new MotdHandler(eventBus, this),
372 new ChannelNotJoinedHandler(eventBus, this),
373 new ConnectionEstablishHandler(eventBus, this),
378 Reply reply = connectionHandler.readReply();
379 eventBus.post(new ReplyReceived(this, reply));
380 logger.trace(String.format("<< %s", reply));
381 String command = reply.command();
382 List<String> parameters = reply.parameters();
384 for (Handler handler : handlers) {
385 if (handler.willHandle(reply)) {
386 handler.handleReply(reply);
391 /* 43x replies are for nick change errors. */
392 if (command.equals("431")) {
393 eventBus.post(new NoNicknameGivenReceived(this, reply));
394 } else if (command.equals("433")) {
395 if (!established.get()) {
396 nickname = nicknameChooser.getNickname();
397 connectionHandler.sendCommand("NICK", nickname);
399 eventBus.post(new NicknameInUseReceived(this, reply));
403 } else if (command.equalsIgnoreCase("NICK")) {
404 eventBus.post(new NicknameChanged(this, reply.source().get(), parameters.get(0)));
407 } else if (command.equalsIgnoreCase("JOIN")) {
408 eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
409 } else if (command.equals("331")) {
410 /* no topic is set. */
411 } else if (command.equals("332")) {
412 eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
413 } else if (command.equalsIgnoreCase("PART")) {
414 eventBus.post(new ChannelLeft(this, parameters.get(0), reply.source().get(), getOptional(parameters, 1)));
415 } else if (command.equalsIgnoreCase("QUIT")) {
416 eventBus.post(new ClientQuit(this, reply.source().get(), parameters.get(0)));
418 /* basic connection housekeeping. */
419 } else if (command.equalsIgnoreCase("PING")) {
420 connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
422 } else if (command.equalsIgnoreCase("KICK")) {
423 eventBus.post(new KickedFromChannel(this, parameters.get(0), reply.source().get(), parameters.get(1), getOptional(parameters, 2)));
425 /* okay, everything else. */
427 eventBus.post(new UnknownReplyReceived(this, reply));
430 eventBus.post(new ConnectionClosed(this));
431 } catch (IOException ioe1) {
432 logger.warn("I/O error", ioe1);
433 eventBus.post(new ConnectionClosed(this, ioe1));
434 } catch (RuntimeException re1) {
435 logger.error("Runtime error", re1);
436 eventBus.post(new ConnectionClosed(this, re1));
438 established.set(false);
439 eventBus.unregister(this);
440 logger.info("Closing Connection.");
442 Closeables.close(connectionHandler, true);
443 } catch (IOException ioe1) {
444 /* will not be thrown. */
451 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
452 if (connectionEstablished.connection() == this) {
453 established.set(true);
462 * Returns an item from the list, or {@link Optional#absent()} if the list is
463 * shorter than required for the given index.
466 * The list to get an item from
468 * The index of the item
470 * The type of the list items
471 * @return This list item wrapped in an {@link Optional}, or {@link
472 * Optional#absent()} if the list is not long enough
474 private static <T> Optional<T> getOptional(List<T> list, int index) {
475 if (index < list.size()) {
476 return Optional.fromNullable(list.get(index));
478 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 BandwidthCountingOutputStream outputStream;
487 /** The input stream. */
488 private final BandwidthCountingInputStream inputStream;
490 /** The input stream of the connection. */
491 private final BufferedReader inputStreamReader;
494 * Creates a new connection handler for the given input stream and output
498 * The input stream of the connection
499 * @param outputStream
500 * The output stream of the connection
501 * @throws UnsupportedEncodingException
502 * if the encoding (currently “UTF-8”) is not valid
504 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
505 this.outputStream = new BandwidthCountingOutputStream(outputStream, 5, SECONDS);
506 this.inputStream = new BandwidthCountingInputStream(inputStream, 5, SECONDS);
507 inputStreamReader = new BufferedReader(new InputStreamReader(this.inputStream, "UTF-8"));
515 * Returns the current rate of the connection’s incoming side.
517 * @return The current input rate (in bytes per second)
519 public long getInputRate() {
520 return inputStream.getCurrentRate();
524 * Returns the current rate of the connection’s outgoing side.
526 * @return The current output rate (in bytes per second)
528 public long getOutputRate() {
529 return outputStream.getCurrentRate();
533 * Sends a command with the given parameters, skipping all {@link
534 * Optional#absent()} optionals.
537 * The command to send
540 * @throws IOException
541 * if an I/O error occurs
543 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
544 List<String> setParameters = new ArrayList<String>();
545 for (Optional<String> maybeSetParameter : parameters) {
546 if (maybeSetParameter.isPresent()) {
547 setParameters.add(maybeSetParameter.get());
550 sendCommand(command, setParameters.toArray(new String[setParameters.size()]));
554 * Sends a command with the given parameters.
557 * The command to send
559 * The parameters of the command
560 * @throws IOException
561 * if an I/O error occurs
562 * @throws IllegalArgumentException
563 * if any parameter but that last contains a space character
565 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
566 StringBuilder commandBuilder = new StringBuilder();
568 commandBuilder.append(command);
569 for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
570 String parameter = parameters[parameterIndex];
571 /* space is only allowed in the last parameter. */
572 commandBuilder.append(' ');
573 if (parameter.contains(" ")) {
574 if (parameterIndex == (parameters.length - 1)) {
575 commandBuilder.append(':');
577 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
580 commandBuilder.append(parameter);
583 logger.trace(String.format(">> %s", commandBuilder));
584 outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
585 outputStream.flush();
589 * Reads a line of reply from the connection.
592 * @throws IOException
593 * if an I/O error occurs
594 * @throws EOFException
597 public Reply readReply() throws IOException, EOFException {
598 String line = inputStreamReader.readLine();
600 throw new EOFException();
603 return Reply.parseLine(line);
611 public void close() throws IOException {
612 Closeables.close(outputStream, true);
613 Closeables.close(inputStreamReader, true);
614 Closeables.close(inputStream, true);