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