<commit_before>/*
 * Copyright 2002-2016 jamod & j2mod development teams
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ghgande.j2mod.modbus.net;

import com.ghgande.j2mod.modbus.util.ThreadPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.*;

/**
 * Class that implements a ModbusTCPListener.
 * <p>
 * <p>
 * If listening, it accepts incoming requests passing them on to be handled.
 * If not listening, silently drops the requests.
 *
 * @author <NAME>
 * @author <NAME>
 * @author <NAME> (4energy)
 * @version 2.0 (March 2016)
 */
public class ModbusTCPListener extends AbstractModbusListener {

    private static final Logger logger = LoggerFactory.getLogger(ModbusTCPListener.class);

    private ServerSocket serverSocket = null;
    private ThreadPool threadPool;
    private Thread listener;
    private boolean useRtuOverTcp;

    /**
     * Constructs a ModbusTCPListener instance.<br>
     *
     * @param poolsize the size of the <tt>ThreadPool</tt> used to handle incoming
     *                 requests.
     * @param addr     the interface to use for listening.
     */
    public ModbusTCPListener(int poolsize, InetAddress addr) {
        this(poolsize, addr, false);
    }

    /**
     * Constructs a ModbusTCPListener instance.<br>
     *
     * @param poolsize      the size of the <tt>ThreadPool</tt> used to handle incoming
     *                      requests.
     * @param addr          the interface to use for listening.
     * @param useRtuOverTcp True if the RTU protocol should be used over TCP
     */
    public ModbusTCPListener(int poolsize, InetAddress addr, boolean useRtuOverTcp) {
        threadPool = new ThreadPool(poolsize);
        address = addr;
        this.useRtuOverTcp = useRtuOverTcp;
    }

    /**
     * /**
     * Constructs a ModbusTCPListener instance.  This interface is created
     * to listen on the wildcard address (0.0.0.0), which will accept TCP packets
     * on all available adapters/interfaces
     *
     * @param poolsize the size of the <tt>ThreadPool</tt> used to handle incoming
     *                 requests.
     */
    public ModbusTCPListener(int poolsize) {
        this(poolsize, false);
    }

    /**
     * /**
     * Constructs a ModbusTCPListener instance.  This interface is created
     * to listen on the wildcard address (0.0.0.0), which will accept TCP packets
     * on all available adapters/interfaces
     *
     * @param poolsize      the size of the <tt>ThreadPool</tt> used to handle incoming
     *                      requests.
     * @param useRtuOverTcp True if the RTU protocol should be used over TCP
     */
    public ModbusTCPListener(int poolsize, boolean useRtuOverTcp) {
        threadPool = new ThreadPool(poolsize);
        try {
            address = InetAddress.getByAddress(new byte[]{0, 0, 0, 0});
        }
        catch (UnknownHostException ex) {
            // Can't happen -- size is fixed.
        }
        this.useRtuOverTcp = useRtuOverTcp;
    }

    @Override
    public void setTimeout(int timeout) {
        super.setTimeout(timeout);
        if (serverSocket != null && listening) {
            try {
                serverSocket.setSoTimeout(timeout);
            }
            catch (SocketException e) {
                logger.error("Cannot set socket timeout", e);
            }
        }
    }

