server: String -> Stream
[nikiroo-utils.git] / src / be / nikiroo / utils / serial / server / ConnectAction.java
index a377ced597f2a6bd84d01fd008f7f5099b9409a3..901632627b218d35469fcc7cb6b71f2af2b8144d 100644 (file)
@@ -1,18 +1,21 @@
 package be.nikiroo.utils.serial.server;
 
-import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStream;
-import java.io.InputStreamReader;
 import java.io.OutputStream;
 import java.net.Socket;
 
 import javax.net.ssl.SSLException;
 
 import be.nikiroo.utils.CryptUtils;
-import be.nikiroo.utils.Version;
+import be.nikiroo.utils.IOUtils;
 import be.nikiroo.utils.serial.Exporter;
 import be.nikiroo.utils.serial.Importer;
+import be.nikiroo.utils.streams.BufferedOutputStream;
+import be.nikiroo.utils.streams.NextableInputStream;
+import be.nikiroo.utils.streams.NextableInputStreamStep;
+import be.nikiroo.utils.streams.ReplaceInputStream;
+import be.nikiroo.utils.streams.ReplaceOutputStream;
 
 /**
  * Base class used for the client/server basic handling.
@@ -26,44 +29,22 @@ import be.nikiroo.utils.serial.Importer;
 abstract class ConnectAction {
        private Socket s;
        private boolean server;
-       private Version version;
-       private Version clientVersion;
 
        private CryptUtils crypt;
 
        private Object lock = new Object();
-       private InputStream in;
-       private OutputStream out;
+       private NextableInputStream in;
+       private BufferedOutputStream out;
        private boolean contentToSend;
 
-       private long bytesReceived;
-       private long bytesSent;
-
        /**
         * Method that will be called when an action is performed on either the
         * client or server this {@link ConnectAction} represent.
         * 
-        * @param version
-        *            the counter part version
-        * 
         * @throws Exception
         *             in case of I/O error
         */
-       abstract protected void action(Version version) throws Exception;
-
-       /**
-        * Method called when we negotiate the version with the client.
-        * <p>
-        * Thus, it is only called on the server.
-        * <p>
-        * Will return the actual server version by default.
-        * 
-        * @param clientVersion
-        *            the client version
-        * 
-        * @return the version to send to the client
-        */
-       abstract protected Version negotiateVersion(Version clientVersion);
+       abstract protected void action() throws Exception;
 
        /**
         * Handler called when an unexpected error occurs in the code.
@@ -85,33 +66,13 @@ abstract class ConnectAction {
         * @param key
         *            an optional key to encrypt all the communications (if NULL,
         *            everything will be sent in clear text)
-        * @param version
-        *            the version of this client-or-server
         */
