Add methods to close the connection.
[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
22 import java.io.BufferedReader;
23 import java.io.Closeable;
24 import java.io.EOFException;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.io.InputStreamReader;
28 import java.io.OutputStream;
29 import java.io.UnsupportedEncodingException;
30 import java.net.InetAddress;
31 import java.net.Socket;
32 import java.net.UnknownHostException;
33 import java.util.ArrayList;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.Set;
37 import java.util.logging.Level;
38 import java.util.logging.Logger;
39 import javax.net.SocketFactory;
40
41 import net.pterodactylus.irc.event.ChannelJoined;
42 import net.pterodactylus.irc.event.ChannelLeft;
43 import net.pterodactylus.irc.event.ChannelMessageReceived;
44 import net.pterodactylus.irc.event.ChannelNicknames;
45 import net.pterodactylus.irc.event.ChannelNotJoined;
46 import net.pterodactylus.irc.event.ChannelNotJoined.Reason;
47 import net.pterodactylus.irc.event.ChannelNoticeReceived;
48 import net.pterodactylus.irc.event.ChannelTopic;
49 import net.pterodactylus.irc.event.ClientQuit;
50 import net.pterodactylus.irc.event.ConnectionClosed;
51 import net.pterodactylus.irc.event.ConnectionEstablished;
52 import net.pterodactylus.irc.event.ConnectionFailed;
53 import net.pterodactylus.irc.event.DccAcceptReceived;
54 import net.pterodactylus.irc.event.DccSendReceived;
55 import net.pterodactylus.irc.event.MotdReceived;
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.PrivateMessageReceived;
60 import net.pterodactylus.irc.event.PrivateNoticeReceived;
61 import net.pterodactylus.irc.event.UnknownReplyReceived;
62 import net.pterodactylus.irc.util.RandomNickname;
63
64 import com.google.common.base.Optional;
65 import com.google.common.collect.Maps;
66 import com.google.common.collect.Sets;
67 import com.google.common.eventbus.EventBus;
68 import com.google.common.io.Closeables;
69 import com.google.common.primitives.Ints;
70 import com.google.common.primitives.Longs;
71 import com.google.common.util.concurrent.AbstractExecutionThreadService;
72 import com.google.common.util.concurrent.Service;
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 boolean established;
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 whether this connection has already been established.
148          *
149          * @return {@code true} as long as this connection is established, {@code
150          *         false} otherwise
151          */
152         public boolean established() {
153                 return established;
154         }
155
156         /**
157          * Returns the nickname that is currently in use by this connection. The
158          * nickname is only available once the connection has been {@link #start()}ed.
159          *
160          * @return The current nickname
161          */
162         public String nickname() {
163                 return nickname;
164         }
165
166         //
167         // MUTATORS
168         //
169
170         /**
171          * Sets the nickname chooser. The nickname chooser is only used during the
172          * creation of the connection.
173          *
174          * @param nicknameChooser
175          *              The nickname chooser
176          * @return This connection
177          */
178         public Connection nicknameChooser(NicknameChooser nicknameChooser) {
179                 this.nicknameChooser = nicknameChooser;
180                 return this;
181         }
182
183         /**
184          * Sets the username to use.
185          *
186          * @param username
187          *              The username to use
188          * @return This connection
189          */
190         public Connection username(String username) {
191                 this.username = Optional.fromNullable(username);
192                 return this;
193         }
194
195         /**
196          * Sets the real name to use.
197          *
198          * @param realName
199          *              The real name to use
200          * @return This connection
201          */
202         public Connection realName(String realName) {
203                 this.realName = Optional.fromNullable(realName);
204                 return this;
205         }
206
207         /**
208          * Sets the optional password for the connection.
209          *
210          * @param password
211          *              The password for the connection
212          * @return This connection
213          */
214         public Connection password(String password) {
215                 this.password = Optional.fromNullable(password);
216                 return this;
217         }
218
219         //
220         // ACTIONS
221         //
222
223         /**
224          * Checks whether the given source is the client represented by this
225          * connection.
226          *
227          * @param source
228          *              The source to check
229          * @return {@code true} if this connection represents the given source, {@code
230          *         false} otherwise
231          */
232         public boolean isSource(Source source) {
233                 return source.nick().isPresent() && source.nick().get().equals(nickname);
234         }
235
236         /**
237          * Joins the given channel.
238          *
239          * @param channel
240          *              The channel to join
241          * @throws IOException
242          *              if an I/O error occurs
243          */
244         public void joinChannel(final String channel) throws IOException {
245                 connectionHandler.sendCommand("JOIN", channel);
246         }
247
248         /**
249          * Sends a message to the given recipient, which may be a channel or another
250          * nickname.
251          *
252          * @param recipient
253          *              The recipient of the message
254          * @param message
255          *              The message
256          * @throws IOException
257          *              if an I/O error occurs
258          */
259         public void sendMessage(String recipient, String message) throws IOException {
260                 connectionHandler.sendCommand("PRIVMSG", recipient, message);
261         }
262
263         /**
264          * Sends a DCC RESUME request to the given recipient.
265          *
266          * @param recipient
267          *              The recipient of the request
268          * @param filename
269          *              The name of the file to resume
270          * @param port
271          *              The port number from the original DCC SEND request
272          * @param position
273          *              The position at which to resume the transfer
274          * @throws IOException
275          *              if an I/O error occurs
276          */
277         public void sendDccResume(String recipient, String filename, int port, long position) throws IOException {
278                 connectionHandler.sendCommand("PRIVMSG", recipient, String.format("\u0001DCC RESUME %s %d %d\u0001", filename, port, position));
279         }
280
281         /**
282          * Closes this connection.
283          *
284          * @throws IOException
285          *              if an I/O error occurs
286          */
287         public void close() throws IOException {
288                 connectionHandler.close();
289         }
290
291         //
292         // ABSTRACTEXECUTIONTHREADSERVICE METHODS
293         //
294
295         @Override
296         protected void startUp() throws IllegalStateException {
297                 checkState(username.isPresent(), "username must be set");
298                 checkState(realName.isPresent(), "realName must be set");
299         }
300
301         @Override
302         protected void run() {
303
304                 /* connect to remote socket. */
305                 try {
306                         Socket socket = socketFactory.createSocket(hostname, port);
307                         connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
308
309                         /* register connection. */
310                         if (password.isPresent()) {
311                                 connectionHandler.sendCommand("PASSWORD", password.get());
312                         }
313                         connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
314                         nickname = nicknameChooser.getNickname();
315                         connectionHandler.sendCommand("NICK", nickname);
316
317                 } catch (IOException ioe1) {
318                         eventBus.post(new ConnectionFailed(this, ioe1));
319                         return;
320                 }
321
322                 /* now read replies and react. */
323                 try {
324                         /* some status variables. */
325                         int oldConnectionStatus = 0;
326                         int connectionStatus = 0;
327                         boolean connected = true;
328                         StringBuilder motd = new StringBuilder();
329                         Set<Nickname> nicks = Sets.newHashSet();
330
331                         /* server modes. */
332                         Map<String, String> nickPrefixes = Maps.newHashMap();
333                         Set<Character> channelTypes = Sets.newHashSet();
334
335                         while (connected) {
336                                 Reply reply = connectionHandler.readReply();
337                                 logger.finest(String.format("<< %s", reply));
338                                 String command = reply.command();
339                                 List<String> parameters = reply.parameters();
340
341                                 /* most common events. */
342                                 if (command.equalsIgnoreCase("PRIVMSG")) {
343                                         String recipient = parameters.get(0);
344                                         String message = parameters.get(1);
345                                         if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
346                                                 /* CTCP! */
347                                                 handleCtcp(reply.source().get(), message);
348                                         } else if (!channelTypes.contains(recipient.charAt(0))) {
349                                                 eventBus.post(new PrivateMessageReceived(this, reply.source().get(), message));
350                                         } else {
351                                                 eventBus.post(new ChannelMessageReceived(this, recipient, reply.source().get(), message));
352                                         }
353
354                                 } else if (command.equalsIgnoreCase("NOTICE")) {
355                                         String recipient = parameters.get(0);
356                                         String message = parameters.get(1);
357                                         if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
358                                                 /* CTCP! */
359                                                 handleCtcp(reply.source().get(), message);
360                                         } else if (!channelTypes.contains(recipient.charAt(0))) {
361                                                 eventBus.post(new PrivateNoticeReceived(this, reply));
362                                         } else {
363                                                 eventBus.post(new ChannelNoticeReceived(this, reply.source().get(), recipient, message));
364                                         }
365
366                                 /* 43x replies are for nick change errors. */
367                                 } else if (command.equals("431")) {
368                                         eventBus.post(new NoNicknameGivenReceived(this, reply));
369                                 } else if (command.equals("433")) {
370                                         if (connectionStatus == 0) {
371                                                 nickname = nicknameChooser.getNickname();
372                                                 connectionHandler.sendCommand("NICK", nickname);
373                                         } else {
374                                                 eventBus.post(new NicknameInUseReceived(this, reply));
375                                         }
376
377                                 /* client stuff. */
378                                 } else if (command.equalsIgnoreCase("NICK")) {
379                                         eventBus.post(new NicknameChanged(this, reply.source().get(), parameters.get(0)));
380
381                                 /* channel stuff. */
382                                 } else if (command.equalsIgnoreCase("JOIN")) {
383                                         eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
384                                 } else if (command.equals("331")) {
385                                         /* no topic is set. */
386                                 } else if (command.equals("332")) {
387                                         eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
388                                 } else if (command.equals("353")) {
389                                         for (String nickname : parameters.get(3).split(" ")) {
390                                                 if (nickPrefixes.containsKey(nickname.substring(0, 1))) {
391                                                         nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
392                                                 } else {
393                                                         nicks.add(new Nickname(nickname, ""));
394                                                 }
395                                         }
396                                 } else if (command.equals("366")) {
397                                         eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
398                                         nicks.clear();
399                                 } else if (command.equalsIgnoreCase("PART")) {
400                                         eventBus.post(new ChannelLeft(this, parameters.get(0), reply.source().get(), getOptional(parameters, 1)));
401                                 } else if (command.equalsIgnoreCase("QUIT")) {
402                                         eventBus.post(new ClientQuit(this, reply.source().get(), parameters.get(0)));
403
404                                 /* common channel join errors. */
405                                 } else if (command.equals("474")) {
406                                         eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.banned));
407                                 } else if (command.equals("473")) {
408                                         eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.inviteOnly));
409                                 } else if (command.equals("475")) {
410                                         eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.badChannelKey));
411
412                                 /* basic connection housekeeping. */
413                                 } else if (command.equalsIgnoreCase("PING")) {
414                                         connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
415
416                                 /* replies 001-004 don’t hold information but they have to be sent on a successful connection. */
417                                 } else if (command.equals("001")) {
418                                         connectionStatus |= 0x01;
419                                 } else if (command.equals("002")) {
420                                         connectionStatus |= 0x02;
421                                 } else if (command.equals("003")) {
422                                         connectionStatus |= 0x04;
423                                 } else if (command.equals("004")) {
424                                         connectionStatus |= 0x08;
425
426                                 /* 005 originally was a bounce message, now used to transmit useful information about the server. */
427                                 } else if (command.equals("005")) {
428                                         for (String parameter : parameters) {
429                                                 if (parameter.startsWith("PREFIX=")) {
430                                                         int openParen = parameter.indexOf('(');
431                                                         int closeParen = parameter.indexOf(')');
432                                                         if ((openParen != -1) && (closeParen != -1)) {
433                                                                 for (int modeCharacterIndex = 1; modeCharacterIndex < (closeParen - openParen); ++modeCharacterIndex) {
434                                                                         char modeCharacter = parameter.charAt(openParen + modeCharacterIndex);
435                                                                         char modeSymbol = parameter.charAt(closeParen + modeCharacterIndex);
436                                                                         nickPrefixes.put(String.valueOf(modeSymbol), String.valueOf(modeCharacter));
437                                                                 }
438                                                                 logger.fine(String.format("Parsed Prefixes: %s", nickPrefixes));
439                                                         }
440                                                 } else if (parameter.startsWith("CHANTYPES=")) {
441                                                         for (int typeIndex = 10; typeIndex < parameter.length(); ++typeIndex) {
442                                                                 channelTypes.add(parameter.charAt(typeIndex));
443                                                         }
444                                                         logger.fine(String.format("Parsed Channel Types: %s", channelTypes));
445                                                 }
446                                         }
447
448                                 /* 375, 372, and 376 handle the server’s MOTD. */
449                                 } else if (command.equals("375")) {
450                                         /* MOTD starts. */
451                                         motd.append(parameters.get(1)).append('\n');
452                                 } else if (command.equals("372")) {
453                                         motd.append(parameters.get(1)).append('\n');
454                                 } else if (command.equals("376")) {
455                                         motd.append(parameters.get(1)).append('\n');
456                                         eventBus.post(new MotdReceived(this, motd.toString()));
457                                         motd.setLength(0);
458
459                                 /* okay, everything else. */
460                                 } else {
461                                         eventBus.post(new UnknownReplyReceived(this, reply));
462                                 }
463
464                                 if ((connectionStatus == 0x0f) && (connectionStatus != oldConnectionStatus)) {
465                                         /* connection succeeded! */
466                                         established = true;
467                                         eventBus.post(new ConnectionEstablished(this));
468                                 }
469                                 oldConnectionStatus = connectionStatus;
470                         }
471                         eventBus.post(new ConnectionClosed(this));
472                 } catch (IOException ioe1) {
473                         logger.log(Level.WARNING, "I/O error", ioe1);
474                         eventBus.post(new ConnectionClosed(this, ioe1));
475                 } finally {
476                         established = false;
477                         logger.info("Closing Connection.");
478                         try {
479                                 Closeables.close(connectionHandler, true);
480                         } catch (IOException ioe1) {
481                                 /* will not be thrown. */
482                         }
483                 }
484
485         }
486
487         //
488         // PRIVATE METHODS
489         //
490
491         /**
492          * Handles a CTCP message.
493          *
494          * @param client
495          *              The client sending the message
496          * @param message
497          *              The message
498          */
499         private void handleCtcp(Source client, String message) {
500                 String[] messageWords = message.substring(1, message.length() - 1).split(" +");
501                 String ctcpCommand = messageWords[0];
502                 if (ctcpCommand.equalsIgnoreCase("DCC")) {
503                         if (messageWords[1].equalsIgnoreCase("SEND")) {
504                                 Optional<InetAddress> inetAddress = parseInetAddress(messageWords[3]);
505                                 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[4]));
506                                 long fileSize = Optional.fromNullable(Longs.tryParse(messageWords[5])).or(-1L);
507                                 if (inetAddress.isPresent() && port.isPresent()) {
508                                         eventBus.post(new DccSendReceived(this, client, messageWords[2], inetAddress.get(), port.get(), fileSize));
509                                 } else {
510                                         logger.warning(String.format("Received malformed DCC SEND: “%s”", message));
511                                 }
512                         } else if (messageWords[1].equalsIgnoreCase("ACCEPT")) {
513                                 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[3]));
514                                 long position = Optional.fromNullable(Longs.tryParse(messageWords[4])).or(-1L);
515                                 if (port.isPresent()) {
516                                         eventBus.post(new DccAcceptReceived(this, client, messageWords[2], port.get(), position));
517                                 } else {
518                                         logger.warning(String.format("Received malformed DCC ACCEPT: “%s”", message));
519                                 }
520                         }
521                 }
522         }
523
524         /**
525          * Returns an item from the list, or {@link Optional#absent()} if the list is
526          * shorter than required for the given index.
527          *
528          * @param list
529          *              The list to get an item from
530          * @param index
531          *              The index of the item
532          * @param <T>
533          *              The type of the list items
534          * @return This list item wrapped in an {@link Optional}, or {@link
535          *         Optional#absent()} if the list is not long enough
536          */
537         private static <T> Optional<T> getOptional(List<T> list, int index) {
538                 if (index < list.size()) {
539                         return Optional.fromNullable(list.get(index));
540                 }
541                 return Optional.absent();
542         }
543
544         /**
545          * Parses the given {@code ip} and returns an {@link InetAddress} from it.
546          *
547          * @param ip
548          *              The IP to parse
549          * @return The parsed inet address, or {@link Optional#absent()} if no inet
550          *         address could be parsed
551          */
552         private Optional<InetAddress> parseInetAddress(String ip) {
553                 Long ipNumber = Longs.tryParse(ip);
554                 if (ipNumber == null) {
555                         return Optional.absent();
556                 }
557
558                 StringBuilder hostname = new StringBuilder(15);
559                 hostname.append((ipNumber >>> 24) & 0xff).append('.');
560                 hostname.append((ipNumber >>> 16) & 0xff).append('.');
561                 hostname.append((ipNumber >>> 8) & 0xff).append('.');
562                 hostname.append(ipNumber & 0xff);
563                 try {
564                         return Optional.of(InetAddress.getByName(hostname.toString()));
565                 } catch (UnknownHostException uhe1) {
566                         return Optional.absent();
567                 }
568         }
569
570         /** Handles input and output for the connection. */
571         private class ConnectionHandler implements Closeable {
572
573                 /** The output stream of the connection. */
574                 private final OutputStream outputStream;
575
576                 /** The input stream of the connection. */
577                 private final BufferedReader inputStreamReader;
578
579                 /**
580                  * Creates a new connection handler for the given input stream and output
581                  * stream.
582                  *
583                  * @param inputStream
584                  *              The input stream of the connection
585                  * @param outputStream
586                  *              The output stream of the connection
587                  * @throws UnsupportedEncodingException
588                  *              if the encoding (currently “UTF-8”) is not valid
589                  */
590                 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
591                         this.outputStream = outputStream;
592                         inputStreamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
593                 }
594
595                 //
596                 // ACTIONS
597                 //
598
599                 /**
600                  * Sends a command with the given parameters, skipping all {@link
601                  * Optional#absent()} optionals.
602                  *
603                  * @param command
604                  *              The command to send
605                  * @param parameters
606                  *              The parameters
607                  * @throws IOException
608                  *              if an I/O error occurs
609                  */
610                 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
611                         List<String> setParameters = new ArrayList<String>();
612                         for (Optional<String> maybeSetParameter : parameters) {
613                                 if (maybeSetParameter.isPresent()) {
614                                         setParameters.add(maybeSetParameter.get());
615                                 }
616                         }
617                         sendCommand(command, setParameters.toArray(new String[setParameters.size()]));
618                 }
619
620                 /**
621                  * Sends a command with the given parameters.
622                  *
623                  * @param command
624                  *              The command to send
625                  * @param parameters
626                  *              The parameters of the command
627                  * @throws IOException
628                  *              if an I/O error occurs
629                  * @throws IllegalArgumentException
630                  *              if any parameter but that last contains a space character
631                  */
632                 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
633                         StringBuilder commandBuilder = new StringBuilder();
634
635                         commandBuilder.append(command);
636                         for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
637                                 String parameter = parameters[parameterIndex];
638                                 /* space is only allowed in the last parameter. */
639                                 commandBuilder.append(' ');
640                                 if (parameter.contains(" ")) {
641                                         if (parameterIndex == (parameters.length - 1)) {
642                                                 commandBuilder.append(':');
643                                         } else {
644                                                 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
645                                         }
646                                 }
647                                 commandBuilder.append(parameter);
648                         }
649
650                         logger.finest(String.format(">> %s", commandBuilder));
651                         outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
652                         outputStream.flush();
653                 }
654
655                 /**
656                  * Reads a line of reply from the connection.
657                  *
658                  * @return The reply
659                  * @throws IOException
660                  *              if an I/O error occurs
661                  * @throws EOFException
662                  *              if EOF was reached
663                  */
664                 public Reply readReply() throws IOException, EOFException {
665                         String line = inputStreamReader.readLine();
666                         if (line == null) {
667                                 throw new EOFException();
668                         }
669
670                         return Reply.parseLine(line);
671                 }
672
673                 //
674                 // CLOSEABLE METHODS
675                 //
676
677                 @Override
678                 public void close() throws IOException {
679                         Closeables.close(outputStream, true);
680                         Closeables.close(inputStreamReader, true);
681                 }
682
683         }
684
685 }