Add method to determine whether a connection represents a given source.
[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          * Checks whether the given source is the client represented by this
205          * connection.
206          *
207          * @param source
208          *              The source to check
209          * @return {@code true} if this connection represents the given source, {@code
210          *         false} otherwise
211          */
212         public boolean isSource(Source source) {
213                 return source.nick().isPresent() && source.nick().get().equals(nickname);
214         }
215
216         /**
217          * Joins the given channel.
218          *
219          * @param channel
220          *              The channel to join
221          * @throws IOException
222          *              if an I/O error occurs
223          */
224         public void joinChannel(final String channel) throws IOException {
225                 connectionHandler.sendCommand("JOIN", channel);
226         }
227
228         /**
229          * Sends a message to the given recipient, which may be a channel or another
230          * nickname.
231          *
232          * @param recipient
233          *              The recipient of the message
234          * @param message
235          *              The message
236          * @throws IOException
237          *              if an I/O error occurs
238          */
239         public void sendMessage(String recipient, String message) throws IOException {
240                 connectionHandler.sendCommand("PRIVMSG", recipient, message);
241         }
242
243         //
244         // ABSTRACTEXECUTIONTHREADSERVICE METHODS
245         //
246
247         @Override
248         protected void startUp() throws IllegalStateException {
249                 checkState(username.isPresent(), "username must be set");
250                 checkState(realName.isPresent(), "realName must be set");
251         }
252
253         @Override
254         protected void run() {
255
256                 /* connect to remote socket. */
257                 try {
258                         Socket socket = socketFactory.createSocket(hostname, port);
259                         connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
260
261                         /* register connection. */
262                         if (password.isPresent()) {
263                                 connectionHandler.sendCommand("PASSWORD", password.get());
264                         }
265                         connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
266                         nickname = nicknameChooser.getNickname();
267                         connectionHandler.sendCommand("NICK", nickname);
268
269                 } catch (IOException ioe1) {
270                         eventBus.post(new ConnectionFailed(this, ioe1));
271                         return;
272                 }
273
274                 /* now read replies and react. */
275                 try {
276                         /* some status variables. */
277                         int oldConnectionStatus = 0;
278                         int connectionStatus = 0;
279                         boolean connected = true;
280                         StringBuilder motd = new StringBuilder();
281                         Set<Nickname> nicks = Sets.newHashSet();
282
283                         /* server modes. */
284                         Map<String, String> nickPrefixes = Maps.newHashMap();
285                         Set<Character> channelTypes = Sets.newHashSet();
286
287                         while (connected) {
288                                 Reply reply = connectionHandler.readReply();
289                                 logger.finest(String.format("<< %s", reply));
290                                 String command = reply.command();
291                                 List<String> parameters = reply.parameters();
292
293                                 /* most common events. */
294                                 if (command.equalsIgnoreCase("PRIVMSG")) {
295                                         String recipient = parameters.get(0);
296                                         String message = parameters.get(1);
297                                         if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
298                                                 /* CTCP! */
299                                                 String[] messageWords = message.substring(1, message.length() - 1).split(" +");
300                                                 String ctcpCommand = messageWords[0];
301                                                 if (ctcpCommand.equalsIgnoreCase("DCC")) {
302                                                         if (messageWords[1].equalsIgnoreCase("SEND")) {
303                                                                 Optional<InetAddress> inetAddress = parseInetAddress(messageWords[3]);
304                                                                 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[4]));
305                                                                 long fileSize = Optional.fromNullable(Longs.tryParse(messageWords[5])).or(-1L);
306                                                                 if (inetAddress.isPresent() && port.isPresent()) {
307                                                                         eventBus.post(new DccSendReceived(this, reply.source().get(), messageWords[2], inetAddress.get(), port.get(), fileSize));
308                                                                 } else {
309                                                                         logger.warning(String.format("Received malformed DCC SEND: “%s”", message));
310                                                                 }
311                                                         }
312                                                 }
313                                         } else if (!channelTypes.contains(recipient.charAt(0))) {
314                                                 eventBus.post(new PrivateMessageReceived(this, reply.source().get(), message));
315                                         } else {
316                                                 eventBus.post(new ChannelMessageReceived(this, recipient, reply.source().get(), message));
317                                         }
318
319                                 /* replies 001-004 don’t hold information but they have to be sent on a successful connection. */
320                                 } else if (command.equals("001")) {
321                                         connectionStatus |= 0x01;
322                                 } else if (command.equals("002")) {
323                                         connectionStatus |= 0x02;
324                                 } else if (command.equals("003")) {
325                                         connectionStatus |= 0x04;
326                                 } else if (command.equals("004")) {
327                                         connectionStatus |= 0x08;
328
329                                 /* 005 originally was a bounce message, now used to transmit useful information about the server. */
330                                 } else if (command.equals("005")) {
331                                         for (String parameter : parameters) {
332                                                 if (parameter.startsWith("PREFIX=")) {
333                                                         int openParen = parameter.indexOf('(');
334                                                         int closeParen = parameter.indexOf(')');
335                                                         if ((openParen != -1) && (closeParen != -1)) {
336                                                                 for (int modeCharacterIndex = 1; modeCharacterIndex < (closeParen - openParen); ++modeCharacterIndex) {
337                                                                         char modeCharacter = parameter.charAt(openParen + modeCharacterIndex);
338                                                                         char modeSymbol = parameter.charAt(closeParen + modeCharacterIndex);
339                                                                         nickPrefixes.put(String.valueOf(modeSymbol), String.valueOf(modeCharacter));
340                                                                 }
341                                                                 logger.fine(String.format("Parsed Prefixes: %s", nickPrefixes));
342                                                         }
343                                                 } else if (parameter.startsWith("CHANTYPES=")) {
344                                                         for (int typeIndex = 10; typeIndex < parameter.length(); ++typeIndex) {
345                                                                 channelTypes.add(parameter.charAt(typeIndex));
346                                                         }
347                                                         logger.fine(String.format("Parsed Channel Types: %s", channelTypes));
348                                                 }
349                                         }
350
351                                 /* 375, 372, and 376 handle the server’s MOTD. */
352                                 } else if (command.equals("375")) {
353                                         /* MOTD starts. */
354                                         motd.append(parameters.get(1)).append('\n');
355                                 } else if (command.equals("372")) {
356                                         motd.append(parameters.get(1)).append('\n');
357                                 } else if (command.equals("376")) {
358                                         motd.append(parameters.get(1)).append('\n');
359                                         eventBus.post(new MotdReceived(this, motd.toString()));
360                                         motd.setLength(0);
361
362                                 /* 43x replies are for nick change errors. */
363                                 } else if (command.equals("431")) {
364                                         eventBus.post(new NoNicknameGivenReceived(this, reply));
365                                 } else if (command.equals("433")) {
366                                         if (connectionStatus == 0) {
367                                                 nickname = nicknameChooser.getNickname();
368                                                 connectionHandler.sendCommand("NICK", nickname);
369                                         } else {
370                                                 eventBus.post(new NicknameInUseReceived(this, reply));
371                                         }
372
373                                 /* channel stuff. */
374                                 } else if (command.equalsIgnoreCase("JOIN")) {
375                                         eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
376                                 } else if (command.equals("331")) {
377                                         /* no topic is set. */
378                                 } else if (command.equals("332")) {
379                                         eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
380                                 } else if (command.equals("353")) {
381                                         for (String nickname : parameters.get(3).split(" ")) {
382                                                 if (nickPrefixes.containsKey(nickname.substring(0, 1))) {
383                                                         nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
384                                                 } else {
385                                                         nicks.add(new Nickname(nickname, ""));
386                                                 }
387                                         }
388                                 } else if (command.equals("366")) {
389                                         eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
390                                         nicks.clear();
391
392                                 /* common channel join errors. */
393                                 } else if (command.equals("474")) {
394                                         eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.banned));
395                                 } else if (command.equals("473")) {
396                                         eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.inviteOnly));
397                                 } else if (command.equals("475")) {
398                                         eventBus.post(new ChannelNotJoined(this, parameters.get(1), Reason.badChannelKey));
399
400                                 /* basic connection housekeeping. */
401                                 } else if (command.equalsIgnoreCase("PING")) {
402                                         connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
403
404                                 /* okay, everything else. */
405                                 } else {
406                                         eventBus.post(new UnknownReplyReceived(this, reply));
407                                 }
408
409                                 if ((connectionStatus == 0x0f) && (connectionStatus != oldConnectionStatus)) {
410                                         /* connection succeeded! */
411                                         eventBus.post(new ConnectionEstablished(this));
412                                 }
413                                 oldConnectionStatus = connectionStatus;
414                         }
415                 } catch (IOException ioe1) {
416                         logger.log(Level.WARNING, "I/O error", ioe1);
417                 } finally {
418                         logger.info("Closing Connection.");
419                         try {
420                                 Closeables.close(connectionHandler, true);
421                         } catch (IOException ioe1) {
422                                 /* will not be thrown. */
423                         }
424                 }
425
426         }
427
428         //
429         // PRIVATE METHODS
430         //
431
432         /**
433          * Returns an item from the list, or {@link Optional#absent()} if the list is
434          * shorter than required for the given index.
435          *
436          * @param list
437          *              The list to get an item from
438          * @param index
439          *              The index of the item
440          * @param <T>
441          *              The type of the list items
442          * @return This list item wrapped in an {@link Optional}, or {@link
443          *         Optional#absent()} if the list is not long enough
444          */
445         private static <T> Optional<T> getOptional(List<T> list, int index) {
446                 if (index < list.size()) {
447                         return Optional.fromNullable(list.get(index));
448                 }
449                 return Optional.absent();
450         }
451
452         /**
453          * Parses the given {@code ip} and returns an {@link InetAddress} from it.
454          *
455          * @param ip
456          *              The IP to parse
457          * @return The parsed inet address, or {@link Optional#absent()} if no inet
458          *         address could be parsed
459          */
460         private Optional<InetAddress> parseInetAddress(String ip) {
461                 Long ipNumber = Longs.tryParse(ip);
462                 if (ipNumber == null) {
463                         return Optional.absent();
464                 }
465
466                 StringBuilder hostname = new StringBuilder(15);
467                 hostname.append((ipNumber >>> 24) & 0xff).append('.');
468                 hostname.append((ipNumber >>> 16) & 0xff).append('.');
469                 hostname.append((ipNumber >>> 8) & 0xff).append('.');
470                 hostname.append(ipNumber & 0xff);
471                 try {
472                         return Optional.of(InetAddress.getByName(hostname.toString()));
473                 } catch (UnknownHostException uhe1) {
474                         return Optional.absent();
475                 }
476         }
477
478         /** Handles input and output for the connection. */
479         private class ConnectionHandler implements Closeable {
480
481                 /** The output stream of the connection. */
482                 private final OutputStream outputStream;
483
484                 /** The input stream of the connection. */
485                 private final BufferedReader inputStreamReader;
486
487                 /**
488                  * Creates a new connection handler for the given input stream and output
489                  * stream.
490                  *
491                  * @param inputStream
492                  *              The input stream of the connection
493                  * @param outputStream
494                  *              The output stream of the connection
495                  * @throws UnsupportedEncodingException
496                  *              if the encoding (currently “UTF-8”) is not valid
497                  */
498                 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
499                         this.outputStream = outputStream;
500                         inputStreamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
501                 }
502
503                 //
504                 // ACTIONS
505                 //
506
507                 /**
508                  * Sends a command with the given parameters, skipping all {@link
509                  * Optional#absent()} optionals.
510                  *
511                  * @param command
512                  *              The command to send
513                  * @param parameters
514                  *              The parameters
515                  * @throws IOException
516                  *              if an I/O error occurs
517                  */
518                 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
519                         List<String> setParameters = new ArrayList<String>();
520                         for (Optional<String> maybeSetParameter : parameters) {
521                                 if (maybeSetParameter.isPresent()) {
522                                         setParameters.add(maybeSetParameter.get());
523                                 }
524                         }
525                         sendCommand(command, setParameters.toArray(new String[setParameters.size()]));
526                 }
527
528                 /**
529                  * Sends a command with the given parameters.
530                  *
531                  * @param command
532                  *              The command to send
533                  * @param parameters
534                  *              The parameters of the command
535                  * @throws IOException
536                  *              if an I/O error occurs
537                  * @throws IllegalArgumentException
538                  *              if any parameter but that last contains a space character
539                  */
540                 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
541                         StringBuilder commandBuilder = new StringBuilder();
542
543                         commandBuilder.append(command);
544                         for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
545                                 String parameter = parameters[parameterIndex];
546                                 /* space is only allowed in the last parameter. */
547                                 commandBuilder.append(' ');
548                                 if (parameter.contains(" ")) {
549                                         if (parameterIndex == (parameters.length - 1)) {
550                                                 commandBuilder.append(':');
551                                         } else {
552                                                 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
553                                         }
554                                 }
555                                 commandBuilder.append(parameter);
556                         }
557
558                         logger.finest(String.format(">> %s", commandBuilder));
559                         outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
560                         outputStream.flush();
561                 }
562
563                 /**
564                  * Reads a line of reply from the connection.
565                  *
566                  * @return The reply
567                  * @throws IOException
568                  *              if an I/O error occurs
569                  * @throws EOFException
570                  *              if EOF was reached
571                  */
572                 public Reply readReply() throws IOException, EOFException {
573                         String line = inputStreamReader.readLine();
574                         if (line == null) {
575                                 throw new EOFException();
576                         }
577
578                         return Reply.parseLine(line);
579                 }
580
581                 //
582                 // CLOSEABLE METHODS
583                 //
584
585                 @Override
586                 public void close() throws IOException {
587                         Closeables.close(outputStream, true);
588                         Closeables.close(inputStreamReader, true);
589                 }
590
591         }
592
593 }