- All Implemented Interfaces:
Runnable, EventDispatcher
HTTP proxy reusing server's I2PSocketManager without outproxy capability.
Nested Class Summary
Nested classes/interfaces inherited from class I2PTunnelHTTPClient
I2PTunnelHTTPClient.WarmSlotModifier and TypeClassDescription(package private) static final classRequest-scoped state machine for one speculative warm socket.Nested classes/interfaces inherited from class I2PTunnelHTTPClientBase
I2PTunnelHTTPClientBase.AuthResult, I2PTunnelHTTPClientBase.OnProxySuccess, I2PTunnelHTTPClientBase.OnTimeoutModifier and TypeClassDescriptionprotected static enumAuthentication result status for HTTP client connections.protected classCallback for successful proxy connections.protected classCallback for timeout events.Field Summary
Fields inherited from class I2PTunnelHTTPClient
AUTH_REALM, BROWSER_KEEPALIVE_TIMEOUT, DEFAULT_JUMP_SERVERS, I2P_CONNECT_MAX_RETRIES, I2P_CONNECT_RETRY_BASE_DELAY, LOCAL_SERVER, NAMING_IN_SESSION_TIMEOUT_MS, NAMING_SERVICE_TIMEOUT_MS, OPT_EMPTY_RETRIES, OPT_KEEPALIVE_BROWSER, OPT_KEEPALIVE_I2P, PROP_ACCEPT, PROP_DISABLE_HELPER, PROP_INTERNAL_SSL, PROP_JUMP_SERVERS, PROP_REFERER, PROP_SSL_SET, PROP_USER_AGENT, PROP_VIAModifier and TypeFieldDescriptionstatic final StringHTTP authentication realm for HTTP proxy.(package private) static final intHow long to wait for another request on the same socket.static final StringDefault jump server URLs.(package private) static final intTotal connect attempts before the client stops retrying and fails the request.(package private) static final longBackoff floor and per-attempt multiply base for I2P connect retries.static final StringLocal HTTP proxy server hostname.(package private) static final longIn-session b32/b33 naming lookup budget, clamped to the shared request connect deadline so naming cannot outlive the request.(package private) static final longNaming-service lookup budget for out-of-session and hostname lookups, clamped to the shared request connect deadline.static final StringConfig key: max reconnects on a zero-byte (empty) upstream response for GET/HEAD.static final StringConfig key to enable browser-side keepalive.static final StringConfig key to enable I2P-side keepalive.static final StringConfig key: false, the default, replaces the browser's Accept header with a generic value for the content types it names; true forwards it unchanged.static final StringConfig key to disable address helper.static final StringConfig key: false denies SSL to I2P destinations, but only once PROP_SSL_SET shows the user configured SSL by hand.static final StringConfig key for jump server list.static final StringAll default to false.static final StringConfig key: set when the user configures SSL by hand.static final StringConfig key to enable sending User-Agent header.static final StringConfig key to enable sending Via header.Fields inherited from class I2PTunnelHTTPClientBase
__requestId, _proxyList, BASIC_AUTH, BROWSER_READ_TIMEOUT, DEFAULT_READ_TIMEOUT, DIGEST_AUTH, ERR_DESTINATION_UNKNOWN, INITIAL_SO_TIMEOUT, PROP_AUTH, PROP_OUTPROXY_AUTH, PROP_OUTPROXY_PW, PROP_OUTPROXY_PW_PREFIX, PROP_OUTPROXY_USER, PROP_OUTPROXY_USER_PREFIX, PROP_PROXY_DIGEST_PREFIX, PROP_PROXY_DIGEST_SHA256_SUFFIX, PROP_PROXY_DIGEST_SUFFIX, PROP_PW, PROP_PW_PREFIX, PROP_SSL_OUTPROXIES, PROP_USE_OUTPROXY_PLUGIN, PROP_USER, SHED_COOKIE, SHED_MAX_REFRESH, SHED_READ_TIMEOUT_MS, SHED_REFRESH_SECONDS, SUCCESS_RESPONSEModifier and TypeFieldDescriptionprotected static final AtomicLongCounter for unique request IDs.List of configured outproxies.static final StringBasic auth type constant.protected static final intSocket read timeout for a browser fetch, four hours as a failsafe.protected static final int-1 (forever) as of 0.9.36, so that large POSTs won't timeout on the read side.static final StringDigest auth type constant.protected static final StringError response when destination is not found.protected static final intThis is a standard soTimeout, not a total timeout.static final StringAll auth.static final StringOutproxy auth property.static final StringOutproxy password property.static final StringOutproxy password property prefix.static final StringOutproxy username property.static final StringPasswords for specific outproxies may be added withoutproxyUsername.fooproxy.i2p=user andoutproxyPassword.fooproxy.i2p=pw.static final StringNew style MD5 auth.static final StringSHA-256 digest suffix.static final StringMD5 digest suffix.static final StringProxy password property.static final StringAdditional users may be added with proxyPassword.user=pw.static final StringProperty for SSL outproxies.static final StringProperty to use local outproxy plugin.static final StringProxy username property.(package private) static final StringCookie that counts meta-refresh retries on a shed connection.(package private) static final intHow many meta-refresh pages to serve before the final 503.(package private) static final intShort SO_TIMEOUT while reading the shed request head (never on the hot path).(package private) static final intRefresh delay in seconds for the intermediate shed page.protected static final StringHTTP 200 response for established CONNECT tunnels.Fields inherited from class I2PTunnelClientBase
_clientId, _context, _executor, _log, _ownDest, DEFAULT_CONNECT_TIMEOUT, DEFAULT_MAX_CONNECTIONS, DEFAULT_SOCKET_OPEN_TIMEOUT, dest, l, listenerReady, MAX_TIMEOUT_FAILOVER, MIN_CONNECT_LEG_MS, mySockets, NO_DEADLINE, POOL_BUILD_DEADLINE_GRACE_MS, PROP_MAX_CONNECTIONS, PROP_USE_SSL, REQUEST_CONNECT_DEADLINE_MS, sockLock, sockMgr, ssModifier and TypeFieldDescriptionprotected longThis client's ID.protected final I2PAppContextThe application context.protected ThreadPoolExecutorThread pool executor.protected final LogThe logger.protected booleanWhether we own our destination.(package private) static final longDefault connect timeout.static final intDefault cap on concurrently handled client connections.static final longDefault socket open timeout in ms, after whichI2PTunnelClientBase.close(boolean)will proceed even with active sockets.protected DestinationThe destination.protected final LoggingThe logging instance.protected booleanProtected for I2Ping since 0.9.11.(package private) static final intLegacy cap on consecutive connect timeouts before abandoning tunnel failover.(package private) static final longMinimum remaining budget for starting one connect leg.List of active sockets.(package private) static final longDeadline sentinel for callers that have not adopted the shared request budget (SOCKS, IRC, DCC, rawcreateI2PSocket): they keep their original per-call limits because this sentinel never reads as expired and never clamps.(package private) static final longOne-shot deadline extension granted while the outbound tunnel pool is still building (poolState() == 0) when the shared budget runs out.static final StringProperty name: max concurrently active client connections handled by one client tunnel.static final StringProperty turning on SSL between the proxy and the client.(package private) static final longSingle wall-clock budget for establishing one proxied request.protected final ObjectGuards sockMgr and mySockets.protected I2PSocketManagerThe socket manager.protected ServerSocketServer socket.Constructor Summary
ConstructorsConstructorDescriptionI2PTunnelHTTPBidirProxy(int localPort, Logging l, I2PSocketManager sockMgr, I2PTunnel tunnel, EventDispatcher notifyThis, long clientId) Create a bidirectional HTTP proxy tunnel on localPort, reusing the server's existing I2P socket manager.Method Summary
Methods inherited from class I2PTunnelHTTPClient
cancelWarmSlot, clientConnectionRun, close, fixupURI, getConnectRetryDelayMs, getDefaultOptions, getDefaultOptions, getRealm, isBrowserPeerClosed, parseEmptyRetries, scaledEmptyReconnectBudget, shouldStopEmptyReconnect, sleepQuietly, startRunning, writeServiceUnavailableModifier and TypeMethodDescription(package private) static voidRetire a request's warm slot: closes an installed socket, releases the permit the slot still holds, and rejects an attempt still in flight (its thread releases the lease when the install is refused).protected voidNote: This does not handle RFC 2616 header line splitting, which is obsoleted in RFC 7230.booleanclose(boolean forced) Overridden to close internal socket too.(package private) static URIFix up a URI whose path or query holds characters that RFC 3986 reserves but that browsers send unescaped: '[', ']', '|', '{' and '}'.(package private) static longgetConnectRetryDelayMs(int attempt) Exponential backoff delay (in ms) before the given connect retry.protected I2PSocketOptionsCreate the default options (using the default timeout, etc).protected I2PSocketOptionsgetDefaultOptions(Properties overrides) Create the default options (using the default timeout, etc).protected StringgetRealm()Authentication realm for the proxy.(package private) static booleanisBrowserPeerClosed(Socket s, I2PTunnelHTTPClient.InputReader reader, String method) Probe whether the browser peer has closed while we wait on I2P connect.(package private) static intparseEmptyRetries(String value) Parse the empty-response retry count from a client option value.(package private) static intscaledEmptyReconnectBudget(int baseBudget, long contentLength) Scale the reconnect attempt budget by the entity size already verified from this exchange's Content-Length header.(package private) static booleanshouldStopEmptyReconnect(int poolState) Whether the empty-response reconnect loop should stop instead of trying again.(package private) static booleansleepQuietly(long delayMs) Sleep for the given delay, restoring the interrupt flag if interrupted.voidActually start working on incoming connections.(package private) static voidwriteServiceUnavailable(OutputStream out, String message) Write a minimal 503 response and close the connection.Methods inherited from class I2PTunnelHTTPClientBase
_t, _t, _t, addrAndPort, authorize, buildShed503Response, buildShedRefreshResponse, decodeIDNHost, getAuthError, getErrorPage, getErrorPage, getPrefix, handleClientException, handleI2PSocketException, isBlockedIPv4Address, isBlockedLocalAddress, isDigestAuthRequired, noteProxyResult, optionsUpdated, parseShedAttempt, sanitizeAuthArgs, sanitizeLogValue, selectProxy, selectSSLProxy, shouldMetaRefresh, summarizeAuthorization, writeErrorMessage, writeErrorMessage, writeErrorMessage, writeErrorMessage, writeFooter, writeFooter, writeShedResponseModifier and TypeMethodDescriptionprotected StringLook up a translation key in this class's resource bundle.protected StringTranslate with one parameter {0}.protected StringTranslate with two parameters {0} and {1}.(package private) static StringFormat the remote address as IP:PORT for ban and failure logging.protected I2PTunnelHTTPClientBase.AuthResultAuthorization Ref: RFC 2617 If the socket is an InternalSocket, no auth required.(package private) static StringFinal shed response after refresh budget is exhausted (or non-HTML).(package private) static StringbuildShedRefreshResponse(int nextAttempt) Intermediate shed page: unquoted meta refresh (no nested quotes in the tag) plus a Set-Cookie bump so the browser retries at mostI2PTunnelHTTPClientBase.SHED_MAX_REFRESHtimes before the final 503.static StringdecodeIDNHost(String host) Decode a hostname for display.protected StringgetAuthError(boolean isStale) What to send if digest auth fails.protected StringgetErrorPage(String base, String backup) Load the error page header file, e.g.protected static StringgetErrorPage(I2PAppContext ctx, String base, String backup) Load the error page header file, e.g.protected StringgetPrefix(long requestId) Generates a unique log prefix for request tracking.protected voidhandleClientException(Exception ex, OutputStream out, String targetRequest, boolean usingWWWProxy, String wwwProxy, long requestId) Handle an exception from a client connection.protected voidhandleI2PSocketException(I2PSocketException ise, OutputStream out, String targetRequest, boolean usingWWWProxy, String wwwProxy) Generate an error page based on the status code in our custom exception.static booleanisBlockedIPv4Address(String host) Determine whether an IPv4 host is in a blocked non-routable block: loopback, "this network", RFC 1918 private, link-local, carrier-grade NAT, benchmarking, documentation, multicast, and reserved space.static booleanisBlockedLocalAddress(String host) Determine whether a proxy request target is a loopback, private, link-local, shared, or otherwise non-routable address that must not be reached through the proxy.protected booleanChecks if HTTP Digest authentication is required by the outproxy.protected voidnoteProxyResult(String proxy, String host, boolean isSSL, boolean ok) Update the cache and note if failed.voidoptionsUpdated(I2PTunnel tunnel) Update the outproxy list then call super.(package private) static intparseShedAttempt(String cookie) How many shed meta-refresh attempts the request's Cookie header already used.sanitizeAuthArgs(Map<String, String> args) Copy digest request arguments into a form safe to log: credential material is redacted, and every remaining value is stripped of line breaks and capped, so a hostile upstream cannot forge extra log lines or grow the log without bound.(package private) static StringsanitizeLogValue(String value) Strip line breaks and cap the length of an attacker-supplied value before it is written to the log, so a hostile username cannot forge extra log lines.protected StringselectProxy(String host) Selects an appropriate outproxy for the given host from the proxy pool.protected StringselectSSLProxy(String host) Selects an SSL-capable outproxy for HTTPS connections.(package private) static booleanshouldMetaRefresh(String method, String accept, int attempt) Whether a shed connection should get a meta-refresh page instead of a 503.(package private) static StringsummarizeAuthorization(String authorization) Summarize an Authorization header for logging without disclosing credential material.protected voidwriteErrorMessage(String errMessage, OutputStream out, String targetRequest, boolean usingWWWProxy, String wwwProxy) No jump servers or extra message.protected voidwriteErrorMessage(String errMessage, OutputStream out, String targetRequest, boolean usingWWWProxy, String wwwProxy, String jumpServers) No extra message.protected voidwriteErrorMessage(String errMessage, String extraMessage, OutputStream out, String targetRequest, boolean usingWWWProxy, String wwwProxy) No jump servers.protected voidwriteErrorMessage(String errMessage, String extraMessage, OutputStream outs, String targetRequest, boolean usingWWWProxy, String wwwProxy, String jumpServers) Write the complete error message to the output stream.static voidwriteFooter(OutputStream out) Write the closing HTML footer and flush it down the stream.static voidwriteFooter(Writer out) Write the closing HTML footer and flush it down the writer.protected voidWrite a real HTTP status on a shed connection so the browser never sees an empty response: HTML GET navigations get a cookie-capped meta-refresh page (up toI2PTunnelHTTPClientBase.SHED_MAX_REFRESHtimes), everything else gets a 503.Methods inherited from class I2PTunnelClientBase
buildSocketManager, buildSocketManager, buildSocketManager, buildSocketManager, clampToDeadlineMs, closeSocket, connectDeadlineFrom, createI2PSocket, createI2PSocket, createI2PSocket, createI2PSocket, destroy, extendDeadlineForBuildingPool, getEffectiveMaxConnections, getListenHost, getLocalPort, getSocketManager, getSocketManager, getSocketOpenTimeout, isConnectTimeout, isDeadlineExpired, legConnectTimeoutMs, manageConnection, poolIsDefinitivelyDown, poolState, resolveEffectiveMaxConnections, resolveMaxConnections, resolveRunnerCeiling, run, shouldContinueFailover, shouldContinueFailover, shouldOuterRetryConnect, shouldOuterRetryConnect, verifySocketManagerModifier and TypeMethodDescriptionprotected I2PSocketManagerFor NON-SHARED clients (ownDest = true).protected static I2PSocketManagerbuildSocketManager(I2PTunnel tunnel) Create a disconnected socket manager for the tunnel, with no private key file.protected static I2PSocketManagerbuildSocketManager(I2PTunnel tunnel, String pkf) Create a disconnected socket manager for the tunnel, loading the persistent client dest from pkf if it is non-null.protected static I2PSocketManagerbuildSocketManager(I2PTunnel tunnel, String pkf, Logging log) Create a disconnected socket manager for the tunnel, loading the persistent client dest from pkf if it is non-null, and logging any key file error to log.(package private) static longclampToDeadlineMs(long requestedMs, long deadlineMs, long nowMs) Clamp a requested timeout to the time left before a shared deadline.static voidClose a socket silently.(package private) static longconnectDeadlineFrom(long nowMs) Compute the shared connect deadline for a request starting now.createI2PSocket(Destination dest) Create a new I2PSocket towards to the specified destination, adding it to the list of connections actually managed by this tunnel.createI2PSocket(Destination dest, int port) Create a new I2PSocket towards to the specified destination, adding it to the list of connections actually managed by this tunnel.createI2PSocket(Destination dest, I2PSocketOptions opt) Create a new I2PSocket towards to the specified destination, adding it to the list of connections actually managed by this tunnel.(package private) I2PSocketcreateI2PSocket(Destination dest, I2PSocketOptions opt, long deadlineMs) Create a new I2PSocket bounded by a shared request deadline.booleandestroy()Note that the tunnel cannot be reopened after this by calling startRunning(), as it will destroy the underlying socket manager.(package private) static longextendDeadlineForBuildingPool(long deadlineMs, long nowMs, int poolState, boolean alreadyExtended) One-shot deadline extension for a request whose outbound tunnel pool is still building when the shared deadline runs out.(package private) intThe effective concurrent-connection cap for this tunnel at the moment the accept loop admits a connection.protected final InetAddressGet the listen host address.final intGet the local port.Returns the I2PSocketManager for this task.protected static I2PSocketManagergetSocketManager(I2PTunnel tunnel, String pkf) This is ONLY for shared clients.longReturns the socket open timeout in ms; close() will proceed after this even with active sockets.(package private) static booleanFor timeout wording.(package private) static booleanisDeadlineExpired(long deadlineMs, long nowMs) Whether a shared connect deadline has passed.(package private) static longlegConnectTimeoutMs(long requestedMs, long deadlineMs, long nowMs) Compute the connect timeout to apply to one failover leg under a shared deadline.protected voidManage the connection just opened on the specified socket.protected booleanAnd none are being built, so further connect retries cannot succeed.protected intRouter-context only, best-effort check of the client outbound tunnel pool.(package private) static intresolveEffectiveMaxConnections(boolean customized, int ownCap, int globalDefault) Pure decision helper forI2PTunnelClientBase.getEffectiveMaxConnections(): pick the per-tunnel override when one was explicitly configured, otherwise the Tuner-managed default cap.(package private) static intresolveMaxConnections(String configured) Resolve the max-concurrent-connections cap from the tunnel's configured value.(package private) static intresolveRunnerCeiling(boolean customized, int effectiveMax) Ceiling to pin on this tunnel's runner pool at creation time.voidrun()Non-final since 0.9.11.(package private) static booleanshouldContinueFailover(int tunnelCount, int attemptsMade, int timeoutFailures, boolean poolDown) Whether another tunnel-failover attempt is worthwhile after a connect failure.(package private) static booleanshouldContinueFailover(int tunnelCount, int attemptsMade, int timeoutFailures, boolean poolDown, boolean poolBuilding) Whether another tunnel-failover attempt is worthwhile after a connect failure.(package private) static booleanshouldOuterRetryConnect(int connectAttempts, int timeoutConnectAttempts, boolean timedOut, boolean poolDown, boolean poolBuilding, boolean browserClosed) Whether the outer HTTP connect loop should retry after a failure.(package private) static booleanshouldOuterRetryConnect(int connectAttempts, int timeoutConnectAttempts, boolean timedOut, int poolState, boolean deadlineExpired) Whether the outer HTTP connect loop should retry after a failure, given the single pool-state snapshot taken for that failure.protected voidCreate the manager if it doesn't exist, AND connect it to the router and build tunnels.Methods inherited from class I2PTunnelTask
connected, disconnected, errorOccurred, getBooleanOption, getId, getTunnel, isOpen, reportAbuse, routerDisconnected, setId, setName, setTunnel, toStringModifier and TypeMethodDescriptionvoidconnected(I2PSession session) For tasks that don't callI2PTunnel.addSession(I2PSession)directly.voiddisconnected(I2PSession session) Called when a session is disconnected.voiderrorOccurred(I2PSession session, String message, Throwable error) Does nothing here.protected booleangetBooleanOption(String opt, boolean dflt) Read a boolean client option from the tunnel's properties.intgetId()The id of the client list entry for this task.The I2PTunnel this task runs inside.booleanisOpen()Whether the tunnel is running and accepting connections.voidreportAbuse(I2PSession session, int severity) Does nothing here.protected voidTell the tunnel that the router connection has dropped.voidsetId(int id) Record the client list entry id for this task.protected voidRecord the display name for this task.voidRebind this task to a different tunnel.toString()The display name given to this task when it was constructed.Methods inherited from class EventDispatcherImpl
attachEventDispatcher, detachEventDispatcher, getEventDispatcher, getEvents, getEventValue, ignoreEvents, notifyEvent, unIgnoreEvents, waitEventValueModifier and TypeMethodDescriptionvoidAttach an EventDispatcher object to the events dispatching chain.voidDetach the specified EventDispatcher object from the events dispatching chain.Object to be used to deliver events (usuallythis, but YMMV).Retrieve the names of all the events that have been received.getEventValue(String name) Retrieve the value currently associated with the specified event value.voidIgnore further event notifications.voidnotifyEvent(String eventName, Object args) Deliver an event.voidAlmost like the method above :-).waitEventValue(String name) Wait until the given event has received a value.
Constructor Details
I2PTunnelHTTPBidirProxy
public I2PTunnelHTTPBidirProxy(int localPort, Logging l, I2PSocketManager sockMgr, I2PTunnel tunnel, EventDispatcher notifyThis, long clientId) Create a bidirectional HTTP proxy tunnel on localPort, reusing the server's existing I2P socket manager. As of 0.9.20 this is fast, and does NOT connect the manager to the router, or open the local socket. You MUST call startRunning() for that.- Parameters:
localPort- the local port to bind tol- the logger the tunnel and its listeners write throughsockMgr- the I2P socket managertunnel- the I2P tunnelnotifyThis- the event dispatcher for notificationsclientId- the client ID- Throws:
IllegalArgumentException- if the I2PTunnel does not contain valid config to contact the router