Search in sources :

Example 21 with I2PSocket

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

the class I2PTunnelDCCServer method expireOutbound.

private void expireOutbound() {
    for (Iterator<LocalAddress> iter = _outgoing.values().iterator(); iter.hasNext(); ) {
        LocalAddress a = iter.next();
        if (a.expire < getTunnel().getContext().clock().now())
            iter.remove();
    }
    for (Iterator<LocalAddress> iter = _active.values().iterator(); iter.hasNext(); ) {
        LocalAddress a = iter.next();
        I2PSocket s = a.socket;
        if (s != null && s.isClosed())
            iter.remove();
    }
}
Also used : I2PSocket(net.i2p.client.streaming.I2PSocket)

Example 22 with I2PSocket

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

the class I2PSOCKSIRCTunnel method clientConnectionRun.

/**
 *  Same as in I2PSOCKSTunnel, but run the filters from I2PTunnelIRCClient
 *  instead of I2PTunnelRunner
 */
@Override
protected void clientConnectionRun(Socket s) {
    I2PSocket destSock = null;
    try {
        // _log.error("SOCKS IRC Tunnel Start");
        try {
            s.setSoTimeout(INITIAL_SO_TIMEOUT);
        } catch (SocketException ioe) {
        }
        SOCKSServer serv = SOCKSServerFactory.createSOCKSServer(_context, s, getTunnel().getClientOptions());
        Socket clientSock = serv.getClientSocket();
        try {
            s.setSoTimeout(0);
        } catch (SocketException ioe) {
        }
        destSock = serv.getDestinationI2PSocket(this);
        StringBuffer expectedPong = new StringBuffer();
        int id = __clientId.incrementAndGet();
        Thread in = new I2PAppThread(new IrcInboundFilter(clientSock, destSock, expectedPong, _log), "SOCKS IRC Client " + id + " in", true);
        in.start();
        // Thread out = new I2PAppThread(new IrcOutboundFilter(clientSock, destSock, expectedPong, _log),
        // "SOCKS IRC Client " + id + " out", true);
        Runnable out = new IrcOutboundFilter(clientSock, destSock, expectedPong, _log);
        // we are called from an unlimited thread pool, so run inline
        // out.start();
        out.run();
    } catch (SOCKSException e) {
        if (_log.shouldLog(Log.WARN))
            _log.warn("Error from SOCKS connection", e);
    } finally {
        // only because we are running it inline
        closeSocket(s);
        if (destSock != null)
            try {
                destSock.close();
            } catch (IOException ioe) {
            }
    }
}
Also used : SocketException(java.net.SocketException) I2PSocket(net.i2p.client.streaming.I2PSocket) SOCKSException(net.i2p.socks.SOCKSException) IOException(java.io.IOException) I2PAppThread(net.i2p.util.I2PAppThread) I2PAppThread(net.i2p.util.I2PAppThread) IrcOutboundFilter(net.i2p.i2ptunnel.irc.IrcOutboundFilter) IrcInboundFilter(net.i2p.i2ptunnel.irc.IrcInboundFilter) Socket(java.net.Socket) I2PSocket(net.i2p.client.streaming.I2PSocket)

Example 23 with I2PSocket

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

the class SOCKS5Server method getDestinationI2PSocket.

/**
 * Get an I2PSocket that can be used to send/receive 8-bit clean data
 * to/from the destination of the SOCKS connection.
 *
 * @return an I2PSocket connected with the destination
 */
