import FIREFOX_52_6_0esr_RELEASE from mozilla-esr52 hg repo

This commit is contained in:
Roy Tam 2018-01-19 03:59:58 +08:00
commit dcd9973243
150858 changed files with 23884658 additions and 0 deletions

View file

@ -0,0 +1,169 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package ch.boye.httpclientandroidlib.impl.auth;
import java.util.Locale;
import ch.boye.httpclientandroidlib.FormattedHeader;
import ch.boye.httpclientandroidlib.Header;
import ch.boye.httpclientandroidlib.HttpRequest;
import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
import ch.boye.httpclientandroidlib.auth.AUTH;
import ch.boye.httpclientandroidlib.auth.AuthenticationException;
import ch.boye.httpclientandroidlib.auth.ChallengeState;
import ch.boye.httpclientandroidlib.auth.ContextAwareAuthScheme;
import ch.boye.httpclientandroidlib.auth.Credentials;
import ch.boye.httpclientandroidlib.auth.MalformedChallengeException;
import ch.boye.httpclientandroidlib.protocol.HTTP;
import ch.boye.httpclientandroidlib.protocol.HttpContext;
import ch.boye.httpclientandroidlib.util.Args;
import ch.boye.httpclientandroidlib.util.CharArrayBuffer;
/**
* Abstract authentication scheme class that serves as a basis
* for all authentication schemes supported by HttpClient. This class
* defines the generic way of parsing an authentication challenge. It
* does not make any assumptions regarding the format of the challenge
* nor does it impose any specific way of responding to that challenge.
*
*
* @since 4.0
*/
@NotThreadSafe
public abstract class AuthSchemeBase implements ContextAwareAuthScheme {
private ChallengeState challengeState;
/**
* Creates an instance of <tt>AuthSchemeBase</tt> with the given challenge
* state.
*
* @since 4.2
*
* @deprecated (4.3) do not use.
*/
@Deprecated
public AuthSchemeBase(final ChallengeState challengeState) {
super();
this.challengeState = challengeState;
}
public AuthSchemeBase() {
super();
}
/**
* Processes the given challenge token. Some authentication schemes
* may involve multiple challenge-response exchanges. Such schemes must be able
* to maintain the state information when dealing with sequential challenges
*
* @param header the challenge header
*
* @throws MalformedChallengeException is thrown if the authentication challenge
* is malformed
*/
public void processChallenge(final Header header) throws MalformedChallengeException {
Args.notNull(header, "Header");
final String authheader = header.getName();
if (authheader.equalsIgnoreCase(AUTH.WWW_AUTH)) {
this.challengeState = ChallengeState.TARGET;
} else if (authheader.equalsIgnoreCase(AUTH.PROXY_AUTH)) {
this.challengeState = ChallengeState.PROXY;
} else {
throw new MalformedChallengeException("Unexpected header name: " + authheader);
}
final CharArrayBuffer buffer;
int pos;
if (header instanceof FormattedHeader) {
buffer = ((FormattedHeader) header).getBuffer();
pos = ((FormattedHeader) header).getValuePos();
} else {
final String s = header.getValue();
if (s == null) {
throw new MalformedChallengeException("Header value is null");
}
buffer = new CharArrayBuffer(s.length());
buffer.append(s);
pos = 0;
}
while (pos < buffer.length() && HTTP.isWhitespace(buffer.charAt(pos))) {
pos++;
}
final int beginIndex = pos;
while (pos < buffer.length() && !HTTP.isWhitespace(buffer.charAt(pos))) {
pos++;
}
final int endIndex = pos;
final String s = buffer.substring(beginIndex, endIndex);
if (!s.equalsIgnoreCase(getSchemeName())) {
throw new MalformedChallengeException("Invalid scheme identifier: " + s);
}
parseChallenge(buffer, pos, buffer.length());
}
@SuppressWarnings("deprecation")
public Header authenticate(
final Credentials credentials,
final HttpRequest request,
final HttpContext context) throws AuthenticationException {
return authenticate(credentials, request);
}
protected abstract void parseChallenge(
CharArrayBuffer buffer, int beginIndex, int endIndex) throws MalformedChallengeException;
/**
* Returns <code>true</code> if authenticating against a proxy, <code>false</code>
* otherwise.
*/
public boolean isProxy() {
return this.challengeState != null && this.challengeState == ChallengeState.PROXY;
}
/**
* Returns {@link ChallengeState} value or <code>null</code> if unchallenged.
*
* @since 4.2
*/
public ChallengeState getChallengeState() {
return this.challengeState;
}
@Override
public String toString() {
final String name = getSchemeName();
if (name != null) {
return name.toUpperCase(Locale.ENGLISH);
} else {
return super.toString();
}
}
}

View file

