# NetSocketWrapper.java

    /*
    ** Module   : NetSocketWrapper.java
    ** Abstract : combines a socket and related input/output streams into a manageable unit
    **
    ** Copyright (c) 2005-2020, Golden Code Development Corporation.
    **
    ** -#- -I- --Date--  ---------------------------------------Description---------------------------------------
    ** 001 NVS 20050308   @20245 Created. This class extends and replaces SSLSocket in net and security packages.
    ** 002 NVS 20050311   @20287 Simplified by removing DataInput and Output streams. Authentication now uses
    **                           ObjectInput and Output streams as well.
    ** 003 GES 20081103   @40327 Rework to remove unnecessary features and to allow non-secure sockets to be used.
    ** 004 GES 20090609   @42628 Provided access to local socket info.
    ** 005 OM  20131022          Added a list of SessionListeners and minimum management methods.
    ** 006 IAS 20160805          Added new operations and extracted the interface
    */
    /*
    ** This program is free software: you can redistribute it and/or modify
    ** it under the terms of the GNU Affero General Public License as
    ** published by the Free Software Foundation, either version 3 of the
    ** License, or (at your option) any later version.
    **
    ** This program is distributed in the hope that it will be useful,
    ** but WITHOUT ANY WARRANTY; without even the implied warranty of
    ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    ** GNU Affero General Public License for more details.
    **
    ** You may find a copy of the GNU Affero GPL version 3 at the following
    ** location: https://www.gnu.org/licenses/agpl-3.0.en.html
    **
    ** Additional terms under GNU Affero GPL version 3 section 7:
    **
    **   Under Section 7 of the GNU Affero GPL version 3, the following additional
    **   terms apply to the works covered under the License.  These additional terms
    **   are non-permissive additional terms allowed under Section 7 of the GNU
    **   Affero GPL version 3 and may not be removed by you.
    **
    **   0. Attribution Requirement.
    **
    **     You must preserve all legal notices or author attributions in the covered
    **     work or Appropriate Legal Notices displayed by works containing the covered
    **     work.  You may not remove from the covered work any author or developer
    **     credit already included within the covered work.
    **
    **   1. No License To Use Trademarks.
    **
    **     This license does not grant any license or rights to use the trademarks
    **     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
    **     of Golden Code Development Corporation. You are not authorized to use the
    **     name Golden Code, FWD, or the names of any author or contributor, for
    **     publicity purposes without written authorization.
    **
    **   2. No Misrepresentation of Affiliation.
    **
    **     You may not represent yourself as Golden Code Development Corporation or FWD.
    **
    **     You may not represent yourself for publicity purposes as associated with
    **     Golden Code Development Corporation, FWD, or any author or contributor to
    **     the covered work, without written authorization.
    **
    **   3. No Misrepresentation of Source or Origin.
    **
    **     You may not represent the covered work as solely your work.  All modified
    **     versions of the covered work must be marked in a reasonable way to make it
    **     clear that the modified work is not originating from Golden Code Development
    **     Corporation or FWD.  All modified versions must contain the notices of
    **     attribution required in this license.
    */

    package com.goldencode.p2j.net;

    import java.io.*;
    import java.net.*;
    import javax.net.ssl.*;

    /**
     * This class represents a (secure) socket and all related input/output streams
     * as a one unit. This solves the problem of temporary streams closing other
     * streams and the underlying socket when finalized.
     */
    public class NetSocketWrapper
    extends NetSocketBase
    implements NetSocket
    {
       /** Embedded socket which may or may not be secure. */
       private final Socket socket;

       /** SSL session. */
       private final SSLSession session;

       /** Data input stream. */
       private final DataInputStream dataInp;

       /** Data output stream. */
       private final DataOutputStream dataOut;

       /**
        * Constructor
        *
        * @param    socket
        *           A connected socket to embed into this class. This may be a
        *           secure socket but it is not required.
        *
        * @throws   IOException
        *           If one of the streams being built on top of the socket throws
        *           the same exception.
        */
       public NetSocketWrapper(Socket socket)
       throws IOException
       {
          this.socket = socket;
          this.socket.setTcpNoDelay(true);
          this.socket.setReceiveBufferSize(BUF_SIZE);
          this.socket.setReceiveBufferSize(BUF_SIZE);

          if (socket instanceof SSLSocket)
          {
             SSLSocket ssl = (SSLSocket) socket;

             // get the SSL session, if this is a secure socket (NOTE: this will
             // cause the SSL handshake to occur if it has not already!)
             session = ssl.getSession();
          }
          else
          {
             session = null;
          }

          // create streams
          dataOut = new DataOutputStream(socket.getOutputStream());
          dataInp = new DataInputStream(socket.getInputStream());
       }

       /**
        * Gets the SSL session.
        *
        * @return   The SSL session or <code>null</code> if the socket is not
        *           secure.
        */
       @Override
       public SSLSession getSession()
       {
          return session;
       }

       /**
        * Closes the socket.
        */
       @Override
       public void close()
       {
          try
          {
             socket.close();
          }
          catch (IOException ex)
          {
             // best efforts
          }
       }

       /**
        * Reports if the socket is closed (and thus can no longer be used).
        *
        * @return   <code>true</code> if the socket is closed.
        */
       @Override
       public boolean isClosed()
       {
          return socket.isClosed();
       }

       /**
        * Access the address of the local system, through which we are connecting.
        *
        * @return   The local address.
        */
       @Override
       public InetAddress getLocalAddr()
       {
          return socket.getLocalAddress();
       }

       /**
        * Access the address of the local system, through which we are connecting.
        *
        * @return   The local socket address.
        */
       @Override
       public InetSocketAddress getLocalSockAddr()
       {
          return new InetSocketAddress(socket.getLocalAddress(), socket.getLocalPort());
       }

       /**
        * Access the address of the remote system, to which we are connecting.
        *
        * @return   The remote address.
        */
       @Override
       public InetAddress getRemoteAddr()
       {
          return socket.getInetAddress();
       }

       /**
        * Access the address of the remote system, to which we are connecting.
        *
        * @return   The remote socket address.
        */
       @Override
       public InetSocketAddress getRemoteSockAddr()
       {
          return new InetSocketAddress(socket.getInetAddress(), socket.getPort());
       }

       /**
        * Flush the output
        */
       @Override
       public void flush()
       throws IOException
       {
          dataOut.flush();
       }

       /**
        * Write byte array to the output
        *
        * @param data
        *        byte array
        */
       @Override
       public void write(byte[] data)
       throws IOException
       {
          dataOut.writeInt(data == null ? -1 : data.length);
          if (data != null)
          {
             dataOut.write(data);
          }
          dataOut.flush();
       }

       /**
        * Read the next portion of raw data (byte array) to the output
        *
        * @return byte array
        */
       @Override
       public byte[] read()
       throws IOException
       {
          int len = dataInp.readInt();
          if (len == -1)
          {
             return null;
          }

          byte[] b = new byte[len];
          int offset = 0;
          while (offset < len)
          {
             offset += dataInp.read(b, offset, len - offset);
          }

          return b;
       }

       /**
        * Read the integer from the input
        *
        * @return integer data
        */
       @Override
       public int readInt()
       throws IOException
       {
          return dataInp.readInt();
       }

       /**
        * Write an integer to the output
        *
        * @param val
        *        integer data to be written
        */
       @Override
       public void writeInt(int val)
       throws IOException
       {
          dataOut.writeInt(val);
       }

       /**
        * Write a byte sequence to the output
        *
        * @param bytes
        *        byte sequence to be written
        */
       @Override
       public void writeBytes(byte[] bytes)
       throws IOException
       {
          dataOut.write(bytes);
       }

       /**
        * Read the byte sequence from the input
        *
        * @param bytes
        *        byte array to be filled by the input bytes
        */
       @Override
       public void readBytes(byte[] bytes)
       throws IOException
       {
          dataInp.readFully(bytes);
       }

       /**
        * Write a boolean to the output
        *
        * @param val
        *        boolean data to be written
        */
       @Override
       public void writeBoolean(boolean val)
       throws IOException
       {
          dataOut.writeBoolean(val);
       }

       /**
        * Read the boolean from the input
        *
        * @return boolean data
        */
       @Override
       public boolean readBoolean()
       throws IOException
       {
          return dataInp.readBoolean();
       }

       /**
        * Read the UTF string from the input
        *
        * @return UTF string
        */
       @Override
       public String readUTF()
       throws IOException
       {
          return dataInp.readUTF();
       }

       /**
        * Write an UTF String to the output
        *
        * @param val
        *        UTF String to be written
        */
       @Override
       public void writeUTF(String val)
       throws IOException
       {
          dataOut.writeUTF(val);
       }
    }