Merge commit '77d3a60869e7a780c6ae069e51530e1eacece5e2'
[fanfix.git] / src / be / nikiroo / utils / serial / server / ServerBridge.java
index b72c98ddd44fe45dcc0b8cb99f97565b4240e6b7..0b734c6bbd6ca105b852406b2a97ec64ee71b589 100644 (file)
@@ -1,8 +1,11 @@
 package be.nikiroo.utils.serial.server;
 
+import java.io.ByteArrayInputStream;
 import java.io.IOException;
+import java.io.InputStream;
 import java.lang.reflect.Array;
 import java.net.Socket;
+import java.net.UnknownHostException;
 
 import be.nikiroo.utils.StringUtils;
 import be.nikiroo.utils.TraceHandler;
@@ -24,7 +27,7 @@ import be.nikiroo.utils.serial.Importer;
 public class ServerBridge extends Server {
        private final String forwardToHost;
        private final int forwardToPort;
-       private final boolean forwardToSsl;
+       private final String forwardToKey;
 
        /**
         * Create a new server that will start listening on the network when
@@ -34,24 +37,31 @@ public class ServerBridge extends Server {
         *            the port to listen on, or 0 to assign any unallocated port
         *            found (which can later on be queried via
         *            {@link ServerBridge#getPort()}
-        * @param ssl
-        *            use an SSL connection (or not)
+        * @param key
+        *            an optional key to encrypt all the communications (if NULL,
+        *            everything will be sent in clear text)
         * @param forwardToHost
         *            the host server to forward the calls to
         * @param forwardToPort
         *            the host port to forward the calls to
-        * @param forwardToSsl
-        *            use an SSL connection for the forward server or not
+        * @param forwardToKey
+        *            an optional key to encrypt all the communications (if NULL,
+        *            everything will be sent in clear text)
         * 
         * @throws IOException
         *             in case of I/O error
+        * @throws UnknownHostException
+        *             if the IP address of the host could not be determined
+        * @throws IllegalArgumentException
+        *             if the port parameter is outside the specified range of valid
+        *             port values, which is between 0 and 65535, inclusive
         */
-       public ServerBridge(int port, boolean ssl, String forwardToHost,
-                       int forwardToPort, boolean forwardToSsl) throws IOException {
-               super(port, ssl);
+       public ServerBridge(int port, String key, String forwardToHost,
+                       int forwardToPort, String forwardToKey) throws IOException {
+               super(port, key);
                this.forwardToHost = forwardToHost;
                this.forwardToPort = forwardToPort;
-               this.forwardToSsl = forwardToSsl;
+               this.forwardToKey = forwardToKey;
        }
 
        /**
@@ -62,25 +72,33 @@ public class ServerBridge extends Server {
         *            the server name (only used for debug info and traces)
         * @param port
         *            the port to listen on
-        * @param ssl
-        *            use an SSL connection (or not)
+        * @param key
+        *            an optional key to encrypt all the communications (if NULL,
+        *            everything will be sent in clear text)
         * @param forwardToHost
         *            the host server to forward the calls to
         * @param forwardToPort
         *            the host port to forward the calls to
-        * @param forwardToSsl
-        *            use an SSL connection for the forward server or not
+        * @param forwardToKey
+        *            an optional key to encrypt all the communications (if NULL,
+        *            everything will be sent in clear text) use an SSL connection
+        *            for the forward server or not
         * 
         * @throws IOException
         *             in case of I/O error
+        * @throws UnknownHostException
+        *             if the IP address of the host could not be determined
+        * @throws IllegalArgumentException
+        *             if the port parameter is outside the specified range of valid
+        *             port values, which is between 0 and 65535, inclusive
         */
-       public ServerBridge(String name, int port, boolean ssl,
-                       String forwardToHost, int forwardToPort, boolean forwardToSsl)
+       public ServerBridge(String name, int port, String key,
+                       String forwardToHost, int forwardToPort, String forwardToKey)
                        throws IOException {
-               super(name, port, ssl);
+               super(name, port, key);
                this.forwardToHost = forwardToHost;
                this.forwardToPort = forwardToPort;
-               this.forwardToSsl = forwardToSsl;
+               this.forwardToKey = forwardToKey;
        }
 
        /**
@@ -107,75 +125,96 @@ public class ServerBridge extends Server {
 
        @Override
        protected ConnectActionServer createConnectActionServer(Socket s) {
-               return new ConnectActionServerString(s) {
+               // Bad impl, not up to date (should work, but not efficient)
+               return new ConnectActionServerString(s, key) {
                        @Override
-                       public void action(final Version clientVersion) throws Exception {
+                       public void action(Version clientVersion) throws Exception {
                                onClientContact(clientVersion);
                                final ConnectActionServerString bridge = this;
 
-                               new ConnectActionClientString(forwardToHost, forwardToPort,
-                                               forwardToSsl, clientVersion) {
-                                       @Override
-                                       public void action(final Version serverVersion)
-                                                       throws Exception {
-                                               onServerContact(serverVersion);
+                               try {
+                                       new ConnectActionClientString(forwardToHost, forwardToPort,
+                                                       forwardToKey) {
+                                               @Override
+                                               public void action(Version serverVersion)
+                                                               throws Exception {
+                                                       onServerContact(serverVersion);
 
-                                               for (String fromClient = bridge.rec(); fromClient != null; fromClient = bridge
-                                                               .rec()) {
-                                                       onRec(clientVersion, fromClient);
-                                                       String fromServer = send(fromClient);
-                                                       onSend(serverVersion, fromServer);
-                                                       bridge.send(fromServer);
+                                                       for (String fromClient = bridge.rec(); fromClient != null; fromClient = bridge
+                                                                       .rec()) {
+                                                               onRec(fromClient);
+                                                               String fromServer = send(fromClient);
+                                                               onSend(fromServer);
+                                                               bridge.send(fromServer);
+                                                       }
+
+                                                       getTraceHandler().trace("=== DONE", 1);
+                                                       getTraceHandler().trace("", 1);
                                                }
-                                       }
-                               }.connect();
+
+                                               @Override
+                                               protected void onError(Exception e) {
+                                                       ServerBridge.this.onError(e);
+                                               }
+                                       }.connect();
+                               } catch (Exception e) {
+                                       ServerBridge.this.onError(e);
+                               }
                        }
                };
        }
 
        /**
         * This is the method that is called each time a client contact us.
-        * 
-        * @param clientVersion
-        *            the client version
         */
        protected void onClientContact(Version clientVersion) {
-               getTraceHandler().trace("<<< CLIENT " + clientVersion);
+               getTraceHandler().trace(">>> CLIENT " + clientVersion);
        }
 
        /**
         * This is the method that is called each time a client contact us.
-        * 
-        * @param serverVersion
-        *            the server version
         */
        protected void onServerContact(Version serverVersion) {
-               getTraceHandler().trace(">>> SERVER " + serverVersion);
+               getTraceHandler().trace("<<< SERVER " + serverVersion);
+               getTraceHandler().trace("");
        }
 
        /**
         * This is the method that is called each time a client contact us.
         * 
-        * @param clientVersion
-        *            the client version
         * @param data
         *            the data sent by the client
         */
-       protected void onRec(Version clientVersion, String data) {
-               trace("<<< CLIENT (" + clientVersion + ")", data);
+       protected void onRec(String data) {
+               trace(">>> CLIENT", data);
        }
 
        /**
         * This is the method that is called each time the forwarded server contact
         * us.
         * 
-        * @param serverVersion
-        *            the client version
         * @param data
         *            the data sent by the client
         */
-       protected void onSend(Version serverVersion, String data) {
-               trace(">>> SERVER (" + serverVersion + ")", data);
+       protected void onSend(String data) {
+               trace("<<< SERVER", data);
+       }
+
+       @Override
+       protected ConnectActionClient getConnectionToMe()
+                       throws UnknownHostException, IOException {
+               return new ConnectActionClientString(new Socket((String) null,
+                               getPort()), key);
+       }
+
+       @Override
+       public void run() {
+               getTraceHandler().trace(
+                               getName() + ": will forward to " + forwardToHost + ":"
+                                               + forwardToPort + " ("
+                                               + (forwardToKey != null ? "encrypted" : "plain text")
+                                               + ")");
+               super.run();
        }
 
        /**
@@ -187,44 +226,44 @@ public class ServerBridge extends Server {
         *            the data to trace
         */
        private void trace(String prefix, String data) {
-               int size = data.length();
-               String ssize = size + " byte";
-               if (size > 1) {
-                       ssize = size + " bytes";
-                       if (size >= 1000) {
-                               size = size / 1000;
-                               ssize = size + " kb";
-                               if (size > 1000) {
-                                       size = size / 1000;
-                                       ssize = size + " MB";
-                               }
-                       }
-               }
+               int size = data == null ? 0 : data.length();
+               String ssize = StringUtils.formatNumber(size) + "bytes";
 
                getTraceHandler().trace(prefix + ": " + ssize, 1);
 
                if (getTraceHandler().getTraceLevel() >= 2) {
                        try {
-                               if (data.startsWith("ZIP:")) {
-                                       data = StringUtils.unzip64(data.substring(4));
+                               while (data.startsWith("ZIP:") || data.startsWith("B64:")) {
+                                       if (data.startsWith("ZIP:")) {
+                                               data = StringUtils.unzip64s(data.substring(4));
+                                       } else if (data.startsWith("B64:")) {
+                                               data = StringUtils.unzip64s(data.substring(4));
+                                       }
                                }
 
-                               Object obj = new Importer().read(data).getValue();
-                               if (obj == null) {
-                                       getTraceHandler().trace("NULL", 2);
-                                       getTraceHandler().trace("NULL", 3);
-                                       getTraceHandler().trace("NULL", 4);
-                               } else {
-                                       if (obj.getClass().isArray()) {
-                                               getTraceHandler().trace(
-                                                               "(" + obj.getClass() + ") with "
-                                                                               + Array.getLength(obj) + "element(s)",
-                                                               3);
+                               InputStream stream = new ByteArrayInputStream(
+                                               StringUtils.getBytes(data));
+                               try {
+                                       Object obj = new Importer().read(stream).getValue();
+                                       if (obj == null) {
+                                               getTraceHandler().trace("NULL", 2);
+                                               getTraceHandler().trace("NULL", 3);
+                                               getTraceHandler().trace("NULL", 4);
                                        } else {
-                                               getTraceHandler().trace("(" + obj.getClass() + ")", 2);
+                                               if (obj.getClass().isArray()) {
+                                                       getTraceHandler().trace(
+                                                                       "(" + obj.getClass() + ") with "
+                                                                                       + Array.getLength(obj)
+                                                                                       + "element(s)", 3);
+                                               } else {
+                                                       getTraceHandler().trace("(" + obj.getClass() + ")",
+                                                                       2);
+                                               }
+                                               getTraceHandler().trace("" + obj.toString(), 3);
+                                               getTraceHandler().trace(data, 4);
                                        }
-                                       getTraceHandler().trace("" + obj.toString(), 3);
-                                       getTraceHandler().trace(data, 4);
+                               } finally {
+                                       stream.close();
                                }
                        } catch (NoSuchMethodException e) {
                                getTraceHandler().trace("(not an object)", 2);
@@ -232,8 +271,7 @@ public class ServerBridge extends Server {
                                getTraceHandler().trace("", 4);
                        } catch (NoSuchFieldException e) {
                                getTraceHandler().trace(
-                                               "(object known but incompatible: " + e.getMessage()
-                                                               + ")", 2);
+                                               "(incompatible: " + e.getMessage() + ")", 2);
                                getTraceHandler().trace(data, 3);
                                getTraceHandler().trace("", 4);
                        } catch (ClassNotFoundException e) {
@@ -242,9 +280,8 @@ public class ServerBridge extends Server {
                                getTraceHandler().trace(data, 3);
                                getTraceHandler().trace("", 4);
                        } catch (Exception e) {
-                               getTraceHandler()
-                                               .trace("(error when trying to decode: "
-                                                               + e.getMessage() + ")", 2);
+                               getTraceHandler().trace(
+                                               "(decode error: " + e.getMessage() + ")", 2);
                                getTraceHandler().trace(data, 3);
                                getTraceHandler().trace("", 4);
                        }
@@ -252,57 +289,4 @@ public class ServerBridge extends Server {
                        getTraceHandler().trace("", 2);
                }
        }
-
-       /**
-        * Start a bridge between 2 servers.
-        * 
-        * @param args
-        *            an array containing:
-        *            <ul>
-        *            <li>The bridge name</li>
-        *            <li>The bridge port</li>
-        *            <li>TRUE for an SSL bridge, FALSE for plain text</li>
-        *            <li>The forward server host</li>
-        *            <li>The forward server port</li>
-        *            <li>TRUE for an SSL forward server, FALSE for plain text</li>
-        *            <li>(optional) a trace level</li>
-        *            </ul>
-        */
-       public static void main(String[] args) {
-               final TraceHandler tracer = new TraceHandler(true, false, 0);
-               try {
-                       if (args.length < 6) {
-                               tracer.error("Invalid syntax.\n"
-                                               + "Syntax: [name] [port] [ssl] [fhost] [fport] [fssl] ([trace level])\n"
-                                               + "\tname: the bridge name\n"
-                                               + "\tport: the bridge port\n"
-                                               + "\tssl: TRUE for an SSL bridge, FALSE for plain text\n"
-                                               + "\tfhost: the forward server host\n"
-                                               + "\tfport: the forward server port\n"
-                                               + "\tfssl: TRUE for an SSL forward server, FALSE for plain text\n"
-                                               + "\ttrace level: the optional trace level (default is 1)\n");
-                               return;
-                       }
-
-                       int i = 0;
-                       String name = args[i++];
-                       int port = Integer.parseInt(args[i++]);
-                       boolean ssl = Boolean.parseBoolean(args[i++]);
-                       String fhost = args[i++];
-                       int fport = Integer.parseInt(args[i++]);
-                       boolean fssl = Boolean.parseBoolean(args[i++]);
-
-                       int traceLevel = 1;
-                       if (args.length > 6) {
-                               traceLevel = Integer.parseInt(args[i++]);
-                       }
-
-                       ServerBridge bridge = new ServerBridge(name, port, ssl, fhost,
-                                       fport, fssl);
-                       bridge.setTraceHandler(new TraceHandler(true, true, traceLevel));
-                       bridge.run();
-               } catch (Exception e) {
-                       tracer.error(e);
-               }
-       }
 }