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