63d12ad830ad9a810c28a381ab1399e47285bd00
[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 import static java.util.Arrays.asList;
22 import static java.util.concurrent.TimeUnit.SECONDS;
23
24 import java.io.BufferedReader;
25 import java.io.Closeable;
26 import java.io.EOFException;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.io.InputStreamReader;
30 import java.io.OutputStream;
31 import java.io.UnsupportedEncodingException;
32 import java.net.InetAddress;
33 import java.net.Socket;
34 import java.net.UnknownHostException;
35 import java.util.ArrayList;
36 import java.util.List;
37 import java.util.Set;
38 import java.util.concurrent.TimeUnit;
39 import java.util.concurrent.atomic.AtomicBoolean;
40
41 import javax.net.SocketFactory;
42
43 import net.pterodactylus.irc.connection.ChannelNotJoinedHandler;
44 import net.pterodactylus.irc.connection.ConnectionEstablishHandler;
45 import net.pterodactylus.irc.connection.Handler;
46 import net.pterodactylus.irc.connection.MotdHandler;
47 import net.pterodactylus.irc.connection.PrefixHandler;
48 import net.pterodactylus.irc.event.ChannelJoined;
49 import net.pterodactylus.irc.event.ChannelLeft;
50 import net.pterodactylus.irc.event.ChannelMessageReceived;
51 import net.pterodactylus.irc.event.ChannelNicknames;
52 import net.pterodactylus.irc.event.ChannelNotJoined;
53 import net.pterodactylus.irc.event.ChannelNotJoined.Reason;
54 import net.pterodactylus.irc.event.ChannelNoticeReceived;
55 import net.pterodactylus.irc.event.ChannelTopic;
56 import net.pterodactylus.irc.event.ClientQuit;
57 import net.pterodactylus.irc.event.ConnectionClosed;
58 import net.pterodactylus.irc.event.ConnectionEstablished;
59 import net.pterodactylus.irc.event.ConnectionFailed;
60 import net.pterodactylus.irc.event.DccAcceptReceived;
61 import net.pterodactylus.irc.event.DccSendReceived;
62 import net.pterodactylus.irc.event.KickedFromChannel;
63 import net.pterodactylus.irc.event.MotdReceived;
64 import net.pterodactylus.irc.event.NicknameChanged;
65 import net.pterodactylus.irc.event.NicknameInUseReceived;
66 import net.pterodactylus.irc.event.NoNicknameGivenReceived;
67 import net.pterodactylus.irc.event.PrivateMessageReceived;
68 import net.pterodactylus.irc.event.PrivateNoticeReceived;
69 import net.pterodactylus.irc.event.ReplyReceived;
70 import net.pterodactylus.irc.event.UnknownReplyReceived;
71 import net.pterodactylus.irc.util.RandomNickname;
72 import net.pterodactylus.xdcc.util.io.BandwidthCountingInputStream;
73 import net.pterodactylus.xdcc.util.io.BandwidthCountingOutputStream;
74
75 import com.google.common.base.Optional;
76 import com.google.common.collect.Sets;
77 import com.google.common.eventbus.EventBus;
78 import com.google.common.eventbus.Subscribe;
79 import com.google.common.io.Closeables;
80 import com.google.common.primitives.Ints;
81 import com.google.common.primitives.Longs;
82 import com.google.common.util.concurrent.AbstractExecutionThreadService;
83 import com.google.common.util.concurrent.Service;
84 import org.apache.log4j.Logger;
85
86 /**
87  * A connection to an IRC server.
88  *
89  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
90  */
91 public class Connection extends AbstractExecutionThreadService implements Service {
92
93         /* The logger. */
94         private static final Logger logger = Logger.getLogger(Connection.class.getName());
95
96         /** The event bus. */
97         private final EventBus eventBus;
98
99         /** The socket factory. */
100         private final SocketFactory socketFactory;
101
102         /** The hostname to connect to. */
103         private final String hostname;
104
105         /** The port to connect to. */
106         private final int port;
107
108         /** The nickname chooser. */
109         private NicknameChooser nicknameChooser = new NicknameChooser() {
110
111                 @Override
112                 public String getNickname() {
113                         return RandomNickname.get();
114                 }
115         };
116
117         /** The nickname. */
118         private String nickname = null;
119
120         /** The username. */
121         private Optional<String> username = Optional.absent();
122
123         /** The real name. */
124         private Optional<String> realName = Optional.absent();
125
126         /** The optional password for the connection. */
127         private Optional<String> password = Optional.absent();
128
129         /** The connection handler. */
130         private ConnectionHandler connectionHandler;
131
132         /** Whether the connection has already been established. */
133         private final AtomicBoolean established = new AtomicBoolean();
134
135         /**
136          * Creates a new connection.
137          *
138          * @param eventBus
139          *              The event bus
140          * @param socketFactory
141          *              The socket factory
142          * @param hostname
143          *              The hostname of the IRC server
144          * @param port
145          *              The port number of the IRC server
146          */
147         public Connection(EventBus eventBus, SocketFactory socketFactory, String hostname, int port) {
148                 this.eventBus = eventBus;
149                 this.socketFactory = socketFactory;
150                 this.hostname = hostname;
151                 this.port = port;
152         }
153
154         //
155         // ACCESSORS
156         //
157
158         /**
159          * Returns the hostname of the remote end of the connection.
160          *
161          * @return The remote’s hostname
162          */
163         public String hostname() {
164                 return hostname;
165         }
166
167         /**
168          * Returns the port number of the remote end of the connection.
169          *
170          * @return The remote’s port number
171          */
172         public int port() {
173                 return port;
174         }
175
176         /**
177          * Returns whether this connection has already been established.
178          *
179          * @return {@code true} as long as this connection is established, {@code
180          *         false} otherwise
181          */
182         public boolean established() {
183                 return established.get();
184         }
185
186         /**
187          * Returns the nickname that is currently in use by this connection. The
188          * nickname is only available once the connection has been {@link #start()}ed.
189          *
190          * @return The current nickname
191          */
192         public String nickname() {
193                 return nickname;
194         }
195
196         //
197         // MUTATORS
198         //
199
200         /**
201          * Sets the nickname chooser. The nickname chooser is only used during the
202          * creation of the connection.
203          *
204          * @param nicknameChooser
205          *              The nickname chooser
206          * @return This connection
207          */
208         public Connection nicknameChooser(NicknameChooser nicknameChooser) {
209                 this.nicknameChooser = nicknameChooser;
210                 return this;
211         }
212
213         /**
214          * Sets the username to use.
215          *
216          * @param username
217          *              The username to use
218          * @return This connection
219          */
220         public Connection username(String username) {
221                 this.username = Optional.fromNullable(username);
222                 return this;
223         }
224
225         /**
226          * Sets the real name to use.
227          *
228          * @param realName
229          *              The real name to use
230          * @return This connection
231          */
232         public Connection realName(String realName) {
233                 this.realName = Optional.fromNullable(realName);
234                 return this;
235         }
236
237         /**
238          * Sets the optional password for the connection.
239          *
240          * @param password
241          *              The password for the connection
242          * @return This connection
243          */
244         public Connection password(String password) {
245                 this.password = Optional.fromNullable(password);
246                 return this;
247         }
248
249         //
250         // ACTIONS
251         //
252
253         /**
254          * Returns the current rate of the connection’s incoming side.
255          *
256          * @return The current input rate (in bytes per second)
257          */
258         public long getInputRate() {
259                 return (connectionHandler != null) ? connectionHandler.getInputRate() : 0;
260         }
261
262         /**
263          * Returns the current rate of the connection’s outgoing side.
264          *
265          * @return The current output rate (in bytes per second)
266          */
267         public long getOutputRate() {
268                 return (connectionHandler != null) ? connectionHandler.getOutputRate() : 0;
269         }
270
271         /**
272          * Checks whether the given source is the client represented by this
273          * connection.
274          *
275          * @param source
276          *              The source to check
277          * @return {@code true} if this connection represents the given source, {@code
278          *         false} otherwise
279          */
280         public boolean isSource(Source source) {
281                 return source.nick().isPresent() && source.nick().get().equals(nickname);
282         }
283
284         /**
285          * Joins the given channel.
286          *
287          * @param channel
288          *              The channel to join
289          * @throws IOException
290          *              if an I/O error occurs
291          */
292         public void joinChannel(final String channel) throws IOException {
293                 connectionHandler.sendCommand("JOIN", channel);
294         }
295
296         /**
297          * Sends a message to the given recipient, which may be a channel or another
298          * nickname.
299          *
300          * @param recipient
301          *              The recipient of the message
302          * @param message
303          *              The message
304          * @throws IOException
305          *              if an I/O error occurs
306          */
307         public void sendMessage(String recipient, String message) throws IOException {
308                 connectionHandler.sendCommand("PRIVMSG", recipient, message);
309         }
310
311         /**
312          * Sends a DCC RESUME request to the given recipient.
313          *
314          * @param recipient
315          *              The recipient of the request
316          * @param filename
317          *              The name of the file to resume
318          * @param port
319          *              The port number from the original DCC SEND request
320          * @param position
321          *              The position at which to resume the transfer
322          * @throws IOException
323          *              if an I/O error occurs
324          */
325         public void sendDccResume(String recipient, String filename, int port, long position) throws IOException {
326                 connectionHandler.sendCommand("PRIVMSG", recipient, String.format("\u0001DCC RESUME %s %d %d\u0001", filename, port, position));
327         }
328
329         /**
330          * Closes this connection.
331          *
332          * @throws IOException
333          *              if an I/O error occurs
334          */
335         public void close() throws IOException {
336                 if (connectionHandler != null) {
337                         connectionHandler.close();
338                 }
339         }
340
341         //
342         // ABSTRACTEXECUTIONTHREADSERVICE METHODS
343         //
344
345         @Override
346         protected void startUp() throws IllegalStateException {
347                 checkState(username.isPresent(), "username must be set");
348                 checkState(realName.isPresent(), "realName must be set");
349         }
350
351         @Override
352         protected void run() {
353
354                 /* connect to remote socket. */
355                 try {
356                         Socket socket = socketFactory.createSocket(hostname, port);
357                         socket.setSoTimeout((int) TimeUnit.MINUTES.toMillis(3));
358                         connectionHandler = new ConnectionHandler(socket.getInputStream(), socket.getOutputStream());
359
360                         /* register connection. */
361                         if (password.isPresent()) {
362                                 connectionHandler.sendCommand("PASSWORD", password.get());
363                         }
364                         connectionHandler.sendCommand("USER", username.get(), "8", "*", realName.get());
365                         nickname = nicknameChooser.getNickname();
366                         connectionHandler.sendCommand("NICK", nickname);
367
368                 } catch (IOException ioe1) {
369                         eventBus.post(new ConnectionFailed(this, ioe1));
370                         return;
371                 }
372
373                 eventBus.register(this);
374                 /* now read replies and react. */
375                 try {
376                         /* some status variables. */
377                         boolean connected = true;
378                         Set<Nickname> nicks = Sets.newHashSet();
379
380                         PrefixHandler prefixHandler = new PrefixHandler();
381                         List<Handler> handlers = asList(
382                                         new MotdHandler(eventBus, this),
383                                         new ChannelNotJoinedHandler(eventBus, this),
384                                         new ConnectionEstablishHandler(eventBus, this),
385                                         prefixHandler
386                         );
387
388                         while (connected) {
389                                 Reply reply = connectionHandler.readReply();
390                                 eventBus.post(new ReplyReceived(this, reply));
391                                 logger.trace(String.format("<< %s", reply));
392                                 String command = reply.command();
393                                 List<String> parameters = reply.parameters();
394
395                                 for (Handler handler : handlers) {
396                                         if (handler.willHandle(reply)) {
397                                                 handler.handleReply(reply);
398                                                 break;
399                                         }
400                                 }
401
402                                 /* most common events. */
403                                 if (command.equalsIgnoreCase("PRIVMSG")) {
404                                         String recipient = parameters.get(0);
405                                         String message = parameters.get(1);
406                                         if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
407                                                 /* CTCP! */
408                                                 handleCtcp(reply.source().get(), message);
409                                         } else if (!prefixHandler.isChannel(recipient)) {
410                                                 eventBus.post(new PrivateMessageReceived(this, reply.source().get(), message));
411                                         } else {
412                                                 eventBus.post(new ChannelMessageReceived(this, recipient, reply.source().get(), message));
413                                         }
414
415                                 } else if (command.equalsIgnoreCase("NOTICE")) {
416                                         String recipient = parameters.get(0);
417                                         String message = parameters.get(1);
418                                         if (message.startsWith("\u0001") && message.endsWith("\u0001")) {
419                                                 /* CTCP! */
420                                                 handleCtcp(reply.source().get(), message);
421                                         } else if (!prefixHandler.isChannel(recipient)) {
422                                                 eventBus.post(new PrivateNoticeReceived(this, reply));
423                                         } else {
424                                                 eventBus.post(new ChannelNoticeReceived(this, reply.source().get(), recipient, message));
425                                         }
426
427                                 /* 43x replies are for nick change errors. */
428                                 } else if (command.equals("431")) {
429                                         eventBus.post(new NoNicknameGivenReceived(this, reply));
430                                 } else if (command.equals("433")) {
431                                         if (!established.get()) {
432                                                 nickname = nicknameChooser.getNickname();
433                                                 connectionHandler.sendCommand("NICK", nickname);
434                                         } else {
435                                                 eventBus.post(new NicknameInUseReceived(this, reply));
436                                         }
437
438                                 /* client stuff. */
439                                 } else if (command.equalsIgnoreCase("NICK")) {
440                                         eventBus.post(new NicknameChanged(this, reply.source().get(), parameters.get(0)));
441
442                                 /* channel stuff. */
443                                 } else if (command.equalsIgnoreCase("JOIN")) {
444                                         eventBus.post(new ChannelJoined(this, parameters.get(0), reply.source().get()));
445                                 } else if (command.equals("331")) {
446                                         /* no topic is set. */
447                                 } else if (command.equals("332")) {
448                                         eventBus.post(new ChannelTopic(this, parameters.get(1), parameters.get(2)));
449                                 } else if (command.equals("353")) {
450                                         for (String nickname : parameters.get(3).split(" ")) {
451                                                 if (prefixHandler.isNickPrefixed(nickname)) {
452                                                         nicks.add(new Nickname(nickname.substring(1), nickname.substring(0, 1)));
453                                                 } else {
454                                                         nicks.add(new Nickname(nickname, ""));
455                                                 }
456                                         }
457                                 } else if (command.equals("366")) {
458                                         eventBus.post(new ChannelNicknames(this, parameters.get(1), nicks));
459                                         nicks.clear();
460                                 } else if (command.equalsIgnoreCase("PART")) {
461                                         eventBus.post(new ChannelLeft(this, parameters.get(0), reply.source().get(), getOptional(parameters, 1)));
462                                 } else if (command.equalsIgnoreCase("QUIT")) {
463                                         eventBus.post(new ClientQuit(this, reply.source().get(), parameters.get(0)));
464
465                                 /* basic connection housekeeping. */
466                                 } else if (command.equalsIgnoreCase("PING")) {
467                                         connectionHandler.sendCommand("PONG", getOptional(parameters, 0), getOptional(parameters, 1));
468
469                                 } else if (command.equalsIgnoreCase("KICK")) {
470                                         eventBus.post(new KickedFromChannel(this, parameters.get(0), reply.source().get(), parameters.get(1), getOptional(parameters, 2)));
471
472                                 /* okay, everything else. */
473                                 } else {
474                                         eventBus.post(new UnknownReplyReceived(this, reply));
475                                 }
476                         }
477                         eventBus.post(new ConnectionClosed(this));
478                 } catch (IOException ioe1) {
479                         logger.warn("I/O error", ioe1);
480                         eventBus.post(new ConnectionClosed(this, ioe1));
481                 } catch (RuntimeException re1) {
482                         logger.error("Runtime error", re1);
483                         eventBus.post(new ConnectionClosed(this, re1));
484                 } finally {
485                         established.set(false);
486                         eventBus.unregister(this);
487                         logger.info("Closing Connection.");
488                         try {
489                                 Closeables.close(connectionHandler, true);
490                         } catch (IOException ioe1) {
491                                 /* will not be thrown. */
492                         }
493                 }
494
495         }
496
497         @Subscribe
498         public void connectionEstablished(ConnectionEstablished connectionEstablished) {
499                 if (connectionEstablished.connection() == this) {
500                         established.set(true);
501                 }
502         }
503
504         //
505         // PRIVATE METHODS
506         //
507
508         /**
509          * Handles a CTCP message.
510          *
511          * @param client
512          *              The client sending the message
513          * @param message
514          *              The message
515          */
516         private void handleCtcp(Source client, String message) {
517                 String[] messageWords = message.substring(1, message.length() - 1).split(" +");
518                 String ctcpCommand = messageWords[0];
519                 if (ctcpCommand.equalsIgnoreCase("DCC")) {
520                         if (messageWords[1].equalsIgnoreCase("SEND")) {
521                                 Optional<InetAddress> inetAddress = parseInetAddress(messageWords[3]);
522                                 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[4]));
523                                 long fileSize = Optional.fromNullable(Longs.tryParse(messageWords[5])).or(-1L);
524                                 if (inetAddress.isPresent() && port.isPresent()) {
525                                         eventBus.post(new DccSendReceived(this, client, messageWords[2], inetAddress.get(), port.get(), fileSize));
526                                 } else {
527                                         logger.warn(String.format("Received malformed DCC SEND: “%s”", message));
528                                 }
529                         } else if (messageWords[1].equalsIgnoreCase("ACCEPT")) {
530                                 Optional<Integer> port = Optional.fromNullable(Ints.tryParse(messageWords[3]));
531                                 long position = (messageWords.length > 4) ? Optional.fromNullable(Longs.tryParse(messageWords[4])).or(-1L) : -1;
532                                 if (port.isPresent()) {
533                                         eventBus.post(new DccAcceptReceived(this, client, messageWords[2], port.get(), position));
534                                 } else {
535                                         logger.warn(String.format("Received malformed DCC ACCEPT: “%s”", message));
536                                 }
537                         }
538                 }
539         }
540
541         /**
542          * Returns an item from the list, or {@link Optional#absent()} if the list is
543          * shorter than required for the given index.
544          *
545          * @param list
546          *              The list to get an item from
547          * @param index
548          *              The index of the item
549          * @param <T>
550          *              The type of the list items
551          * @return This list item wrapped in an {@link Optional}, or {@link
552          *         Optional#absent()} if the list is not long enough
553          */
554         private static <T> Optional<T> getOptional(List<T> list, int index) {
555                 if (index < list.size()) {
556                         return Optional.fromNullable(list.get(index));
557                 }
558                 return Optional.absent();
559         }
560
561         /**
562          * Parses the given {@code ip} and returns an {@link InetAddress} from it.
563          *
564          * @param ip
565          *              The IP to parse
566          * @return The parsed inet address, or {@link Optional#absent()} if no inet
567          *         address could be parsed
568          */
569         private Optional<InetAddress> parseInetAddress(String ip) {
570                 Long ipNumber = Longs.tryParse(ip);
571                 if (ipNumber == null) {
572                         return Optional.absent();
573                 }
574
575                 StringBuilder hostname = new StringBuilder(15);
576                 hostname.append((ipNumber >>> 24) & 0xff).append('.');
577                 hostname.append((ipNumber >>> 16) & 0xff).append('.');
578                 hostname.append((ipNumber >>> 8) & 0xff).append('.');
579                 hostname.append(ipNumber & 0xff);
580                 try {
581                         return Optional.of(InetAddress.getByName(hostname.toString()));
582                 } catch (UnknownHostException uhe1) {
583                         return Optional.absent();
584                 }
585         }
586
587         /** Handles input and output for the connection. */
588         private class ConnectionHandler implements Closeable {
589
590                 /** The output stream of the connection. */
591                 private final BandwidthCountingOutputStream outputStream;
592
593                 /** The input stream. */
594                 private final BandwidthCountingInputStream inputStream;
595
596                 /** The input stream of the connection. */
597                 private final BufferedReader inputStreamReader;
598
599                 /**
600                  * Creates a new connection handler for the given input stream and output
601                  * stream.
602                  *
603                  * @param inputStream
604                  *              The input stream of the connection
605                  * @param outputStream
606                  *              The output stream of the connection
607                  * @throws UnsupportedEncodingException
608                  *              if the encoding (currently “UTF-8”) is not valid
609                  */
610                 private ConnectionHandler(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
611                         this.outputStream = new BandwidthCountingOutputStream(outputStream, 5, SECONDS);
612                         this.inputStream = new BandwidthCountingInputStream(inputStream, 5, SECONDS);
613                         inputStreamReader = new BufferedReader(new InputStreamReader(this.inputStream, "UTF-8"));
614                 }
615
616                 //
617                 // ACTIONS
618                 //
619
620                 /**
621                  * Returns the current rate of the connection’s incoming side.
622                  *
623                  * @return The current input rate (in bytes per second)
624                  */
625                 public long getInputRate() {
626                         return inputStream.getCurrentRate();
627                 }
628
629                 /**
630                  * Returns the current rate of the connection’s outgoing side.
631                  *
632                  * @return The current output rate (in bytes per second)
633                  */
634                 public long getOutputRate() {
635                         return outputStream.getCurrentRate();
636                 }
637
638                 /**
639                  * Sends a command with the given parameters, skipping all {@link
640                  * Optional#absent()} optionals.
641                  *
642                  * @param command
643                  *              The command to send
644                  * @param parameters
645                  *              The parameters
646                  * @throws IOException
647                  *              if an I/O error occurs
648                  */
649                 public void sendCommand(String command, Optional<String>... parameters) throws IOException {
650                         List<String> setParameters = new ArrayList<String>();
651                         for (Optional<String> maybeSetParameter : parameters) {
652                                 if (maybeSetParameter.isPresent()) {
653                                         setParameters.add(maybeSetParameter.get());
654                                 }
655                         }
656                         sendCommand(command, setParameters.toArray(new String[setParameters.size()]));
657                 }
658
659                 /**
660                  * Sends a command with the given parameters.
661                  *
662                  * @param command
663                  *              The command to send
664                  * @param parameters
665                  *              The parameters of the command
666                  * @throws IOException
667                  *              if an I/O error occurs
668                  * @throws IllegalArgumentException
669                  *              if any parameter but that last contains a space character
670                  */
671                 public void sendCommand(String command, String... parameters) throws IOException, IllegalArgumentException {
672                         StringBuilder commandBuilder = new StringBuilder();
673
674                         commandBuilder.append(command);
675                         for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
676                                 String parameter = parameters[parameterIndex];
677                                 /* space is only allowed in the last parameter. */
678                                 commandBuilder.append(' ');
679                                 if (parameter.contains(" ")) {
680                                         if (parameterIndex == (parameters.length - 1)) {
681                                                 commandBuilder.append(':');
682                                         } else {
683                                                 throw new IllegalArgumentException(String.format("parameter “%s” must not contain space!", parameter));
684                                         }
685                                 }
686                                 commandBuilder.append(parameter);
687                         }
688
689                         logger.trace(String.format(">> %s", commandBuilder));
690                         outputStream.write((commandBuilder.toString() + "\r\n").getBytes("UTF-8"));
691                         outputStream.flush();
692                 }
693
694                 /**
695                  * Reads a line of reply from the connection.
696                  *
697                  * @return The reply
698                  * @throws IOException
699                  *              if an I/O error occurs
700                  * @throws EOFException
701                  *              if EOF was reached
702                  */
703                 public Reply readReply() throws IOException, EOFException {
704                         String line = inputStreamReader.readLine();
705                         if (line == null) {
706                                 throw new EOFException();
707                         }
708
709                         return Reply.parseLine(line);
710                 }
711
712                 //
713                 // CLOSEABLE METHODS
714                 //
715
716                 @Override
717                 public void close() throws IOException {
718                         Closeables.close(outputStream, true);
719                         Closeables.close(inputStreamReader, true);
720                         Closeables.close(inputStream, true);
721                 }
722
723         }
724
725 }