Print escape characters to logger
[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", reply));
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         /**
382          * Returns an item from the list, or {@link Optional#empty()} if the list is
383          * shorter than required for the given index.
384          *
385          * @param list
386          *              The list to get an item from
387          * @param index
388          *              The index of the item
389          * @param <T>
390          *              The type of the list items
391          * @return This list item wrapped in an {@link Optional}, or {@link
392          *         Optional#empty()} if the list is not long enough
393          */
394         private static <T> Optional<T> getOptional(List<T> list, int index) {
395                 if (index < list.size()) {
396                         return Optional.ofNullable(list.get(index));
397                 }
398                 return Optional.empty();
399         }
400
401         /** Handles input and output for the connection. */
402         private class ConnectionHandler implements Closeable {
403
404                 /** The output stream of the connection. */
405                 private final BandwidthCountingOutputStream outputStream;
406
407                 /** The input stream. */
408                 private final BandwidthCountingInputStream inputStream;
409
410                 /** The input stream of the connection. */
411                 private final BufferedReader inputStreamReader;
412
413                 /**
414                  * Creates a new connection handler for the given input stream and output
415                  * stream.
416                  *
417                  * @param inputStream
418                  *              The input stream of the connection
419                  * @param outputStream
420                  *              The output stream of the connection
421                  * @throws UnsupportedEncodingException
422                  *              if the encoding (currently “UTF-8”) is not valid
423                  */
424                 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
425                         this.outputStream = new BandwidthCountingOutputStream(outputStream, 5, SECONDS);
426                         this.inputStream = new BandwidthCountingInputStream(inputStream, 5, SECONDS);
427                         inputStreamReader = new BufferedReader(new InputStreamReader(this.inputStream, "UTF-8"));
428                 }
429
430                 //
431                 // ACTIONS
432                 //
433
434                 /**
435                  * Returns the current rate of the connection’s incoming side.
436                  *
437                  * @return The current input rate (in bytes per second)
438                  */
439                 public long getInputRate() {
440                         return inputStream.getCurrentRate();
441                 }
442
443                 /**
444                  * Returns the current rate of the connection’s outgoing side.
445                  *
446                  * @return The current output rate (in bytes per second)
447                  */
448                 public long getOutputRate() {
449                         return outputStream.getCurrentRate();
450                 }
451
452                 /**
453                  * Sends a command with the given parameters, skipping all {@link
454                  * Optional#absent()} optionals.
455                  *
456                  * @param command
457                  *              The command to send
458                  * @param parameters
459                  *              The parameters
460                  * @throws IOException
461                  *              if an I/O error occurs
462                  */
463                 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
464                         List<String> setParameters = new ArrayList<String>();
465                         for (Optional<String> maybeSetParameter : parameters) {
466                                 if (maybeSetParameter.isPresent()) {
467                                         setParameters.add(maybeSetParameter.get());
468                                 }
469                         }
470                         sendCommand(command, setParameters.toArray(new String[setParameters.size()]));
471                 }
472
473                 /**
474                  * Sends a command with the given parameters.
475                  *
476                  * @param command
477                  *              The command to send
478                  * @param parameters
479                  *              The parameters of the command
480                  * @throws IOException
481                  *              if an I/O error occurs
482                  * @throws IllegalArgumentException
483                  *              if any parameter but that last contains a space character
484                  */
485                 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
486                         StringBuilder commandBuilder = new StringBuilder();
487
488                         commandBuilder.append(command);
489                         for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
490                                 String parameter = parameters[parameterIndex];
491                                 /* space is only allowed in the last parameter. */
492                                 commandBuilder.append(' ');
493                                 if (parameter.contains(" ")) {
494                                         if (parameterIndex == (parameters.length - 1)) {
495                                                 commandBuilder.append(':');
496                                         } else {
497                                                 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
498                                         }
499                                 }
500                                 commandBuilder.append(parameter);
501                         }
502
503                         logger.trace(String.format(">> %s", addEscapeCharacters(commandBuilder)));
504                         outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
505                         outputStream.flush();
506                 }
507
508                 private String addEscapeCharacters(StringBuilder commandBuilder) {
509                         StringBuilder escaped = new StringBuilder();
510                         for (char c : commandBuilder.toString().toCharArray()) {
511                                 if (c < 32) {
512                                         escaped.append("\\CTRL[").append((int) c).append("]");
513                                 } else {
514                                         escaped.append(c);
515                                 }
516                         }
517                         return escaped.toString();
518                 }
519
520                 /**
521                  * Reads a line of reply from the connection.
522                  *
523                  * @return The reply
524                  * @throws IOException
525                  *              if an I/O error occurs
526                  * @throws EOFException
527                  *              if EOF was reached
528                  */
529                 public Reply readReply() throws IOException, EOFException {
530                         String line = inputStreamReader.readLine();
531                         if (line == null) {
532                                 throw new EOFException();
533                         }
534
535                         return Reply.parseLine(line);
536                 }
537
538                 //
539                 // CLOSEABLE METHODS
540                 //
541
542                 @Override
543                 public void close() throws IOException {
544                         Closeables.close(outputStream, true);
545                         Closeables.close(inputStreamReader, true);
546                         Closeables.close(inputStream, true);
547                 }
548
549         }
550
551 }