/* 
 * Copyright 2012 by AVM GmbH <info@avm.de>
 *
 * This software contains free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License ("License") as 
 * published by the Free Software Foundation  (version 3 of the License). 
 * This software is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the copy of the 
 * License you received along with this software for more details.
 */

package de.avm.android.tr064.net;

import java.security.KeyStore;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.params.AuthPolicy;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

/*
 * SSL HTTP client factory
 * - TLS
 * - accepting self signed certificates
 * - accepting all hosts
 * - optional HTTP digest authentication
 */
public class SoapSSLClientFactory
{
	private static final String TAG = "SoapSSLClientFactory";

	/**
	 * Create HTTP client with SSL and digest authentication
	 * @param username auth username
	 * @param password auth password
	 * @param httpsPort SSL port
	 * @param certificates trusted certificates
	 * @return HTTPS client
	 */
	public static DefaultHttpClient getClientWithDigestAuth(int httpsPort,
			String username, String password, KeyStore certificates)
	{
		DefaultHttpClient client = getClient(httpsPort, certificates);
		
		// digest authentication
		client.getParams().setParameter("http.auth.scheme-pref",
				AuthPolicy.DIGEST);
        client.getCredentialsProvider().setCredentials(
        		new AuthScope(AuthScope.ANY), 
        		new UsernamePasswordCredentials(username, password));

		return client;
	}

	/**
	 * Create HTTP client with SSL
	 * @param httpsPort SSL port
	 * @param certificates trusted certificates
	 * @return HTTPS client
	 */
	public static DefaultHttpClient getClient(int httpsPort,
			KeyStore certificates)
	{
		DefaultHttpClient client = new DefaultHttpClient();
		try
		{
	        client.getConnectionManager().getSchemeRegistry().register(
	        		new Scheme("https", SoapSSLSocketFactory
	        				.getInstance(certificates), httpsPort));
		}
		catch(Exception e)
		{
			Log.e(TAG, "Failed to register HTTPS scheme with HTTP client.", e);
		}
		return client;
	}
}