@ -0,0 +1,219 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package ch.boye.httpclientandroidlib.impl.auth;
import java.nio.charset.Charset;
import org.mozilla.apache.commons.codec.binary.Base64;
import ch.boye.httpclientandroidlib.Consts;
import ch.boye.httpclientandroidlib.Header;
import ch.boye.httpclientandroidlib.HttpRequest;
import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
import ch.boye.httpclientandroidlib.auth.AUTH;
import ch.boye.httpclientandroidlib.auth.AuthenticationException;
import ch.boye.httpclientandroidlib.auth.ChallengeState;
import ch.boye.httpclientandroidlib.auth.Credentials;
import ch.boye.httpclientandroidlib.auth.MalformedChallengeException;
import ch.boye.httpclientandroidlib.message.BufferedHeader;
import ch.boye.httpclientandroidlib.protocol.BasicHttpContext;
import ch.boye.httpclientandroidlib.protocol.HttpContext;
import ch.boye.httpclientandroidlib.util.Args;
import ch.boye.httpclientandroidlib.util.CharArrayBuffer;
import ch.boye.httpclientandroidlib.util.EncodingUtils;
/**
* Basic authentication scheme as defined in RFC 2617.
*
* @since 4.0
*/
@NotThreadSafe
public class BasicScheme extends RFC2617Scheme {
/* Base64 instance removed by HttpClient for Android script. */
/** Whether the basic authentication process is complete */
private boolean complete;
/**
* @since 4.3
*/
public BasicScheme(final Charset credentialsCharset) {
super(credentialsCharset);
/* Base64 instance removed by HttpClient for Android script. */
this.complete = false;
}
/**
* Creates an instance of <tt>BasicScheme</tt> with the given challenge
* state.
*
* @since 4.2
*
* @deprecated (4.3) do not use.
*/
@Deprecated
public BasicScheme(final ChallengeState challengeState) {
super(challengeState);
/* Base64 instance removed by HttpClient for Android script. */
}
public BasicScheme() {
this(Consts.ASCII);
}
/**
* Returns textual designation of the basic authentication scheme.
*
* @return <code>basic</code>
*/
public String getSchemeName() {
return "basic";
}
/**
* Processes the Basic challenge.
*
* @param header the challenge header
*
* @throws MalformedChallengeException is thrown if the authentication challenge
* is malformed
*/
@Override
public void processChallenge(
final Header header) throws MalformedChallengeException {
super.processChallenge(header);
this.complete = true;
}
/**
* Tests if the Basic authentication process has been completed.
*
* @return <tt>true</tt> if Basic authorization has been processed,
* <tt>false</tt> otherwise.
*/
public boolean isComplete() {
return this.complete;
}
/**
* Returns <tt>false</tt>. Basic authentication scheme is request based.
*
* @return <tt>false</tt>.
*/
public boolean isConnectionBased() {
return false;
}
/**
* @deprecated (4.2) Use {@link ch.boye.httpclientandroidlib.auth.ContextAwareAuthScheme#authenticate(
* Credentials, HttpRequest, ch.boye.httpclientandroidlib.protocol.HttpContext)}
*/
@Deprecated
public Header authenticate(
final Credentials credentials, final HttpRequest request) throws AuthenticationException {
return authenticate(credentials, request, new BasicHttpContext());
}
/**
* Produces basic authorization header for the given set of {@link Credentials}.
*
* @param credentials The set of credentials to be used for authentication
* @param request The request being authenticated
* @throws ch.boye.httpclientandroidlib.auth.InvalidCredentialsException if authentication
* credentials are not valid or not applicable for this authentication scheme
* @throws AuthenticationException if authorization string cannot
* be generated due to an authentication failure
*
* @return a basic authorization string
*/
@Override
public Header authenticate(
final Credentials credentials,
final HttpRequest request,
final HttpContext context) throws AuthenticationException {
Args.notNull(credentials, "Credentials");
Args.notNull(request, "HTTP request");
final StringBuilder tmp = new StringBuilder();
tmp.append(credentials.getUserPrincipal().getName());
tmp.append(":");
tmp.append((credentials.getPassword() == null) ? "null" : credentials.getPassword());
final byte[] base64password = Base64.encodeBase64(
EncodingUtils.getBytes(tmp.toString(), getCredentialsCharset(request)));
final CharArrayBuffer buffer = new CharArrayBuffer(32);
if (isProxy()) {
buffer.append(AUTH.PROXY_AUTH_RESP);
} else {
buffer.append(AUTH.WWW_AUTH_RESP);
}
buffer.append(": Basic ");
buffer.append(base64password, 0, base64password.length);
return new BufferedHeader(buffer);
}
/**
* Returns a basic <tt>Authorization</tt> header value for the given
* {@link Credentials} and charset.
*
* @param credentials The credentials to encode.
* @param charset The charset to use for encoding the credentials
*
* @return a basic authorization header
*
* @deprecated (4.3) use {@link #authenticate(Credentials, HttpRequest, HttpContext)}.
*/
@Deprecated
public static Header authenticate(
final Credentials credentials,
final String charset,
final boolean proxy) {
Args.notNull(credentials, "Credentials");
Args.notNull(charset, "charset");
final StringBuilder tmp = new StringBuilder();
tmp.append(credentials.getUserPrincipal().getName());
tmp.append(":");
tmp.append((credentials.getPassword() == null) ? "null" : credentials.getPassword());
final byte[] base64password = Base64.encodeBase64(
EncodingUtils.getBytes(tmp.toString(), charset));
final CharArrayBuffer buffer = new CharArrayBuffer(32);
if (proxy) {
buffer.append(AUTH.PROXY_AUTH_RESP);
} else {
buffer.append(AUTH.WWW_AUTH_RESP);
}
buffer.append(": Basic ");
buffer.append(base64password, 0, base64password.length);
return new BufferedHeader(buffer);
}
}

View file

@ -0,0 +1,71 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package ch.boye.httpclientandroidlib.impl.auth;
import java.nio.charset.Charset;
import ch.boye.httpclientandroidlib.annotation.Immutable;
import ch.boye.httpclientandroidlib.auth.AuthScheme;
import ch.boye.httpclientandroidlib.auth.AuthSchemeFactory;
import ch.boye.httpclientandroidlib.auth.AuthSchemeProvider;
import ch.boye.httpclientandroidlib.params.HttpParams;
import ch.boye.httpclientandroidlib.protocol.HttpContext;
/**
* {@link AuthSchemeProvider} implementation that creates and initializes
* {@link BasicScheme} instances.
*
* @since 4.0
*/
@Immutable
@SuppressWarnings("deprecation")
public class BasicSchemeFactory implements AuthSchemeFactory, AuthSchemeProvider {
private final Charset charset;
/**
* @since 4.3
*/
public BasicSchemeFactory(final Charset charset) {
super();
this.charset = charset;
}
public BasicSchemeFactory() {
this(null);
}
public AuthScheme newInstance(final HttpParams params) {
return new BasicScheme();
}
public AuthScheme create(final HttpContext context) {
return new BasicScheme(this.charset);
}
}

View file

