Handle CTCP in notices, too.
[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         // ABSTRACTEXECUTIONTHREADSERVICE METHODS
283         //
284
285         @Override
286         protected void startUp() throws IllegalStateException {
287                 checkState(username.isPresent(), "username must be set");
288                 checkState(realName.isPresent(), "realName must be set");
289         }
290
291         @Override
292         protected void run() {
293
294                 /* connect to remote socket. */
295                 try {
296                         Socket socket = socketFactory.createSocket(hostname, port);
297                         connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
298
299                         /* register connection. */
300                         if (password.isPresent()) {
301                                 connectionHandler.sendCommand("PASSWORD", password.get());
302                         }
303                         connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
304                         nickname = nicknameChooser.getNickname();
305                         connectionHandler.sendCommand("NICK", nickname);
306
307                 } catch (IOException ioe1) {
308                         eventBus.post(new ConnectionFailed(this, ioe1));
309                         return;
310                 }
311
312                 /* now read replies and react. */
313                 try {
314                         /* some status variables. */
315                         int oldConnectionStatus = 0;
316                         int connectionStatus = 0;
317                         boolean connected = true;
318                         StringBuilder motd = new StringBuilder();
319                         Set<Nickname> nicks = Sets.newHashSet();
320
321                         /* server modes. */
322                         Map<String, String> nickPrefixes = Maps.newHashMap();
323                         Set<Character> channelTypes = Sets.newHashSet();
324
325                         while (connected) {
326                                 Reply reply = connectionHandler.readReply();
327                                 logger.finest(String.format("<< %s", reply));
328                                 String command = reply.command();
329                                 List<String> parameters = reply.parameters();
330
331                                 /* most common events. */
332                                 if (command.equalsIgnoreCase("PRIVMSG")) {
333                                         String recipient = parameters.get(0);
334                                         String message = parameters.get(1);
335                                         if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
336                                                 /* CTCP! */
337                                                 handleCtcp(reply.source().get(), message);
338                                         } else if (!channelTypes.contains(recipient.charAt(0))) {
339                                                 eventBus.post(new PrivateMessageReceived(this, reply.source().get(), message));
340                                         } else {
341                                                 eventBus.post(new ChannelMessageReceived(this, recipient, reply.source().get(), message));
342                                         }
343
344                                 } else if (command.equalsIgnoreCase("NOTICE")) {
345                                         String recipient = parameters.get(0);
346                                         String message = parameters.get(1);
347                                         if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
348                                                 /* CTCP! */
349                                                 handleCtcp(reply.source().get(), message);
350                                         } else if (!channelTypes.contains(recipient.charAt(0))) {
351                                                 eventBus.post(new PrivateNoticeReceived(this, reply));
352                                         } else {
353                                                 eventBus.post(new ChannelNoticeReceived(this, reply.source().get(), recipient, message));
354                                         }
355
356                                 /* 43x replies are for nick change errors. */
357                                 } else if (command.equals("431")) {
358                                         eventBus.post(new NoNicknameGivenReceived(this, reply));
359                                 } else if (command.equals("433")) {
360                                         if (connectionStatus == 0) {
361                                                 nickname = nicknameChooser.getNickname();
362                                                 connectionHandler.sendCommand("NICK", nickname);
363                                         } else {
364                                                 eventBus.post(new NicknameInUseReceived(this, reply));
365                                         }
366
367                                 /* client stuff. */
368                                 } else if (command.equalsIgnoreCase("NICK")) {
369                                         eventBus.post(new NicknameChanged(this, reply.source().get(), parameters.get(0)));
370
371                                 /* channel stuff. */
372                                 } else if (command.equalsIgnoreCase("JOIN")) {
373                                         eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
374                                 } else if (command.equals("331")) {
375                                         /* no topic is set. */
376                                 } else if (command.equals("332")) {
377                                         eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
378                                 } else if (command.equals("353")) {
379                                         for (String nickname : parameters.get(3).split(" ")) {
380                                                 if (nickPrefixes.containsKey(nickname.substring(0, 1))) {
381                                                         nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
382                                                 } else {
383                                                         nicks.add(new Nickname(nickname, ""));
384                                                 }
385                                         }
386                                 } else if (command.equals("366")) {
387                                         eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
388                                         nicks.clear();
389                                 } else if (command.equalsIgnoreCase("PART")) {
390                                         eventBus.post(new ChannelLeft(this, parameters.get(0), reply.source().get(), getOptional(parameters, 1)));
391                                 } else if (command.equalsIgnoreCase("QUIT")) {
392                                         eventBus.post(new ClientQuit(this, reply.source().get(), parameters.get(0)));
393
394                                 /* common channel join errors. */
395                                 } else if (command.equals("474")) {
396                                         eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.banned));
397                                 } else if (command.equals("473")) {
398                                         eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.inviteOnly));
399                                 } else if (command.equals("475")) {
400                                         eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.badChannelKey));
401
402                                 /* basic connection housekeeping. */
403                                 } else if (command.equalsIgnoreCase("PING")) {
404                                         connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
405
406                                 /* replies 001-004 don’t hold information but they have to be sent on a successful connection. */
407                                 } else if (command.equals("001")) {
408                                         connectionStatus |= 0x01;
409                                 } else if (command.equals("002")) {
410                                         connectionStatus |= 0x02;
411                                 } else if (command.equals("003")) {
412                                         connectionStatus |= 0x04;
413                                 } else if (command.equals("004")) {
414                                         connectionStatus |= 0x08;
415
416                                 /* 005 originally was a bounce message, now used to transmit useful information about the server. */
417                                 } else if (command.equals("005")) {
418                                         for (String parameter : parameters) {
419                                                 if (parameter.startsWith("PREFIX=")) {
420                                                         int openParen = parameter.indexOf('(');
421                                                         int closeParen = parameter.indexOf(')');
422                                                         if ((openParen != -1) && (closeParen != -1)) {
423                                                                 for (int modeCharacterIndex = 1; modeCharacterIndex < (closeParen - openParen); ++modeCharacterIndex) {
424                                                                         char modeCharacter = parameter.charAt(openParen + modeCharacterIndex);
425                                                                         char modeSymbol = parameter.charAt(closeParen + modeCharacterIndex);
426                                                                         nickPrefixes.put(String.valueOf(modeSymbol), String.valueOf(modeCharacter));
427                                                                 }
428                                                                 logger.fine(String.format("Parsed Prefixes: %s", nickPrefixes));
429                                                         }
430                                                 } else if (parameter.startsWith("CHANTYPES=")) {
431                                                         for (int typeIndex = 10; typeIndex < parameter.length(); ++typeIndex) {
432                                                                 channelTypes.add(parameter.charAt(typeIndex));
433                                                         }
434                                                         logger.fine(String.format("Parsed Channel Types: %s", channelTypes));
435                                                 }
436                                         }
437
438                                 /* 375, 372, and 376 handle the server’s MOTD. */
439                                 } else if (command.equals("375")) {
440                                         /* MOTD starts. */
441                                         motd.append(parameters.get(1)).append('\n');
442                                 } else if (command.equals("372")) {
443                                         motd.append(parameters.get(1)).append('\n');
444                                 } else if (command.equals("376")) {
445                                         motd.append(parameters.get(1)).append('\n');
446                                         eventBus.post(new MotdReceived(this, motd.toString()));
447                                         motd.setLength(0);
448
449                                 /* okay, everything else. */
450                                 } else {
451                                         eventBus.post(new UnknownReplyReceived(this, reply));
452                                 }
453
454                                 if ((connectionStatus == 0x0f) && (connectionStatus != oldConnectionStatus)) {
455                                         /* connection succeeded! */
456                                         established = true;
457                                         eventBus.post(new ConnectionEstablished(this));
458                                 }
459                                 oldConnectionStatus = connectionStatus;
460                         }
461                         eventBus.post(new ConnectionClosed(this));
462                 } catch (IOException ioe1) {
463                         logger.log(Level.WARNING, "I/O error", ioe1);
464                         eventBus.post(new ConnectionClosed(this, ioe1));
465                 } finally {
466                         established = false;
467                         logger.info("Closing Connection.");
468                         try {
469                                 Closeables.close(connectionHandler, true);
470                         } catch (IOException ioe1) {
471                                 /* will not be thrown. */
472                         }
473                 }
474
475         }
476
477         //
478         // PRIVATE METHODS
479         //
480
481         /**
482          * Handles a CTCP message.
483          *
484          * @param client
485          *              The client sending the message
486          * @param message
487          *              The message
488          */
489         private void handleCtcp(Source client, String message) {
490                 String[] messageWords = message.substring(1, message.length() - 1).split(" +");
491                 String ctcpCommand = messageWords[0];
492                 if (ctcpCommand.equalsIgnoreCase("DCC")) {
493                         if (messageWords[1].equalsIgnoreCase("SEND")) {
494                                 Optional<InetAddress> inetAddress = parseInetAddress(messageWords[3]);
495                                 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[4]));
496                                 long fileSize = Optional.fromNullable(Longs.tryParse(messageWords[5])).or(-1L);
497                                 if (inetAddress.isPresent() && port.isPresent()) {
498                                         eventBus.post(new DccSendReceived(this, client, messageWords[2], inetAddress.get(), port.get(), fileSize));
499                                 } else {
500                                         logger.warning(String.format("Received malformed DCC SEND: “%s”", message));
501                                 }
502                         } else if (messageWords[1].equalsIgnoreCase("ACCEPT")) {
503                                 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[3]));
504                                 long position = Optional.fromNullable(Longs.tryParse(messageWords[4])).or(-1L);
505                                 if (port.isPresent()) {
506                                         eventBus.post(new DccAcceptReceived(this, client, messageWords[2], port.get(), position));
507                                 } else {
508                                         logger.warning(String.format("Received malformed DCC ACCEPT: “%s”", message));
509                                 }
510                         }
511                 }
512         }
513
514         /**
515          * Returns an item from the list, or {@link Optional#absent()} if the list is
516          * shorter than required for the given index.
517          *
518          * @param list
519          *              The list to get an item from
520          * @param index
521          *              The index of the item
522          * @param <T>
523          *              The type of the list items
524          * @return This list item wrapped in an {@link Optional}, or {@link
525          *         Optional#absent()} if the list is not long enough
526          */
527         private static <T> Optional<T> getOptional(List<T> list, int index) {
528                 if (index < list.size()) {
529                         return Optional.fromNullable(list.get(index));
530                 }
531                 return Optional.absent();
532         }
533
534         /**
535          * Parses the given {@code ip} and returns an {@link InetAddress} from it.
536          *
537          * @param ip
538          *              The IP to parse
539          * @return The parsed inet address, or {@link Optional#absent()} if no inet
540          *         address could be parsed
541          */
542         private Optional<InetAddress> parseInetAddress(String ip) {
543                 Long ipNumber = Longs.tryParse(ip);
544                 if (ipNumber == null) {
545                         return Optional.absent();
546                 }
547
548                 StringBuilder hostname = new StringBuilder(15);
549                 hostname.append((ipNumber >>> 24) & 0xff).append('.');
550                 hostname.append((ipNumber >>> 16) & 0xff).append('.');
551                 hostname.append((ipNumber >>> 8) & 0xff).append('.');
552                 hostname.append(ipNumber & 0xff);
553                 try {
554                         return Optional.of(InetAddress.getByName(hostname.toString()));
555                 } catch (UnknownHostException uhe1) {
556                         return Optional.absent();
557                 }
558         }
559
560         /** Handles input and output for the connection. */
561         private class ConnectionHandler implements Closeable {
562
563                 /** The output stream of the connection. */
564                 private final OutputStream outputStream;
565
566                 /** The input stream of the connection. */
567                 private final BufferedReader inputStreamReader;
568
569                 /**
570                  * Creates a new connection handler for the given input stream and output
571                  * stream.
572                  *
573                  * @param inputStream
574                  *              The input stream of the connection
575                  * @param outputStream
576                  *              The output stream of the connection
577                  * @throws UnsupportedEncodingException
578                  *              if the encoding (currently “UTF-8”) is not valid
579                  */
580                 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
581                         this.outputStream = outputStream;
582                         inputStreamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
583                 }
584
585                 //
586                 // ACTIONS
587                 //
588
589                 /**
590                  * Sends a command with the given parameters, skipping all {@link
591                  * Optional#absent()} optionals.
592                  *
593                  * @param command
594                  *              The command to send
595                  * @param parameters
596                  *              The parameters
597                  * @throws IOException
598                  *              if an I/O error occurs
599                  */
600                 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
601                         List<String> setParameters = new ArrayList<String>();
602                         for (Optional<String> maybeSetParameter : parameters) {
603                                 if (maybeSetParameter.isPresent()) {
604                                         setParameters.add(maybeSetParameter.get());
605                                 }
606                         }
607                         sendCommand(command, setParameters.toArray(new String[setParameters.size()]));
608                 }
609
610                 /**
611                  * Sends a command with the given parameters.
612                  *
613                  * @param command
614                  *              The command to send
615                  * @param parameters
616                  *              The parameters of the command
617                  * @throws IOException
618                  *              if an I/O error occurs
619                  * @throws IllegalArgumentException
620                  *              if any parameter but that last contains a space character
621                  */
622                 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
623                         StringBuilder commandBuilder = new StringBuilder();
624
625                         commandBuilder.append(command);
626                         for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
627                                 String parameter = parameters[parameterIndex];
628                                 /* space is only allowed in the last parameter. */
629                                 commandBuilder.append(' ');
630                                 if (parameter.contains(" ")) {
631                                         if (parameterIndex == (parameters.length - 1)) {
632                                                 commandBuilder.append(':');
633                                         } else {
634                                                 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
635                                         }
636                                 }
637                                 commandBuilder.append(parameter);
638                         }
639
640                         logger.finest(String.format(">> %s", commandBuilder));
641                         outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
642                         outputStream.flush();
643                 }
644
645                 /**
646                  * Reads a line of reply from the connection.
647                  *
648                  * @return The reply
649                  * @throws IOException
650                  *              if an I/O error occurs
651                  * @throws EOFException
652                  *              if EOF was reached
653                  */
654                 public Reply readReply() throws IOException, EOFException {
655                         String line = inputStreamReader.readLine();
656                         if (line == null) {
657                                 throw new EOFException();
658                         }
659
660                         return Reply.parseLine(line);
661                 }
662
663                 //
664                 // CLOSEABLE METHODS
665                 //
666
667                 @Override
668                 public void close() throws IOException {
669                         Closeables.close(outputStream, true);
670                         Closeables.close(inputStreamReader, true);
671                 }
672
673         }
674
675 }