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