KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > socks > server > Ident


1 package socks.server;
2 import java.io.BufferedReader JavaDoc;
3 import java.io.IOException JavaDoc;
4 import java.io.InputStreamReader JavaDoc;
5 import java.io.InterruptedIOException JavaDoc;
6 import java.net.ConnectException JavaDoc;
7 import java.net.InetSocketAddress JavaDoc;
8 import java.net.Socket JavaDoc;
9 import java.util.StringTokenizer JavaDoc;
10
11 /**
12  Class Ident provides means to obtain user name of the owner of the socket
13  on remote machine, providing remote machine runs identd daemon.
14  <p>
15  To use it:
16    <tt><pre>
17    Socket s = ss.accept();
18    Ident id = new Ident(s);
19    if(id.successful) goUseUser(id.userName);
20    else handleIdentError(id.errorCode,id.errorMessage)
21    </pre></tt>
22 */

23 public class Ident{
24
25     /** Error Message can be null.*/
26     public String JavaDoc errorMessage;
27     /** Host type as returned by daemon, can be null, if error happened*/
28     public String JavaDoc hostType;
29     /** User name as returned by the identd daemon, or null, if it failed*/
30     public String JavaDoc userName;
31
32     /** If this is true then userName and hostType contain valid values.
33         Else errorCode contain the error code, and errorMessage contains
34         the corresponding message.
35     */

36     public boolean successful;
37     /** Error code*/
38     public int errorCode;
39     /** Identd on port 113 can't be contacted*/
40     public static final int ERR_NO_CONNECT = 1;
41     /** Connection timed out*/
42     public static final int ERR_TIMEOUT = 2;
43     /** Identd daemon responded with ERROR, in this case errorMessage
44         contains the string explanation, as send by the daemon.
45     */

46     public static final int ERR_PROTOCOL = 3;
47     /**
48      When parsing server response protocol error happened.
49     */

50     public static final int ERR_PROTOCOL_INCORRECT = 4;
51
52
53     /** Maximum amount of time we should wait before dropping the
54       connection to identd server.Setting it to 0 implies infinit
55       timeout.
56     */

57     public static final int connectionTimeout = 10000;
58     
59
60     /**
61      Constructor tries to connect to Identd daemon on the host of the
62      given socket, and retrieve user name of the owner of given socket
63      connection on remote machine. After constructor returns public
64      fields are initialised to whatever the server returned.
65      <p>
66      If user name was successfully retrieved successful is set to true,
67      and userName and hostType are set to whatever server returned. If
68      however for some reason user name was not obtained, successful is set
69      to false and errorCode contains the code explaining the reason of
70      failure, and errorMessage contains human readable explanation.
71      <p>
72      Constructor may block, for a while.
73      @param s Socket whose ownership on remote end should be obtained.
74     */

75     public Ident(Socket JavaDoc s ){
76       Socket JavaDoc sock = null;
77       successful = false; //We are pessimistic
78

79       try{
80         sock = new Socket JavaDoc();
81         sock.setSoTimeout(connectionTimeout);
82         sock.connect(new InetSocketAddress JavaDoc(s.getInetAddress(),113), connectionTimeout);
83         byte[] request = (""+s.getPort()+" , "+
84                              s.getLocalPort()+"\r\n").getBytes();
85
86         sock.getOutputStream().write(request);
87
88         BufferedReader JavaDoc in = new BufferedReader JavaDoc(
89                             new InputStreamReader JavaDoc(sock.getInputStream()));
90
91         parseResponse(in.readLine());
92
93       }catch(InterruptedIOException JavaDoc iioe){
94         errorCode = ERR_TIMEOUT;
95         errorMessage = "Connection to identd timed out.";
96       }catch(ConnectException JavaDoc ce){
97         errorCode = ERR_NO_CONNECT;
98         errorMessage = "Connection to identd server failed.";
99
100       }catch(IOException JavaDoc ioe){
101         errorCode = ERR_NO_CONNECT;
102         errorMessage = ""+ioe;
103       }finally{
104         try{ if(sock!=null) sock.close();}catch(IOException JavaDoc ioe){};
105       }
106     }
107
108     private void parseResponse(String JavaDoc response){
109       if(response == null){
110          errorCode = ERR_PROTOCOL_INCORRECT;
111          errorMessage = "Identd server closed connection.";
112          return;
113       }
114
115       StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(response,":");
116       if(st.countTokens() < 3){
117          errorCode = ERR_PROTOCOL_INCORRECT;
118          errorMessage = "Can't parse server response.";
119          return;
120       }
121
122       st.nextToken(); //Discard first token, it's basically what we have send
123
String JavaDoc command = st.nextToken().trim().toUpperCase();
124
125       if(command.equals("USERID") && st.countTokens() >= 2){
126         successful = true;
127         hostType = st.nextToken().trim();
128         userName = st.nextToken().trim();//Get all that is left
129
}else if(command.equals("ERROR")){
130         errorCode = ERR_PROTOCOL;
131         errorMessage = st.nextToken();
132       }else{
133         errorCode = ERR_PROTOCOL_INCORRECT;
134         System.out.println("Opa!");
135         errorMessage = "Can't parse server response.";
136       }
137
138
139     }
140
141 ///////////////////////////////////////////////
142
//USED for Testing
143
/*
144     public static void main(String[] args) throws IOException{
145
146        Socket s = null;
147        s = new Socket("gp101-16", 1391);
148
149        Ident id = new Ident(s);
150        if(id.successful){
151          System.out.println("User: "+id.userName);
152          System.out.println("HostType: "+id.hostType);
153        }else{
154          System.out.println("ErrorCode: "+id.errorCode);
155          System.out.println("ErrorMessage: "+id.errorMessage);
156
157        }
158
159        if(s!= null) s.close();
160     }
161 //*/

162
163 }
164
Popular Tags