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