KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > SocksEcho


1 import java.awt.*;
2 import java.awt.event.*;
3 import java.net.*;
4 import java.io.*;
5 import socks.*;
6
7 public class SocksEcho extends Frame
8                        implements ActionListener,
9                                   Runnable JavaDoc,
10                                   WindowListener{
11
12 //GUI components
13
TextField host_text,
14              port_text,
15              input_text;
16    Button proxy_button,
17           accept_button,
18           clear_button,
19           connect_button,
20           udp_button,
21           quit_button;
22    TextArea output_textarea;
23    Label status_label;
24
25    SocksDialog socks_dialog;
26
27 //Network related members
28
Proxy proxy=null;
29    int port;
30    String JavaDoc host;
31    Thread JavaDoc net_thread=null;
32    InputStream in=null;
33    OutputStream out=null;
34    Socket sock=null;
35    ServerSocket server_sock = null;
36    Socks5DatagramSocket udp_sock;
37
38    Object JavaDoc net_lock = new Object JavaDoc();
39    int mode=COMMAND_MODE;
40
41    //Possible mode states.
42
static final int LISTEN_MODE = 0;
43    static final int CONNECT_MODE = 1;
44    static final int UDP_MODE = 2;
45    static final int COMMAND_MODE = 3;
46    static final int ABORT_MODE = 4;
47
48    //Maximum datagram size
49
static final int MAX_DATAGRAM_SIZE = 1024;
50
51 // Constructors
52
////////////////////////////////////
53
public SocksEcho(){
54      super("SocksEcho");
55      guiInit();
56      socks_dialog = new SocksDialog(this);
57      socks_dialog.useThreads = false;
58
59
60      URL icon_url = SocksEcho.class.getResource("SocksEcho.gif");
61      if(icon_url != null){
62        try{
63          Object JavaDoc content = icon_url.getContent();
64          if(content instanceof java.awt.image.ImageProducer JavaDoc)
65             setIconImage(createImage((java.awt.image.ImageProducer JavaDoc) content));
66        }catch(IOException ioe){
67        }
68      }
69
70      addWindowListener(this);
71      Component component[] = getComponents();
72      for(int i=0;i<component.length;++i)
73        if(component[i] instanceof Button)
74          ((Button)component[i]).addActionListener(this);
75        else if(component[i] instanceof TextField)
76          ((TextField)component[i]).addActionListener(this);
77           
78    }
79
80 //ActionListener interface
81
///////////////////////////
82
public void actionPerformed(ActionEvent ae){
83       Object JavaDoc source = ae.getSource();
84
85       if(source == proxy_button)
86          onProxy();
87       else if(source == quit_button)
88          onQuit();
89       else if(source == connect_button || source == port_text
90                                        || source == host_text)
91          onConnect();
92       else if(source == input_text)
93          onInput();
94       else if(source == accept_button)
95          onAccept();
96       else if(source == udp_button)
97          onUDP();
98       else if(source == clear_button)
99          onClear();
100    }
101
102 //Runnable interface
103
///////////////////////////////
104

105 public void run(){
106     boolean finished_OK = true;
107     try{
108       switch(mode){
109         case UDP_MODE:
110            startUDP();
111            doUDPPipe();
112            break;
113         case LISTEN_MODE:
114            doAccept();
115            doPipe();
116            break;
117         case CONNECT_MODE:
118            doConnect();
119            doPipe();
120            break;
121         default:
122           warn("Unexpected mode in run() method");
123       }
124
125    }catch(UnknownHostException uh_ex){
126         if(mode != ABORT_MODE){
127       finished_OK = false;
128       status("Host "+host+" has no DNS entry.");
129       uh_ex.printStackTrace();
130        }
131    }catch(IOException io_ex){
132        if(mode != ABORT_MODE){
133       finished_OK = false;
134           status(""+io_ex);
135           io_ex.printStackTrace();
136       }
137    }finally{
138       if(mode == ABORT_MODE) status("Connection closed");
139       else if(finished_OK) status("Connection closed by foreign host.");
140
141       onDisconnect();
142    }
143 }
144
145 //Private methods
146
////////////////////////////////////////////////////////////////////////
147

148 // GUI event handlers.
149
//////////////////////////
150

151    private void onConnect(){
152       if(mode == CONNECT_MODE){
153         status("Diconnecting...");
154         abort_connection();
155         return;
156       }else if(mode != COMMAND_MODE)
157         return;
158
159       if(!readHost()) return;
160       if(!readPort()) return;
161
162       if(proxy == null){
163          warn("Proxy is not set");
164          onProxy();
165          return;
166       }
167
168       startNetThread(CONNECT_MODE);
169       status("Connecting to "+host+":"+port+" ...");
170
171       connect_button.setLabel("Disconnect");
172       connect_button.invalidate();
173       accept_button.setEnabled(false);
174       udp_button.setEnabled(false);
175       doLayout();
176       input_text.requestFocus();
177    }
178
179    private void onDisconnect(){
180       synchronized(net_lock){
181          mode = COMMAND_MODE;
182          connect_button.setLabel("Connect");
183          accept_button.setLabel("Accept");
184          udp_button.setLabel("UDP");
185          accept_button.setEnabled(true);
186          connect_button.setEnabled(true);
187          udp_button.setEnabled(true);
188          server_sock = null;
189          sock = null;
190          out = null;
191          in = null;
192          net_thread = null;
193       }
194    }
195
196    private void onAccept(){
197       if(mode == LISTEN_MODE){
198          abort_connection();
199          return;
200       }else if(mode != COMMAND_MODE) return;
201
202       if(!readHost()) return;
203       if(!readPort()) port = 0;
204
205       if(proxy == null){
206          warn("Proxy is not set");
207          onProxy();
208          return;
209       }
210
211       startNetThread(LISTEN_MODE);
212
213       accept_button.setLabel("Abort");
214       connect_button.setEnabled(false);
215       udp_button.setEnabled(false);
216       input_text.requestFocus();
217    }
218
219    private void onUDP(){
220       if(mode == UDP_MODE){
221         abort_connection();
222         return;
223       }else if(mode == ABORT_MODE) return;
224
225       if(proxy == null){
226          warn("Proxy is not set");
227          onProxy();
228          return;
229       }
230
231       startNetThread(UDP_MODE);
232       udp_button.setLabel("Abort");
233       connect_button.setEnabled(false);
234       accept_button.setEnabled(false);
235       udp_button.invalidate();
236       doLayout();
237       input_text.requestFocus();
238    }
239
240    private void onInput(){
241       String JavaDoc send_string = input_text.getText()+"\n";
242       switch(mode){
243         case ABORT_MODE: //Fall through
244
case COMMAND_MODE:
245           return;
246         case CONNECT_MODE://Fall through
247
case LISTEN_MODE:
248           synchronized(net_lock){
249             if(out == null) return;
250             send(send_string);
251           }
252           break;
253         case UDP_MODE:
254           if(!readHost()) return;
255           if(!readPort()) return;
256           sendUDP(send_string,host,port);
257           break;
258         default:
259           print("Unknown mode in onInput():"+mode);
260
261       }
262       input_text.setText("");
263       print(send_string);
264    }
265
266    private void onClear(){
267       output_textarea.setText("");
268    }
269    private void onProxy(){
270       Proxy p;
271       p = socks_dialog.getProxy(proxy);
272       if(p != null) proxy = p;
273       if( proxy != null && proxy instanceof Socks5Proxy)
274          ((Socks5Proxy) proxy).resolveAddrLocally(false);
275    }
276    private void onQuit(){
277       dispose();
278       System.exit(0);
279    }
280
281 //Data retrieval functions
282
//////////////////////////
283

284    /**
285     * Reads the port field, returns false if parsing fails.
286     */

287    private boolean readPort(){
288       try{
289          port = Integer.parseInt(port_text.getText());
290       }catch(NumberFormatException JavaDoc nfe){
291          warn("Port invalid!");
292          return false;
293       }
294       return true;
295    }
296    private boolean readHost(){
297       host = host_text.getText();
298       host.trim();
299       if(host.length() < 1){
300         warn("Host is not set");
301         return false;
302       }
303       return true;
304    }
305
306 //Display functions
307
///////////////////
308

309    private void status(String JavaDoc s){
310       status_label.setText(s);
311    }
312    private void println(String JavaDoc s){
313       output_textarea.append(s+"\n");
314    }
315    private void print(String JavaDoc s){
316       output_textarea.append(s);
317    }
318    private void warn(String JavaDoc s){
319       status(s);
320       //System.err.println(s);
321
}
322
323 //Network related functions
324
////////////////////////////
325

326    private void startNetThread(int m){
327       mode = m;
328       net_thread = new Thread JavaDoc(this);
329       net_thread.start();
330    }
331
332    private void abort_connection(){
333       synchronized(net_lock){
334          if(mode == COMMAND_MODE) return;
335          mode = ABORT_MODE;
336          if(net_thread!=null){
337             try{
338               if(sock!=null) sock.close();
339               if(server_sock!=null) server_sock.close();
340               if(udp_sock!=null) udp_sock.close();
341             }catch(IOException ioe){
342             }
343             net_thread.interrupt();
344             net_thread = null;
345          }
346       }
347    }
348
349    private void doAccept() throws IOException{
350
351      println("Trying to accept from "+host);
352      status("Trying to accept from "+host);
353      println("Using proxy:"+proxy);
354      server_sock = new SocksServerSocket(proxy,host,port);
355
356      //server_sock.setSoTimeout(30000);
357

358      println("Listenning on: "+server_sock.getInetAddress()+
359                           ":" +server_sock.getLocalPort());
360      sock = server_sock.accept();
361      println("Accepted from:"+sock.getInetAddress()+":"+
362                               sock.getPort());
363
364      status("Accepted from:"+sock.getInetAddress().getHostAddress()
365                         +":"+sock.getPort());
366                                            
367      server_sock.close(); //Even though this doesn't do anything
368
}
369    private void doConnect() throws IOException{
370      println("Trying to connect to:"+host+":"+port);
371      println("Using proxy:"+proxy);
372      sock = new SocksSocket(proxy,host,port);
373      println("Connected to:"+sock.getInetAddress()+":"+port);
374      status("Connected to: "+sock.getInetAddress().getHostAddress()
375                        +":" +port);
376      println("Via-Proxy:"+sock.getLocalAddress()+":"+
377                           sock.getLocalPort());
378
379    }
380    private void doPipe() throws IOException{
381       out = sock.getOutputStream();
382       in = sock.getInputStream();
383
384       byte[] buf = new byte[1024];
385       int bytes_read;
386       while((bytes_read = in.read(buf)) > 0){
387           print(new String JavaDoc(buf,0,bytes_read));
388       }
389
390    }
391    private void startUDP() throws IOException{
392      udp_sock = new Socks5DatagramSocket(proxy,0,null);
393      println("UDP started on "+udp_sock.getLocalAddress()+":"+
394                                udp_sock.getLocalPort());
395      status("UDP:"+udp_sock.getLocalAddress().getHostAddress()+":"
396                   +udp_sock.getLocalPort());
397    }
398
399    private void doUDPPipe() throws IOException{
400      DatagramPacket dp = new DatagramPacket(new byte[MAX_DATAGRAM_SIZE],
401                                             MAX_DATAGRAM_SIZE);
402      while(true){
403        udp_sock.receive(dp);
404        print("UDP\n"+
405          "From:"+dp.getAddress()+":"+dp.getPort()+"\n"+
406          "\n"+
407              //Java 1.2
408
//new String(dp.getData(),dp.getOffset(),dp.getLength())+"\n"
409
//Java 1.1
410
new String JavaDoc(dp.getData(),0,dp.getLength())+"\n"
411             );
412        dp.setLength(MAX_DATAGRAM_SIZE);
413      }
414    }
415    
416    private void sendUDP(String JavaDoc message,String JavaDoc host,int port){
417       if(!udp_sock.isProxyAlive(100)){
418          status("Proxy closed connection");
419          abort_connection();
420          return;
421       }
422
423       try{
424          byte[] data = message.getBytes();
425          DatagramPacket dp = new DatagramPacket(data,data.length,null,port);
426          udp_sock.send(dp,host);
427       }catch(UnknownHostException uhe){
428          status("Host "+host+" has no DNS entry.");
429       }catch(IOException ioe){
430          status("IOException:"+ioe);
431          abort_connection();
432       }
433
434    }
435
436    private void send(String JavaDoc s){
437       try{
438         out.write(s.getBytes());
439       }catch(IOException io_ex){
440         println("IOException:"+io_ex);
441         abort_connection();
442       }
443    }
444
445
446 /*======================================================================
447   Form:
448   Table:
449           +---+---------------+
450           | | |
451           +---+---+---+---+---+
452           | | | | | |
453           +---+---+---+---+---+
454           | |
455           +-------------------+
456           | |
457           +---+---+---+---+---+
458           | | | | | |
459           +---+---+---+---+---+
460           | |
461           +-------------------+
462 */

463
464    void guiInit(){
465       //Some default names used
466
Label label;
467       Container container;
468
469       GridBagConstraints c = new GridBagConstraints();
470
471       container = this;
472       //container = new Panel();
473
container.setLayout(new GridBagLayout());
474       container.setBackground(SystemColor.menu);
475       c.insets = new Insets(3,3,3,3);
476       
477       c.gridx=0; c.gridy=0;
478       c.gridwidth=1; c.gridheight=1;
479       c.anchor=GridBagConstraints.NORTHEAST;
480       label = new Label("Host:");
481       container.add(label,c);
482       
483       c.gridx=0; c.gridy=1;
484       c.gridwidth=1; c.gridheight=1;
485       c.anchor=GridBagConstraints.NORTHEAST;
486       label = new Label("Port:");
487       container.add(label,c);
488
489       c.gridx = 0; c.gridy = 5;
490       c.gridwidth=GridBagConstraints.REMAINDER;c.gridheight=1;
491       c.fill = GridBagConstraints.HORIZONTAL;
492       c.insets = new Insets(0,0,0,0);
493       status_label = new Label("");
494       container.add(status_label,c);
495       c.insets = new Insets(3,3,3,3);
496       
497
498       c.gridx=1; c.gridy=0;
499       c.gridwidth=GridBagConstraints.REMAINDER; c.gridheight=1;
500       c.anchor=GridBagConstraints.NORTHWEST;
501       c.fill = GridBagConstraints.HORIZONTAL;
502       host_text = new TextField("");
503       container.add(host_text,c);
504
505       
506       c.weightx = 1.0;
507       c.fill = GridBagConstraints.NONE;
508       c.gridx=1; c.gridy=1;
509       c.gridwidth=1; c.gridheight=1;
510       c.anchor=GridBagConstraints.NORTHWEST;
511       port_text = new TextField("",5);
512       container.add(port_text,c);
513
514       c.weightx = 0.0;
515       c.gridx=0; c.gridy=3;
516       c.fill = GridBagConstraints.HORIZONTAL;
517       c.gridwidth=GridBagConstraints.REMAINDER; c.gridheight=1;
518       c.anchor=GridBagConstraints.NORTHWEST;
519       input_text = new TextField("");
520       container.add(input_text,c);
521
522       c.fill = GridBagConstraints.NONE;
523       c.gridx=2; c.gridy=1;
524       c.gridwidth=1; c.gridheight=1;
525       c.anchor=GridBagConstraints.NORTHEAST;
526       connect_button = new Button("Connect");
527       container.add(connect_button,c);
528       
529       c.gridx=3; c.gridy=1;
530       c.gridwidth=1; c.gridheight=1;
531       c.anchor=GridBagConstraints.EAST;
532       accept_button = new Button("Accept");
533       container.add(accept_button,c);
534
535       
536       c.gridx=4; c.gridy=1;
537       c.gridwidth=1; c.gridheight=1;
538       c.anchor=GridBagConstraints.EAST;
539       udp_button = new Button("UDP");
540       container.add(udp_button,c);
541       
542       
543       c.gridx=0; c.gridy=4;
544       c.gridwidth=1; c.gridheight=1;
545       c.anchor=GridBagConstraints.NORTHWEST;
546       proxy_button = new Button("Proxy...");
547       container.add(proxy_button,c);
548       
549       c.gridx=3; c.gridy=4;
550       c.gridwidth=1; c.gridheight=1;
551       c.anchor=GridBagConstraints.NORTHEAST;
552       clear_button = new Button("Clear");
553       container.add(clear_button,c);
554       
555       c.gridx=4; c.gridy=4;
556       c.gridwidth=1; c.gridheight=1;
557       c.anchor=GridBagConstraints.EAST;
558       quit_button = new Button("Quit");
559       container.add(quit_button,c);
560
561       c.weightx = 1.0;
562       c.weighty = 1.0;
563       c.fill = GridBagConstraints.BOTH;
564       c.gridx=0; c.gridy=2;
565       c.gridwidth=GridBagConstraints.REMAINDER; c.gridheight=1;
566       c.anchor=GridBagConstraints.NORTHWEST;
567       output_textarea = new TextArea("",10,50);
568       output_textarea.setFont(new Font("Monospaced",Font.PLAIN,11));
569       output_textarea.setEditable(false);
570       //output_textarea.setEnabled(false);
571
container.add(output_textarea,c);
572
573    }//end guiInit
574

575
576 // WindowListener Interface
577
/////////////////////////////////
578
public void windowActivated(java.awt.event.WindowEvent JavaDoc e){
579    }
580    public void windowDeactivated(java.awt.event.WindowEvent JavaDoc e){
581    }
582    public void windowOpened(java.awt.event.WindowEvent JavaDoc e){
583    }
584    public void windowClosing(java.awt.event.WindowEvent JavaDoc e){
585       if(e.getWindow() == this) onQuit();
586       else
587         e.getWindow().dispose();
588    }
589    public void windowClosed(java.awt.event.WindowEvent JavaDoc e){
590    }
591    public void windowIconified(java.awt.event.WindowEvent JavaDoc e){
592    }
593    public void windowDeiconified(java.awt.event.WindowEvent JavaDoc e){
594    }
595
596
597 // Main
598
////////////////////////////////////
599
public static void main(String JavaDoc[] args){
600       SocksEcho socksecho = new SocksEcho();
601       socksecho.pack();
602       socksecho.show();
603    }
604  }//end class
605
Popular Tags