@ -0,0 +1,489 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package ch.boye.httpclientandroidlib.impl.auth;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.StringTokenizer;
import ch.boye.httpclientandroidlib.Consts;
import ch.boye.httpclientandroidlib.Header;
import ch.boye.httpclientandroidlib.HttpEntity;
import ch.boye.httpclientandroidlib.HttpEntityEnclosingRequest;
import ch.boye.httpclientandroidlib.HttpRequest;
import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
import ch.boye.httpclientandroidlib.auth.AUTH;
import ch.boye.httpclientandroidlib.auth.AuthenticationException;
import ch.boye.httpclientandroidlib.auth.ChallengeState;
import ch.boye.httpclientandroidlib.auth.Credentials;
import ch.boye.httpclientandroidlib.auth.MalformedChallengeException;
import ch.boye.httpclientandroidlib.message.BasicHeaderValueFormatter;
import ch.boye.httpclientandroidlib.message.BasicNameValuePair;
import ch.boye.httpclientandroidlib.message.BufferedHeader;
import ch.boye.httpclientandroidlib.protocol.BasicHttpContext;
import ch.boye.httpclientandroidlib.protocol.HttpContext;
import ch.boye.httpclientandroidlib.util.Args;
import ch.boye.httpclientandroidlib.util.CharArrayBuffer;
import ch.boye.httpclientandroidlib.util.EncodingUtils;
/**
* Digest authentication scheme as defined in RFC 2617.
* Both MD5 (default) and MD5-sess are supported.
* Currently only qop=auth or no qop is supported. qop=auth-int
* is unsupported. If auth and auth-int are provided, auth is
* used.
* <p/>
* Since the digest username is included as clear text in the generated
* Authentication header, the charset of the username must be compatible
* with the HTTP element charset used by the connection.
*
* @since 4.0
*/
@NotThreadSafe
public class DigestScheme extends RFC2617Scheme {
/**
* Hexa values used when creating 32 character long digest in HTTP DigestScheme
* in case of authentication.
*
* @see #encode(byte[])
*/
private static final char[] HEXADECIMAL = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
'e', 'f'
};
/** Whether the digest authentication process is complete */
private boolean complete;
private static final int QOP_UNKNOWN = -1;
private static final int QOP_MISSING = 0;
private static final int QOP_AUTH_INT = 1;
private static final int QOP_AUTH = 2;
private String lastNonce;
private long nounceCount;
private String cnonce;
private String a1;
private String a2;
/**
* @since 4.3
*/
public DigestScheme(final Charset credentialsCharset) {
super(credentialsCharset);
this.complete = false;
}
/**
* Creates an instance of <tt>DigestScheme</tt> with the given challenge
* state.
*
* @since 4.2
*
* @deprecated (4.3) do not use.
*/
@Deprecated
public DigestScheme(final ChallengeState challengeState) {
super(challengeState);
}
public DigestScheme() {
this(Consts.ASCII);
}
/**
* Processes the Digest challenge.
*
* @param header the challenge header
*
* @throws MalformedChallengeException is thrown if the authentication challenge
* is malformed
*/
@Override
public void processChallenge(
final Header header) throws MalformedChallengeException {
super.processChallenge(header);
this.complete = true;
}
/**
* Tests if the Digest authentication process has been completed.
*
* @return <tt>true</tt> if Digest authorization has been processed,
* <tt>false</tt> otherwise.
*/
public boolean isComplete() {
final String s = getParameter("stale");
if ("true".equalsIgnoreCase(s)) {
return false;
} else {
return this.complete;
}
}
/**
* Returns textual designation of the digest authentication scheme.
*
* @return <code>digest</code>
*/
public String getSchemeName() {
return "digest";
}
/**
* Returns <tt>false</tt>. Digest authentication scheme is request based.
*
* @return <tt>false</tt>.
*/
public boolean isConnectionBased() {
return false;
}
public void overrideParamter(final String name, final String value) {
getParameters().put(name, value);
}
/**
* @deprecated (4.2) Use {@link ch.boye.httpclientandroidlib.auth.ContextAwareAuthScheme#authenticate(
* Credentials, HttpRequest, ch.boye.httpclientandroidlib.protocol.HttpContext)}
*/
@Deprecated
public Header authenticate(
final Credentials credentials, final HttpRequest request) throws AuthenticationException {
return authenticate(credentials, request, new BasicHttpContext());
}
/**
* Produces a digest authorization string for the given set of
* {@link Credentials}, method name and URI.
*
* @param credentials A set of credentials to be used for athentication
* @param request The request being authenticated
*
* @throws ch.boye.httpclientandroidlib.auth.InvalidCredentialsException if authentication credentials
* are not valid or not applicable for this authentication scheme
* @throws AuthenticationException if authorization string cannot
* be generated due to an authentication failure
*
* @return a digest authorization string
*/
@Override
public Header authenticate(
final Credentials credentials,
final HttpRequest request,
final HttpContext context) throws AuthenticationException {
Args.notNull(credentials, "Credentials");
Args.notNull(request, "HTTP request");
if (getParameter("realm") == null) {
throw new AuthenticationException("missing realm in challenge");
}
if (getParameter("nonce") == null) {
throw new AuthenticationException("missing nonce in challenge");
}
// Add method name and request-URI to the parameter map
getParameters().put("methodname", request.getRequestLine().getMethod());
getParameters().put("uri", request.getRequestLine().getUri());
final String charset = getParameter("charset");
if (charset == null) {
getParameters().put("charset", getCredentialsCharset(request));
}
return createDigestHeader(credentials, request);
}
private static MessageDigest createMessageDigest(
final String digAlg) throws UnsupportedDigestAlgorithmException {
try {
return MessageDigest.getInstance(digAlg);
} catch (final Exception e) {
throw new UnsupportedDigestAlgorithmException(
"Unsupported algorithm in HTTP Digest authentication: "
+ digAlg);
}
}
/**
* Creates digest-response header as defined in RFC2617.
*
* @param credentials User credentials
*
* @return The digest-response as String.
*/
private Header createDigestHeader(
final Credentials credentials,
final HttpRequest request) throws AuthenticationException {
final String uri = getParameter("uri");
final String realm = getParameter("realm");
final String nonce = getParameter("nonce");
final String opaque = getParameter("opaque");
final String method = getParameter("methodname");
String algorithm = getParameter("algorithm");
// If an algorithm is not specified, default to MD5.
if (algorithm == null) {
algorithm = "MD5";
}
final Set<String> qopset = new HashSet<String>(8);
int qop = QOP_UNKNOWN;
final String qoplist = getParameter("qop");
if (qoplist != null) {
final StringTokenizer tok = new StringTokenizer(qoplist, ",");
while (tok.hasMoreTokens()) {
final String variant = tok.nextToken().trim();
qopset.add(variant.toLowerCase(Locale.ENGLISH));
}
if (request instanceof HttpEntityEnclosingRequest && qopset.contains("auth-int")) {
qop = QOP_AUTH_INT;
} else if (qopset.contains("auth")) {
qop = QOP_AUTH;
}
} else {
qop = QOP_MISSING;
}
if (qop == QOP_UNKNOWN) {
throw new AuthenticationException("None of the qop methods is supported: " + qoplist);
}
String charset = getParameter("charset");
if (charset == null) {
charset = "ISO-8859-1";
}
String digAlg = algorithm;
if (digAlg.equalsIgnoreCase("MD5-sess")) {
digAlg = "MD5";
}
final MessageDigest digester;
try {
digester = createMessageDigest(digAlg);
} catch (final UnsupportedDigestAlgorithmException ex) {
throw new AuthenticationException("Unsuppported digest algorithm: " + digAlg);
}
final String uname = credentials.getUserPrincipal().getName();
final String pwd = credentials.getPassword();
if (nonce.equals(this.lastNonce)) {
nounceCount++;
} else {
nounceCount = 1;
cnonce = null;
lastNonce = nonce;
}
final StringBuilder sb = new StringBuilder(256);
final Formatter formatter = new Formatter(sb, Locale.US);
formatter.format("%08x", nounceCount);
formatter.close();
final String nc = sb.toString();
if (cnonce == null) {
cnonce = createCnonce();
}
a1 = null;
a2 = null;
// 3.2.2.2: Calculating digest
if (algorithm.equalsIgnoreCase("MD5-sess")) {
// H( unq(username-value) ":" unq(realm-value) ":" passwd )
// ":" unq(nonce-value)
// ":" unq(cnonce-value)
// calculated one per session
sb.setLength(0);
sb.append(uname).append(':').append(realm).append(':').append(pwd);
final String checksum = encode(digester.digest(EncodingUtils.getBytes(sb.toString(), charset)));
sb.setLength(0);
sb.append(checksum).append(':').append(nonce).append(':').append(cnonce);
a1 = sb.toString();
} else {
// unq(username-value) ":" unq(realm-value) ":" passwd
sb.setLength(0);
sb.append(uname).append(':').append(realm).append(':').append(pwd);
a1 = sb.toString();
}
final String hasha1 = encode(digester.digest(EncodingUtils.getBytes(a1, charset)));
if (qop == QOP_AUTH) {
// Method ":" digest-uri-value
a2 = method + ':' + uri;
} else if (qop == QOP_AUTH_INT) {
// Method ":" digest-uri-value ":" H(entity-body)
HttpEntity entity = null;
if (request instanceof HttpEntityEnclosingRequest) {
entity = ((HttpEntityEnclosingRequest) request).getEntity();
}
if (entity != null && !entity.isRepeatable()) {
// If the entity is not repeatable, try falling back onto QOP_AUTH
if (qopset.contains("auth")) {
qop = QOP_AUTH;
a2 = method + ':' + uri;
} else {
throw new AuthenticationException("Qop auth-int cannot be used with " +
"a non-repeatable entity");
}
} else {
final HttpEntityDigester entityDigester = new HttpEntityDigester(digester);
try {
if (entity != null) {
entity.writeTo(entityDigester);
}
entityDigester.close();
} catch (final IOException ex) {
throw new AuthenticationException("I/O error reading entity content", ex);
}
a2 = method + ':' + uri + ':' + encode(entityDigester.getDigest());
}
} else {
a2 = method + ':' + uri;
}
final String hasha2 = encode(digester.digest(EncodingUtils.getBytes(a2, charset)));
// 3.2.2.1
final String digestValue;
if (qop == QOP_MISSING) {
sb.setLength(0);
sb.append(hasha1).append(':').append(nonce).append(':').append(hasha2);
digestValue = sb.toString();
} else {
sb.setLength(0);
sb.append(hasha1).append(':').append(nonce).append(':').append(nc).append(':')
.append(cnonce).append(':').append(qop == QOP_AUTH_INT ? "auth-int" : "auth")
.append(':').append(hasha2);
digestValue = sb.toString();
}
final String digest = encode(digester.digest(EncodingUtils.getAsciiBytes(digestValue)));
final CharArrayBuffer buffer = new CharArrayBuffer(128);
if (isProxy()) {
buffer.append(AUTH.PROXY_AUTH_RESP);
} else {
buffer.append(AUTH.WWW_AUTH_RESP);
}
buffer.append(": Digest ");
final List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(20);
params.add(new BasicNameValuePair("username", uname));
params.add(new BasicNameValuePair("realm", realm));
params.add(new BasicNameValuePair("nonce", nonce));
params.add(new BasicNameValuePair("uri", uri));
params.add(new BasicNameValuePair("response", digest));
if (qop != QOP_MISSING) {
params.add(new BasicNameValuePair("qop", qop == QOP_AUTH_INT ? "auth-int" : "auth"));
params.add(new BasicNameValuePair("nc", nc));
params.add(new BasicNameValuePair("cnonce", cnonce));
}
// algorithm cannot be null here
params.add(new BasicNameValuePair("algorithm", algorithm));
if (opaque != null) {
params.add(new BasicNameValuePair("opaque", opaque));
}
for (int i = 0; i < params.size(); i++) {
final BasicNameValuePair param = params.get(i);
if (i > 0) {
buffer.append(", ");
}
final String name = param.getName();
final boolean noQuotes = ("nc".equals(name) || "qop".equals(name)
|| "algorithm".equals(name));
BasicHeaderValueFormatter.INSTANCE.formatNameValuePair(buffer, param, !noQuotes);
}
return new BufferedHeader(buffer);
}
String getCnonce() {
return cnonce;
}
String getA1() {
return a1;
}
String getA2() {
return a2;
}
/**
* Encodes the 128 bit (16 bytes) MD5 digest into a 32 characters long
* <CODE>String</CODE> according to RFC 2617.
*
* @param binaryData array containing the digest
* @return encoded MD5, or <CODE>null</CODE> if encoding failed
*/
static String encode(final byte[] binaryData) {
final int n = binaryData.length;
final char[] buffer = new char[n * 2];
for (int i = 0; i < n; i++) {
final int low = (binaryData[i] & 0x0f);
final int high = ((binaryData[i] & 0xf0) >> 4);
buffer[i * 2] = HEXADECIMAL[high];
buffer[(i * 2) + 1] = HEXADECIMAL[low];
}
return new String(buffer);
}
/**
* Creates a random cnonce value based on the current time.
*
* @return The cnonce value as String.
*/
public static String createCnonce() {
final SecureRandom rnd = new SecureRandom();
final byte[] tmp = new byte[8];
rnd.nextBytes(tmp);
return encode(tmp);
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("DIGEST [complete=").append(complete)
.append(", nonce=").append(lastNonce)
.append(", nc=").append(nounceCount)
.append("]");
return builder.toString();
}
}

