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