Add toString() method to default connection
[xudocci.git] / src / main / java / net / pterodactylus / irc / DefaultConnection.java
1 /*
2  * XdccDownloader - Connection.java - Copyright © 2013 David Roden
3  *
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.pterodactylus.irc;
19
20 import static com.google.common.base.Preconditions.checkState;
21 import static java.util.Arrays.asList;
22 import static java.util.concurrent.TimeUnit.SECONDS;
23
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;
41
42 import javax.net.SocketFactory;
43
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;
69
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;
76
77 /**
78  * A connection to an IRC server.
79  *
80  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
81  */
82 public class DefaultConnection extends AbstractExecutionThreadService implements Service,
83                 Connection {
84
85         /* The logger. */
86         private static final Logger logger = Logger.getLogger(DefaultConnection.class.getName());
87
88         /** The event bus. */
89         private final EventBus eventBus;
90
91         /** The socket factory. */
92         private final SocketFactory socketFactory;
93
94         /** The hostname to connect to. */
95         private final String hostname;
96
97         /** The port to connect to. */
98         private final int port;
99
100         /** The nickname chooser. */
101         private NicknameChooser nicknameChooser = new NicknameChooser() {
102
103                 @Override
104                 public String getNickname() {
105                         return RandomNickname.get();
106                 }
107         };
108
109         /** The nickname. */
110         private String nickname = null;
111
112         /** The username. */
113         private Optional<String> username = Optional.empty();
114
115         /** The real name. */
116         private Optional<String> realName = Optional.empty();
117
118         /** The optional password for the connection. */
119         private Optional<String> password = Optional.empty();
120
121         /** The connection handler. */
122         private ConnectionHandler connectionHandler;
123
124         /** Whether the connection has already been established. */
125         private final AtomicBoolean established = new AtomicBoolean();
126         private final AtomicReference<Instant> connectionTime = new AtomicReference<>();
127
128         /**
129          * Creates a new connection.
130          *
131          * @param eventBus
132          *              The event bus
133          * @param socketFactory
134          *              The socket factory
135          * @param hostname
136          *              The hostname of the IRC server
137          * @param port
138          *              The port number of the IRC server
139          */
140         public DefaultConnection(EventBus eventBus, SocketFactory socketFactory, String hostname,
141                         int port) {
142                 this.eventBus = eventBus;
143                 this.socketFactory = socketFactory;
144                 this.hostname = hostname;
145                 this.port = port;
146         }
147
148         //
149         // ACCESSORS
150         //
151
152         @Override
153         public String hostname() {
154                 return hostname;
155         }
156
157         @Override
158         public int port() {
159                 return port;
160         }
161
162         @Override
163         public boolean established() {
164                 return established.get();
165         }
166
167         @Override
168         public String nickname() {
169                 return nickname;
170         }
171
172         @Override
173         public Connection username(String username) {
174                 this.username = Optional.ofNullable(username);
175                 return this;
176         }
177
178         @Override
179         public Connection realName(String realName) {
180                 this.realName = Optional.ofNullable(realName);
181                 return this;
182         }
183
184         @Override
185         public Connection password(String password) {
186                 this.password = Optional.ofNullable(password);
187                 return this;
188         }
189
190         //
191         // ACTIONS
192         //
193
194         @Override
195         public long getInputRate() {
196                 return (connectionHandler != null) ? connectionHandler.getInputRate() : 0;
197         }
198
199         @Override
200         public long getOutputRate() {
201                 return (connectionHandler != null) ? connectionHandler.getOutputRate() : 0;
202         }
203
204         @Override
205         public boolean isSource(Source source) {
206                 return source.nick().isPresent() && source.nick().get().equals(nickname);
207         }
208
209         @Override
210         public void joinChannel(final String channel) throws IOException {
211                 connectionHandler.sendCommand("JOIN", channel);
212         }
213
214         @Override
215         public void sendMessage(String recipient, String message) throws IOException {
216                 connectionHandler.sendCommand("PRIVMSG", recipient, message);
217         }
218
219         @Override
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));
223         }
224
225         @Override
226         public void open() {
227                 start();
228         }
229
230         @Override
231         public void close() throws IOException {
232                 if (connectionHandler != null) {
233                         connectionHandler.close();
234                 }
235         }
236
237         @Override
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();
242         }
243
244         //
245         // ABSTRACTEXECUTIONTHREADSERVICE METHODS
246         //
247
248         @Override
249         protected void startUp() throws IllegalStateException {
250                 checkState(username.isPresent(), "username must be set");
251                 checkState(realName.isPresent(), "realName must be set");
252         }
253
254         @Override
255         protected void run() {
256
257                 /* connect to remote socket. */
258                 try {
259                         Socket socket = socketFactory.createSocket(hostname, port);
260                         socket.setSoTimeout((int) TimeUnit.MINUTES.toMillis(3));
261                         connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
262
263                         /* register connection. */
264                         if (password.isPresent()) {
265                                 connectionHandler.sendCommand("PASSWORD", password.get());
266                         }
267                         connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
268                         nickname = nicknameChooser.getNickname();
269                         connectionHandler.sendCommand("NICK", nickname);
270
271                 } catch (IOException ioe1) {
272                         eventBus.post(new ConnectionFailed(this, ioe1));
273                         return;
274                 }
275
276                 eventBus.register(this);
277                 /* now read replies and react. */
278                 try {
279                         /* some status variables. */
280                         boolean connected = true;
281
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)
288                                                         .addCommand("431",
289                                                                         (s, p) -> new NoNicknameGivenReceived(
290                                                                                         this))
291                                                         .addCommand("NICK",
292                                                                         (s, p) -> new NicknameChanged(this,
293                                                                                         s.get(), p.get(0)))
294                                                         .addCommand("JOIN",
295                                                                         (s, p) -> new ChannelJoined(this,
296                                                                                         p.get(0), s.get()))
297                                                         .addCommand("332",
298                                                                         (s, p) -> new ChannelTopic(this, p.get(1),
299                                                                                         p.get(2)))
300                                                         .addCommand("PART",
301                                                                         (s, p) -> new ChannelLeft(this, p.get(0),
302                                                                                         s.get(), getOptional(p, 1)))
303                                                         .addCommand("QUIT",
304                                                                         (s, p) -> new ClientQuit(this, s.get(),
305                                                                                         p.get(0)))
306                                                         .addCommand("KICK",
307                                                                         (s, p) -> new KickedFromChannel(this,
308                                                                                         p.get(0), s.get(), p.get(1),
309                                                                                         getOptional(p, 2))),
310                                         new MotdHandler(eventBus, this),
311                                         new ChannelNotJoinedHandler(eventBus, this),
312                                         new ConnectionEstablishHandler(eventBus, this),
313                                         prefixHandler
314                         );
315
316                         while (connected) {
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();
322
323                                 for (Handler handler : handlers) {
324                                         if (handler.willHandle(reply)) {
325                                                 handler.handleReply(reply);
326                                                 break;
327                                         }
328                                 }
329
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);
335                                         } else {
336                                                 eventBus.post(new NicknameInUseReceived(this, reply));
337                                         }
338
339
340                                 /* basic connection housekeeping. */
341                                 } else if (command.equalsIgnoreCase("PING")) {
342                                         connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
343
344                                 /* okay, everything else. */
345                                 } else {
346                                         eventBus.post(new UnknownReplyReceived(this, reply));
347                                 }
348                         }
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));
356                 } finally {
357                         established.set(false);
358                         eventBus.unregister(this);
359                         logger.info("Closing Connection.");
360                         try {
361                                 Closeables.close(connectionHandler, true);
362                         } catch (IOException ioe1) {
363                                 /* will not be thrown. */
364                         }
365                 }
366
367         }
368
369         @Subscribe
370         public void connectionEstablished(ConnectionEstablished connectionEstablished) {
371                 if (connectionEstablished.connection() == this) {
372                         connectionTime.set(Instant.now());
373                         established.set(true);
374                 }
375         }
376
377         //
378         // PRIVATE METHODS
379         //
380
381         private String addEscapeCharacters(String line) {
382                 StringBuilder escaped = new StringBuilder();
383                 for (char c : line.toCharArray()) {
384                         if (c < 32) {
385                                 escaped.append("\\CTRL[").append((int) c).append("]");
386                         } else {
387                                 escaped.append(c);
388                         }
389                 }
390                 return escaped.toString();
391         }
392
393         /**
394          * Returns an item from the list, or {@link Optional#empty()} if the list is
395          * shorter than required for the given index.
396          *
397          * @param list
398          *              The list to get an item from
399          * @param index
400          *              The index of the item
401          * @param <T>
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
405          */
406         private static <T> Optional<T> getOptional(List<T> list, int index) {
407                 if (index < list.size()) {
408                         return Optional.ofNullable(list.get(index));
409                 }
410                 return Optional.empty();
411         }
412
413         @Override
414         public String toString() {
415                 return String.format("→ %s:%d", hostname, port);
416         }
417
418         /** Handles input and output for the connection. */
419         private class ConnectionHandler implements Closeable {
420
421                 /** The output stream of the connection. */
422                 private final BandwidthCountingOutputStream outputStream;
423
424                 /** The input stream. */
425                 private final BandwidthCountingInputStream inputStream;
426
427                 /** The input stream of the connection. */
428                 private final BufferedReader inputStreamReader;
429
430                 /**
431                  * Creates a new connection handler for the given input stream and output
432                  * stream.
433                  *
434                  * @param inputStream
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
440                  */
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"));
445                 }
446
447                 //
448                 // ACTIONS
449                 //
450
451                 /**
452                  * Returns the current rate of the connection’s incoming side.
453                  *
454                  * @return The current input rate (in bytes per second)
455                  */
456                 public long getInputRate() {
457                         return inputStream.getCurrentRate();
458                 }
459
460                 /**
461                  * Returns the current rate of the connection’s outgoing side.
462                  *
463                  * @return The current output rate (in bytes per second)
464                  */
465                 public long getOutputRate() {
466                         return outputStream.getCurrentRate();
467                 }
468
469                 /**
470                  * Sends a command with the given parameters, skipping all {@link
471                  * Optional#absent()} optionals.
472                  *
473                  * @param command
474                  *              The command to send
475                  * @param parameters
476                  *              The parameters
477                  * @throws IOException
478                  *              if an I/O error occurs
479                  */
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());
485                                 }
486                         }
487                         sendCommand(command, setParameters.toArray(new String[setParameters.size()]));
488                 }
489
490                 /**
491                  * Sends a command with the given parameters.
492                  *
493                  * @param command
494                  *              The command to send
495                  * @param parameters
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
501                  */
502                 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
503                         StringBuilder commandBuilder = new StringBuilder();
504
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(':');
513                                         } else {
514                                                 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
515                                         }
516                                 }
517                                 commandBuilder.append(parameter);
518                         }
519
520                         logger.trace(String.format(">> %s", commandBuilder));
521                         outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
522                         outputStream.flush();
523                 }
524
525                 /**
526                  * Reads a line of reply from the connection.
527                  *
528                  * @return The reply
529                  * @throws IOException
530                  *              if an I/O error occurs
531                  * @throws EOFException
532                  *              if EOF was reached
533                  */
534                 public Reply readReply() throws IOException, EOFException {
535                         String line = inputStreamReader.readLine();
536                         if (line == null) {
537                                 throw new EOFException();
538                         }
539
540                         return Reply.parseLine(line);
541                 }
542
543                 //
544                 // CLOSEABLE METHODS
545                 //
546
547                 @Override
548                 public void close() throws IOException {
549                         Closeables.close(outputStream, true);
550                         Closeables.close(inputStreamReader, true);
551                         Closeables.close(inputStream, true);
552                 }
553
554         }
555
556 }