Search in sources :

Example 1 with I2PServerSocket

use of net.i2p.client.streaming.I2PServerSocket in project i2p.i2p by i2p.

the class ConnectionAcceptor method run2.

private void run2() {
    while (!stop) {
        I2PServerSocket serverSocket = _util.getServerSocket();
        while ((serverSocket == null) && (!stop)) {
            if (!(_util.isConnecting() || _util.connected())) {
                stop = true;
                break;
            }
            try {
                Thread.sleep(10 * 1000);
            } catch (InterruptedException ie) {
            }
            serverSocket = _util.getServerSocket();
        }
        if (stop)
            break;
        try {
            I2PSocket socket = serverSocket.accept();
            if (socket == null) {
                continue;
            } else {
                if (socket.getPeerDestination().equals(_util.getMyDestination())) {
                    _log.error("Incoming connection from myself");
                    try {
                        socket.close();
                    } catch (IOException ioe) {
                    }
                    continue;
                }
                Hash h = socket.getPeerDestination().calculateHash();
                if (socket.getLocalPort() == 80) {
                    _badCounter.increment(h);
                    if (_log.shouldLog(Log.WARN))
                        _log.error("Dropping incoming HTTP from " + h);
                    try {
                        socket.close();
                    } catch (IOException ioe) {
                    }
                    continue;
                }
                int bad = _badCounter.count(h);
                if (bad >= MAX_BAD) {
                    if (_log.shouldLog(Log.WARN))
                        _log.warn("Rejecting connection from " + h + " after " + bad + " failures, max is " + MAX_BAD);
                    try {
                        socket.close();
                    } catch (IOException ioe) {
                    }
                    continue;
                }
                Thread t = new I2PAppThread(new Handler(socket), "I2PSnark incoming connection");
                t.start();
            }
        } catch (I2PException ioe) {
            int level = stop ? Log.WARN : Log.ERROR;
            if (_log.shouldLog(level))
                _log.log(level, "Error while accepting", ioe);
            synchronized (this) {
                if (!stop) {
                    locked_halt();
                    thread = null;
                    stop = true;
                }
            }
        } catch (ConnectException ioe) {
            // which does not currently call our halt(), although it should
            if (_log.shouldWarn())
                _log.warn("Error while accepting", ioe);
            synchronized (this) {
                if (!stop) {
                    locked_halt();
                    thread = null;
                    stop = true;
                }
            }
        } catch (IOException ioe) {
            int level = stop ? Log.WARN : Log.ERROR;
            if (_log.shouldLog(level))
                _log.log(level, "Error while accepting", ioe);
            synchronized (this) {
                if (!stop) {
                    locked_halt();
                    thread = null;
                    stop = true;
                }
            }
        }
    // catch oom?
    }
    if (_log.shouldLog(Log.WARN))
        _log.warn("ConnectionAcceptor closed");
}
Also used : I2PException(net.i2p.I2PException) I2PSocket(net.i2p.client.streaming.I2PSocket) IOException(java.io.IOException) I2PServerSocket(net.i2p.client.streaming.I2PServerSocket) Hash(net.i2p.data.Hash) I2PAppThread(net.i2p.util.I2PAppThread) I2PAppThread(net.i2p.util.I2PAppThread) ConnectException(java.net.ConnectException)

Example 2 with I2PServerSocket

use of net.i2p.client.streaming.I2PServerSocket in project i2p.i2p by i2p.

the class ConnectionAcceptor method locked_halt.

/**
 *  Caller must synch
 *  @since 0.9.9
 */
private void locked_halt() {
    I2PServerSocket ss = _util.getServerSocket();
    if (ss != null) {
        try {
            ss.close();
        } catch (I2PException ioe) {
        }
    }
    _badCounter.clear();
    _cleaner.cancel();
}
Also used : I2PException(net.i2p.I2PException) I2PServerSocket(net.i2p.client.streaming.I2PServerSocket)

Example 3 with I2PServerSocket

use of net.i2p.client.streaming.I2PServerSocket in project i2p.i2p by i2p.

the class MUXlisten method run.

/**
 * MUX sockets, fire off a thread to connect, get destination info, and do I/O
 */
