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