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