public void run() {
    I2PServerSocket SS = null;
    Thread t = null;
    Thread q = null;
    try {
        wlock();
        try {
            try {
                info.add("RUNNING", Boolean.TRUE);
            } catch (Exception e) {
                lock.set(false);
                return;
            }
        } catch (Exception e) {
            lock.set(false);
            return;
        } finally {
            wunlock();
        }
        lives.set(true);
        lock.set(false);
        quit: {
            try {
                tg = new ThreadGroup(N);
                {
                    if (go_out) {
                        // I2P -> TCP
                        SS = socketManager.getServerSocket();
                        I2Plistener conn = new I2Plistener(SS, socketManager, info, database, _log, lives);
                        t = new I2PAppThread(tg, conn, "BOBI2Plistener " + N);
                        t.start();
                    }
                    if (come_in) {
                        // TCP -> I2P
                        TCPlistener conn = new TCPlistener(listener, socketManager, info, database, _log, lives);
                        q = new I2PAppThread(tg, conn, "BOBTCPlistener " + N);
                        q.start();
                    }
                    wlock();
                    try {
                        try {
                            info.add("STARTING", Boolean.FALSE);
                        } catch (Exception e) {
                            break quit;
                        }
                    } catch (Exception e) {
                        break quit;
                    } finally {
                        wunlock();
                    }
                    boolean spin = true;
                    while (spin && lives.get()) {
                        try {
                            // sleep for 1 second
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            break quit;
                        }
                        rlock();
                        try {
                            try {
                                spin = info.get("STOPPING").equals(Boolean.FALSE);
                            } catch (Exception e) {
                                break quit;
                            }
                        } catch (Exception e) {
                            break quit;
                        } finally {
                            runlock();
                        }
                    }
                }
            // die
            } catch (Exception e) {
                // System.out.println("MUXlisten: Caught an exception" + e);
                break quit;
            }
        }
    // quit
    } finally {
        lives.set(false);
        // Some grace time.
        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
        }
        try {
            wlock();
            try {
                info.add("STARTING", Boolean.FALSE);
                info.add("STOPPING", Boolean.TRUE);
                info.add("RUNNING", Boolean.FALSE);
            } catch (Exception e) {
                lock.set(false);
                return;
            }
        } catch (Exception e) {
        } finally {
            wunlock();
        }
        // Start cleanup.
        while (!lock.compareAndSet(false, true)) {
        // wait
        }
        if (SS != null) {
            try {
                SS.close();
            } catch (I2PException ex) {
            }
        }
        if (listener != null) {
            try {
                listener.close();
            } catch (IOException e) {
            }
        }
        // Some grace time.
        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
        }
        // Hopefully nuke stuff here...
        {
            String groupName = tg.getName();
            try {
                _log.warn("destroySocketManager " + groupName);
                socketManager.destroySocketManager();
                _log.warn("destroySocketManager Successful" + groupName);
            } catch (Exception e) {
                // nop
                _log.warn("destroySocketManager Failed" + groupName);
                _log.warn(e.toString());
            }
        }
        // zero out everything.
        try {
            wlock();
            try {
                info.add("STARTING", Boolean.FALSE);
                info.add("STOPPING", Boolean.FALSE);
                info.add("RUNNING", Boolean.FALSE);
            } catch (Exception e) {
                lock.set(false);
                return;
            } finally {
                wunlock();
            }
        } catch (Exception e) {
        }
        // Should we force waiting for all threads??
        lock.set(false);
        // Wait around till all threads are collected.
        if (tg != null) {
            String groupName = tg.getName();
            // System.out.println("BOB: MUXlisten: Starting thread collection for: " + groupName);
            _log.warn("BOB: MUXlisten: Starting thread collection for: " + groupName);
            if (tg.activeCount() + tg.activeGroupCount() != 0) {
                // visit(tg, 0, groupName);
                int foo = tg.activeCount() + tg.activeGroupCount();
                // Happily spin forever :-(
                while (foo != 0) {
                    foo = tg.activeCount() + tg.activeGroupCount();
                    // bar = lives;
                    try {
                        // sleep for 100 ms (One tenth second)
                        Thread.sleep(100);
                    } catch (InterruptedException ex) {
                    // nop
                    }
                }
            }
            // System.out.println("BOB: MUXlisten: Threads went away. Success: " + groupName);
            _log.warn("BOB: MUXlisten: Threads went away. Success: " + groupName);
            tg.destroy();
            // Zap reference to the ThreadGroup so the JVM can GC it.
            tg = null;
        }
        try {
            socketManager.destroySocketManager();
        } catch (Exception e) {
        // nop
        }
    }
}
Also used : I2PException(net.i2p.I2PException) IOException(java.io.IOException) I2PServerSocket(net.i2p.client.streaming.I2PServerSocket) IOException(java.io.IOException) I2PException(net.i2p.I2PException) I2PAppThread(net.i2p.util.I2PAppThread) I2PAppThread(net.i2p.util.I2PAppThread)