    @Override
    public void run() {
        try {
            /*
             * A server socket is opened with a connectivity queue of a size
             * specified in int floodProtection. Concurrent login handling under
             * normal circumstances should be alright, denial of service
             * attacks via massive parallel program logins can probably be
             * prevented.
             */
            int floodProtection = 100;
            serverSocket = new ServerSocket(port, floodProtection, address);
            serverSocket.setSoTimeout(timeout);
            logger.debug("Listening to {} (Port {})", serverSocket.toString(), port);
        }

        // Catch any fatal errors and set the listening flag to false to indicate an error
        catch (Exception e) {
            error = String.format("Cannot start TCP listener - %s", e.getMessage());
            listening = false;
            return;
        }

        listener = Thread.currentThread();
        listening = true;
        try {

            // Infinite loop, taking care of resources in case of a lot of
            // parallel logins
            listening = true;
            while (listening) {
                Socket incoming;
                try {
                    incoming = serverSocket.accept();
                }
                catch (SocketTimeoutException e) {
                    continue;
                }
                logger.debug("Making new connection {}", incoming.toString());
                if (listening) {
                    threadPool.execute(new TCPConnectionHandler(this, new TCPSlaveConnection(incoming, useRtuOverTcp)));
                }
                else {
                    incoming.close();
                }<commit_msg>Propagate ModbusTCPListener timeout to the TCPSlaveConnection (#59)<commit_after>/*
 * Copyright 2002-2016 jamod & j2mod development teams
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ghgande.j2mod.modbus.net;

import com.ghgande.j2mod.modbus.util.ThreadPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.*;

/**
 * Class that implements a ModbusTCPListener.
 * <p>
 * <p>
 * If listening, it accepts incoming requests passing them on to be handled.
 * If not listening, silently drops the requests.
 *
 * @author <NAME>
 * @author <NAME>
 * @author <NAME> (4energy)
 * @version 2.0 (March 2016)
 */
public class ModbusTCPListener extends AbstractModbusListener {

    private static final Logger logger = LoggerFactory.getLogger(ModbusTCPListener.class);

    private ServerSocket serverSocket = null;
    private ThreadPool threadPool;
    private Thread listener;
    private boolean useRtuOverTcp;

    /**
     * Constructs a ModbusTCPListener instance.<br>
     *
     * @param poolsize the size of the <tt>ThreadPool</tt> used to handle incoming
     *                 requests.
     * @param addr     the interface to use for listening.
     */
    public ModbusTCPListener(int poolsize, InetAddress addr) {
        this(poolsize, addr, false);
    }

    /**
     * Constructs a ModbusTCPListener instance.<br>
     *
     * @param poolsize      the size of the <tt>ThreadPool</tt> used to handle incoming
     *                      requests.
     * @param addr          the interface to use for listening.
     * @param useRtuOverTcp True if the RTU protocol should be used over TCP
     */
    public ModbusTCPListener(int poolsize, InetAddress addr, boolean useRtuOverTcp) {
        threadPool = new ThreadPool(poolsize);
        address = addr;
        this.useRtuOverTcp = useRtuOverTcp;
    }

    /**
     * /**
     * Constructs a ModbusTCPListener instance.  This interface is created
     * to listen on the wildcard address (0.0.0.0), which will accept TCP packets
     * on all available adapters/interfaces
     *
     * @param poolsize the size of the <tt>ThreadPool</tt> used to handle incoming
     *                 requests.
     */
    public ModbusTCPListener(int poolsize) {
        this(poolsize, false);
    }

    /**
     * /**
     * Constructs a ModbusTCPListener instance.  This interface is created
     * to listen on the wildcard address (0.0.0.0), which will accept TCP packets
     * on all available adapters/interfaces
     *
     * @param poolsize      the size of the <tt>ThreadPool</tt> used to handle incoming
     *                      requests.
     * @param useRtuOverTcp True if the RTU protocol should be used over TCP
     */
    public ModbusTCPListener(int poolsize, boolean useRtuOverTcp) {
        threadPool = new ThreadPool(poolsize);
        try {
            address = InetAddress.getByAddress(new byte[]{0, 0, 0, 0});
        }
        catch (UnknownHostException ex) {
            // Can't happen -- size is fixed.
        }
        this.useRtuOverTcp = useRtuOverTcp;
    }

    @Override
    public void setTimeout(int timeout) {
        super.setTimeout(timeout);
        if (serverSocket != null && listening) {
            try {
                serverSocket.setSoTimeout(timeout);
            }
            catch (SocketException e) {
                logger.error("Cannot set socket timeout", e);
            }
        }
    }

    @Override
    public void run() {
        try {
            /*
             * A server socket is opened with a connectivity queue of a size
             * specified in int floodProtection. Concurrent login handling under
             * normal circumstances should be alright, denial of service
             * attacks via massive parallel program logins can probably be
             * prevented.
             */
            int floodProtection = 100;
            serverSocket = new ServerSocket(port, floodProtection, address);
            serverSocket.setSoTimeout(timeout);
            logger.debug("Listening to {} (Port {})", serverSocket.toString(), port);
        }

        // Catch any fatal errors and set the listening flag to false to indicate an error
        catch (Exception e) {
            error = String.format("Cannot start TCP listener - %s", e.getMessage());
            listening = false;
            return;
        }

        listener = Thread.currentThread();
        listening = true;
        try {

            // Infinite loop, taking care of resources in case of a lot of
            // parallel logins
            listening = true;
            while (listening) {
                Socket incoming;
                try {
                    incoming = serverSocket.accept();
                }
                catch (SocketTimeoutException e) {
                    continue;
                }
                logger.debug("Making new connection {}", incoming.toString());
                if (listening) {
                    TCPSlaveConnection slave =  new TCPSlaveConnection(incoming, useRtuOverTcp);
                    slave.setTimeout(timeout);
                    threadPool.execute(new TCPConnectionHandler(this, slave));
                }
                else {
                    incoming.close();
                }
{'fraction_non_alphanumeric': 0.08139332870048645, 'fraction_numerical': 0.006949270326615705, 'mean_word_length': 2.0522269353128313, 'pattern_counts': {'":': 0, '<': 33, '<?xml version=': 0, '>': 33, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 4, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3227827', 'n_tokens_mistral': 3025, 'n_tokens_neox': 2926, 'n_words': 1018}