private void ntlmChallenge(
      String authenticateHeader, //
      Request request, //
      HttpHeaders headers, //
      Realm realm, //
      NettyResponseFuture<?> future) {

    if (authenticateHeader.equals("NTLM")) {
      // server replied bare NTLM => we didn't preemptively sent Type1Msg
      String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
      // FIXME we might want to filter current NTLM and add (leave other
      // Authorization headers untouched)
      headers.set(HttpHeaders.Names.AUTHORIZATION, "NTLM " + challengeHeader);
      future.getInAuth().set(false);

    } else {
      String serverChallenge = authenticateHeader.substring("NTLM ".length()).trim();
      String challengeHeader =
          NtlmEngine.INSTANCE.generateType3Msg(
              realm.getPrincipal(),
              realm.getPassword(),
              realm.getNtlmDomain(),
              realm.getNtlmHost(),
              serverChallenge);
      // FIXME we might want to filter current NTLM and add (leave other
      // Authorization headers untouched)
      headers.set(HttpHeaders.Names.AUTHORIZATION, "NTLM " + challengeHeader);
    }
  }
  public static String perConnectionAuthorizationHeader(
      Request request, ProxyServer proxyServer, Realm realm) {
    String authorizationHeader = null;

    if (realm != null && realm.getUsePreemptiveAuth()) {
      switch (realm.getScheme()) {
        case NTLM:
          String msg = NtlmEngine.INSTANCE.generateType1Msg();
          authorizationHeader = "NTLM " + msg;
          break;
        case KERBEROS:
        case SPNEGO:
          String host;
          if (proxyServer != null) host = proxyServer.getHost();
          else if (request.getVirtualHost() != null) host = request.getVirtualHost();
          else host = request.getUri().getHost();

          authorizationHeader = "Negotiate " + SpnegoEngine.instance().generateToken(host);
          break;
        default:
          break;
      }
    }

    return authorizationHeader;
  }
  public static String perConnectionProxyAuthorizationHeader(
      Request request, ProxyServer proxyServer, boolean connect) {
    String proxyAuthorization = null;

    if (connect) {
      List<String> auth = getProxyAuthorizationHeader(request);
      String ntlmHeader = getNTLM(auth);
      if (ntlmHeader != null) {
        proxyAuthorization = ntlmHeader;
      }

    } else if (proxyServer != null
        && proxyServer.getPrincipal() != null
        && proxyServer.getScheme().isLikeNtlm()) {
      List<String> auth = getProxyAuthorizationHeader(request);
      if (getNTLM(auth) == null) {
        String msg = NtlmEngine.INSTANCE.generateType1Msg();
        proxyAuthorization = "NTLM " + msg;
      }
    }

    return proxyAuthorization;
  }