View file

@ -0,0 +1,71 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package ch.boye.httpclientandroidlib.impl.auth;
import java.nio.charset.Charset;
import ch.boye.httpclientandroidlib.annotation.Immutable;
import ch.boye.httpclientandroidlib.auth.AuthScheme;
import ch.boye.httpclientandroidlib.auth.AuthSchemeFactory;
import ch.boye.httpclientandroidlib.auth.AuthSchemeProvider;
import ch.boye.httpclientandroidlib.params.HttpParams;
import ch.boye.httpclientandroidlib.protocol.HttpContext;
/**
* {@link AuthSchemeProvider} implementation that creates and initializes
* {@link DigestScheme} instances.
*
* @since 4.0
*/
@Immutable
@SuppressWarnings("deprecation")
public class DigestSchemeFactory implements AuthSchemeFactory, AuthSchemeProvider {
private final Charset charset;
/**
* @since 4.3
*/
public DigestSchemeFactory(final Charset charset) {
super();
this.charset = charset;
}
public DigestSchemeFactory() {
this(null);
}
public AuthScheme newInstance(final HttpParams params) {
return new DigestScheme();
}
public AuthScheme create(final HttpContext context) {
return new DigestScheme(this.charset);
}
}

View file

@ -0,0 +1,245 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package ch.boye.httpclientandroidlib.impl.auth;
import java.io.IOException;
import java.util.Locale;
import java.util.Map;
import java.util.Queue;
import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
/* LogFactory removed by HttpClient for Android script. */
import ch.boye.httpclientandroidlib.Header;
import ch.boye.httpclientandroidlib.HttpException;
import ch.boye.httpclientandroidlib.HttpHost;
import ch.boye.httpclientandroidlib.HttpRequest;
import ch.boye.httpclientandroidlib.HttpResponse;
import ch.boye.httpclientandroidlib.auth.AuthOption;
import ch.boye.httpclientandroidlib.auth.AuthProtocolState;
import ch.boye.httpclientandroidlib.auth.AuthScheme;
import ch.boye.httpclientandroidlib.auth.AuthState;
import ch.boye.httpclientandroidlib.auth.AuthenticationException;
import ch.boye.httpclientandroidlib.auth.ContextAwareAuthScheme;
import ch.boye.httpclientandroidlib.auth.Credentials;
import ch.boye.httpclientandroidlib.auth.MalformedChallengeException;
import ch.boye.httpclientandroidlib.client.AuthenticationStrategy;
import ch.boye.httpclientandroidlib.protocol.HttpContext;
import ch.boye.httpclientandroidlib.util.Asserts;
/**
* @since 4.3
*/
public class HttpAuthenticator {
public HttpClientAndroidLog log;
public HttpAuthenticator(final HttpClientAndroidLog log) {
super();
this.log = log != null ? log : new HttpClientAndroidLog(getClass());
}
public HttpAuthenticator() {
this(null);
}
public boolean isAuthenticationRequested(
final HttpHost host,
final HttpResponse response,
final AuthenticationStrategy authStrategy,
final AuthState authState,
final HttpContext context) {
if (authStrategy.isAuthenticationRequested(host, response, context)) {
this.log.debug("Authentication required");
if (authState.getState() == AuthProtocolState.SUCCESS) {
authStrategy.authFailed(host, authState.getAuthScheme(), context);
}
return true;
} else {
switch (authState.getState()) {
case CHALLENGED:
case HANDSHAKE:
this.log.debug("Authentication succeeded");
authState.setState(AuthProtocolState.SUCCESS);
authStrategy.authSucceeded(host, authState.getAuthScheme(), context);
break;
case SUCCESS:
break;
default:
authState.setState(AuthProtocolState.UNCHALLENGED);
}
return false;
}
}
public boolean handleAuthChallenge(
final HttpHost host,
final HttpResponse response,
final AuthenticationStrategy authStrategy,
final AuthState authState,
final HttpContext context) {
try {
if (this.log.isDebugEnabled()) {
this.log.debug(host.toHostString() + " requested authentication");
}
final Map<String, Header> challenges = authStrategy.getChallenges(host, response, context);
if (challenges.isEmpty()) {
this.log.debug("Response contains no authentication challenges");
return false;
}
final AuthScheme authScheme = authState.getAuthScheme();
switch (authState.getState()) {
case FAILURE:
return false;
case SUCCESS:
authState.reset();
break;
case CHALLENGED:
case HANDSHAKE:
if (authScheme == null) {
this.log.debug("Auth scheme is null");
authStrategy.authFailed(host, null, context);
authState.reset();
authState.setState(AuthProtocolState.FAILURE);
return false;
}
case UNCHALLENGED:
if (authScheme != null) {
final String id = authScheme.getSchemeName();
final Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH));
if (challenge != null) {
this.log.debug("Authorization challenge processed");
authScheme.processChallenge(challenge);
if (authScheme.isComplete()) {
this.log.debug("Authentication failed");
authStrategy.authFailed(host, authState.getAuthScheme(), context);
authState.reset();
authState.setState(AuthProtocolState.FAILURE);
return false;
} else {
authState.setState(AuthProtocolState.HANDSHAKE);
return true;
}
} else {
authState.reset();
// Retry authentication with a different scheme
}
}
}
final Queue<AuthOption> authOptions = authStrategy.select(challenges, host, response, context);
if (authOptions != null && !authOptions.isEmpty()) {
if (this.log.isDebugEnabled()) {
this.log.debug("Selected authentication options: " + authOptions);
}
authState.setState(AuthProtocolState.CHALLENGED);
authState.update(authOptions);
return true;
} else {
return false;
}
} catch (final MalformedChallengeException ex) {
if (this.log.isWarnEnabled()) {
this.log.warn("Malformed challenge: " + ex.getMessage());
}
authState.reset();
return false;
}
}
public void generateAuthResponse(
final HttpRequest request,
final AuthState authState,
final HttpContext context) throws HttpException, IOException {
AuthScheme authScheme = authState.getAuthScheme();
Credentials creds = authState.getCredentials();
switch (authState.getState()) {
case FAILURE:
return;
case SUCCESS:
ensureAuthScheme(authScheme);
if (authScheme.isConnectionBased()) {
return;
}
break;
case CHALLENGED:
final Queue<AuthOption> authOptions = authState.getAuthOptions();
if (authOptions != null) {
while (!authOptions.isEmpty()) {
final AuthOption authOption = authOptions.remove();
authScheme = authOption.getAuthScheme();
creds = authOption.getCredentials();
authState.update(authScheme, creds);
if (this.log.isDebugEnabled()) {
this.log.debug("Generating response to an authentication challenge using "
+ authScheme.getSchemeName() + " scheme");
}
try {
final Header header = doAuth(authScheme, creds, request, context);
request.addHeader(header);
break;
} catch (final AuthenticationException ex) {
if (this.log.isWarnEnabled()) {
this.log.warn(authScheme + " authentication error: " + ex.getMessage());
}
}
}
return;
} else {
ensureAuthScheme(authScheme);
}
}
if (authScheme != null) {
try {
final Header header = doAuth(authScheme, creds, request, context);
request.addHeader(header);
} catch (final AuthenticationException ex) {
if (this.log.isErrorEnabled()) {
this.log.error(authScheme + " authentication error: " + ex.getMessage());
}
}
}
}
private void ensureAuthScheme(final AuthScheme authScheme) {
Asserts.notNull(authScheme, "Auth scheme");
}
@SuppressWarnings("deprecation")
private Header doAuth(
final AuthScheme authScheme,
final Credentials creds,
final HttpRequest request,
final HttpContext context) throws AuthenticationException {
if (authScheme instanceof ContextAwareAuthScheme) {
return ((ContextAwareAuthScheme) authScheme).authenticate(creds, request, context);
} else {
return authScheme.authenticate(creds, request);
}
}
}

