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