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