View file

@ -0,0 +1,75 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package ch.boye.httpclientandroidlib.impl.auth;
import java.io.IOException;
import java.io.OutputStream;
import java.security.MessageDigest;
class HttpEntityDigester extends OutputStream {
private final MessageDigest digester;
private boolean closed;
private byte[] digest;
HttpEntityDigester(final MessageDigest digester) {
super();
this.digester = digester;
this.digester.reset();
}
@Override
public void write(final int b) throws IOException {
if (this.closed) {
throw new IOException("Stream has been already closed");
}
this.digester.update((byte) b);
}
@Override
public void write(final byte[] b, final int off, final int len) throws IOException {
if (this.closed) {
throw new IOException("Stream has been already closed");
}
this.digester.update(b, off, len);
}
@Override
public void close() throws IOException {
if (this.closed) {
return;
}
this.closed = true;
this.digest = this.digester.digest();
super.close();
}
public byte[] getDigest() {
return this.digest;
}
}

View file

@ -0,0 +1,70 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package ch.boye.httpclientandroidlib.impl.auth;
/**
* Abstract NTLM authentication engine. The engine can be used to
* generate Type1 messages and Type3 messages in response to a
* Type2 challenge.
*
* @since 4.0
*/
public interface NTLMEngine {
/**
* Generates a Type1 message given the domain and workstation.
*
* @param domain Optional Windows domain name. Can be <code>null</code>.
* @param workstation Optional Windows workstation name. Can be
* <code>null</code>.
* @return Type1 message
* @throws NTLMEngineException
*/
String generateType1Msg(
String domain,
String workstation) throws NTLMEngineException;
/**
* Generates a Type3 message given the user credentials and the
* authentication challenge.
*
* @param username Windows user name
* @param password Password
* @param domain Windows domain name
* @param workstation Windows workstation name
* @param challenge Type2 challenge.
* @return Type3 response.
* @throws NTLMEngineException
*/
String generateType3Msg(
String username,
String password,
String domain,
String workstation,
String challenge) throws NTLMEngineException;
}

