Extract connection interface.
[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.util.ArrayList;
34 import java.util.List;
35 import java.util.concurrent.TimeUnit;
36 import java.util.concurrent.atomic.AtomicBoolean;
37
38 import javax.net.SocketFactory;
39
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;
65
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;
73
74 /**
75  * A connection to an IRC server.
76  *
77  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
78  */
79 public class DefaultConnection extends AbstractExecutionThreadService implements Service,
80                 Connection {
81
82         /* The logger. */
83         private static final Logger logger = Logger.getLogger(DefaultConnection.class.getName());
84
85         /** The event bus. */
86         private final EventBus eventBus;
87
88         /** The socket factory. */
89         private final SocketFactory socketFactory;
90
91         /** The hostname to connect to. */
92         private final String hostname;
93
94         /** The port to connect to. */
95         private final int port;
96
97         /** The nickname chooser. */
98         private NicknameChooser nicknameChooser = new NicknameChooser() {
99
100                 @Override
101                 public String getNickname() {
102                         return RandomNickname.get();
103                 }
104         };
105
106         /** The nickname. */
107         private String nickname = null;
108
109         /** The username. */
110         private Optional<String> username = Optional.absent();
111
112         /** The real name. */
113         private Optional<String> realName = Optional.absent();
114
115         /** The optional password for the connection. */
116         private Optional<String> password = Optional.absent();
117
118         /** The connection handler. */
119         private ConnectionHandler connectionHandler;
120
121         /** Whether the connection has already been established. */
122         private final AtomicBoolean established = new AtomicBoolean();
123
124         /**
125          * Creates a new connection.
126          *
127          * @param eventBus
128          *              The event bus
129          * @param socketFactory
130          *              The socket factory
131          * @param hostname
132          *              The hostname of the IRC server
133          * @param port
134          *              The port number of the IRC server
135          */
136         public DefaultConnection(EventBus eventBus, SocketFactory socketFactory, String hostname,
137                         int port) {
138                 this.eventBus = eventBus;
139                 this.socketFactory = socketFactory;
140                 this.hostname = hostname;
141                 this.port = port;
142         }
143
144         //
145         // ACCESSORS
146         //
147
148         @Override
149         public String hostname() {
150                 return hostname;
151         }
152
153         @Override
154         public int port() {
155                 return port;
156         }
157
158         @Override
159         public boolean established() {
160                 return established.get();
161         }
162
163         @Override
164         public String nickname() {
165                 return nickname;
166         }
167
168         @Override
169         public Connection username(String username) {
170                 this.username = Optional.fromNullable(username);
171                 return this;
172         }
173
174         @Override
175         public Connection realName(String realName) {
176                 this.realName = Optional.fromNullable(realName);
177                 return this;
178         }
179
180         @Override
181         public Connection password(String password) {
182                 this.password = Optional.fromNullable(password);
183                 return this;
184         }
185
186         //
187         // ACTIONS
188         //
189
190         @Override
191         public long getInputRate() {
192                 return (connectionHandler != null) ? connectionHandler.getInputRate() : 0;
193         }
194
195         @Override
196         public long getOutputRate() {
197                 return (connectionHandler != null) ? connectionHandler.getOutputRate() : 0;
198         }
199
200         @Override
201         public boolean isSource(Source source) {
202                 return source.nick().isPresent() && source.nick().get().equals(nickname);
203         }
204
205         @Override
206         public void joinChannel(final String channel) throws IOException {
207                 connectionHandler.sendCommand("JOIN", channel);
208         }
209
210         @Override
211         public void sendMessage(String recipient, String message) throws IOException {
212                 connectionHandler.sendCommand("PRIVMSG", recipient, message);
213         }
214
215         @Override
216         public void sendDccResume(String recipient, String filename, int port, long position) throws IOException {
217                 connectionHandler.sendCommand("PRIVMSG", recipient,
218                                 String.format("\u0001DCC RESUME %s %d %d\u0001", filename, port, position));
219         }
220
221         @Override
222         public void open() {
223                 start();
224         }
225
226         @Override
227         public void close() throws IOException {
228                 if (connectionHandler != null) {
229                         connectionHandler.close();
230                 }
231         }
232
233         //
234         // ABSTRACTEXECUTIONTHREADSERVICE METHODS
235         //
236
237         @Override
238         protected void startUp() throws IllegalStateException {
239                 checkState(username.isPresent(), "username must be set");
240                 checkState(realName.isPresent(), "realName must be set");
241         }
242
243         @Override
244         protected void run() {
245
246                 /* connect to remote socket. */
247                 try {
248                         Socket socket = socketFactory.createSocket(hostname, port);
249                         socket.setSoTimeout((int) TimeUnit.MINUTES.toMillis(3));
250                         connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
251
252                         /* register connection. */
253                         if (password.isPresent()) {
254                                 connectionHandler.sendCommand("PASSWORD", password.get());
255                         }
256                         connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
257                         nickname = nicknameChooser.getNickname();
258                         connectionHandler.sendCommand("NICK", nickname);
259
260                 } catch (IOException ioe1) {
261                         eventBus.post(new ConnectionFailed(this, ioe1));
262                         return;
263                 }
264
265                 eventBus.register(this);
266                 /* now read replies and react. */
267                 try {
268                         /* some status variables. */
269                         boolean connected = true;
270
271                         PrefixHandler prefixHandler = new PrefixHandler();
272                         List<Handler> handlers = asList(
273                                         new MessageHandler(eventBus, this, prefixHandler),
274                                         new CtcpHandler(eventBus, this),
275                                         new ChannelNickHandler(eventBus, this, prefixHandler),
276                                         new SimpleCommandHandler(eventBus)
277                                                         .addCommand("431",
278                                                                         (s, p) -> new NoNicknameGivenReceived(
279                                                                                         this))
280                                                         .addCommand("NICK",
281                                                                         (s, p) -> new NicknameChanged(this,
282                                                                                         s.get(), p.get(0)))
283                                                         .addCommand("JOIN",
284                                                                         (s, p) -> new ChannelJoined(this,
285                                                                                         p.get(0), s.get()))
286                                                         .addCommand("332",
287                                                                         (s, p) -> new ChannelTopic(this, p.get(1),
288                                                                                         p.get(2)))
289                                                         .addCommand("PART",
290                                                                         (s, p) -> new ChannelLeft(this, p.get(0),
291                                                                                         s.get(), getOptional(p, 1)))
292                                                         .addCommand("QUIT",
293                                                                         (s, p) -> new ClientQuit(this, s.get(),
294                                                                                         p.get(0)))
295                                                         .addCommand("KICK",
296                                                                         (s, p) -> new KickedFromChannel(this,
297                                                                                         p.get(0), s.get(), p.get(1),
298                                                                                         getOptional(p, 2))),
299                                         new MotdHandler(eventBus, this),
300                                         new ChannelNotJoinedHandler(eventBus, this),
301                                         new ConnectionEstablishHandler(eventBus, this),
302                                         prefixHandler
303                         );
304
305                         while (connected) {
306                                 Reply reply = connectionHandler.readReply();
307                                 eventBus.post(new ReplyReceived(this, reply));
308                                 logger.trace(String.format("<< %s", reply));
309                                 String command = reply.command();
310                                 List<String> parameters = reply.parameters();
311
312                                 for (Handler handler : handlers) {
313                                         if (handler.willHandle(reply)) {
314                                                 handler.handleReply(reply);
315                                                 break;
316                                         }
317                                 }
318
319                                 /* 43x replies are for nick change errors. */
320                                 if (command.equals("433")) {
321                                         if (!established.get()) {
322                                                 nickname = nicknameChooser.getNickname();
323                                                 connectionHandler.sendCommand("NICK", nickname);
324                                         } else {
325                                                 eventBus.post(new NicknameInUseReceived(this, reply));
326                                         }
327
328
329                                 /* basic connection housekeeping. */
330                                 } else if (command.equalsIgnoreCase("PING")) {
331                                         connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
332
333                                 /* okay, everything else. */
334                                 } else {
335                                         eventBus.post(new UnknownReplyReceived(this, reply));
336                                 }
337                         }
338                         eventBus.post(new ConnectionClosed(this));
339                 } catch (IOException ioe1) {
340                         logger.warn("I/O error", ioe1);
341                         eventBus.post(new ConnectionClosed(this, ioe1));
342                 } catch (RuntimeException re1) {
343                         logger.error("Runtime error", re1);
344                         eventBus.post(new ConnectionClosed(this, re1));
345                 } finally {
346                         established.set(false);
347                         eventBus.unregister(this);
348                         logger.info("Closing Connection.");
349                         try {
350                                 Closeables.close(connectionHandler, true);
351                         } catch (IOException ioe1) {
352                                 /* will not be thrown. */
353                         }
354                 }
355
356         }
357
358         @Subscribe
359         public void connectionEstablished(ConnectionEstablished connectionEstablished) {
360                 if (connectionEstablished.connection() == this) {
361                         established.set(true);
362                 }
363         }
364
365         //
366         // PRIVATE METHODS
367         //
368
369         /**
370          * Returns an item from the list, or {@link Optional#absent()} if the list is
371          * shorter than required for the given index.
372          *
373          * @param list
374          *              The list to get an item from
375          * @param index
376          *              The index of the item
377          * @param <T>
378          *              The type of the list items
379          * @return This list item wrapped in an {@link Optional}, or {@link
380          *         Optional#absent()} if the list is not long enough
381          */
382         private static <T> Optional<T> getOptional(List<T> list, int index) {
383                 if (index < list.size()) {
384                         return Optional.fromNullable(list.get(index));
385                 }
386                 return Optional.absent();
387         }
388
389         /** Handles input and output for the connection. */
390         private class ConnectionHandler implements Closeable {
391
392                 /** The output stream of the connection. */
393                 private final BandwidthCountingOutputStream outputStream;
394
395                 /** The input stream. */
396                 private final BandwidthCountingInputStream inputStream;
397
398                 /** The input stream of the connection. */
399                 private final BufferedReader inputStreamReader;
400
401                 /**
402                  * Creates a new connection handler for the given input stream and output
403                  * stream.
404                  *
405                  * @param inputStream
406                  *              The input stream of the connection
407                  * @param outputStream
408                  *              The output stream of the connection
409                  * @throws UnsupportedEncodingException
410                  *              if the encoding (currently “UTF-8”) is not valid
411                  */
412                 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
413                         this.outputStream = new BandwidthCountingOutputStream(outputStream, 5, SECONDS);
414                         this.inputStream = new BandwidthCountingInputStream(inputStream, 5, SECONDS);
415                         inputStreamReader = new BufferedReader(new InputStreamReader(this.inputStream, "UTF-8"));
416                 }
417
418                 //
419                 // ACTIONS
420                 //
421
422                 /**
423                  * Returns the current rate of the connection’s incoming side.
424                  *
425                  * @return The current input rate (in bytes per second)
426                  */
427                 public long getInputRate() {
428                         return inputStream.getCurrentRate();
429                 }
430
431                 /**
432                  * Returns the current rate of the connection’s outgoing side.
433                  *
434                  * @return The current output rate (in bytes per second)
435                  */
436                 public long getOutputRate() {
437                         return outputStream.getCurrentRate();
438                 }
439
440                 /**
441                  * Sends a command with the given parameters, skipping all {@link
442                  * Optional#absent()} optionals.
443                  *
444                  * @param command
445                  *              The command to send
446                  * @param parameters
447                  *              The parameters
448                  * @throws IOException
449                  *              if an I/O error occurs
450                  */
451                 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
452                         List<String> setParameters = new ArrayList<String>();
453                         for (Optional<String> maybeSetParameter : parameters) {
454                                 if (maybeSetParameter.isPresent()) {
455                                         setParameters.add(maybeSetParameter.get());
456                                 }
457                         }
458                         sendCommand(command, setParameters.toArray(new String[setParameters.size()]));
459                 }
460
461                 /**
462                  * Sends a command with the given parameters.
463                  *
464                  * @param command
465                  *              The command to send
466                  * @param parameters
467                  *              The parameters of the command
468                  * @throws IOException
469                  *              if an I/O error occurs
470                  * @throws IllegalArgumentException
471                  *              if any parameter but that last contains a space character
472                  */
473                 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
474                         StringBuilder commandBuilder = new StringBuilder();
475
476                         commandBuilder.append(command);
477                         for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
478                                 String parameter = parameters[parameterIndex];
479                                 /* space is only allowed in the last parameter. */
480                                 commandBuilder.append(' ');
481                                 if (parameter.contains(" ")) {
482                                         if (parameterIndex == (parameters.length - 1)) {
483                                                 commandBuilder.append(':');
484                                         } else {
485                                                 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
486                                         }
487                                 }
488                                 commandBuilder.append(parameter);
489                         }
490
491                         logger.trace(String.format(">> %s", commandBuilder));
492                         outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
493                         outputStream.flush();
494                 }
495
496                 /**
497                  * Reads a line of reply from the connection.
498                  *
499                  * @return The reply
500                  * @throws IOException
501                  *              if an I/O error occurs
502                  * @throws EOFException
503                  *              if EOF was reached
504                  */
505                 public Reply readReply() throws IOException, EOFException {
506                         String line = inputStreamReader.readLine();
507                         if (line == null) {
508                                 throw new EOFException();
509                         }
510
511                         return Reply.parseLine(line);
512                 }
513
514                 //
515                 // CLOSEABLE METHODS
516                 //
517
518                 @Override
519                 public void close() throws IOException {
520                         Closeables.close(outputStream, true);
521                         Closeables.close(inputStreamReader, true);
522                         Closeables.close(inputStream, true);
523                 }
524
525         }
526
527 }