Example 4 with I2PServerSocket

use of net.i2p.client.streaming.I2PServerSocket in project i2p.i2p by i2p.

the class I2PTunnelServer method run.

/**
 *  If usePool is set, this starts the executor pool.
 *  Then, do the accept() loop, and either
 *  hands each I2P socket to the executor or runs it in-line.
 */
public void run() {
    i2pss = sockMgr.getServerSocket();
    if (_log.shouldLog(Log.WARN)) {
        if (_usePool)
            _log.warn("Starting executor with " + getHandlerCount() + " threads max");
        else
            _log.warn("Threads disabled, running blockingHandles inline");
    }
    if (_usePool) {
        _executor = new CustomThreadPoolExecutor(getHandlerCount(), "ServerHandler pool " + remoteHost + ':' + remotePort);
    }
    TunnelControllerGroup tcg = TunnelControllerGroup.getInstance();
    if (tcg != null) {
        _clientExecutor = tcg.getClientExecutor();
    } else {
        // Fallback in case TCG.getInstance() is null, never instantiated
        // and we were not started by TCG.
        // Maybe a plugin loaded before TCG? Should be rare.
        // Never shut down.
        _clientExecutor = new TunnelControllerGroup.CustomThreadPoolExecutor();
    }
    I2PSocket i2ps = null;
    while (open) {
        try {
            i2ps = null;
            I2PServerSocket ci2pss = i2pss;
            if (ci2pss == null)
                throw new I2PException("I2PServerSocket closed");
            // returns non-null as of 0.9.17
            i2ps = ci2pss.accept();
            if (_usePool) {
                try {
                    _executor.execute(new Handler(i2ps));
                } catch (RejectedExecutionException ree) {
                    try {
                        i2ps.reset();
                    } catch (IOException ioe) {
                    }
                    if (open)
                        _log.logAlways(Log.WARN, "ServerHandler queue full, dropping incoming connection to " + remoteHost + ':' + remotePort + "; increase server max threads or " + PROP_HANDLER_COUNT + "; current is " + getHandlerCount());
                }
            } else {
                // use only for standard servers that can't get slowlorissed! Not for http or irc
                blockingHandle(i2ps);
            }
        } catch (RouterRestartException rre) {
            // Delay and loop if router is soft restarting
            _log.logAlways(Log.WARN, "Waiting for router restart");
            if (i2ps != null)
                try {
                    i2ps.close();
                } catch (IOException ioe) {
                }
            try {
                Thread.sleep(2 * 60 * 1000);
            } catch (InterruptedException ie) {
            }
            // This should be the same as before, but we have to call getServerSocket()
            // so sockMgr will call ConnectionManager.setAllowIncomingConnections(true) again
            i2pss = sockMgr.getServerSocket();
        } catch (I2PException ipe) {
            if (_log.shouldLog(Log.ERROR))
                _log.error("Error accepting - KILLING THE TUNNEL SERVER", ipe);
            open = false;
            if (i2ps != null)
                try {
                    i2ps.close();
                } catch (IOException ioe) {
                }
            break;
        } catch (ConnectException ce) {
            if (_log.shouldLog(Log.ERROR))
                _log.error("Error accepting", ce);
            open = false;
            if (i2ps != null)
                try {
                    i2ps.close();
                } catch (IOException ioe) {
                }
            break;
        } catch (SocketTimeoutException ste) {
            // ignored, we never set the timeout
            if (i2ps != null)
                try {
                    i2ps.close();
                } catch (IOException ioe) {
                }
        } catch (RuntimeException e) {
            // streaming borkage
            if (_log.shouldLog(Log.ERROR))
                _log.error("Uncaught exception accepting", e);
            if (i2ps != null)
                try {
                    i2ps.close();
                } catch (IOException ioe) {
                }
            // not killing the server..
            try {
                Thread.sleep(500);
            } catch (InterruptedException ie) {
            }
        }
    }
    if (_executor != null && !_executor.isTerminating() && !_executor.isShutdown())
        _executor.shutdownNow();
}
Also used : I2PException(net.i2p.I2PException) I2PSocket(net.i2p.client.streaming.I2PSocket) RouterRestartException(net.i2p.client.streaming.RouterRestartException) IOException(java.io.IOException) I2PServerSocket(net.i2p.client.streaming.I2PServerSocket) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) SocketTimeoutException(java.net.SocketTimeoutException) ConnectException(java.net.ConnectException)