View file

@ -0,0 +1,67 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package ch.boye.httpclientandroidlib.impl.auth;
import ch.boye.httpclientandroidlib.annotation.Immutable;
import ch.boye.httpclientandroidlib.auth.AuthenticationException;
/**
* Signals NTLM protocol failure.
*
*
* @since 4.0
*/
@Immutable
public class NTLMEngineException extends AuthenticationException {
private static final long serialVersionUID = 6027981323731768824L;
public NTLMEngineException() {
super();
}
/**
* Creates a new NTLMEngineException with the specified message.
*
* @param message the exception detail message
*/
public NTLMEngineException(final String message) {
super(message);
}
/**
* Creates a new NTLMEngineException with the specified detail message and cause.
*
* @param message the exception detail message
* @param cause the <tt>Throwable</tt> that caused this exception, or <tt>null</tt>
* if the cause is unavailable, unknown, or not a <tt>Throwable</tt>
*/
public NTLMEngineException(final String message, final Throwable cause) {
super(message, cause);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,164 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package ch.boye.httpclientandroidlib.impl.auth;
import ch.boye.httpclientandroidlib.Header;
import ch.boye.httpclientandroidlib.HttpRequest;
import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
import ch.boye.httpclientandroidlib.auth.AUTH;
import ch.boye.httpclientandroidlib.auth.AuthenticationException;
import ch.boye.httpclientandroidlib.auth.Credentials;
import ch.boye.httpclientandroidlib.auth.InvalidCredentialsException;
import ch.boye.httpclientandroidlib.auth.MalformedChallengeException;
import ch.boye.httpclientandroidlib.auth.NTCredentials;
import ch.boye.httpclientandroidlib.message.BufferedHeader;
import ch.boye.httpclientandroidlib.util.Args;
import ch.boye.httpclientandroidlib.util.CharArrayBuffer;
/**
* NTLM is a proprietary authentication scheme developed by Microsoft
* and optimized for Windows platforms.
*
* @since 4.0
*/
@NotThreadSafe
public class NTLMScheme extends AuthSchemeBase {
enum State {
UNINITIATED,
CHALLENGE_RECEIVED,
MSG_TYPE1_GENERATED,
MSG_TYPE2_RECEVIED,
MSG_TYPE3_GENERATED,
FAILED,
}
private final NTLMEngine engine;
private State state;
private String challenge;
public NTLMScheme(final NTLMEngine engine) {
super();
Args.notNull(engine, "NTLM engine");
this.engine = engine;
this.state = State.UNINITIATED;
this.challenge = null;
}
/**
* @since 4.3
*/
public NTLMScheme() {
this(new NTLMEngineImpl());
}
public String getSchemeName() {
return "ntlm";
}
public String getParameter(final String name) {
// String parameters not supported
return null;
}
public String getRealm() {
// NTLM does not support the concept of an authentication realm
return null;
}
public boolean isConnectionBased() {
return true;
}
@Override
protected void parseChallenge(
final CharArrayBuffer buffer,
final int beginIndex, final int endIndex) throws MalformedChallengeException {
this.challenge = buffer.substringTrimmed(beginIndex, endIndex);
if (this.challenge.length() == 0) {
if (this.state == State.UNINITIATED) {
this.state = State.CHALLENGE_RECEIVED;
} else {
this.state = State.FAILED;
}
} else {
if (this.state.compareTo(State.MSG_TYPE1_GENERATED) < 0) {
this.state = State.FAILED;
throw new MalformedChallengeException("Out of sequence NTLM response message");
} else if (this.state == State.MSG_TYPE1_GENERATED) {
this.state = State.MSG_TYPE2_RECEVIED;
}
}
}
public Header authenticate(
final Credentials credentials,
final HttpRequest request) throws AuthenticationException {
NTCredentials ntcredentials = null;
try {
ntcredentials = (NTCredentials) credentials;
} catch (final ClassCastException e) {
throw new InvalidCredentialsException(
"Credentials cannot be used for NTLM authentication: "
+ credentials.getClass().getName());
}
String response = null;
if (this.state == State.FAILED) {
throw new AuthenticationException("NTLM authentication failed");
} else if (this.state == State.CHALLENGE_RECEIVED) {
response = this.engine.generateType1Msg(
ntcredentials.getDomain(),
ntcredentials.getWorkstation());
this.state = State.MSG_TYPE1_GENERATED;
} else if (this.state == State.MSG_TYPE2_RECEVIED) {
response = this.engine.generateType3Msg(
ntcredentials.getUserName(),
ntcredentials.getPassword(),
ntcredentials.getDomain(),
ntcredentials.getWorkstation(),
this.challenge);
this.state = State.MSG_TYPE3_GENERATED;
} else {
throw new AuthenticationException("Unexpected state: " + this.state);
}
final CharArrayBuffer buffer = new CharArrayBuffer(32);
if (isProxy()) {
buffer.append(AUTH.PROXY_AUTH_RESP);
} else {
buffer.append(AUTH.WWW_AUTH_RESP);
}
buffer.append(": NTLM ");
buffer.append(response);
return new BufferedHeader(buffer);
}
public boolean isComplete() {
return this.state == State.MSG_TYPE3_GENERATED || this.state == State.FAILED;
}
}

View file

@ -0,0 +1,56 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package ch.boye.httpclientandroidlib.impl.auth;
import ch.boye.httpclientandroidlib.annotation.Immutable;
import ch.boye.httpclientandroidlib.auth.AuthScheme;
import ch.boye.httpclientandroidlib.auth.AuthSchemeFactory;
import ch.boye.httpclientandroidlib.auth.AuthSchemeProvider;
import ch.boye.httpclientandroidlib.params.HttpParams;
import ch.boye.httpclientandroidlib.protocol.HttpContext;
/**
* {@link AuthSchemeProvider} implementation that creates and initializes
* {@link NTLMScheme} instances configured to use the default {@link NTLMEngine}
* implementation.
*
* @since 4.1
*/
@Immutable
@SuppressWarnings("deprecation")
public class NTLMSchemeFactory implements AuthSchemeFactory, AuthSchemeProvider {
public AuthScheme newInstance(final HttpParams params) {
return new NTLMScheme();
}
public AuthScheme create(final HttpContext context) {
return new NTLMScheme();
}
}

View file

@ -0,0 +1,151 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package ch.boye.httpclientandroidlib.impl.auth;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import ch.boye.httpclientandroidlib.Consts;
import ch.boye.httpclientandroidlib.HeaderElement;
import ch.boye.httpclientandroidlib.HttpRequest;
import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
import ch.boye.httpclientandroidlib.auth.ChallengeState;
import ch.boye.httpclientandroidlib.auth.MalformedChallengeException;
import ch.boye.httpclientandroidlib.auth.params.AuthPNames;
import ch.boye.httpclientandroidlib.message.BasicHeaderValueParser;
import ch.boye.httpclientandroidlib.message.HeaderValueParser;
import ch.boye.httpclientandroidlib.message.ParserCursor;
import ch.boye.httpclientandroidlib.util.CharArrayBuffer;
/**
* Abstract authentication scheme class that lays foundation for all
* RFC 2617 compliant authentication schemes and provides capabilities common
* to all authentication schemes defined in RFC 2617.
*
* @since 4.0
*/
@SuppressWarnings("deprecation")
@NotThreadSafe // AuthSchemeBase, params
public abstract class RFC2617Scheme extends AuthSchemeBase {
private final Map<String, String> params;
private final Charset credentialsCharset;
/**
* Creates an instance of <tt>RFC2617Scheme</tt> with the given challenge
* state.
*
* @since 4.2
*
* @deprecated (4.3) do not use.
*/
@Deprecated
public RFC2617Scheme(final ChallengeState challengeState) {
super(challengeState);
this.params = new HashMap<String, String>();
this.credentialsCharset = Consts.ASCII;
}
/**
* @since 4.3
*/
public RFC2617Scheme(final Charset credentialsCharset) {
super();
this.params = new HashMap<String, String>();
this.credentialsCharset = credentialsCharset != null ? credentialsCharset : Consts.ASCII;
}
public RFC2617Scheme() {
this(Consts.ASCII);
}
/**
* @since 4.3
*/
public Charset getCredentialsCharset() {
return credentialsCharset;
}
String getCredentialsCharset(final HttpRequest request) {
String charset = (String) request.getParams().getParameter(AuthPNames.CREDENTIAL_CHARSET);
if (charset == null) {
charset = getCredentialsCharset().name();
}
return charset;
}
@Override
protected void parseChallenge(
final CharArrayBuffer buffer, final int pos, final int len) throws MalformedChallengeException {
final HeaderValueParser parser = BasicHeaderValueParser.INSTANCE;
final ParserCursor cursor = new ParserCursor(pos, buffer.length());
final HeaderElement[] elements = parser.parseElements(buffer, cursor);
if (elements.length == 0) {
throw new MalformedChallengeException("Authentication challenge is empty");
}
this.params.clear();
for (final HeaderElement element : elements) {
this.params.put(element.getName().toLowerCase(Locale.ENGLISH), element.getValue());
}
}
/**
* Returns authentication parameters map. Keys in the map are lower-cased.
*
* @return the map of authentication parameters
*/
protected Map<String, String> getParameters() {
return this.params;
}
/**
* Returns authentication parameter with the given name, if available.
*
* @param name The name of the parameter to be returned
*
* @return the parameter with the given name
*/
public String getParameter(final String name) {
if (name == null) {
return null;
}
return this.params.get(name.toLowerCase(Locale.ENGLISH));
}
/**
* Returns authentication realm. The realm may not be null.
*
* @return the authentication realm
*/
public String getRealm() {
return getParameter("realm");
}
}

View file

@ -0,0 +1,47 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package ch.boye.httpclientandroidlib.impl.auth;
import java.io.IOException;
/**
* Abstract SPNEGO token generator. Implementations should take an Kerberos ticket and transform
* into a SPNEGO token.
* <p>
* Implementations of this interface are expected to be thread-safe.
*
* @since 4.1
*
* @deprecated (4.2) subclass {@link KerberosScheme} and override
* {@link KerberosScheme#generateGSSToken(byte[], org.ietf.jgss.Oid, String)}
*/
@Deprecated
public interface SpnegoTokenGenerator {
byte [] generateSpnegoDERObject(byte [] kerberosTicket) throws IOException;
}

View file

@ -0,0 +1,69 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package ch.boye.httpclientandroidlib.impl.auth;
import ch.boye.httpclientandroidlib.annotation.Immutable;
/**
* Authentication credentials required to respond to a authentication
* challenge are invalid
*
*
* @since 4.0
*/
@Immutable
public class UnsupportedDigestAlgorithmException extends RuntimeException {
private static final long serialVersionUID = 319558534317118022L;
/**
* Creates a new UnsupportedAuthAlgoritmException with a <tt>null</tt> detail message.
*/
public UnsupportedDigestAlgorithmException() {
super();
}
/**
* Creates a new UnsupportedAuthAlgoritmException with the specified message.
*
* @param message the exception detail message
*/
public UnsupportedDigestAlgorithmException(final String message) {
super(message);
}
/**
* Creates a new UnsupportedAuthAlgoritmException with the specified detail message and cause.
*
* @param message the exception detail message
* @param cause the <tt>Throwable</tt> that caused this exception, or <tt>null</tt>
* if the cause is unavailable, unknown, or not a <tt>Throwable</tt>
*/
public UnsupportedDigestAlgorithmException(final String message, final Throwable cause) {
super(message, cause);
}
}

View file

@ -0,0 +1,32 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
/**
* Default implementations of standard and common HTTP authentication
* schemes.
*/
package ch.boye.httpclientandroidlib.impl.auth;