-       protected ConnectAction(Socket s, boolean server, String key,
-                       Version version) {
+       protected ConnectAction(Socket s, boolean server, String key) {
                this.s = s;
                this.server = server;
                if (key != null) {
                        crypt = new CryptUtils(key);
                }
-
-               if (version == null) {
-                       this.version = new Version();
-               } else {
-                       this.version = version;
-               }
-
-               clientVersion = new Version();
-       }
-
-       /**
-        * The version of this client-or-server.
-        * 
-        * @return the version
-        */
-       public Version getVersion() {
-               return version;
        }
 
        /**
@@ -120,7 +81,7 @@ abstract class ConnectAction {
         * @return the amount of bytes received
         */
        public long getBytesReceived() {
-               return bytesReceived;
+               return in.getBytesRead();
        }
 
        /**
@@ -128,8 +89,8 @@ abstract class ConnectAction {
         * 
         * @return the amount of bytes sent
         */
-       public long getBytesSent() {
-               return bytesSent;
+       public long getBytesWritten() {
+               return out.getBytesWritten();
        }
 
        /**
@@ -137,48 +98,20 @@ abstract class ConnectAction {
         */
        public void connect() {
                try {
-                       in = s.getInputStream();
-                       try {
-                               out = s.getOutputStream();
-                               try {
-                                       if (server) {
-                                               String line;
-                                               try {
-                                                       line = readLine(in);
-                                               } catch (SSLException e) {
-                                                       out.write("Unauthorized\n".getBytes());
-                                                       throw e;
-                                               }
+                       // TODO: assure that \b is never used, make sure \n usage is OK
+                       in = new NextableInputStream(s.getInputStream(),
+                                       new NextableInputStreamStep('\b'));
 
-                                               if (line != null && line.startsWith("VERSION ")) {
-                                                       // "VERSION client-version" (VERSION 1.0.0)
-                                                       Version clientVersion = new Version(
-                                                                       line.substring("VERSION ".length()));
-                                                       this.clientVersion = clientVersion;
-                                                       Version v = negotiateVersion(clientVersion);
-                                                       if (v == null) {
-                                                               v = new Version();
-                                                       }
-
-                                                       sendString("VERSION " + v.toString());
-                                               }
-
-                                               action(clientVersion);
-                                       } else {
-                                               String v = sendString("VERSION " + version.toString());
-                                               if (v != null && v.startsWith("VERSION ")) {
-                                                       v = v.substring("VERSION ".length());
-                                               }
+                       try {
+                               out = new BufferedOutputStream(s.getOutputStream());
 
-                                               action(new Version(v));
-                                       }
+                               try {
+                                       action();
                                } finally {
                                        out.close();
-                                       out = null;
                                }
                        } finally {
                                in.close();
-                               in = null;
                        }
                } catch (Exception e) {
                        onError(e);
@@ -199,8 +132,9 @@ abstract class ConnectAction {
         * @param data
         *            the data to send
         * 
-        * @return the answer (which can be NULL) if this action is a client, always
-        *         NULL if it is a server
+        * @return the answer (which can be NULL if no answer, or NULL for an answer
+        *         which is NULL) if this action is a client, always NULL if it is a
+        *         server
         * 
         * @throws IOException
         *             in case of I/O error
@@ -215,15 +149,7 @@ abstract class ConnectAction {
         */
        protected Object sendObject(Object data) throws IOException,
                        NoSuchFieldException, NoSuchMethodException, ClassNotFoundException {
-               synchronized (lock) {
-                       String rep = sendString(new Exporter().append(data).toString(true,
-                                       true));
-                       if (rep != null) {
-                               return new Importer().read(rep).getValue();
-                       }
-
-                       return null;
-               }
+               return send(out, data, false);
        }
 
        /**
@@ -253,12 +179,7 @@ abstract class ConnectAction {
        protected Object recObject() throws IOException, NoSuchFieldException,
                        NoSuchMethodException, ClassNotFoundException,
                        java.lang.NullPointerException {
-               String str = recString();
-               if (str == null) {
-                       throw new NullPointerException("No more data available");
-               }
-
-               return new Importer().read(str).getValue();
+               return rec(false);
        }
 
        /**
@@ -277,17 +198,20 @@ abstract class ConnectAction {
         *             in case of crypt error
         */
        protected String sendString(String line) throws IOException {
-               synchronized (lock) {
-                       writeLine(out, line);
-
-                       if (server) {
-                               out.flush();
-                               return null;
-                       }
-
-                       contentToSend = true;
-                       return recString();
+               try {
+                       return (String) send(out, line, true);
+               } catch (NoSuchFieldException e) {
+                       // Cannot happen
+                       e.printStackTrace();
+               } catch (NoSuchMethodException e) {
+                       // Cannot happen
+                       e.printStackTrace();
+               } catch (ClassNotFoundException e) {
+                       // Cannot happen
+                       e.printStackTrace();
                }
+
+               return null;
        }
 
        /**
@@ -299,7 +223,7 @@ abstract class ConnectAction {
         * <p>
         * Will only flush the data if there is contentToSend.
         * 
-        * @return the answer (which can be NULL)
+        * @return the answer (which can be NULL if no more content)
         * 
         * @throws IOException
         *             in case of I/O error
@@ -307,73 +231,177 @@ abstract class ConnectAction {
         *             in case of crypt error
         */
        protected String recString() throws IOException {
-               synchronized (lock) {
-                       if (server || contentToSend) {
-                               if (contentToSend) {
-                                       out.flush();
-                                       contentToSend = false;
-                               }
-
-                               return readLine(in);
-                       }
-
-                       return null;
+               try {
+                       return (String) rec(true);
+               } catch (NoSuchFieldException e) {
+                       // Cannot happen
+                       e.printStackTrace();
+               } catch (NoSuchMethodException e) {
+                       // Cannot happen
+                       e.printStackTrace();
+               } catch (ClassNotFoundException e) {
+                       // Cannot happen
+                       e.printStackTrace();
+               } catch (NullPointerException e) {
+                       // Should happen
+                       e.printStackTrace();
                }
+
+               return null;
        }
 
        /**
-        * Read a possibly encrypted line.
+        * Serialise and send the given object to the counter part (and, only for
+        * client, return the deserialised answer -- the server will always receive
+        * NULL).
         * 
-        * @param in
-        *            the stream to read from
-        * @return the unencrypted line
+        * @param out
+        *            the stream to write to
+        * @param data
+        *            the data to write
+        * @param asString
+        *            TRUE to write it as a String, FALSE to write it as an Object
         * 
+        * @return the answer (which can be NULL if no answer, or NULL for an answer
+        *         which is NULL) if this action is a client, always NULL if it is a
+        *         server
         * 
         * @throws IOException
         *             in case of I/O error
         * @throws SSLException
         *             in case of crypt error
+        * @throws IOException
+        *             in case of I/O error
+        * @throws NoSuchFieldException
+        *             if the serialised data contains information about a field
+        *             which does actually not exist in the class we know of
+        * @throws NoSuchMethodException
+        *             if a class described in the serialised data cannot be created
+        *             because it is not compatible with this code
+        * @throws ClassNotFoundException
+        *             if a class described in the serialised data cannot be found
         */
-       private String readLine(InputStream in) throws IOException {
-               if (inReader == null) {
-                       inReader = new BufferedReader(new InputStreamReader(in));
-               }
-               String line = inReader.readLine();
-               if (line != null) {
-                       bytesReceived += line.length();
+       private Object send(BufferedOutputStream out, Object data, boolean asString)
+                       throws IOException, NoSuchFieldException, NoSuchMethodException,
+                       ClassNotFoundException, java.lang.NullPointerException {
+
+               synchronized (lock) {
+                       OutputStream sub;
                        if (crypt != null) {
-                               line = crypt.decrypt64s(line, false);
+                               sub = crypt.encrypt64(out.open(), false);
+                       } else {
+                               sub = out.open();
                        }
-               }
 
-               return line;
-       }
+                       // TODO: could be possible to check for non-crypt and only
+                       // do it for crypt
+                       sub = new ReplaceOutputStream(sub, //
+                                       new String[] { "\\", "\b" }, //
+                                       new String[] { "\\\\", "\\b" });
+
+                       try {
+                               if (asString) {
+                                       sub.write(data.toString().getBytes("UTF-8"));
+                               } else {
+                                       new Exporter(sub).append(data);
+                               }
+                       } finally {
+                               sub.close();
+                       }
 
-       private BufferedReader inReader;
+                       out.write('\b');
+
+                       if (server) {
+                               out.flush();
+                               return null;
+                       }
+
+                       contentToSend = true;
+                       try {
+                               return rec(asString);
+                       } catch (NullPointerException e) {
+                               // We accept no data here for Objects
+                       }
+
+                       return null;
+               }
+       }
 
        /**
-        * Write a line, possible encrypted.
+        * Reserved for the server: flush the data to the client and retrieve its
+        * answer.
+        * <p>
+        * Also used internally for the client (only do something if there is
+        * contentToSend).
+        * <p>
+        * Will only flush the data if there is contentToSend.
+        * <p>
+        * Note that the behaviour is slightly different for String and Object
+        * reading regarding exceptions:
+        * <ul>
+        * <li>NULL means that the counter part has no more data to send</li>
+        * <li>All the exceptions except {@link IOException} are there for Object
+        * conversion</li>
+        * </ul>
+        * 
+        * @param asString
+        *            TRUE for String reading, FALSE for Object reading (which can
+        *            still be a String)
+        * 
+        * @return the deserialised answer (which can actually be NULL)
         * 
-        * @param out
-        *            the stream to write to
-        * @param line
-        *            the line to write
         * @throws IOException
         *             in case of I/O error
-        * @throws SSLException
-        *             in case of crypt error
+        * @throws NoSuchFieldException
+        *             if the serialised data contains information about a field
+        *             which does actually not exist in the class we know of
+        * @throws NoSuchMethodException
+        *             if a class described in the serialised data cannot be created
+        *             because it is not compatible with this code
+        * @throws ClassNotFoundException
+        *             if a class described in the serialised data cannot be found
+        * @throws java.lang.NullPointerException
+        *             for Objects only: if the counter part has no data to send
         */
-       private void writeLine(OutputStream out, String line) throws IOException {
-               if (crypt == null) {
-                       out.write(line.getBytes());
-                       bytesSent += line.length();
-               } else {
-                       // TODO: how NOT to create so many big Strings?
-                       String b64 = crypt.encrypt64(line, false);
-                       out.write(b64.getBytes());
-                       bytesSent += b64.length();
+       private Object rec(boolean asString) throws IOException,
+                       NoSuchFieldException, NoSuchMethodException,
+                       ClassNotFoundException, java.lang.NullPointerException {
+
+               synchronized (lock) {
+                       if (server || contentToSend) {
+                               if (contentToSend) {
+                                       out.flush();
+                                       contentToSend = false;
+                               }
+
+                               if (in.next()) {
+                                       // TODO: could be possible to check for non-crypt and only
+                                       // do it for crypt
+                                       InputStream read = new ReplaceInputStream(in.open(), //
+                                                       new String[] { "\\\\", "\\b" }, //
+                                                       new String[] { "\\", "\b" });
+
+                                       try {
+                                               if (crypt != null) {
+                                                       read = crypt.decrypt64(read, false);
+                                               }
+
+                                               if (asString) {
+                                                       return IOUtils.readSmallStream(read);
+                                               }
+
+                                               return new Importer().read(read).getValue();
+                                       } finally {
+                                               read.close();
+                                       }
+                               }
+
+                               if (!asString) {
+                                       throw new NullPointerException();
+                               }
+                       }
+
+                       return null;
                }
-               out.write("\n".getBytes());
-               bytesSent++;
        }
 }
\ No newline at end of file