Path: blob/master/test/jdk/java/net/httpclient/DigestEchoServer.java
41149 views
/*1* Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223import com.sun.net.httpserver.BasicAuthenticator;24import com.sun.net.httpserver.HttpServer;25import com.sun.net.httpserver.HttpsConfigurator;26import com.sun.net.httpserver.HttpsParameters;27import com.sun.net.httpserver.HttpsServer;2829import java.io.Closeable;30import java.io.IOException;31import java.io.InputStream;32import java.io.OutputStream;33import java.io.OutputStreamWriter;34import java.io.PrintWriter;35import java.io.Writer;36import java.math.BigInteger;37import java.net.Authenticator;38import java.net.HttpURLConnection;39import java.net.InetAddress;40import java.net.InetSocketAddress;41import java.net.MalformedURLException;42import java.net.PasswordAuthentication;43import java.net.ServerSocket;44import java.net.Socket;45import java.net.StandardSocketOptions;46import java.net.URI;47import java.net.URISyntaxException;48import java.net.URL;49import java.nio.charset.StandardCharsets;50import java.security.MessageDigest;51import java.security.NoSuchAlgorithmException;52import java.time.Instant;53import java.util.ArrayList;54import java.util.Arrays;55import java.util.Base64;56import java.util.HexFormat;57import java.util.List;58import java.util.Locale;59import java.util.Objects;60import java.util.Optional;61import java.util.Random;62import java.util.StringTokenizer;63import java.util.concurrent.CompletableFuture;64import java.util.concurrent.CopyOnWriteArrayList;65import java.util.concurrent.atomic.AtomicInteger;66import java.util.stream.Collectors;67import java.util.stream.Stream;68import javax.net.ssl.SSLContext;69import sun.net.www.HeaderParser;70import java.net.http.HttpClient.Version;7172/**73* A simple HTTP server that supports Basic or Digest authentication.74* By default this server will echo back whatever is present75* in the request body. Note that the Digest authentication is76* a test implementation implemented only for tests purposes.77* @author danielfuchs78*/79public abstract class DigestEchoServer implements HttpServerAdapters {8081public static final boolean DEBUG =82Boolean.parseBoolean(System.getProperty("test.debug", "false"));83public static final boolean NO_LINGER =84Boolean.parseBoolean(System.getProperty("test.nolinger", "false"));85public static final boolean TUNNEL_REQUIRES_HOST =86Boolean.parseBoolean(System.getProperty("test.requiresHost", "false"));87public enum HttpAuthType {88SERVER, PROXY, SERVER307, PROXY30589/* add PROXY_AND_SERVER and SERVER_PROXY_NONE */90};91public enum HttpAuthSchemeType { NONE, BASICSERVER, BASIC, DIGEST };92public static final HttpAuthType DEFAULT_HTTP_AUTH_TYPE = HttpAuthType.SERVER;93public static final String DEFAULT_PROTOCOL_TYPE = "https";94public static final HttpAuthSchemeType DEFAULT_SCHEME_TYPE = HttpAuthSchemeType.DIGEST;9596public static class HttpTestAuthenticator extends Authenticator {97private final String realm;98private final String username;99// Used to prevent incrementation of 'count' when calling the100// authenticator from the server side.101private final ThreadLocal<Boolean> skipCount = new ThreadLocal<>();102// count will be incremented every time getPasswordAuthentication()103// is called from the client side.104final AtomicInteger count = new AtomicInteger();105106public HttpTestAuthenticator(String realm, String username) {107this.realm = realm;108this.username = username;109}110@Override111protected PasswordAuthentication getPasswordAuthentication() {112if (skipCount.get() == null || skipCount.get().booleanValue() == false) {113System.out.println("Authenticator called: " + count.incrementAndGet());114}115return new PasswordAuthentication(getUserName(),116new char[] {'d','e','n', 't'});117}118// Called by the server side to get the password of the user119// being authentified.120public final char[] getPassword(String user) {121if (user.equals(username)) {122skipCount.set(Boolean.TRUE);123try {124return getPasswordAuthentication().getPassword();125} finally {126skipCount.set(Boolean.FALSE);127}128}129throw new SecurityException("User unknown: " + user);130}131public final String getUserName() {132return username;133}134public final String getRealm() {135return realm;136}137}138139public static final HttpTestAuthenticator AUTHENTICATOR;140static {141AUTHENTICATOR = new HttpTestAuthenticator("earth", "arthur");142}143144145final HttpTestServer serverImpl; // this server endpoint146final DigestEchoServer redirect; // the target server where to redirect 3xx147final HttpTestHandler delegate; // unused148final String key;149150DigestEchoServer(String key,151HttpTestServer server,152DigestEchoServer target,153HttpTestHandler delegate) {154this.key = key;155this.serverImpl = server;156this.redirect = target;157this.delegate = delegate;158}159160public static void main(String[] args)161throws IOException {162163DigestEchoServer server = create(Version.HTTP_1_1,164DEFAULT_PROTOCOL_TYPE,165DEFAULT_HTTP_AUTH_TYPE,166AUTHENTICATOR,167DEFAULT_SCHEME_TYPE);168try {169System.out.println("Server created at " + server.getAddress());170System.out.println("Strike <Return> to exit");171System.in.read();172} finally {173System.out.println("stopping server");174server.stop();175}176}177178private static String toString(HttpTestRequestHeaders headers) {179return headers.entrySet().stream()180.map((e) -> e.getKey() + ": " + e.getValue())181.collect(Collectors.joining("\n"));182}183184public static DigestEchoServer create(Version version,185String protocol,186HttpAuthType authType,187HttpAuthSchemeType schemeType)188throws IOException {189return create(version, protocol, authType, AUTHENTICATOR, schemeType);190}191192public static DigestEchoServer create(Version version,193String protocol,194HttpAuthType authType,195HttpTestAuthenticator auth,196HttpAuthSchemeType schemeType)197throws IOException {198return create(version, protocol, authType, auth, schemeType, null);199}200201public static DigestEchoServer create(Version version,202String protocol,203HttpAuthType authType,204HttpTestAuthenticator auth,205HttpAuthSchemeType schemeType,206HttpTestHandler delegate)207throws IOException {208Objects.requireNonNull(authType);209Objects.requireNonNull(auth);210switch(authType) {211// A server that performs Server Digest authentication.212case SERVER: return createServer(version, protocol, authType, auth,213schemeType, delegate, "/");214// A server that pretends to be a Proxy and performs215// Proxy Digest authentication. If protocol is HTTPS,216// then this will create a HttpsProxyTunnel that will217// handle the CONNECT request for tunneling.218case PROXY: return createProxy(version, protocol, authType, auth,219schemeType, delegate, "/");220// A server that sends 307 redirect to a server that performs221// Digest authentication.222// Note: 301 doesn't work here because it transforms POST into GET.223case SERVER307: return createServerAndRedirect(version,224protocol,225HttpAuthType.SERVER,226auth, schemeType,227delegate, 307);228// A server that sends 305 redirect to a proxy that performs229// Digest authentication.230// Note: this is not correctly stubbed/implemented in this test.231case PROXY305: return createServerAndRedirect(version,232protocol,233HttpAuthType.PROXY,234auth, schemeType,235delegate, 305);236default:237throw new InternalError("Unknown server type: " + authType);238}239}240241242/**243* The SocketBindableFactory ensures that the local port used by an HttpServer244* or a proxy ServerSocket previously created by the current test/VM will not245* get reused by a subsequent test in the same VM.246* This is to avoid having the test client trying to reuse cached connections.247*/248private static abstract class SocketBindableFactory<B> {249private static final int MAX = 10;250private static final CopyOnWriteArrayList<String> addresses =251new CopyOnWriteArrayList<>();252protected B createInternal() throws IOException {253final int max = addresses.size() + MAX;254final List<B> toClose = new ArrayList<>();255try {256for (int i = 1; i <= max; i++) {257B bindable = createBindable();258InetSocketAddress address = getAddress(bindable);259String key = "localhost:" + address.getPort();260if (addresses.addIfAbsent(key)) {261System.out.println("Socket bound to: " + key262+ " after " + i + " attempt(s)");263return bindable;264}265System.out.println("warning: address " + key266+ " already used. Retrying bind.");267// keep the port bound until we get a port that we haven't268// used already269toClose.add(bindable);270}271} finally {272// if we had to retry, then close the socket we're not273// going to use.274for (B b : toClose) {275try { close(b); } catch (Exception x) { /* ignore */ }276}277}278throw new IOException("Couldn't bind socket after " + max + " attempts: "279+ "addresses used before: " + addresses);280}281282protected abstract B createBindable() throws IOException;283284protected abstract InetSocketAddress getAddress(B bindable);285286protected abstract void close(B bindable) throws IOException;287}288289/*290* Used to create ServerSocket for a proxy.291*/292private static final class ServerSocketFactory293extends SocketBindableFactory<ServerSocket> {294private static final ServerSocketFactory instance = new ServerSocketFactory();295296static ServerSocket create() throws IOException {297return instance.createInternal();298}299300@Override301protected ServerSocket createBindable() throws IOException {302ServerSocket ss = new ServerSocket();303ss.setReuseAddress(false);304ss.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));305return ss;306}307308@Override309protected InetSocketAddress getAddress(ServerSocket socket) {310return new InetSocketAddress(socket.getInetAddress(), socket.getLocalPort());311}312313@Override314protected void close(ServerSocket socket) throws IOException {315socket.close();316}317}318319/*320* Used to create HttpServer321*/322private static abstract class H1ServerFactory<S extends HttpServer>323extends SocketBindableFactory<S> {324@Override325protected S createBindable() throws IOException {326S server = newHttpServer();327server.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);328return server;329}330331@Override332protected InetSocketAddress getAddress(S server) {333return server.getAddress();334}335336@Override337protected void close(S server) throws IOException {338server.stop(1);339}340341/*342* Returns a HttpServer or a HttpsServer in different subclasses.343*/344protected abstract S newHttpServer() throws IOException;345}346347/*348* Used to create Http2TestServer349*/350private static abstract class H2ServerFactory<S extends Http2TestServer>351extends SocketBindableFactory<S> {352@Override353protected S createBindable() throws IOException {354final S server;355try {356server = newHttpServer();357} catch (IOException io) {358throw io;359} catch (Exception x) {360throw new IOException(x);361}362return server;363}364365@Override366protected InetSocketAddress getAddress(S server) {367return server.getAddress();368}369370@Override371protected void close(S server) throws IOException {372server.stop();373}374375/*376* Returns a HttpServer or a HttpsServer in different subclasses.377*/378protected abstract S newHttpServer() throws Exception;379}380381private static final class Http2ServerFactory extends H2ServerFactory<Http2TestServer> {382private static final Http2ServerFactory instance = new Http2ServerFactory();383384static Http2TestServer create() throws IOException {385return instance.createInternal();386}387388@Override389protected Http2TestServer newHttpServer() throws Exception {390return new Http2TestServer("localhost", false, 0);391}392}393394private static final class Https2ServerFactory extends H2ServerFactory<Http2TestServer> {395private static final Https2ServerFactory instance = new Https2ServerFactory();396397static Http2TestServer create() throws IOException {398return instance.createInternal();399}400401@Override402protected Http2TestServer newHttpServer() throws Exception {403return new Http2TestServer("localhost", true, 0);404}405}406407private static final class Http1ServerFactory extends H1ServerFactory<HttpServer> {408private static final Http1ServerFactory instance = new Http1ServerFactory();409410static HttpServer create() throws IOException {411return instance.createInternal();412}413414@Override415protected HttpServer newHttpServer() throws IOException {416return HttpServer.create();417}418}419420private static final class Https1ServerFactory extends H1ServerFactory<HttpsServer> {421private static final Https1ServerFactory instance = new Https1ServerFactory();422423static HttpsServer create() throws IOException {424return instance.createInternal();425}426427@Override428protected HttpsServer newHttpServer() throws IOException {429return HttpsServer.create();430}431}432433static Http2TestServer createHttp2Server(String protocol) throws IOException {434final Http2TestServer server;435if ("http".equalsIgnoreCase(protocol)) {436server = Http2ServerFactory.create();437} else if ("https".equalsIgnoreCase(protocol)) {438server = Https2ServerFactory.create();439} else {440throw new InternalError("unsupported protocol: " + protocol);441}442return server;443}444445static HttpTestServer createHttpServer(Version version, String protocol)446throws IOException447{448switch(version) {449case HTTP_1_1:450return HttpTestServer.of(createHttp1Server(protocol));451case HTTP_2:452return HttpTestServer.of(createHttp2Server(protocol));453default:454throw new InternalError("Unexpected version: " + version);455}456}457458static HttpServer createHttp1Server(String protocol) throws IOException {459final HttpServer server;460if ("http".equalsIgnoreCase(protocol)) {461server = Http1ServerFactory.create();462} else if ("https".equalsIgnoreCase(protocol)) {463server = configure(Https1ServerFactory.create());464} else {465throw new InternalError("unsupported protocol: " + protocol);466}467return server;468}469470static HttpsServer configure(HttpsServer server) throws IOException {471try {472SSLContext ctx = SSLContext.getDefault();473server.setHttpsConfigurator(new Configurator(ctx));474} catch (NoSuchAlgorithmException ex) {475throw new IOException(ex);476}477return server;478}479480481static void setContextAuthenticator(HttpTestContext ctxt,482HttpTestAuthenticator auth) {483final String realm = auth.getRealm();484com.sun.net.httpserver.Authenticator authenticator =485new BasicAuthenticator(realm) {486@Override487public boolean checkCredentials(String username, String pwd) {488return auth.getUserName().equals(username)489&& new String(auth.getPassword(username)).equals(pwd);490}491};492ctxt.setAuthenticator(authenticator);493}494495public static DigestEchoServer createServer(Version version,496String protocol,497HttpAuthType authType,498HttpTestAuthenticator auth,499HttpAuthSchemeType schemeType,500HttpTestHandler delegate,501String path)502throws IOException {503Objects.requireNonNull(authType);504Objects.requireNonNull(auth);505506HttpTestServer impl = createHttpServer(version, protocol);507String key = String.format("DigestEchoServer[PID=%s,PORT=%s]:%s:%s:%s:%s",508ProcessHandle.current().pid(),509impl.getAddress().getPort(),510version, protocol, authType, schemeType);511final DigestEchoServer server = new DigestEchoServerImpl(key, impl, null, delegate);512final HttpTestHandler handler =513server.createHandler(schemeType, auth, authType, false);514HttpTestContext context = impl.addHandler(handler, path);515server.configureAuthentication(context, schemeType, auth, authType);516impl.start();517return server;518}519520public static DigestEchoServer createProxy(Version version,521String protocol,522HttpAuthType authType,523HttpTestAuthenticator auth,524HttpAuthSchemeType schemeType,525HttpTestHandler delegate,526String path)527throws IOException {528Objects.requireNonNull(authType);529Objects.requireNonNull(auth);530531if (version == Version.HTTP_2 && protocol.equalsIgnoreCase("http")) {532System.out.println("WARNING: can't use HTTP/1.1 proxy with unsecure HTTP/2 server");533version = Version.HTTP_1_1;534}535HttpTestServer impl = createHttpServer(version, protocol);536String key = String.format("DigestEchoServer[PID=%s,PORT=%s]:%s:%s:%s:%s",537ProcessHandle.current().pid(),538impl.getAddress().getPort(),539version, protocol, authType, schemeType);540final DigestEchoServer server = "https".equalsIgnoreCase(protocol)541? new HttpsProxyTunnel(key, impl, null, delegate)542: new DigestEchoServerImpl(key, impl, null, delegate);543544final HttpTestHandler hh = server.createHandler(HttpAuthSchemeType.NONE,545null, HttpAuthType.SERVER,546server instanceof HttpsProxyTunnel);547HttpTestContext ctxt = impl.addHandler(hh, path);548server.configureAuthentication(ctxt, schemeType, auth, authType);549impl.start();550551return server;552}553554public static DigestEchoServer createServerAndRedirect(555Version version,556String protocol,557HttpAuthType targetAuthType,558HttpTestAuthenticator auth,559HttpAuthSchemeType schemeType,560HttpTestHandler targetDelegate,561int code300)562throws IOException {563Objects.requireNonNull(targetAuthType);564Objects.requireNonNull(auth);565566// The connection between client and proxy can only567// be a plain connection: SSL connection to proxy568// is not supported by our client connection.569String targetProtocol = targetAuthType == HttpAuthType.PROXY570? "http"571: protocol;572DigestEchoServer redirectTarget =573(targetAuthType == HttpAuthType.PROXY)574? createProxy(version, protocol, targetAuthType,575auth, schemeType, targetDelegate, "/")576: createServer(version, targetProtocol, targetAuthType,577auth, schemeType, targetDelegate, "/");578HttpTestServer impl = createHttpServer(version, protocol);579String key = String.format("RedirectingServer[PID=%s,PORT=%s]:%s:%s:%s:%s",580ProcessHandle.current().pid(),581impl.getAddress().getPort(),582version, protocol,583HttpAuthType.SERVER, code300)584+ "->" + redirectTarget.key;585final DigestEchoServer redirectingServer =586new DigestEchoServerImpl(key, impl, redirectTarget, null);587InetSocketAddress redirectAddr = redirectTarget.getAddress();588URL locationURL = url(targetProtocol, redirectAddr, "/");589final HttpTestHandler hh = redirectingServer.create300Handler(key, locationURL,590HttpAuthType.SERVER, code300);591impl.addHandler(hh,"/");592impl.start();593return redirectingServer;594}595596public abstract InetSocketAddress getServerAddress();597public abstract InetSocketAddress getProxyAddress();598public abstract InetSocketAddress getAddress();599public abstract void stop();600public abstract Version getServerVersion();601602private static class DigestEchoServerImpl extends DigestEchoServer {603DigestEchoServerImpl(String key,604HttpTestServer server,605DigestEchoServer target,606HttpTestHandler delegate) {607super(key, Objects.requireNonNull(server), target, delegate);608}609610public InetSocketAddress getAddress() {611return new InetSocketAddress(InetAddress.getLoopbackAddress(),612serverImpl.getAddress().getPort());613}614615public InetSocketAddress getServerAddress() {616return new InetSocketAddress(InetAddress.getLoopbackAddress(),617serverImpl.getAddress().getPort());618}619620public InetSocketAddress getProxyAddress() {621return new InetSocketAddress(InetAddress.getLoopbackAddress(),622serverImpl.getAddress().getPort());623}624625public Version getServerVersion() {626return serverImpl.getVersion();627}628629public void stop() {630serverImpl.stop();631if (redirect != null) {632redirect.stop();633}634}635}636637protected void writeResponse(HttpTestExchange he) throws IOException {638if (delegate == null) {639he.sendResponseHeaders(HttpURLConnection.HTTP_OK, -1);640he.getResponseBody().write(he.getRequestBody().readAllBytes());641} else {642delegate.handle(he);643}644}645646private HttpTestHandler createHandler(HttpAuthSchemeType schemeType,647HttpTestAuthenticator auth,648HttpAuthType authType,649boolean tunelled) {650return new HttpNoAuthHandler(key, authType, tunelled);651}652653void configureAuthentication(HttpTestContext ctxt,654HttpAuthSchemeType schemeType,655HttpTestAuthenticator auth,656HttpAuthType authType) {657switch(schemeType) {658case DIGEST:659// DIGEST authentication is handled by the handler.660ctxt.addFilter(new HttpDigestFilter(key, auth, authType));661break;662case BASIC:663// BASIC authentication is handled by the filter.664ctxt.addFilter(new HttpBasicFilter(key, auth, authType));665break;666case BASICSERVER:667switch(authType) {668case PROXY: case PROXY305:669// HttpServer can't support Proxy-type authentication670// => we do as if BASIC had been specified, and we will671// handle authentication in the handler.672ctxt.addFilter(new HttpBasicFilter(key, auth, authType));673break;674case SERVER: case SERVER307:675if (ctxt.getVersion() == Version.HTTP_1_1) {676// Basic authentication is handled by HttpServer677// directly => the filter should not perform678// authentication again.679setContextAuthenticator(ctxt, auth);680ctxt.addFilter(new HttpNoAuthFilter(key, authType));681} else {682ctxt.addFilter(new HttpBasicFilter(key, auth, authType));683}684break;685default:686throw new InternalError(key + ": Invalid combination scheme="687+ schemeType + " authType=" + authType);688}689case NONE:690// No authentication at all.691ctxt.addFilter(new HttpNoAuthFilter(key, authType));692break;693default:694throw new InternalError(key + ": No such scheme: " + schemeType);695}696}697698private HttpTestHandler create300Handler(String key, URL proxyURL,699HttpAuthType type, int code300)700throws MalformedURLException701{702return new Http3xxHandler(key, proxyURL, type, code300);703}704705// Abstract HTTP filter class.706private abstract static class AbstractHttpFilter extends HttpTestFilter {707708final HttpAuthType authType;709final String type;710public AbstractHttpFilter(HttpAuthType authType, String type) {711this.authType = authType;712this.type = type;713}714715String getLocation() {716return "Location";717}718String getAuthenticate() {719return authType == HttpAuthType.PROXY720? "Proxy-Authenticate" : "WWW-Authenticate";721}722String getAuthorization() {723return authType == HttpAuthType.PROXY724? "Proxy-Authorization" : "Authorization";725}726int getUnauthorizedCode() {727return authType == HttpAuthType.PROXY728? HttpURLConnection.HTTP_PROXY_AUTH729: HttpURLConnection.HTTP_UNAUTHORIZED;730}731String getKeepAlive() {732return "keep-alive";733}734String getConnection() {735return authType == HttpAuthType.PROXY736? "Proxy-Connection" : "Connection";737}738protected abstract boolean isAuthentified(HttpTestExchange he) throws IOException;739protected abstract void requestAuthentication(HttpTestExchange he) throws IOException;740protected void accept(HttpTestExchange he, HttpChain chain) throws IOException {741chain.doFilter(he);742}743744@Override745public String description() {746return "Filter for " + type;747}748@Override749public void doFilter(HttpTestExchange he, HttpChain chain) throws IOException {750try {751System.out.println(type + ": Got " + he.getRequestMethod()752+ ": " + he.getRequestURI()753+ "\n" + DigestEchoServer.toString(he.getRequestHeaders()));754755// Assert only a single value for Expect. Not directly related756// to digest authentication, but verifies good client behaviour.757List<String> expectValues = he.getRequestHeaders().get("Expect");758if (expectValues != null && expectValues.size() > 1) {759throw new IOException("Expect: " + expectValues);760}761762if (!isAuthentified(he)) {763try {764requestAuthentication(he);765he.sendResponseHeaders(getUnauthorizedCode(), -1);766System.out.println(type767+ ": Sent back " + getUnauthorizedCode());768} finally {769he.close();770}771} else {772accept(he, chain);773}774} catch (RuntimeException | Error | IOException t) {775System.err.println(type776+ ": Unexpected exception while handling request: " + t);777t.printStackTrace(System.err);778he.close();779throw t;780}781}782783}784785// WARNING: This is not a full fledged implementation of DIGEST.786// It does contain bugs and inaccuracy.787final static class DigestResponse {788final String realm;789final String username;790final String nonce;791final String cnonce;792final String nc;793final String uri;794final String algorithm;795final String response;796final String qop;797final String opaque;798799public DigestResponse(String realm, String username, String nonce,800String cnonce, String nc, String uri,801String algorithm, String qop, String opaque,802String response) {803this.realm = realm;804this.username = username;805this.nonce = nonce;806this.cnonce = cnonce;807this.nc = nc;808this.uri = uri;809this.algorithm = algorithm;810this.qop = qop;811this.opaque = opaque;812this.response = response;813}814815String getAlgorithm(String defval) {816return algorithm == null ? defval : algorithm;817}818String getQoP(String defval) {819return qop == null ? defval : qop;820}821822// Code stolen from DigestAuthentication:823824private static String encode(String src, char[] passwd, MessageDigest md) {825try {826md.update(src.getBytes("ISO-8859-1"));827} catch (java.io.UnsupportedEncodingException uee) {828assert false;829}830if (passwd != null) {831byte[] passwdBytes = new byte[passwd.length];832for (int i=0; i<passwd.length; i++)833passwdBytes[i] = (byte)passwd[i];834md.update(passwdBytes);835Arrays.fill(passwdBytes, (byte)0x00);836}837byte[] digest = md.digest();838return HexFormat.of().formatHex(digest);839}840841public static String computeDigest(boolean isRequest,842String reqMethod,843char[] password,844DigestResponse params)845throws NoSuchAlgorithmException846{847848String A1, HashA1;849String algorithm = params.getAlgorithm("MD5");850boolean md5sess = algorithm.equalsIgnoreCase ("MD5-sess");851852MessageDigest md = MessageDigest.getInstance(md5sess?"MD5":algorithm);853854if (params.username == null) {855throw new IllegalArgumentException("missing username");856}857if (params.realm == null) {858throw new IllegalArgumentException("missing realm");859}860if (params.uri == null) {861throw new IllegalArgumentException("missing uri");862}863if (params.nonce == null) {864throw new IllegalArgumentException("missing nonce");865}866867A1 = params.username + ":" + params.realm + ":";868HashA1 = encode(A1, password, md);869870String A2;871if (isRequest) {872A2 = reqMethod + ":" + params.uri;873} else {874A2 = ":" + params.uri;875}876String HashA2 = encode(A2, null, md);877String combo, finalHash;878879if ("auth".equals(params.qop)) { /* RRC2617 when qop=auth */880if (params.cnonce == null) {881throw new IllegalArgumentException("missing nonce");882}883if (params.nc == null) {884throw new IllegalArgumentException("missing nonce");885}886combo = HashA1+ ":" + params.nonce + ":" + params.nc + ":" +887params.cnonce + ":auth:" +HashA2;888889} else { /* for compatibility with RFC2069 */890combo = HashA1 + ":" +891params.nonce + ":" +892HashA2;893}894finalHash = encode(combo, null, md);895return finalHash;896}897898public static DigestResponse create(String raw) {899String username, realm, nonce, nc, uri, response, cnonce,900algorithm, qop, opaque;901HeaderParser parser = new HeaderParser(raw);902username = parser.findValue("username");903realm = parser.findValue("realm");904nonce = parser.findValue("nonce");905nc = parser.findValue("nc");906uri = parser.findValue("uri");907cnonce = parser.findValue("cnonce");908response = parser.findValue("response");909algorithm = parser.findValue("algorithm");910qop = parser.findValue("qop");911opaque = parser.findValue("opaque");912return new DigestResponse(realm, username, nonce, cnonce, nc, uri,913algorithm, qop, opaque, response);914}915916}917918private static class HttpNoAuthFilter extends AbstractHttpFilter {919920static String type(String key, HttpAuthType authType) {921String type = authType == HttpAuthType.SERVER922? "NoAuth Server Filter" : "NoAuth Proxy Filter";923return "["+type+"]:"+key;924}925926public HttpNoAuthFilter(String key, HttpAuthType authType) {927super(authType, type(key, authType));928}929930@Override931protected boolean isAuthentified(HttpTestExchange he) throws IOException {932return true;933}934935@Override936protected void requestAuthentication(HttpTestExchange he) throws IOException {937throw new InternalError("Should not com here");938}939940@Override941public String description() {942return "Passthrough Filter";943}944945}946947// An HTTP Filter that performs Basic authentication948private static class HttpBasicFilter extends AbstractHttpFilter {949950static String type(String key, HttpAuthType authType) {951String type = authType == HttpAuthType.SERVER952? "Basic Server Filter" : "Basic Proxy Filter";953return "["+type+"]:"+key;954}955956private final HttpTestAuthenticator auth;957public HttpBasicFilter(String key, HttpTestAuthenticator auth,958HttpAuthType authType) {959super(authType, type(key, authType));960this.auth = auth;961}962963@Override964protected void requestAuthentication(HttpTestExchange he)965throws IOException966{967String headerName = getAuthenticate();968String headerValue = "Basic realm=\"" + auth.getRealm() + "\"";969he.getResponseHeaders().addHeader(headerName, headerValue);970System.out.println(type + ": Requesting Basic Authentication, "971+ headerName + " : "+ headerValue);972}973974@Override975protected boolean isAuthentified(HttpTestExchange he) {976if (he.getRequestHeaders().containsKey(getAuthorization())) {977List<String> authorization =978he.getRequestHeaders().get(getAuthorization());979for (String a : authorization) {980System.out.println(type + ": processing " + a);981int sp = a.indexOf(' ');982if (sp < 0) return false;983String scheme = a.substring(0, sp);984if (!"Basic".equalsIgnoreCase(scheme)) {985System.out.println(type + ": Unsupported scheme '"986+ scheme +"'");987return false;988}989if (a.length() <= sp+1) {990System.out.println(type + ": value too short for '"991+ scheme +"'");992return false;993}994a = a.substring(sp+1);995return validate(a);996}997return false;998}999return false;1000}10011002boolean validate(String a) {1003byte[] b = Base64.getDecoder().decode(a);1004String userpass = new String (b);1005int colon = userpass.indexOf (':');1006String uname = userpass.substring (0, colon);1007String pass = userpass.substring (colon+1);1008return auth.getUserName().equals(uname) &&1009new String(auth.getPassword(uname)).equals(pass);1010}10111012@Override1013public String description() {1014return "Filter for BASIC authentication: " + type;1015}10161017}101810191020// An HTTP Filter that performs Digest authentication1021// WARNING: This is not a full fledged implementation of DIGEST.1022// It does contain bugs and inaccuracy.1023private static class HttpDigestFilter extends AbstractHttpFilter {10241025static String type(String key, HttpAuthType authType) {1026String type = authType == HttpAuthType.SERVER1027? "Digest Server Filter" : "Digest Proxy Filter";1028return "["+type+"]:"+key;1029}10301031// This is a very basic DIGEST - used only for the purpose of testing1032// the client implementation. Therefore we can get away with never1033// updating the server nonce as it makes the implementation of the1034// server side digest simpler.1035private final HttpTestAuthenticator auth;1036private final byte[] nonce;1037private final String ns;1038public HttpDigestFilter(String key, HttpTestAuthenticator auth, HttpAuthType authType) {1039super(authType, type(key, authType));1040this.auth = auth;1041nonce = new byte[16];1042new Random(Instant.now().toEpochMilli()).nextBytes(nonce);1043ns = new BigInteger(1, nonce).toString(16);1044}10451046@Override1047protected void requestAuthentication(HttpTestExchange he)1048throws IOException {1049String separator;1050Version v = he.getExchangeVersion();1051if (v == Version.HTTP_1_1) {1052separator = "\r\n ";1053} else if (v == Version.HTTP_2) {1054separator = " ";1055} else {1056throw new InternalError(String.valueOf(v));1057}1058String headerName = getAuthenticate();1059String headerValue = "Digest realm=\"" + auth.getRealm() + "\","1060+ separator + "qop=\"auth\","1061+ separator + "nonce=\"" + ns +"\"";1062he.getResponseHeaders().addHeader(headerName, headerValue);1063System.out.println(type + ": Requesting Digest Authentication, "1064+ headerName + " : " + headerValue);1065}10661067@Override1068protected boolean isAuthentified(HttpTestExchange he) {1069if (he.getRequestHeaders().containsKey(getAuthorization())) {1070List<String> authorization = he.getRequestHeaders().get(getAuthorization());1071for (String a : authorization) {1072System.out.println(type + ": processing " + a);1073int sp = a.indexOf(' ');1074if (sp < 0) return false;1075String scheme = a.substring(0, sp);1076if (!"Digest".equalsIgnoreCase(scheme)) {1077System.out.println(type + ": Unsupported scheme '" + scheme +"'");1078return false;1079}1080if (a.length() <= sp+1) {1081System.out.println(type + ": value too short for '" + scheme +"'");1082return false;1083}1084a = a.substring(sp+1);1085DigestResponse dgr = DigestResponse.create(a);1086return validate(he.getRequestURI(), he.getRequestMethod(), dgr);1087}1088return false;1089}1090return false;1091}10921093boolean validate(URI uri, String reqMethod, DigestResponse dg) {1094if (!"MD5".equalsIgnoreCase(dg.getAlgorithm("MD5"))) {1095System.out.println(type + ": Unsupported algorithm "1096+ dg.algorithm);1097return false;1098}1099if (!"auth".equalsIgnoreCase(dg.getQoP("auth"))) {1100System.out.println(type + ": Unsupported qop "1101+ dg.qop);1102return false;1103}1104try {1105if (!dg.nonce.equals(ns)) {1106System.out.println(type + ": bad nonce returned by client: "1107+ nonce + " expected " + ns);1108return false;1109}1110if (dg.response == null) {1111System.out.println(type + ": missing digest response.");1112return false;1113}1114char[] pa = auth.getPassword(dg.username);1115return verify(uri, reqMethod, dg, pa);1116} catch(IllegalArgumentException | SecurityException1117| NoSuchAlgorithmException e) {1118System.out.println(type + ": " + e.getMessage());1119return false;1120}1121}112211231124boolean verify(URI uri, String reqMethod, DigestResponse dg, char[] pw)1125throws NoSuchAlgorithmException {1126String response = DigestResponse.computeDigest(true, reqMethod, pw, dg);1127if (!dg.response.equals(response)) {1128System.out.println(type + ": bad response returned by client: "1129+ dg.response + " expected " + response);1130return false;1131} else {1132// A real server would also verify the uri=<request-uri>1133// parameter - but this is just a test...1134System.out.println(type + ": verified response " + response);1135}1136return true;1137}113811391140@Override1141public String description() {1142return "Filter for DIGEST authentication: " + type;1143}1144}11451146// Abstract HTTP handler class.1147private abstract static class AbstractHttpHandler implements HttpTestHandler {11481149final HttpAuthType authType;1150final String type;1151public AbstractHttpHandler(HttpAuthType authType, String type) {1152this.authType = authType;1153this.type = type;1154}11551156String getLocation() {1157return "Location";1158}11591160@Override1161public void handle(HttpTestExchange he) throws IOException {1162try {1163sendResponse(he);1164} catch (RuntimeException | Error | IOException t) {1165System.err.println(type1166+ ": Unexpected exception while handling request: " + t);1167t.printStackTrace(System.err);1168throw t;1169} finally {1170he.close();1171}1172}11731174protected abstract void sendResponse(HttpTestExchange he) throws IOException;11751176}11771178static String stype(String type, String key, HttpAuthType authType, boolean tunnelled) {1179type = type + (authType == HttpAuthType.SERVER1180? " Server" : " Proxy")1181+ (tunnelled ? " Tunnelled" : "");1182return "["+type+"]:"+key;1183}11841185private class HttpNoAuthHandler extends AbstractHttpHandler {11861187// true if this server is behind a proxy tunnel.1188final boolean tunnelled;1189public HttpNoAuthHandler(String key, HttpAuthType authType, boolean tunnelled) {1190super(authType, stype("NoAuth", key, authType, tunnelled));1191this.tunnelled = tunnelled;1192}11931194@Override1195protected void sendResponse(HttpTestExchange he) throws IOException {1196if (DEBUG) {1197System.out.println(type + ": headers are: "1198+ DigestEchoServer.toString(he.getRequestHeaders()));1199}1200if (authType == HttpAuthType.SERVER && tunnelled) {1201// Verify that the client doesn't send us proxy-* headers1202// used to establish the proxy tunnel1203Optional<String> proxyAuth = he.getRequestHeaders()1204.keySet().stream()1205.filter("proxy-authorization"::equalsIgnoreCase)1206.findAny();1207if (proxyAuth.isPresent()) {1208System.out.println(type + " found "1209+ proxyAuth.get() + ": failing!");1210throw new IOException(proxyAuth.get()1211+ " found by " + type + " for "1212+ he.getRequestURI());1213}1214}1215DigestEchoServer.this.writeResponse(he);1216}12171218}12191220// A dummy HTTP Handler that redirects all incoming requests1221// by sending a back 3xx response code (301, 305, 307 etc..)1222private class Http3xxHandler extends AbstractHttpHandler {12231224private final URL redirectTargetURL;1225private final int code3XX;1226public Http3xxHandler(String key, URL proxyURL, HttpAuthType authType, int code300) {1227super(authType, stype("Server" + code300, key, authType, false));1228this.redirectTargetURL = proxyURL;1229this.code3XX = code300;1230}12311232int get3XX() {1233return code3XX;1234}12351236@Override1237public void sendResponse(HttpTestExchange he) throws IOException {1238System.out.println(type + ": Got " + he.getRequestMethod()1239+ ": " + he.getRequestURI()1240+ "\n" + DigestEchoServer.toString(he.getRequestHeaders()));1241System.out.println(type + ": Redirecting to "1242+ (authType == HttpAuthType.PROXY3051243? "proxy" : "server"));1244he.getResponseHeaders().addHeader(getLocation(),1245redirectTargetURL.toExternalForm().toString());1246he.sendResponseHeaders(get3XX(), -1);1247System.out.println(type + ": Sent back " + get3XX() + " "1248+ getLocation() + ": " + redirectTargetURL.toExternalForm().toString());1249}1250}12511252static class Configurator extends HttpsConfigurator {1253public Configurator(SSLContext ctx) {1254super(ctx);1255}12561257@Override1258public void configure (HttpsParameters params) {1259params.setSSLParameters (getSSLContext().getSupportedSSLParameters());1260}1261}12621263static final long start = System.nanoTime();1264public static String now() {1265long now = System.nanoTime() - start;1266long secs = now / 1000_000_000;1267long mill = (now % 1000_000_000) / 1000_000;1268long nan = now % 1000_000;1269return String.format("[%d s, %d ms, %d ns] ", secs, mill, nan);1270}12711272static class ProxyAuthorization {1273final HttpAuthSchemeType schemeType;1274final HttpTestAuthenticator authenticator;1275private final byte[] nonce;1276private final String ns;1277private final String key;12781279ProxyAuthorization(String key, HttpAuthSchemeType schemeType, HttpTestAuthenticator auth) {1280this.key = key;1281this.schemeType = schemeType;1282this.authenticator = auth;1283nonce = new byte[16];1284new Random(Instant.now().toEpochMilli()).nextBytes(nonce);1285ns = new BigInteger(1, nonce).toString(16);1286}12871288String doBasic(Optional<String> authorization) {1289String offset = "proxy-authorization: basic ";1290String authstring = authorization.orElse("");1291if (!authstring.toLowerCase(Locale.US).startsWith(offset)) {1292return "Proxy-Authenticate: BASIC " + "realm=\""1293+ authenticator.getRealm() +"\"";1294}1295authstring = authstring1296.substring(offset.length())1297.trim();1298byte[] base64 = Base64.getDecoder().decode(authstring);1299String up = new String(base64, StandardCharsets.UTF_8);1300int colon = up.indexOf(':');1301if (colon < 1) {1302return "Proxy-Authenticate: BASIC " + "realm=\""1303+ authenticator.getRealm() +"\"";1304}1305String u = up.substring(0, colon);1306String p = up.substring(colon+1);1307char[] pw = authenticator.getPassword(u);1308if (!p.equals(new String(pw))) {1309return "Proxy-Authenticate: BASIC " + "realm=\""1310+ authenticator.getRealm() +"\"";1311}1312System.out.println(now() + key + " Proxy basic authentication success");1313return null;1314}13151316String doDigest(Optional<String> authorization) {1317String offset = "proxy-authorization: digest ";1318String authstring = authorization.orElse("");1319if (!authstring.toLowerCase(Locale.US).startsWith(offset)) {1320return "Proxy-Authenticate: " +1321"Digest realm=\"" + authenticator.getRealm() + "\","1322+ "\r\n qop=\"auth\","1323+ "\r\n nonce=\"" + ns +"\"";1324}1325authstring = authstring1326.substring(offset.length())1327.trim();1328boolean validated = false;1329try {1330DigestResponse dgr = DigestResponse.create(authstring);1331validated = validate("CONNECT", dgr);1332} catch (Throwable t) {1333t.printStackTrace();1334}1335if (!validated) {1336return "Proxy-Authenticate: " +1337"Digest realm=\"" + authenticator.getRealm() + "\","1338+ "\r\n qop=\"auth\","1339+ "\r\n nonce=\"" + ns +"\"";1340}1341return null;1342}13431344134513461347boolean validate(String reqMethod, DigestResponse dg) {1348String type = now() + this.getClass().getSimpleName() + ":" + key;1349if (!"MD5".equalsIgnoreCase(dg.getAlgorithm("MD5"))) {1350System.out.println(type + ": Unsupported algorithm "1351+ dg.algorithm);1352return false;1353}1354if (!"auth".equalsIgnoreCase(dg.getQoP("auth"))) {1355System.out.println(type + ": Unsupported qop "1356+ dg.qop);1357return false;1358}1359try {1360if (!dg.nonce.equals(ns)) {1361System.out.println(type + ": bad nonce returned by client: "1362+ nonce + " expected " + ns);1363return false;1364}1365if (dg.response == null) {1366System.out.println(type + ": missing digest response.");1367return false;1368}1369char[] pa = authenticator.getPassword(dg.username);1370return verify(type, reqMethod, dg, pa);1371} catch(IllegalArgumentException | SecurityException1372| NoSuchAlgorithmException e) {1373System.out.println(type + ": " + e.getMessage());1374return false;1375}1376}137713781379boolean verify(String type, String reqMethod, DigestResponse dg, char[] pw)1380throws NoSuchAlgorithmException {1381String response = DigestResponse.computeDigest(true, reqMethod, pw, dg);1382if (!dg.response.equals(response)) {1383System.out.println(type + ": bad response returned by client: "1384+ dg.response + " expected " + response);1385return false;1386} else {1387// A real server would also verify the uri=<request-uri>1388// parameter - but this is just a test...1389System.out.println(type + ": verified response " + response);1390}1391return true;1392}13931394public boolean authorize(StringBuilder response, String requestLine, String headers) {1395String message = "<html><body><p>Authorization Failed%s</p></body></html>\r\n";1396if (authenticator == null && schemeType != HttpAuthSchemeType.NONE) {1397message = String.format(message, " No Authenticator Set");1398response.append("HTTP/1.1 407 Proxy Authentication Failed\r\n");1399response.append("Content-Length: ")1400.append(message.getBytes(StandardCharsets.UTF_8).length)1401.append("\r\n\r\n");1402response.append(message);1403return false;1404}1405Optional<String> authorization = Stream.of(headers.split("\r\n"))1406.filter((k) -> k.toLowerCase(Locale.US).startsWith("proxy-authorization:"))1407.findFirst();1408String authenticate = null;1409switch(schemeType) {1410case BASIC:1411case BASICSERVER:1412authenticate = doBasic(authorization);1413break;1414case DIGEST:1415authenticate = doDigest(authorization);1416break;1417case NONE:1418response.append("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");1419return true;1420default:1421throw new InternalError("Unknown scheme type: " + schemeType);1422}1423if (authenticate != null) {1424message = String.format(message, "");1425response.append("HTTP/1.1 407 Proxy Authentication Required\r\n");1426response.append("Content-Length: ")1427.append(message.getBytes(StandardCharsets.UTF_8).length)1428.append("\r\n")1429.append(authenticate)1430.append("\r\n\r\n");1431response.append(message);1432return false;1433}1434response.append("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");1435return true;1436}1437}14381439public interface TunnelingProxy {1440InetSocketAddress getProxyAddress();1441void stop();1442}14431444// This is a bit hacky: HttpsProxyTunnel is an HTTPTestServer hidden1445// behind a fake proxy that only understands CONNECT requests.1446// The fake proxy is just a server socket that intercept the1447// CONNECT and then redirect streams to the real server.1448static class HttpsProxyTunnel extends DigestEchoServer1449implements Runnable, TunnelingProxy {14501451final ServerSocket ss;1452final CopyOnWriteArrayList<CompletableFuture<Void>> connectionCFs1453= new CopyOnWriteArrayList<>();1454volatile ProxyAuthorization authorization;1455volatile boolean stopped;1456public HttpsProxyTunnel(String key, HttpTestServer server, DigestEchoServer target,1457HttpTestHandler delegate)1458throws IOException {1459this(key, server, target, delegate, ServerSocketFactory.create());1460}1461private HttpsProxyTunnel(String key, HttpTestServer server, DigestEchoServer target,1462HttpTestHandler delegate, ServerSocket ss)1463throws IOException {1464super("HttpsProxyTunnel:" + ss.getLocalPort() + ":" + key,1465server, target, delegate);1466System.out.flush();1467System.err.println("WARNING: HttpsProxyTunnel is an experimental test class");1468this.ss = ss;1469start();1470}14711472final void start() throws IOException {1473Thread t = new Thread(this, "ProxyThread");1474t.setDaemon(true);1475t.start();1476}14771478@Override1479public Version getServerVersion() {1480// serverImpl is not null when this proxy1481// serves a single server. It will be null1482// if this proxy can serve multiple servers.1483if (serverImpl != null) return serverImpl.getVersion();1484return null;1485}14861487@Override1488public void stop() {1489stopped = true;1490if (serverImpl != null) {1491serverImpl.stop();1492}1493if (redirect != null) {1494redirect.stop();1495}1496try {1497ss.close();1498} catch (IOException ex) {1499if (DEBUG) ex.printStackTrace(System.out);1500}1501}150215031504@Override1505void configureAuthentication(HttpTestContext ctxt,1506HttpAuthSchemeType schemeType,1507HttpTestAuthenticator auth,1508HttpAuthType authType) {1509if (authType == HttpAuthType.PROXY || authType == HttpAuthType.PROXY305) {1510authorization = new ProxyAuthorization(key, schemeType, auth);1511} else {1512super.configureAuthentication(ctxt, schemeType, auth, authType);1513}1514}15151516boolean badRequest(StringBuilder response, String hostport, List<String> hosts) {1517String message = null;1518if (hosts.isEmpty()) {1519message = "No host header provided\r\n";1520} else if (hosts.size() > 1) {1521message = "Multiple host headers provided\r\n";1522for (String h : hosts) {1523message = message + "host: " + h + "\r\n";1524}1525} else {1526String h = hosts.get(0);1527if (!hostport.equalsIgnoreCase(h)1528&& !hostport.equalsIgnoreCase(h + ":80")1529&& !hostport.equalsIgnoreCase(h + ":443")) {1530message = "Bad host provided: [" + h1531+ "] doesnot match [" + hostport + "]\r\n";1532}1533}1534if (message != null) {1535int length = message.getBytes(StandardCharsets.UTF_8).length;1536response.append("HTTP/1.1 400 BadRequest\r\n")1537.append("Content-Length: " + length)1538.append("\r\n\r\n")1539.append(message);1540return true;1541}15421543return false;1544}15451546boolean authorize(StringBuilder response, String requestLine, String headers) {1547if (authorization != null) {1548return authorization.authorize(response, requestLine, headers);1549}1550response.append("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");1551return true;1552}15531554// Pipe the input stream to the output stream.1555private synchronized Thread pipe(InputStream is, OutputStream os, char tag, CompletableFuture<Void> end) {1556return new Thread("TunnelPipe("+tag+")") {1557@Override1558public void run() {1559try {1560int c = 0;1561try {1562while ((c = is.read()) != -1) {1563os.write(c);1564os.flush();1565// if DEBUG prints a + or a - for each transferred1566// character.1567if (DEBUG) System.out.print(tag);1568}1569is.close();1570} catch (IOException ex) {1571if (DEBUG || !stopped && c > -1)1572ex.printStackTrace(System.out);1573end.completeExceptionally(ex);1574} finally {1575try {os.close();} catch (Throwable t) {}1576}1577} finally {1578end.complete(null);1579}1580}1581};1582}15831584@Override1585public InetSocketAddress getAddress() {1586return new InetSocketAddress(InetAddress.getLoopbackAddress(),1587ss.getLocalPort());1588}1589@Override1590public InetSocketAddress getProxyAddress() {1591return getAddress();1592}1593@Override1594public InetSocketAddress getServerAddress() {1595// serverImpl can be null if this proxy can serve1596// multiple servers.1597if (serverImpl != null) {1598return serverImpl.getAddress();1599}1600return null;1601}160216031604// This is a bit shaky. It doesn't handle continuation1605// lines, but our client shouldn't send any.1606// Read a line from the input stream, swallowing the final1607// \r\n sequence. Stops at the first \n, doesn't complain1608// if it wasn't preceded by '\r'.1609//1610String readLine(InputStream r) throws IOException {1611StringBuilder b = new StringBuilder();1612int c;1613while ((c = r.read()) != -1) {1614if (c == '\n') break;1615b.appendCodePoint(c);1616}1617if (b.codePointAt(b.length() -1) == '\r') {1618b.delete(b.length() -1, b.length());1619}1620return b.toString();1621}16221623@Override1624public void run() {1625Socket clientConnection = null;1626Socket targetConnection = null;1627try {1628while (!stopped) {1629System.out.println(now() + "Tunnel: Waiting for client");1630Socket toClose;1631targetConnection = clientConnection = null;1632try {1633toClose = clientConnection = ss.accept();1634if (NO_LINGER) {1635// can be useful to trigger "Connection reset by peer"1636// errors on the client side.1637clientConnection.setOption(StandardSocketOptions.SO_LINGER, 0);1638}1639} catch (IOException io) {1640if (DEBUG || !stopped) io.printStackTrace(System.out);1641break;1642}1643System.out.println(now() + "Tunnel: Client accepted");1644StringBuilder headers = new StringBuilder();1645InputStream ccis = clientConnection.getInputStream();1646OutputStream ccos = clientConnection.getOutputStream();1647Writer w = new OutputStreamWriter(1648clientConnection.getOutputStream(), "UTF-8");1649PrintWriter pw = new PrintWriter(w);1650System.out.println(now() + "Tunnel: Reading request line");1651String requestLine = readLine(ccis);1652System.out.println(now() + "Tunnel: Request line: " + requestLine);1653if (requestLine.startsWith("CONNECT ")) {1654// We should probably check that the next word following1655// CONNECT is the host:port of our HTTPS serverImpl.1656// Some improvement for a followup!1657StringTokenizer tokenizer = new StringTokenizer(requestLine);1658String connect = tokenizer.nextToken();1659assert connect.equalsIgnoreCase("connect");1660String hostport = tokenizer.nextToken();1661InetSocketAddress targetAddress;1662List<String> hosts = new ArrayList<>();1663try {1664URI uri = new URI("https", hostport, "/", null, null);1665int port = uri.getPort();1666port = port == -1 ? 443 : port;1667targetAddress = new InetSocketAddress(uri.getHost(), port);1668if (serverImpl != null) {1669assert targetAddress.getHostString()1670.equalsIgnoreCase(serverImpl.getAddress().getHostString());1671assert targetAddress.getPort() == serverImpl.getAddress().getPort();1672}1673} catch (Throwable x) {1674System.err.printf("Bad target address: \"%s\" in \"%s\"%n",1675hostport, requestLine);1676toClose.close();1677continue;1678}16791680// Read all headers until we find the empty line that1681// signals the end of all headers.1682String line = requestLine;1683while(!line.equals("")) {1684System.out.println(now() + "Tunnel: Reading header: "1685+ (line = readLine(ccis)));1686headers.append(line).append("\r\n");1687int index = line.indexOf(':');1688if (index >= 0) {1689String key = line.substring(0, index).trim();1690if (key.equalsIgnoreCase("host")) {1691hosts.add(line.substring(index+1).trim());1692}1693}1694}1695StringBuilder response = new StringBuilder();1696if (TUNNEL_REQUIRES_HOST) {1697if (badRequest(response, hostport, hosts)) {1698System.out.println(now() + "Tunnel: Sending " + response);1699// send the 400 response1700pw.print(response.toString());1701pw.flush();1702toClose.close();1703continue;1704} else {1705assert hosts.size() == 1;1706System.out.println(now()1707+ "Tunnel: Host header verified " + hosts);1708}1709}17101711final boolean authorize = authorize(response, requestLine, headers.toString());1712if (!authorize) {1713System.out.println(now() + "Tunnel: Sending "1714+ response);1715// send the 407 response1716pw.print(response.toString());1717pw.flush();1718toClose.close();1719continue;1720}1721System.out.println(now()1722+ "Tunnel connecting to target server at "1723+ targetAddress.getAddress() + ":" + targetAddress.getPort());1724targetConnection = new Socket(1725targetAddress.getAddress(),1726targetAddress.getPort());17271728// Then send the 200 OK response to the client1729System.out.println(now() + "Tunnel: Sending "1730+ response);1731pw.print(response);1732pw.flush();1733} else {1734// This should not happen. If it does then just print an1735// error - both on out and err, and close the accepted1736// socket1737System.out.println("WARNING: Tunnel: Unexpected status line: "1738+ requestLine + " received by "1739+ ss.getLocalSocketAddress()1740+ " from "1741+ toClose.getRemoteSocketAddress()1742+ " - closing accepted socket");1743// Print on err1744System.err.println("WARNING: Tunnel: Unexpected status line: "1745+ requestLine + " received by "1746+ ss.getLocalSocketAddress()1747+ " from "1748+ toClose.getRemoteSocketAddress());1749// close accepted socket.1750toClose.close();1751System.err.println("Tunnel: accepted socket closed.");1752continue;1753}17541755// Pipe the input stream of the client connection to the1756// output stream of the target connection and conversely.1757// Now the client and target will just talk to each other.1758System.out.println(now() + "Tunnel: Starting tunnel pipes");1759CompletableFuture<Void> end, end1, end2;1760Thread t1 = pipe(ccis, targetConnection.getOutputStream(), '+',1761end1 = new CompletableFuture<>());1762Thread t2 = pipe(targetConnection.getInputStream(), ccos, '-',1763end2 = new CompletableFuture<>());1764var end11 = end1.whenComplete((r, t) -> exceptionally(end2, t));1765var end22 = end2.whenComplete((r, t) -> exceptionally(end1, t));1766end = CompletableFuture.allOf(end11, end22);1767Socket tc = targetConnection;1768end.whenComplete(1769(r,t) -> {1770try { toClose.close(); } catch (IOException x) { }1771try { tc.close(); } catch (IOException x) { }1772finally {connectionCFs.remove(end);}1773});1774connectionCFs.add(end);1775targetConnection = clientConnection = null;1776t1.start();1777t2.start();1778}1779} catch (Throwable ex) {1780close(clientConnection, ex);1781close(targetConnection, ex);1782close(ss, ex);1783ex.printStackTrace(System.err);1784} finally {1785System.out.println(now() + "Tunnel: exiting (stopped=" + stopped + ")");1786connectionCFs.forEach(cf -> cf.complete(null));1787}1788}17891790void exceptionally(CompletableFuture<?> cf, Throwable t) {1791if (t != null) cf.completeExceptionally(t);1792}17931794void close(Closeable c, Throwable e) {1795if (c == null) return;1796try {1797c.close();1798} catch (IOException x) {1799e.addSuppressed(x);1800}1801}1802}18031804/**1805* Creates a TunnelingProxy that can serve multiple servers.1806* The server address is extracted from the CONNECT request line.1807* @param authScheme The authentication scheme supported by the proxy.1808* Typically one of DIGEST, BASIC, NONE.1809* @return A new TunnelingProxy able to serve multiple servers.1810* @throws IOException If the proxy could not be created.1811*/1812public static TunnelingProxy createHttpsProxyTunnel(HttpAuthSchemeType authScheme)1813throws IOException {1814HttpsProxyTunnel result = new HttpsProxyTunnel("", null, null, null);1815if (authScheme != HttpAuthSchemeType.NONE) {1816result.configureAuthentication(null,1817authScheme,1818AUTHENTICATOR,1819HttpAuthType.PROXY);1820}1821return result;1822}18231824private static String protocol(String protocol) {1825if ("http".equalsIgnoreCase(protocol)) return "http";1826else if ("https".equalsIgnoreCase(protocol)) return "https";1827else throw new InternalError("Unsupported protocol: " + protocol);1828}18291830public static URL url(String protocol, InetSocketAddress address,1831String path) throws MalformedURLException {1832return new URL(protocol(protocol),1833address.getHostString(),1834address.getPort(), path);1835}18361837public static URI uri(String protocol, InetSocketAddress address,1838String path) throws URISyntaxException {1839return new URI(protocol(protocol) + "://" +1840address.getHostString() + ":" +1841address.getPort() + path);1842}1843}184418451846