001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.apache.commons.net.bsd;
019
020import java.io.IOException;
021import java.io.InputStream;
022import java.net.BindException;
023import java.net.InetAddress;
024import java.net.ServerSocket;
025import java.net.Socket;
026import java.net.SocketException;
027import java.net.UnknownHostException;
028
029import org.apache.commons.net.io.SocketInputStream;
030
031/***
032 * RCommandClient is very similar to
033 * {@link org.apache.commons.net.bsd.RExecClient},
034 * from which it is derived, and implements the rcmd() facility that
035 * first appeared in 4.2BSD Unix.  rcmd() is the facility used by the rsh
036 * (rshell) and other commands to execute a command on another machine
037 * from a trusted host without issuing a password.  The trust relationship
038 * between two machines is established by the contents of a machine's
039 * /etc/hosts.equiv file and a user's .rhosts file.  These files specify
040 * from which hosts and accounts on those hosts rcmd() requests will be
041 * accepted.  The only additional measure for establishing trust is that
042 * all client connections must originate from a port between 512 and 1023.
043 * Consequently, there is an upper limit to the number of rcmd connections
044 * that can be running simultaneously.   The required ports are reserved
045 * ports on Unix systems, and can only be bound by a
046 * process running with root permissions (to accomplish this rsh, rlogin,
047 * and related commands usualy have the suid bit set).  Therefore, on a
048 * Unix system, you will only be able to successfully use the RCommandClient
049 * class if the process runs as root.  However, there is no such restriction
050 * on Windows95 and some other systems.  The security risks are obvious.
051 * However, when carefully used, rcmd() can be very useful when used behind
052 * a firewall.
053 * <p>
054 * As with virtually all of the client classes in org.apache.commons.net, this
055 * class derives from SocketClient.  But it overrides most of its connection
056 * methods so that the local Socket will originate from an acceptable
057 * rshell port.  The way to use RCommandClient is to first connect
058 * to the server, call the {@link #rcommand  rcommand() } method,
059 * and then
060 * fetch the connection's input, output, and optionally error streams.
061 * Interaction with the remote command is controlled entirely through the
062 * I/O streams.  Once you have finished processing the streams, you should
063 * invoke {@link org.apache.commons.net.bsd.RExecClient#disconnect disconnect() }
064 *  to clean up properly.
065 * <p>
066 * By default the standard output and standard error streams of the
067 * remote process are transmitted over the same connection, readable
068 * from the input stream returned by
069 * {@link org.apache.commons.net.bsd.RExecClient#getInputStream getInputStream() }
070 * .  However, it is
071 * possible to tell the rshd daemon to return the standard error
072 * stream over a separate connection, readable from the input stream
073 * returned by {@link org.apache.commons.net.bsd.RExecClient#getErrorStream getErrorStream() }
074 * .  You
075 * can specify that a separate connection should be created for standard
076 * error by setting the boolean <code> separateErrorStream </code>
077 * parameter of {@link #rcommand  rcommand() } to <code> true </code>.
078 * The standard input of the remote process can be written to through
079 * the output stream returned by
080 * {@link org.apache.commons.net.bsd.RExecClient#getOutputStream getOutputStream() }
081 * .
082 * <p>
083 * <p>
084 * @see org.apache.commons.net.SocketClient
085 * @see RExecClient
086 * @see RLoginClient
087 ***/
088
089public class RCommandClient extends RExecClient
090{
091    /***
092     * The default rshell port.  Set to 514 in BSD Unix.
093     ***/
094    public static final int DEFAULT_PORT = 514;
095
096    /***
097     * The smallest port number an rcmd client may use.  By BSD convention
098     * this number is 512.
099     ***/
100    public static final int MIN_CLIENT_PORT = 512;
101
102    /***
103     * The largest port number an rcmd client may use.  By BSD convention
104     * this number is 1023.
105     ***/
106    public static final int MAX_CLIENT_PORT = 1023;
107
108    // Overrides method in RExecClient in order to implement proper
109    // port number limitations.
110    @Override
111    InputStream _createErrorStream() throws IOException
112    {
113        int localPort;
114        ServerSocket server;
115        Socket socket;
116
117        localPort = MAX_CLIENT_PORT;
118        server = null; // Keep compiler from barfing
119
120        for (localPort = MAX_CLIENT_PORT; localPort >= MIN_CLIENT_PORT; --localPort)
121        {
122            try
123            {
124                server = _serverSocketFactory_.createServerSocket(localPort, 1,
125                         getLocalAddress());
126                break; // got a socket
127            }
128            catch (SocketException e)
129            {
130                continue;
131            }
132        }
133
134        if (server == null) {
135            throw new BindException("All ports in use.");
136        }
137
138        _output_.write(Integer.toString(server.getLocalPort()).getBytes());
139        _output_.write('\0');
140        _output_.flush();
141
142        socket = server.accept();
143        server.close();
144
145        if (isRemoteVerificationEnabled() && !verifyRemote(socket))
146        {
147            socket.close();
148            throw new IOException(
149                "Security violation: unexpected connection attempt by " +
150                socket.getInetAddress().getHostAddress());
151        }
152
153        return (new SocketInputStream(socket, socket.getInputStream()));
154    }
155
156    /***
157     * The default RCommandClient constructor.  Initializes the
158     * default port to <code> DEFAULT_PORT </code>.
159     ***/
160    public RCommandClient()
161    {
162        setDefaultPort(DEFAULT_PORT);
163    }
164
165
166    /***
167     * Opens a Socket connected to a remote host at the specified port and
168     * originating from the specified local address using a port in a range
169     * acceptable to the BSD rshell daemon.
170     * Before returning, {@link org.apache.commons.net.SocketClient#_connectAction_  _connectAction_() }
171     * is called to perform connection initialization actions.
172     * <p>
173     * @param host  The remote host.
174     * @param port  The port to connect to on the remote host.
175     * @param localAddr  The local address to use.
176     * @exception SocketException If the socket timeout could not be set.
177     * @exception BindException If all acceptable rshell ports are in use.
178     * @exception IOException If the socket could not be opened.  In most
179     *  cases you will only want to catch IOException since SocketException is
180     *  derived from it.
181     ***/
182    public void connect(InetAddress host, int port, InetAddress localAddr)
183    throws SocketException, BindException, IOException
184    {
185        int localPort;
186
187        localPort = MAX_CLIENT_PORT;
188
189        for (localPort = MAX_CLIENT_PORT; localPort >= MIN_CLIENT_PORT; --localPort)
190        {
191            try
192            {
193                _socket_ =
194                    _socketFactory_.createSocket(host, port, localAddr, localPort);
195            }
196            catch (BindException be) {
197                continue;
198            }
199            catch (SocketException e)
200            {
201                continue;
202            }
203            break;
204        }
205
206        if (localPort < MIN_CLIENT_PORT) {
207            throw new BindException("All ports in use or insufficient permssion.");
208        }
209
210        _connectAction_();
211    }
212
213
214
215    /***
216     * Opens a Socket connected to a remote host at the specified port and
217     * originating from the current host at a port in a range acceptable
218     * to the BSD rshell daemon.
219     * Before returning, {@link org.apache.commons.net.SocketClient#_connectAction_  _connectAction_() }
220     * is called to perform connection initialization actions.
221     * <p>
222     * @param host  The remote host.
223     * @param port  The port to connect to on the remote host.
224     * @exception SocketException If the socket timeout could not be set.
225     * @exception BindException If all acceptable rshell ports are in use.
226     * @exception IOException If the socket could not be opened.  In most
227     *  cases you will only want to catch IOException since SocketException is
228     *  derived from it.
229     ***/
230    @Override
231    public void connect(InetAddress host, int port)
232    throws SocketException, IOException
233    {
234        connect(host, port, InetAddress.getLocalHost());
235    }
236
237
238    /***
239     * Opens a Socket connected to a remote host at the specified port and
240     * originating from the current host at a port in a range acceptable
241     * to the BSD rshell daemon.
242     * Before returning, {@link org.apache.commons.net.SocketClient#_connectAction_  _connectAction_() }
243     * is called to perform connection initialization actions.
244     * <p>
245     * @param hostname  The name of the remote host.
246     * @param port  The port to connect to on the remote host.
247     * @exception SocketException If the socket timeout could not be set.
248     * @exception BindException If all acceptable rshell ports are in use.
249     * @exception IOException If the socket could not be opened.  In most
250     *  cases you will only want to catch IOException since SocketException is
251     *  derived from it.
252     * @exception UnknownHostException If the hostname cannot be resolved.
253     ***/
254    @Override
255    public void connect(String hostname, int port)
256    throws SocketException, IOException, UnknownHostException
257    {
258        connect(InetAddress.getByName(hostname), port, InetAddress.getLocalHost());
259    }
260
261
262    /***
263     * Opens a Socket connected to a remote host at the specified port and
264     * originating from the specified local address using a port in a range
265     * acceptable to the BSD rshell daemon.
266     * Before returning, {@link org.apache.commons.net.SocketClient#_connectAction_  _connectAction_() }
267     * is called to perform connection initialization actions.
268     * <p>
269     * @param hostname  The remote host.
270     * @param port  The port to connect to on the remote host.
271     * @param localAddr  The local address to use.
272     * @exception SocketException If the socket timeout could not be set.
273     * @exception BindException If all acceptable rshell ports are in use.
274     * @exception IOException If the socket could not be opened.  In most
275     *  cases you will only want to catch IOException since SocketException is
276     *  derived from it.
277     ***/
278    public void connect(String hostname, int port, InetAddress localAddr)
279    throws SocketException, IOException
280    {
281        connect(InetAddress.getByName(hostname), port, localAddr);
282    }
283
284
285    /***
286     * Opens a Socket connected to a remote host at the specified port and
287     * originating from the specified local address and port. The
288     * local port must lie between <code> MIN_CLIENT_PORT </code> and
289     * <code> MAX_CLIENT_PORT </code> or an IllegalArgumentException will
290     * be thrown.
291     * Before returning, {@link org.apache.commons.net.SocketClient#_connectAction_  _connectAction_() }
292     * is called to perform connection initialization actions.
293     * <p>
294     * @param host  The remote host.
295     * @param port  The port to connect to on the remote host.
296     * @param localAddr  The local address to use.
297     * @param localPort  The local port to use.
298     * @exception SocketException If the socket timeout could not be set.
299     * @exception IOException If the socket could not be opened.  In most
300     *  cases you will only want to catch IOException since SocketException is
301     *  derived from it.
302     * @exception IllegalArgumentException If an invalid local port number
303     *            is specified.
304     ***/
305    @Override
306    public void connect(InetAddress host, int port,
307                        InetAddress localAddr, int localPort)
308    throws SocketException, IOException, IllegalArgumentException
309    {
310        if (localPort < MIN_CLIENT_PORT || localPort > MAX_CLIENT_PORT) {
311            throw new IllegalArgumentException("Invalid port number " + localPort);
312        }
313        super.connect(host, port, localAddr, localPort);
314    }
315
316
317    /***
318     * Opens a Socket connected to a remote host at the specified port and
319     * originating from the specified local address and port. The
320     * local port must lie between <code> MIN_CLIENT_PORT </code> and
321     * <code> MAX_CLIENT_PORT </code> or an IllegalArgumentException will
322     * be thrown.
323     * Before returning, {@link org.apache.commons.net.SocketClient#_connectAction_  _connectAction_() }
324     * is called to perform connection initialization actions.
325     * <p>
326     * @param hostname  The name of the remote host.
327     * @param port  The port to connect to on the remote host.
328     * @param localAddr  The local address to use.
329     * @param localPort  The local port to use.
330     * @exception SocketException If the socket timeout could not be set.
331     * @exception IOException If the socket could not be opened.  In most
332     *  cases you will only want to catch IOException since SocketException is
333     *  derived from it.
334     * @exception UnknownHostException If the hostname cannot be resolved.
335     * @exception IllegalArgumentException If an invalid local port number
336     *            is specified.
337     ***/
338    @Override
339    public void connect(String hostname, int port,
340                        InetAddress localAddr, int localPort)
341    throws SocketException, IOException, IllegalArgumentException, UnknownHostException
342    {
343        if (localPort < MIN_CLIENT_PORT || localPort > MAX_CLIENT_PORT) {
344            throw new IllegalArgumentException("Invalid port number " + localPort);
345        }
346        super.connect(hostname, port, localAddr, localPort);
347    }
348
349
350    /***
351     * Remotely executes a command through the rshd daemon on the server
352     * to which the RCommandClient is connected.  After calling this method,
353     * you may interact with the remote process through its standard input,
354     * output, and error streams.  You will typically be able to detect
355     * the termination of the remote process after reaching end of file
356     * on its standard output (accessible through
357     * {@link #getInputStream  getInputStream() }.  Disconnecting
358     * from the server or closing the process streams before reaching
359     * end of file will not necessarily terminate the remote process.
360     * <p>
361     * If a separate error stream is requested, the remote server will
362     * connect to a local socket opened by RCommandClient, providing an
363     * independent stream through which standard error will be transmitted.
364     * The local socket must originate from a secure port (512 - 1023),
365     * and rcommand() ensures that this will be so.
366     * RCommandClient will also do a simple security check when it accepts a
367     * connection for this error stream.  If the connection does not originate
368     * from the remote server, an IOException will be thrown.  This serves as
369     * a simple protection against possible hijacking of the error stream by
370     * an attacker monitoring the rexec() negotiation.  You may disable this
371     * behavior with
372     * {@link org.apache.commons.net.bsd.RExecClient#setRemoteVerificationEnabled setRemoteVerificationEnabled()}
373     * .
374     * <p>
375     * @param localUsername  The user account on the local machine that is
376     *        requesting the command execution.
377     * @param remoteUsername  The account name on the server through which to
378     *        execute the command.
379     * @param command   The command, including any arguments, to execute.
380     * @param separateErrorStream True if you would like the standard error
381     *        to be transmitted through a different stream than standard output.
382     *        False if not.
383     * @exception IOException If the rcommand() attempt fails.  The exception
384     *            will contain a message indicating the nature of the failure.
385     ***/
386    public void rcommand(String localUsername, String remoteUsername,
387                         String command, boolean separateErrorStream)
388    throws IOException
389    {
390        rexec(localUsername, remoteUsername, command, separateErrorStream);
391    }
392
393
394    /***
395     * Same as
396     * <code> rcommand(localUsername, remoteUsername, command, false); </code>
397     ***/
398    public void rcommand(String localUsername, String remoteUsername,
399                         String command)
400    throws IOException
401    {
402        rcommand(localUsername, remoteUsername, command, false);
403    }
404
405}
406