Example 5 with I2PServerSocket

use of net.i2p.client.streaming.I2PServerSocket in project i2p.i2p by i2p.

the class Snark method x_startTorrent.

private void x_startTorrent() {
    boolean ok = _util.connect();
    if (!ok)
        fatal("Unable to connect to I2P");
    if (coordinator == null) {
        I2PServerSocket serversocket = _util.getServerSocket();
        if (serversocket == null)
            fatal("Unable to listen for I2P connections");
        else {
            Destination d = serversocket.getManager().getSession().getMyDestination();
            if (_log.shouldLog(Log.INFO))
                _log.info("Listening on I2P destination " + d.toBase64() + " / " + d.calculateHash().toBase64());
        }
        if (_log.shouldLog(Log.INFO))
            _log.info("Starting PeerCoordinator, ConnectionAcceptor, and TrackerClient");
        activity = "Collecting pieces";
        coordinator = new PeerCoordinator(_util, id, infoHash, meta, storage, this, this);
        coordinator.setUploaded(savedUploaded);
        if (_peerCoordinatorSet != null) {
            // multitorrent
            _peerCoordinatorSet.add(coordinator);
        } else {
            // single torrent
            acceptor = new ConnectionAcceptor(_util, new PeerAcceptor(coordinator));
        }
        // TODO pass saved closest DHT nodes to the tracker? or direct to the coordinator?
        trackerclient = new TrackerClient(_util, meta, additionalTrackerURL, coordinator, this);
    }
    // ensure acceptor is running when in multitorrent
    if (_peerCoordinatorSet != null && acceptor != null) {
        acceptor.startAccepting();
    }
    stopped = false;
    if (coordinator.halted()) {
        coordinator.restart();
        if (_peerCoordinatorSet != null)
            _peerCoordinatorSet.add(coordinator);
    }
    if (!trackerclient.started()) {
        trackerclient.start();
    } else if (trackerclient.halted()) {
        if (storage != null) {
            try {
                storage.reopen();
            } catch (IOException ioe) {
                try {
                    storage.close();
                } catch (IOException ioee) {
                    ioee.printStackTrace();
                }
                fatal("Could not reopen storage", ioe);
            }
        }
        trackerclient.start();
    } else {
        if (_log.shouldLog(Log.INFO))
            _log.info("NOT starting TrackerClient???");
    }
}
Also used : Destination(net.i2p.data.Destination) IOException(java.io.IOException) I2PServerSocket(net.i2p.client.streaming.I2PServerSocket)

Aggregations

I2PServerSocket (net.i2p.client.streaming.I2PServerSocket)6 I2PException (net.i2p.I2PException)5 IOException (java.io.IOException)4 ConnectException (java.net.ConnectException)2 I2PSocket (net.i2p.client.streaming.I2PSocket)2 I2PAppThread (net.i2p.util.I2PAppThread)2 InterruptedIOException (java.io.InterruptedIOException)1 SocketTimeoutException (java.net.SocketTimeoutException)1 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)1 RouterRestartException (net.i2p.client.streaming.RouterRestartException)1 Destination (net.i2p.data.Destination)1 Hash (net.i2p.data.Hash)1