001    /*
002     * Copyright 2003-2004 The Apache Software Foundation
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     *     http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    package examples;
017    
018    import java.io.InputStream;
019    import java.io.OutputStream;
020    import java.io.FileOutputStream;
021    import java.io.IOException;
022    import org.apache.commons.net.telnet.TelnetClient;
023    import org.apache.commons.net.telnet.TelnetNotificationHandler;
024    import org.apache.commons.net.telnet.SimpleOptionHandler;
025    import org.apache.commons.net.telnet.EchoOptionHandler;
026    import org.apache.commons.net.telnet.TerminalTypeOptionHandler;
027    import org.apache.commons.net.telnet.SuppressGAOptionHandler;
028    import org.apache.commons.net.telnet.InvalidTelnetOptionException;
029    import java.util.StringTokenizer;
030    
031    
032    /***
033     * This is a simple example of use of TelnetClient.
034     * An external option handler (SimpleTelnetOptionHandler) is used.
035     * Initial configuration requested by TelnetClient will be:
036     * WILL ECHO, WILL SUPPRESS-GA, DO SUPPRESS-GA.
037     * VT100 terminal type will be subnegotiated.
038     * <p>
039     * Also, use of the sendAYT(), getLocalOptionState(), getRemoteOptionState()
040     * is demonstrated.
041     * When connected, type AYT to send an AYT command to the server and see
042     * the result.
043     * Type OPT to see a report of the state of the first 25 options.
044     * <p>
045     * @author Bruno D'Avanzo
046     ***/
047    public class TelnetClientExample implements Runnable, TelnetNotificationHandler
048    {
049        static TelnetClient tc = null;
050    
051        /***
052         * Main for the TelnetClientExample.
053         ***/
054        public static void main(String[] args) throws IOException
055        {
056            FileOutputStream fout = null;
057    
058            if(args.length < 1)
059            {
060                System.err.println("Usage: TelnetClientExample1 <remote-ip> [<remote-port>]");
061                System.exit(1);
062            }
063    
064            String remoteip = args[0];
065    
066            int remoteport;
067    
068            if (args.length > 1)
069            {
070                remoteport = (new Integer(args[1])).intValue();
071            }
072            else
073            {
074                remoteport = 23;
075            }
076    
077            try
078            {
079                fout = new FileOutputStream ("spy.log", true);
080            }
081            catch (Exception e)
082            {
083                System.err.println(
084                    "Exception while opening the spy file: "
085                    + e.getMessage());
086            }
087    
088            tc = new TelnetClient();
089    
090            TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false);
091            EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
092            SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);
093    
094            try
095            {
096                tc.addOptionHandler(ttopt);
097                tc.addOptionHandler(echoopt);
098                tc.addOptionHandler(gaopt);
099            }
100            catch (InvalidTelnetOptionException e)
101            {
102                System.err.println("Error registering option handlers: " + e.getMessage());
103            }
104    
105            while (true)
106            {
107                boolean end_loop = false;
108                try
109                {
110                    tc.connect(remoteip, remoteport);
111    
112    
113                    Thread reader = new Thread (new TelnetClientExample());
114                    tc.registerNotifHandler(new TelnetClientExample());
115                    System.out.println("TelnetClientExample");
116                    System.out.println("Type AYT to send an AYT telnet command");
117                    System.out.println("Type OPT to print a report of status of options (0-24)");
118                    System.out.println("Type REGISTER to register a new SimpleOptionHandler");
119                    System.out.println("Type UNREGISTER to unregister an OptionHandler");
120                    System.out.println("Type SPY to register the spy (connect to port 3333 to spy)");
121                    System.out.println("Type UNSPY to stop spying the connection");
122    
123                    reader.start();
124                    OutputStream outstr = tc.getOutputStream();
125    
126                    byte[] buff = new byte[1024];
127                    int ret_read = 0;
128    
129                    do
130                    {
131                        try
132                        {
133                            ret_read = System.in.read(buff);
134                            if(ret_read > 0)
135                            {
136                                if((new String(buff, 0, ret_read)).startsWith("AYT"))
137                                {
138                                    try
139                                    {
140                                        System.out.println("Sending AYT");
141    
142                                        System.out.println("AYT response:" + tc.sendAYT(5000));
143                                    }
144                                    catch (Exception e)
145                                    {
146                                        System.err.println("Exception waiting AYT response: " + e.getMessage());
147                                    }
148                                }
149                                else if((new String(buff, 0, ret_read)).startsWith("OPT"))
150                                {
151                                     System.out.println("Status of options:");
152                                     for(int ii=0; ii<25; ii++)
153                                        System.out.println("Local Option " + ii + ":" + tc.getLocalOptionState(ii) + " Remote Option " + ii + ":" + tc.getRemoteOptionState(ii));
154                                }
155                                else if((new String(buff, 0, ret_read)).startsWith("REGISTER"))
156                                {
157                                    StringTokenizer st = new StringTokenizer(new String(buff));
158                                    try
159                                    {
160                                        st.nextToken();
161                                        int opcode = (new Integer(st.nextToken())).intValue();
162                                        boolean initlocal = (new Boolean(st.nextToken())).booleanValue();
163                                        boolean initremote = (new Boolean(st.nextToken())).booleanValue();
164                                        boolean acceptlocal = (new Boolean(st.nextToken())).booleanValue();
165                                        boolean acceptremote = (new Boolean(st.nextToken())).booleanValue();
166                                        SimpleOptionHandler opthand = new SimpleOptionHandler(opcode, initlocal, initremote,
167                                                                        acceptlocal, acceptremote);
168                                        tc.addOptionHandler(opthand);
169                                    }
170                                    catch (Exception e)
171                                    {
172                                        if(e instanceof InvalidTelnetOptionException)
173                                        {
174                                            System.err.println("Error registering option: " + e.getMessage());
175                                        }
176                                        else
177                                        {
178                                            System.err.println("Invalid REGISTER command.");
179                                            System.err.println("Use REGISTER optcode initlocal initremote acceptlocal acceptremote");
180                                            System.err.println("(optcode is an integer.)");
181                                            System.err.println("(initlocal, initremote, acceptlocal, acceptremote are boolean)");
182                                        }
183                                    }
184                                }
185                                else if((new String(buff, 0, ret_read)).startsWith("UNREGISTER"))
186                                {
187                                    StringTokenizer st = new StringTokenizer(new String(buff));
188                                    try
189                                    {
190                                        st.nextToken();
191                                        int opcode = (new Integer(st.nextToken())).intValue();
192                                        tc.deleteOptionHandler(opcode);
193                                    }
194                                    catch (Exception e)
195                                    {
196                                        if(e instanceof InvalidTelnetOptionException)
197                                        {
198                                            System.err.println("Error unregistering option: " + e.getMessage());
199                                        }
200                                        else
201                                        {
202                                            System.err.println("Invalid UNREGISTER command.");
203                                            System.err.println("Use UNREGISTER optcode");
204                                            System.err.println("(optcode is an integer)");
205                                        }
206                                    }
207                                }
208                                else if((new String(buff, 0, ret_read)).startsWith("SPY"))
209                                {
210                                    try
211                                    {
212                                        tc.registerSpyStream(fout);
213                                    }
214                                    catch (Exception e)
215                                    {
216                                        System.err.println("Error registering the spy");
217                                    }
218                                }
219                                else if((new String(buff, 0, ret_read)).startsWith("UNSPY"))
220                                {
221                                    tc.stopSpyStream();
222                                }
223                                else
224                                {
225                                    try
226                                    {
227                                            outstr.write(buff, 0 , ret_read);
228                                            outstr.flush();
229                                    }
230                                    catch (Exception e)
231                                    {
232                                            end_loop = true;
233                                    }
234                                }
235                            }
236                        }
237                        catch (Exception e)
238                        {
239                            System.err.println("Exception while reading keyboard:" + e.getMessage());
240                            end_loop = true;
241                        }
242                    }
243                    while((ret_read > 0) && (end_loop == false));
244    
245                    try
246                    {
247                        tc.disconnect();
248                    }
249                    catch (Exception e)
250                    {
251                              System.err.println("Exception while connecting:" + e.getMessage());
252                    }
253                }
254                catch (Exception e)
255                {
256                        System.err.println("Exception while connecting:" + e.getMessage());
257                        System.exit(1);
258                }
259            }
260        }
261    
262    
263        /***
264         * Callback method called when TelnetClient receives an option
265         * negotiation command.
266         * <p>
267         * @param negotiation_code - type of negotiation command received
268         * (RECEIVED_DO, RECEIVED_DONT, RECEIVED_WILL, RECEIVED_WONT)
269         * <p>
270         * @param option_code - code of the option negotiated
271         * <p>
272         ***/
273        public void receivedNegotiation(int negotiation_code, int option_code)
274        {
275            String command = null;
276            if(negotiation_code == TelnetNotificationHandler.RECEIVED_DO)
277            {
278                command = "DO";
279            }
280            else if(negotiation_code == TelnetNotificationHandler.RECEIVED_DONT)
281            {
282                command = "DONT";
283            }
284            else if(negotiation_code == TelnetNotificationHandler.RECEIVED_WILL)
285            {
286                command = "WILL";
287            }
288            else if(negotiation_code == TelnetNotificationHandler.RECEIVED_WONT)
289            {
290                command = "WONT";
291            }
292            System.out.println("Received " + command + " for option code " + option_code);
293       }
294    
295        /***
296         * Reader thread.
297         * Reads lines from the TelnetClient and echoes them
298         * on the screen.
299         ***/
300        public void run()
301        {
302            InputStream instr = tc.getInputStream();
303    
304            try
305            {
306                byte[] buff = new byte[1024];
307                int ret_read = 0;
308    
309                do
310                {
311                    ret_read = instr.read(buff);
312                    if(ret_read > 0)
313                    {
314                        System.out.print(new String(buff, 0, ret_read));
315                    }
316                }
317                while (ret_read >= 0);
318            }
319            catch (Exception e)
320            {
321                System.err.println("Exception while reading socket:" + e.getMessage());
322            }
323    
324            try
325            {
326                tc.disconnect();
327            }
328            catch (Exception e)
329            {
330                System.err.println("Exception while closing telnet:" + e.getMessage());
331            }
332        }
333    }
334