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