# NetSocket.java

    /*
    ** Module   : NetSocket.java
    ** Abstract : combines a socket/channel and related input/output streams into a manageable unit
    **
    ** Copyright (c) 2005-2023, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- --JPRM-- ---------------------------- 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
    ** 007 IAS 20200722          Refactored to the new NetSocket API.
    ** 009 IAS 20200726          Fixed TRACE and NIO flags defaults.
    ** 009 IAS 20200729          Process large messages, fixed handshake
    ** 010 IAS 20210329          Re-worked logging and NIO configuration
    ** 011 GBB 20230512          Logging methods replaced by CentralLogger/ConversionStatus.
    */
    /*
    ** 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 java.net.Socket;
    import java.nio.channels.*;
    import java.util.*;
    import java.util.logging.*;

    import javax.net.ssl.*;

    import com.goldencode.p2j.util.logging.*;

    /**
     * This interface represents a (secure) socket/channel and all related input/output streams as a one unit.
     */
    public interface NetSocket
    {
       /** Logger */
       static final CentralLogger LOG = CentralLogger.get(NetSocket.class.getName(), true, true);

       /** Handshake timeout (ms) */
       static final long handshakeTimeout = 5000L;

       /** I/O buffers' size */
       static final int BUF_SIZE = 32 * 1024;

       /** NetSocket factory instance */
       NetSocketFactory FACTORY = new NetSocketFactory()
       {
          /**
           * Create NetSocket which uses object streams for I/O
           *
           * @param socket
           *        Underlying Socket
           *
           * @return NetSocket which uses object streams for I/O
           */
          public NetSocket create(Socket socket) throws IOException
          {
             NetSocket ns = new NetSocketWrapper(socket);
             return LOG.isLoggable(Level.FINEST) ? new LoggingNetSocket(ns) : ns;
          }

          /**
           * Create NetSocket which uses insecure NIO SocketChannel for I/O
           *
           * @param channel
           *        Underlying NIO SocketChannel
           *
           * @return NetSocket which uses insecure NIO SocketChannel for I/O
           */
          public NetSocket create(SocketChannel channel) throws IOException
          {
             NetSocket ns = new NIONetSocket(channel);
             return LOG.isLoggable(Level.FINEST) ? new LoggingNetSocket(ns) : ns;
          }

          /**
           * Create NetSocket which uses SSL over NIO SocketChannel for I/O
           *
           * @param engine
           *        SSLEngine instance
           * @param channel
           *        Underlying NIO SocketChannel
           *
           * @return NetSocket which uses SSL over NIO SocketChannel for I/O
           */
          public NetSocket create(SSLEngine engine, SocketChannel channel) throws IOException
          {
             NetSocket ns = new NIOSslSocket(engine, channel);
             return LOG.isLoggable(Level.FINEST) ? new LoggingNetSocket(ns) : ns;
          }
       };

       /**
        *  Write message to the log
        *
        * @param message
        *        message to be written
        */
       default void traceln(String message)
       {
          if (LOG.isLoggable(Level.FINEST))
          {
             LOG.log(Level.FINEST,
                   String.format("%s: %s", Thread.currentThread().getName(), message));
          }
       }

       /**
         * Write a message to the log using the specified format string and
         * arguments.
         *
         * @param  fmt
         *         A format string
         *
         * @param  args
         *         Arguments referenced by the format specifiers in the format
         *         string.
         */
       default void tracef(String fmt, Object...args)
       {
          if (LOG.isLoggable(Level.FINEST))
          {
             traceln(String.format(fmt, args));
          }
       }

       /**
        * NetSocket factory
        */
       public interface NetSocketFactory
       {
          /**
           * Create NetSocket which uses object streams for I/O
           *
           * @param socket
           *        Underlying Socket
           *
           * @return NetSocket which uses object streams for I/O
           * @throws   IOException
           *           on error
           */
          NetSocket create(Socket socket)
          throws IOException;

          /**
           * Create NetSocket which uses insecure NIO SocketChannel for I/O
           *
           * @param channel
           *        Underlying NIO SocketChannel
           *
           * @return NetSocket which uses insecure NIO SocketChannel for I/O
           * @throws   IOException
           *           on error
           */
          NetSocket create(SocketChannel channel)
          throws IOException;

          /**
           * Create NetSocket which uses SSL over NIO SocketChannel for I/O
           *
           * @param engine
           *        SSLEngine instance
           * @param channel
           *        Underlying NIO SocketChannel
           *
           * @return NetSocket which uses SSL over NIO SocketChannel for I/O
           * @throws   IOException
           *           on error
           */
          NetSocket create(SSLEngine engine, SocketChannel channel)
          throws IOException;
       }

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

       /**
        * Closes the socket.
        */
       void close();

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

       /**
        * Access the address of the local system, through which we are connecting.
        *
        * @return   The local address.
        */
       InetAddress getLocalAddr();

       /**
        * Access the address of the local system, through which we are connecting.
        *
        * @return   The local socket address.
        */
       InetSocketAddress getLocalSockAddr();

       /**
        * Access the address of the remote system, to which we are connecting.
        *
        * @return   The remote address.
        */
       InetAddress getRemoteAddr();

       /**
        * Access the address of the remote system, to which we are connecting.
        *
        * @return   The remote socket address.
        */
       InetSocketAddress getRemoteSockAddr();

       /**
        * Gets the list with added session listeners. May return <code>null</code> if none has
        * been added.
        *
        * @return  The current session listener.
        */
       List<SessionListener> getSessionListeners();

       /**
        * Adds a session listener.
        *
        * @param   sessionListener
        *          A session listener to be added.
        */
       void addSessionListener(SessionListener sessionListener);

       /**
        * Flush the output if applicable
        * @throws   IOException
        *           on error
        */
       default void flush()
       throws IOException
       {
         // DO NOTHING
       }

       /**
        * Write byte array to the output
        *
        * @param data
        *        byte array
        * @throws   IOException
        *           on error
        */
       void write(byte[] data)
       throws IOException;

       /**
        * Read the next portion of raw data (byte array) to the output
        *
        * @return byte array
        * @throws   IOException
        *           on error
        */
       byte[] read()
       throws IOException;

       /**
        * Read the integer from the input
        *
        * @return integer data
        * @throws   IOException
        *           on error
        */
       int readInt()
       throws IOException;

       /**
        * Write an integer to the output
        *
        * @param val
        *        integer data to be written
        * @throws   IOException
        *           on error
        */
       void writeInt(int val)
       throws IOException;

       /**
        * Write a byte sequence to the output
        *
        * @param bytes
        *        byte sequence to be written
        * @throws   IOException
        *           on error
        */
       void writeBytes(byte[] bytes)
       throws IOException;

       /**
        * Read the byte sequence from the input
        *
        * @param bytes
        *        byte array to be filled by the input bytes
        * @throws   IOException
        *           on error
        */
       void readBytes(byte[] bytes)
       throws IOException;

       /**
        * Write a boolean to the output
        *
        * @param val
        *        boolean data to be written
        * @throws   IOException
        *           on error
        */
       void writeBoolean(boolean val)
       throws IOException;

       /**
        * Read the boolean from the input
        *
        * @return boolean data
        * @throws   IOException
        *           on error
        */
       boolean readBoolean()
       throws IOException;

       /**
        * Read the UTF string from the input
        *
        * @return UTF string
        * @throws   IOException
        *           on error
        */
       String readUTF()
       throws IOException;

       /**
        * Write an UTF String to the output
        *
        * @param val
        *        UTF String to be written
        * @throws   IOException
        *           on error
        */
       void writeUTF(String val)
       throws IOException;
    }