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