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.time.Duration;
34 import java.time.Instant;
35 import java.util.ArrayList;
36 import java.util.List;
37 import java.util.Optional;
38 import java.util.concurrent.TimeUnit;
39 import java.util.concurrent.atomic.AtomicBoolean;
40 import java.util.concurrent.atomic.AtomicReference;
42 import javax.net.SocketFactory;
44 import net.pterodactylus.irc.connection.ChannelNickHandler;
45 import net.pterodactylus.irc.connection.ChannelNotJoinedHandler;
46 import net.pterodactylus.irc.connection.ConnectionEstablishHandler;
47 import net.pterodactylus.irc.connection.CtcpHandler;
48 import net.pterodactylus.irc.connection.Handler;
49 import net.pterodactylus.irc.connection.MessageHandler;
50 import net.pterodactylus.irc.connection.MotdHandler;
51 import net.pterodactylus.irc.connection.PrefixHandler;
52 import net.pterodactylus.irc.connection.SimpleCommandHandler;
53 import net.pterodactylus.irc.event.ChannelJoined;
54 import net.pterodactylus.irc.event.ChannelLeft;
55 import net.pterodactylus.irc.event.ChannelTopic;
56 import net.pterodactylus.irc.event.ClientQuit;
57 import net.pterodactylus.irc.event.ConnectionClosed;
58 import net.pterodactylus.irc.event.ConnectionEstablished;
59 import net.pterodactylus.irc.event.ConnectionFailed;
60 import net.pterodactylus.irc.event.KickedFromChannel;
61 import net.pterodactylus.irc.event.NicknameChanged;
62 import net.pterodactylus.irc.event.NicknameInUseReceived;
63 import net.pterodactylus.irc.event.NoNicknameGivenReceived;
64 import net.pterodactylus.irc.event.ReplyReceived;
65 import net.pterodactylus.irc.event.UnknownReplyReceived;
66 import net.pterodactylus.irc.util.RandomNickname;
67 import net.pterodactylus.xdcc.util.io.BandwidthCountingInputStream;
68 import net.pterodactylus.xdcc.util.io.BandwidthCountingOutputStream;
70 import com.google.common.eventbus.EventBus;
71 import com.google.common.eventbus.Subscribe;
72 import com.google.common.io.Closeables;
73 import com.google.common.util.concurrent.AbstractExecutionThreadService;
74 import com.google.common.util.concurrent.Service;
75 import org.apache.log4j.Logger;
78 * A connection to an IRC server.
80 * @author <a href="mailto:bombe@pterodactylus.net">David âBombeâ Roden</a>
82 public class DefaultConnection extends AbstractExecutionThreadService implements Service,
86 private static final Logger logger = Logger.getLogger(DefaultConnection.class.getName());
89 private final EventBus eventBus;
91 /** The socket factory. */
92 private final SocketFactory socketFactory;
94 /** The hostname to connect to. */
95 private final String hostname;
97 /** The port to connect to. */
98 private final int port;
100 /** The nickname chooser. */
101 private NicknameChooser nicknameChooser = new NicknameChooser() {
104 public String getNickname() {
105 return RandomNickname.get();
110 private String nickname = null;
113 private Optional<String> username = Optional.empty();
115 /** The real name. */
116 private Optional<String> realName = Optional.empty();
118 /** The optional password for the connection. */
119 private Optional<String> password = Optional.empty();
121 /** The connection handler. */
122 private ConnectionHandler connectionHandler;
124 /** Whether the connection has already been established. */
125 private final AtomicBoolean established = new AtomicBoolean();
126 private final AtomicReference<Instant> connectionTime = new AtomicReference<>();
129 * Creates a new connection.
133 * @param socketFactory
136 * The hostname of the IRC server
138 * The port number of the IRC server
140 public DefaultConnection(EventBus eventBus, SocketFactory socketFactory, String hostname,
142 this.eventBus = eventBus;
143 this.socketFactory = socketFactory;
144 this.hostname = hostname;
153 public String hostname() {
163 public boolean established() {
164 return established.get();
168 public String nickname() {
173 public Connection username(String username) {
174 this.username = Optional.ofNullable(username);
179 public Connection realName(String realName) {
180 this.realName = Optional.ofNullable(realName);
185 public Connection password(String password) {
186 this.password = Optional.ofNullable(password);
195 public long getInputRate() {
196 return (connectionHandler != null) ? connectionHandler.getInputRate() : 0;
200 public long getOutputRate() {
201 return (connectionHandler != null) ? connectionHandler.getOutputRate() : 0;
205 public boolean isSource(Source source) {
206 return source.nick().isPresent() && source.nick().get().equals(nickname);
210 public void joinChannel(final String channel) throws IOException {
211 connectionHandler.sendCommand("JOIN", channel);
215 public void sendMessage(String recipient, String message) throws IOException {
216 connectionHandler.sendCommand("PRIVMSG", recipient, message);
220 public void sendDccResume(String recipient, String filename, int port, long position) throws IOException {
221 connectionHandler.sendCommand("PRIVMSG", recipient,
222 String.format("\u0001DCC RESUME %s %d %d\u0001", filename, port, position));
231 public void close() throws IOException {
232 if (connectionHandler != null) {
233 connectionHandler.close();
238 public java.util.Optional<Duration> getUptime() {
239 return established.get() ?
240 java.util.Optional.of(Duration.between(connectionTime.get(), Instant.now())) :
241 java.util.Optional.<Duration>empty();
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 socket.setSoTimeout((int) TimeUnit.MINUTES.toMillis(3));
261 connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
263 /* register connection. */
264 if (password.isPresent()) {
265 connectionHandler.sendCommand("PASSWORD", password.get());
267 connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
268 nickname = nicknameChooser.getNickname();
269 connectionHandler.sendCommand("NICK", nickname);
271 } catch (IOException ioe1) {
272 eventBus.post(new ConnectionFailed(this, ioe1));
276 eventBus.register(this);
277 /* now read replies and react. */
279 /* some status variables. */
280 boolean connected = true;
282 PrefixHandler prefixHandler = new PrefixHandler();
283 List<Handler> handlers = asList(
284 new MessageHandler(eventBus, this, prefixHandler),
285 new CtcpHandler(eventBus, this),
286 new ChannelNickHandler(eventBus, this, prefixHandler),
287 new SimpleCommandHandler(eventBus)
289 (s, p) -> new NoNicknameGivenReceived(
292 (s, p) -> new NicknameChanged(this,
295 (s, p) -> new ChannelJoined(this,
298 (s, p) -> new ChannelTopic(this, p.get(1),
301 (s, p) -> new ChannelLeft(this, p.get(0),
302 s.get(), getOptional(p, 1)))
304 (s, p) -> new ClientQuit(this, s.get(),
307 (s, p) -> new KickedFromChannel(this,
308 p.get(0), s.get(), p.get(1),
310 new MotdHandler(eventBus, this),
311 new ChannelNotJoinedHandler(eventBus, this),
312 new ConnectionEstablishHandler(eventBus, this),
317 Reply reply = connectionHandler.readReply();
318 eventBus.post(new ReplyReceived(this, reply));
319 logger.trace(String.format("<< %s", addEscapeCharacters(reply.toString())));
320 String command = reply.command();
321 List<String> parameters = reply.parameters();
323 for (Handler handler : handlers) {
324 if (handler.willHandle(reply)) {
325 handler.handleReply(reply);
330 /* 43x replies are for nick change errors. */
331 if (command.equals("433")) {
332 if (!established.get()) {
333 nickname = nicknameChooser.getNickname();
334 connectionHandler.sendCommand("NICK", nickname);
336 eventBus.post(new NicknameInUseReceived(this, reply));
340 /* basic connection housekeeping. */
341 } else if (command.equalsIgnoreCase("PING")) {
342 connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
344 /* okay, everything else. */
346 eventBus.post(new UnknownReplyReceived(this, reply));
349 eventBus.post(new ConnectionClosed(this));
350 } catch (IOException ioe1) {
351 logger.warn("I/O error", ioe1);
352 eventBus.post(new ConnectionClosed(this, ioe1));
353 } catch (RuntimeException re1) {
354 logger.error("Runtime error", re1);
355 eventBus.post(new ConnectionClosed(this, re1));
357 established.set(false);
358 eventBus.unregister(this);
359 logger.info("Closing Connection.");
361 Closeables.close(connectionHandler, true);
362 } catch (IOException ioe1) {
363 /* will not be thrown. */
370 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
371 if (connectionEstablished.connection() == this) {
372 connectionTime.set(Instant.now());
373 established.set(true);
381 private String addEscapeCharacters(String line) {
382 StringBuilder escaped = new StringBuilder();
383 for (char c : line.toCharArray()) {
385 escaped.append("\\CTRL[").append((int) c).append("]");
390 return escaped.toString();
394 * Returns an item from the list, or {@link Optional#empty()} if the list is
395 * shorter than required for the given index.
398 * The list to get an item from
400 * The index of the item
402 * The type of the list items
403 * @return This list item wrapped in an {@link Optional}, or {@link
404 * Optional#empty()} if the list is not long enough
406 private static <T> Optional<T> getOptional(List<T> list, int index) {
407 if (index < list.size()) {
408 return Optional.ofNullable(list.get(index));
410 return Optional.empty();
414 public String toString() {
415 return String.format("â %s:%d", hostname, port);
418 /** Handles input and output for the connection. */
419 private class ConnectionHandler implements Closeable {
421 /** The output stream of the connection. */
422 private final BandwidthCountingOutputStream outputStream;
424 /** The input stream. */
425 private final BandwidthCountingInputStream inputStream;
427 /** The input stream of the connection. */
428 private final BufferedReader inputStreamReader;
431 * Creates a new connection handler for the given input stream and output
435 * The input stream of the connection
436 * @param outputStream
437 * The output stream of the connection
438 * @throws UnsupportedEncodingException
439 * if the encoding (currently âUTF-8â) is not valid
441 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
442 this.outputStream = new BandwidthCountingOutputStream(outputStream, 5, SECONDS);
443 this.inputStream = new BandwidthCountingInputStream(inputStream, 5, SECONDS);
444 inputStreamReader = new BufferedReader(new InputStreamReader(this.inputStream, "UTF-8"));
452 * Returns the current rate of the connectionâs incoming side.
454 * @return The current input rate (in bytes per second)
456 public long getInputRate() {
457 return inputStream.getCurrentRate();
461 * Returns the current rate of the connectionâs outgoing side.
463 * @return The current output rate (in bytes per second)
465 public long getOutputRate() {
466 return outputStream.getCurrentRate();
470 * Sends a command with the given parameters, skipping all {@link
471 * Optional#absent()} optionals.
474 * The command to send
477 * @throws IOException
478 * if an I/O error occurs
480 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
481 List<String> setParameters = new ArrayList<String>();
482 for (Optional<String> maybeSetParameter : parameters) {
483 if (maybeSetParameter.isPresent()) {
484 setParameters.add(maybeSetParameter.get());
487 sendCommand(command, setParameters.toArray(new String[setParameters.size()]));
491 * Sends a command with the given parameters.
494 * The command to send
496 * The parameters of the command
497 * @throws IOException
498 * if an I/O error occurs
499 * @throws IllegalArgumentException
500 * if any parameter but that last contains a space character
502 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
503 StringBuilder commandBuilder = new StringBuilder();
505 commandBuilder.append(command);
506 for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
507 String parameter = parameters[parameterIndex];
508 /* space is only allowed in the last parameter. */
509 commandBuilder.append(' ');
510 if (parameter.contains(" ")) {
511 if (parameterIndex == (parameters.length - 1)) {
512 commandBuilder.append(':');
514 throw new IllegalArgumentException(String.format("parameter â%sâ must not contain space!", parameter));
517 commandBuilder.append(parameter);
520 logger.trace(String.format(">> %s", commandBuilder));
521 outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
522 outputStream.flush();
526 * Reads a line of reply from the connection.
529 * @throws IOException
530 * if an I/O error occurs
531 * @throws EOFException
534 public Reply readReply() throws IOException, EOFException {
535 String line = inputStreamReader.readLine();
537 throw new EOFException();
540 return Reply.parseLine(line);
548 public void close() throws IOException {
549 Closeables.close(outputStream, true);
550 Closeables.close(inputStreamReader, true);
551 Closeables.close(inputStream, true);