1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.directory.kerberos.client;
21
22
23 import java.io.DataInputStream;
24 import java.io.IOException;
25 import java.io.OutputStream;
26 import java.net.DatagramPacket;
27 import java.net.DatagramSocket;
28 import java.net.InetSocketAddress;
29 import java.net.Socket;
30 import java.net.SocketAddress;
31 import java.nio.ByteBuffer;
32
33
34
35
36
37
38
39 public class KerberosChannel
40 {
41
42 private Socket tcpSocket;
43
44
45 private DatagramSocket udpSocket;
46
47
48 private DataInputStream in;
49
50
51 private OutputStream out;
52
53
54 private boolean useUdp;
55
56 private int timeOut = 60000;
57
58
59 private SocketAddress udpServerAddr = null;
60
61
62 protected void openConnection( String hostName, int portNo, int timeOut, boolean isUdp ) throws IOException
63 {
64 this.useUdp = isUdp;
65 this.timeOut = timeOut;
66
67 if ( isUdp )
68 {
69 udpServerAddr = new InetSocketAddress( hostName, portNo );
70 udpSocket = new DatagramSocket();
71 }
72 else
73 {
74 tcpSocket = new Socket( hostName, portNo );
75 tcpSocket.setSoTimeout( ( int ) timeOut );
76 in = new DataInputStream( tcpSocket.getInputStream() );
77 out = tcpSocket.getOutputStream();
78 }
79 }
80
81
82 protected ByteBuffer sendAndReceive( ByteBuffer encodedBuf ) throws IOException
83 {
84 byte[] reqData = encodedBuf.array();
85
86 ByteBuffer repData;
87
88 if ( useUdp )
89 {
90 DatagramPacket reqPacket = new DatagramPacket( reqData, reqData.length, udpServerAddr );
91 udpSocket.send( reqPacket );
92
93 byte[] buffer = new byte[2048];
94 DatagramPacket repPacket = new DatagramPacket( buffer, buffer.length );
95 udpSocket.receive( repPacket );
96
97 byte[] receivedData = repPacket.getData();
98 repData = ByteBuffer.allocate( receivedData.length );
99 repData.put( receivedData );
100 }
101 else
102 {
103 out.write( reqData );
104 out.flush();
105
106 int len = in.readInt();
107
108 repData = ByteBuffer.allocate( len + 4 );
109 repData.putInt( len );
110
111 byte[] tmp = new byte[1024 * 8];
112 while ( in.available() > 0 )
113 {
114 int read = in.read( tmp );
115 repData.put( tmp, 0, read );
116 }
117 }
118
119 repData.flip();
120
121 return repData;
122 }
123
124
125 protected boolean isUseTcp()
126 {
127 return !useUdp;
128 }
129
130
131 protected void close() throws IOException
132 {
133 if ( useUdp )
134 {
135 if ( udpSocket != null )
136 {
137 udpSocket.close();
138 }
139 }
140 else
141 {
142 if ( tcpSocket != null )
143 {
144 tcpSocket.close();
145 }
146 }
147 }
148 }