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