NextableInputStream: separate base behaviour from nextable
[fanfix.git] / src / be / nikiroo / utils / serial / server / ServerBridge.java
CommitLineData
8537d55a
NR
1package be.nikiroo.utils.serial.server;
2
3import java.io.IOException;
452f38c8 4import java.lang.reflect.Array;
8537d55a 5import java.net.Socket;
f4053377 6import java.net.UnknownHostException;
8537d55a 7
452f38c8 8import be.nikiroo.utils.StringUtils;
8537d55a
NR
9import be.nikiroo.utils.TraceHandler;
10import be.nikiroo.utils.Version;
11import be.nikiroo.utils.serial.Importer;
12
13/**
14 * This class implements a simple server that can bridge two other
15 * {@link Server}s.
16 * <p>
17 * It can, of course, inspect the data that goes through it (by default, it
18 * prints traces of the data).
19 * <p>
20 * Note: this {@link ServerBridge} has to be discarded after use (cannot be
21 * started twice).
22 *
23 * @author niki
24 */
25public class ServerBridge extends Server {
26 private final String forwardToHost;
27 private final int forwardToPort;
8468bb79 28 private final String forwardToKey;
8537d55a
NR
29
30 /**
31 * Create a new server that will start listening on the network when
32 * {@link ServerBridge#start()} is called.
33 *
34 * @param port
35 * the port to listen on, or 0 to assign any unallocated port
36 * found (which can later on be queried via
37 * {@link ServerBridge#getPort()}
8468bb79
NR
38 * @param key
39 * an optional key to encrypt all the communications (if NULL,
40 * everything will be sent in clear text)
452f38c8
NR
41 * @param forwardToHost
42 * the host server to forward the calls to
43 * @param forwardToPort
44 * the host port to forward the calls to
8468bb79
NR
45 * @param forwardToKey
46 * an optional key to encrypt all the communications (if NULL,
47 * everything will be sent in clear text)
8537d55a
NR
48 *
49 * @throws IOException
50 * in case of I/O error
f4053377
NR
51 * @throws UnknownHostException
52 * if the IP address of the host could not be determined
53 * @throws IllegalArgumentException
54 * if the port parameter is outside the specified range of valid
55 * port values, which is between 0 and 65535, inclusive
8537d55a 56 */
8468bb79
NR
57 public ServerBridge(int port, String key, String forwardToHost,
58 int forwardToPort, String forwardToKey) throws IOException {
59 super(port, key);
8537d55a
NR
60 this.forwardToHost = forwardToHost;
61 this.forwardToPort = forwardToPort;
8468bb79 62 this.forwardToKey = forwardToKey;
8537d55a
NR
63 }
64
65 /**
66 * Create a new server that will start listening on the network when
67 * {@link ServerBridge#start()} is called.
68 *
69 * @param name
70 * the server name (only used for debug info and traces)
71 * @param port
72 * the port to listen on
8468bb79
NR
73 * @param key
74 * an optional key to encrypt all the communications (if NULL,
75 * everything will be sent in clear text)
452f38c8
NR
76 * @param forwardToHost
77 * the host server to forward the calls to
78 * @param forwardToPort
79 * the host port to forward the calls to
8468bb79
NR
80 * @param forwardToKey
81 * an optional key to encrypt all the communications (if NULL,
82 * everything will be sent in clear text) use an SSL connection
83 * for the forward server or not
8537d55a
NR
84 *
85 * @throws IOException
86 * in case of I/O error
f4053377
NR
87 * @throws UnknownHostException
88 * if the IP address of the host could not be determined
89 * @throws IllegalArgumentException
90 * if the port parameter is outside the specified range of valid
91 * port values, which is between 0 and 65535, inclusive
8537d55a 92 */
8468bb79
NR
93 public ServerBridge(String name, int port, String key,
94 String forwardToHost, int forwardToPort, String forwardToKey)
8537d55a 95 throws IOException {
8468bb79 96 super(name, port, key);
8537d55a
NR
97 this.forwardToHost = forwardToHost;
98 this.forwardToPort = forwardToPort;
8468bb79 99 this.forwardToKey = forwardToKey;
8537d55a
NR
100 }
101
102 /**
103 * The traces handler for this {@link Server}.
104 * <p>
452f38c8 105 * The trace levels are handled as follow:
8537d55a 106 * <ul>
452f38c8
NR
107 * <li>1: it will only print basic IN/OUT messages with length</li>
108 * <li>2: it will try to interpret it as an object (SLOW) and print the
109 * object class if possible</li>
110 * <li>3: it will try to print the {@link Object#toString()} value, or the
111 * data if it is not an object</li>
112 * <li>4: it will also print the unzipped serialised value if it is an
113 * object</li>
8537d55a
NR
114 * </ul>
115 *
116 * @param tracer
117 * the new traces handler
118 */
119 @Override
120 public void setTraceHandler(TraceHandler tracer) {
121 super.setTraceHandler(tracer);
122 }
123
124 @Override
125 protected ConnectActionServer createConnectActionServer(Socket s) {
8468bb79 126 return new ConnectActionServerString(s, key) {
8537d55a
NR
127 @Override
128 public void action(final Version clientVersion) throws Exception {
129 onClientContact(clientVersion);
130 final ConnectActionServerString bridge = this;
131
f4053377
NR
132 try {
133 new ConnectActionClientString(forwardToHost, forwardToPort,
8468bb79 134 forwardToKey, clientVersion) {
f4053377
NR
135 @Override
136 public void action(final Version serverVersion)
137 throws Exception {
138 onServerContact(serverVersion);
8537d55a 139
f4053377
NR
140 for (String fromClient = bridge.rec(); fromClient != null; fromClient = bridge
141 .rec()) {
142 onRec(clientVersion, fromClient);
143 String fromServer = send(fromClient);
144 onSend(serverVersion, fromServer);
145 bridge.send(fromServer);
146 }
d827da2a 147
f4053377
NR
148 getTraceHandler().trace("=== DONE", 1);
149 getTraceHandler().trace("", 1);
150 }
0ff71477 151
f4053377
NR
152 @Override
153 protected void onError(Exception e) {
154 ServerBridge.this.onError(e);
155 }
156 }.connect();
157 } catch (Exception e) {
158 ServerBridge.this.onError(e);
159 }
8537d55a
NR
160 }
161 };
162 }
163
164 /**
165 * This is the method that is called each time a client contact us.
166 *
167 * @param clientVersion
168 * the client version
8537d55a
NR
169 */
170 protected void onClientContact(Version clientVersion) {
d827da2a 171 getTraceHandler().trace(">>> CLIENT " + clientVersion);
8537d55a
NR
172 }
173
174 /**
175 * This is the method that is called each time a client contact us.
176 *
177 * @param serverVersion
178 * the server version
8537d55a
NR
179 */
180 protected void onServerContact(Version serverVersion) {
d827da2a 181 getTraceHandler().trace("<<< SERVER " + serverVersion);
217a3310 182 getTraceHandler().trace("");
8537d55a
NR
183 }
184
185 /**
186 * This is the method that is called each time a client contact us.
187 *
188 * @param clientVersion
189 * the client version
190 * @param data
191 * the data sent by the client
192 */
193 protected void onRec(Version clientVersion, String data) {
d827da2a 194 trace(">>> CLIENT (" + clientVersion + ")", data);
8537d55a
NR
195 }
196
197 /**
198 * This is the method that is called each time the forwarded server contact
199 * us.
200 *
201 * @param serverVersion
202 * the client version
203 * @param data
204 * the data sent by the client
205 */
206 protected void onSend(Version serverVersion, String data) {
d827da2a 207 trace("<<< SERVER (" + serverVersion + ")", data);
8537d55a
NR
208 }
209
f4053377
NR
210 @Override
211 public void run() {
212 getTraceHandler().trace(
213 getName() + ": will forward to " + forwardToHost + ":"
214 + forwardToPort + " ("
8468bb79
NR
215 + (forwardToKey != null ? "encrypted" : "plain text")
216 + ")");
f4053377
NR
217 super.run();
218 }
219
8537d55a
NR
220 /**
221 * Trace the data with the given prefix.
222 *
223 * @param prefix
224 * the prefix (client, server, version...)
225 * @param data
226 * the data to trace
227 */
228 private void trace(String prefix, String data) {
f8f2afb4 229 int size = data == null ? 0 : data.length();
8468bb79 230 String ssize = StringUtils.formatNumber(size) + "bytes";
452f38c8
NR
231
232 getTraceHandler().trace(prefix + ": " + ssize, 1);
8537d55a
NR
233
234 if (getTraceHandler().getTraceLevel() >= 2) {
235 try {
a359464f
NR
236 while (data.startsWith("ZIP:") || data.startsWith("B64:")) {
237 if (data.startsWith("ZIP:")) {
238 data = StringUtils.unbase64s(data.substring(4), true);
239 } else if (data.startsWith("B64:")) {
240 data = StringUtils.unbase64s(data.substring(4), false);
241 }
452f38c8
NR
242 }
243
8537d55a
NR
244 Object obj = new Importer().read(data).getValue();
245 if (obj == null) {
452f38c8 246 getTraceHandler().trace("NULL", 2);
8537d55a
NR
247 getTraceHandler().trace("NULL", 3);
248 getTraceHandler().trace("NULL", 4);
249 } else {
452f38c8
NR
250 if (obj.getClass().isArray()) {
251 getTraceHandler().trace(
252 "(" + obj.getClass() + ") with "
253 + Array.getLength(obj) + "element(s)",
254 3);
255 } else {
256 getTraceHandler().trace("(" + obj.getClass() + ")", 2);
257 }
258 getTraceHandler().trace("" + obj.toString(), 3);
259 getTraceHandler().trace(data, 4);
8537d55a 260 }
452f38c8
NR
261 } catch (NoSuchMethodException e) {
262 getTraceHandler().trace("(not an object)", 2);
263 getTraceHandler().trace(data, 3);
264 getTraceHandler().trace("", 4);
265 } catch (NoSuchFieldException e) {
266 getTraceHandler().trace(
217a3310 267 "(incompatible: " + e.getMessage() + ")", 2);
452f38c8
NR
268 getTraceHandler().trace(data, 3);
269 getTraceHandler().trace("", 4);
270 } catch (ClassNotFoundException e) {
271 getTraceHandler().trace(
272 "(unknown object: " + e.getMessage() + ")", 2);
273 getTraceHandler().trace(data, 3);
274 getTraceHandler().trace("", 4);
8537d55a 275 } catch (Exception e) {
217a3310
NR
276 getTraceHandler().trace(
277 "(decode error: " + e.getMessage() + ")", 2);
452f38c8
NR
278 getTraceHandler().trace(data, 3);
279 getTraceHandler().trace("", 4);
8537d55a
NR
280 }
281
452f38c8 282 getTraceHandler().trace("", 2);
8537d55a
NR
283 }
284 }
8537d55a 285}