public I2PSocket getDestinationI2PSocket(I2PSOCKSTunnel t) throws SOCKSException {
    setupServer();
    if (connHostName == null) {
        _log.error("BUG: destination host name has not been initialized!");
        throw new SOCKSException("BUG! See the logs!");
    }
    if (connPort == 0) {
        _log.error("BUG: destination port has not been initialized!");
        throw new SOCKSException("BUG! See the logs!");
    }
    // for errors
    DataOutputStream out;
    try {
        out = new DataOutputStream(clientSock.getOutputStream());
    } catch (IOException e) {
        throw new SOCKSException("Connection error", e);
    }
    // FIXME: here we should read our config file, select an
    // outproxy, and instantiate the proper socket class that
    // handles the outproxy itself (SOCKS4a, SOCKS5, HTTP CONNECT...).
    I2PSocket destSock;
    try {
        if (connHostName.toLowerCase(Locale.US).endsWith(".i2p")) {
            // Let's not do a new Dest for every request, huh?
            // I2PSocketManager sm = I2PSocketManagerFactory.createManager();
            // destSock = sm.connect(I2PTunnel.destFromName(connHostName), null);
            Destination dest = _context.namingService().lookup(connHostName);
            if (dest == null) {
                try {
                    sendRequestReply(Reply.HOST_UNREACHABLE, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
                } catch (IOException ioe) {
                }
                throw new SOCKSException("Host not found");
            }
            if (_log.shouldDebug())
                _log.debug("connecting to " + connHostName + "...");
            Properties overrides = new Properties();
            I2PSocketOptions sktOpts = t.buildOptions(overrides);
            sktOpts.setPort(connPort);
            destSock = t.createI2PSocket(dest, sktOpts);
        } else if ("localhost".equals(connHostName) || "127.0.0.1".equals(connHostName)) {
            String err = "No localhost accesses allowed through the Socks Proxy";
            _log.error(err);
            try {
                sendRequestReply(Reply.CONNECTION_NOT_ALLOWED_BY_RULESET, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
            } catch (IOException ioe) {
            }
            throw new SOCKSException(err);
        /**
         **
         *            } else if (connPort == 80) {
         *                // rewrite GET line to include hostname??? or add Host: line???
         *                // or forward to local eepProxy (but that's a Socket not an I2PSocket)
         *                // use eepProxy configured outproxies?
         *                String err = "No handler for HTTP outproxy implemented";
         *                _log.error(err);
         *                try {
         *                    sendRequestReply(Reply.CONNECTION_NOT_ALLOWED_BY_RULESET, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
         *                } catch (IOException ioe) {}
         *                throw new SOCKSException(err);
         ***
         */
        } else {
            Outproxy outproxy = getOutproxyPlugin();
            if (outproxy != null) {
                // but here, we wrap a Socket in a I2PSocket and use the regular Runner.
                try {
                    destSock = new SocketWrapper(outproxy.connect(connHostName, connPort));
                } catch (IOException ioe) {
                    try {
                        sendRequestReply(Reply.HOST_UNREACHABLE, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
                    } catch (IOException ioe2) {
                    }
                    throw new SOCKSException("connect failed via outproxy plugin", ioe);
                }
            } else {
                List<String> proxies = t.getProxies(connPort);
                if (proxies == null || proxies.isEmpty()) {
                    String err = "No outproxy configured for port " + connPort + " and no default configured either";
                    _log.error(err);
                    try {
                        sendRequestReply(Reply.CONNECTION_NOT_ALLOWED_BY_RULESET, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
                    } catch (IOException ioe) {
                    }
                    throw new SOCKSException(err);
                }
                int p = _context.random().nextInt(proxies.size());
                String proxy = proxies.get(p);
                if (_log.shouldLog(Log.DEBUG))
                    _log.debug("connecting to proxy " + proxy + " for " + connHostName + " port " + connPort);
                try {
                    destSock = outproxyConnect(t, proxy);
                } catch (SOCKSException se) {
                    try {
                        sendRequestReply(Reply.HOST_UNREACHABLE, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
                    } catch (IOException ioe) {
                    }
                    throw se;
                }
            }
        }
        confirmConnection();
        _log.debug("connection confirmed - exchanging data...");
    } catch (DataFormatException e) {
        if (_log.shouldLog(Log.WARN))
            _log.warn("socks error", e);
        try {
            sendRequestReply(Reply.HOST_UNREACHABLE, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
        } catch (IOException ioe) {
        }
        throw new SOCKSException("Error in destination format");
    } catch (IOException e) {
        if (_log.shouldLog(Log.WARN))
            _log.warn("socks error", e);
        try {
            sendRequestReply(Reply.HOST_UNREACHABLE, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
        } catch (IOException ioe) {
        }
        throw new SOCKSException("Connection error", e);
    } catch (I2PException e) {
        if (_log.shouldLog(Log.WARN))
            _log.warn("socks error", e);
        try {
            sendRequestReply(Reply.HOST_UNREACHABLE, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
        } catch (IOException ioe) {
        }
        throw new SOCKSException("Connection error", e);
    }
    return destSock;
}
Also used : I2PException(net.i2p.I2PException) Destination(net.i2p.data.Destination) DataOutputStream(java.io.DataOutputStream) SOCKSException(net.i2p.socks.SOCKSException) I2PSocket(net.i2p.client.streaming.I2PSocket) Outproxy(net.i2p.app.Outproxy) I2PSocketOptions(net.i2p.client.streaming.I2PSocketOptions) IOException(java.io.IOException) Properties(java.util.Properties) DataFormatException(net.i2p.data.DataFormatException) ArrayList(java.util.ArrayList) List(java.util.List)

Example 24 with I2PSocket

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

the class I2PTunnelClientBase method createI2PSocket.

/**
 * Create a new I2PSocket towards to the specified destination,
 * adding it to the list of connections actually managed by this
 * tunnel.
 *
 * @param dest The destination to connect to, non-null
 * @param opt Option to be used to open when opening the socket
 * @return a new I2PSocket
 *
 * @throws ConnectException if the peer refuses the connection
 * @throws NoRouteToHostException if the peer is not found or not reachable
 * @throws InterruptedIOException if the connection timeouts
 * @throws I2PException if there is some other I2P-related problem
 */
public I2PSocket createI2PSocket(Destination dest, I2PSocketOptions opt) throws I2PException, ConnectException, NoRouteToHostException, InterruptedIOException {
    if (dest == null)
        throw new NullPointerException();
    I2PSocket i2ps;
    verifySocketManager();
    i2ps = sockMgr.connect(dest, opt);
    synchronized (sockLock) {
        mySockets.add(i2ps);
    }
    return i2ps;
}
Also used : I2PSocket(net.i2p.client.streaming.I2PSocket)

Example 25 with I2PSocket

use of net.i2p.client.streaming.I2PSocket 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)

Aggregations

I2PSocket (net.i2p.client.streaming.I2PSocket)28 IOException (java.io.IOException)21 I2PException (net.i2p.I2PException)15 Destination (net.i2p.data.Destination)12 Socket (java.net.Socket)8 I2PSocketOptions (net.i2p.client.streaming.I2PSocketOptions)8 I2PAppThread (net.i2p.util.I2PAppThread)7 SocketException (java.net.SocketException)6 Properties (java.util.Properties)5 SOCKSException (net.i2p.socks.SOCKSException)5 InterruptedIOException (java.io.InterruptedIOException)4 OutputStream (java.io.OutputStream)4 ConnectException (java.net.ConnectException)4 SocketTimeoutException (java.net.SocketTimeoutException)4 Outproxy (net.i2p.app.Outproxy)4 Hash (net.i2p.data.Hash)4 DataOutputStream (java.io.DataOutputStream)3 InputStream (java.io.InputStream)3 List (java.util.List)3 I2PSession (net.i2p.client.I2PSession)3