/*
 * Created on Jun 6, 2004
 *
 * Paros and its related class files.
 * 
 * Paros is an HTTP/HTTPS proxy for assessing web application security.
 * Copyright (C) 2003-2004 Chinotec Technologies Company
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the Clarified Artistic License
 * as published by the Free Software Foundation.
 * 
 * This program 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
 * Clarified Artistic License for more details.
 * 
 * You should have received a copy of the Clarified Artistic License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package org.parosproxy.paros.network;

import java.util.Vector;
import java.util.regex.Pattern;

import org.parosproxy.paros.common.FileXML;
import org.w3c.dom.Document;
import org.w3c.dom.Element;




/**
 *
 * To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
public class ConnectionParam extends FileXML {

	private static final String CONNECTION = "connection";

	private static final String PROXY_CHAIN_NAME = "proxyChainName";
	private static final String PROXY_CHAIN_PORT = "proxyChainPort";
	private static final String PROXY_CHAIN_SKIP_NAME = "proxyChainSkipName";
	private static final String PROXY_CHAIN_REALM = "proxyChainRealm";
	private static final String PROXY_CHAIN_USER_NAME = "proxyChainUserName";
	private static final String PROXY_CHAIN_PASSWORD = "proxyChainPassword";
	
	private static final String[] PATH_PROXY_CHAIN_NAME = {CONNECTION, PROXY_CHAIN_NAME};
	private static final String[] PATH_PROXY_CHAIN_PORT = {CONNECTION, PROXY_CHAIN_PORT};
	private static final String[] PATH_PROXY_CHAIN_SKIP_NAME = {CONNECTION, PROXY_CHAIN_SKIP_NAME};
	private static final String[] PATH_PROXY_CHAIN_REALM = {CONNECTION, PROXY_CHAIN_REALM};
	private static final String[] PATH_PROXY_CHAIN_USER_NAME = {CONNECTION, PROXY_CHAIN_USER_NAME};
	private static final String[] PATH_PROXY_CHAIN_PASSWORD = {CONNECTION, PROXY_CHAIN_PASSWORD};
	
	private String proxyChainName = "";
	private int proxyChainPort = 8080;
	private String proxyChainSkipName = "";
	private String proxyChainRealm = "";
	private String proxyChainUserName = "";
	private String proxyChainPassword = "";
	
	private Vector listAuth = new Vector();

	private Pattern					patternSkip = null;
	private Document mDoc = null;
	
	public ConnectionParam() {
		super(CONNECTION);
	}
	
	protected void parse() {

		setProxyChainName(getValue(PROXY_CHAIN_NAME));
		try {
			setProxyChainPort(Integer.parseInt(getValue(PROXY_CHAIN_PORT)));
		} catch (Exception e) {}
		setProxyChainSkipName(getValue(PROXY_CHAIN_SKIP_NAME));
		setProxyChainUserName(getValue(PROXY_CHAIN_USER_NAME));
		setProxyChainPassword(getValue(PROXY_CHAIN_PASSWORD));				
		
		parseAuthentication();
	}
	
	
	public String getProxyChainName() {
		return proxyChainName;
	}
	
	public void setProxyChainName(String proxyChainName) {
		this.proxyChainName = proxyChainName.trim();
		setValue(PATH_PROXY_CHAIN_NAME, this.proxyChainName);
	}
	
	public int getProxyChainPort() {
		return proxyChainPort;
	}
	
	public void setProxyChainPort(int proxyChainPort) {
		this.proxyChainPort = proxyChainPort;
		setValue(PATH_PROXY_CHAIN_PORT, Integer.toString(this.proxyChainPort));
	}

	public String getProxyChainSkipName() {
		return proxyChainSkipName;
	}
	
	public void setProxyChainSkipName(String proxyChainSkipName) {
		this.proxyChainSkipName = proxyChainSkipName.trim();
		setValue(PATH_PROXY_CHAIN_SKIP_NAME, this.proxyChainSkipName);
		parseProxyChainSkip(this.proxyChainSkipName);
	}

	public String getProxyChainRealm() {
		return proxyChainRealm;
	}
	
	public void setProxyChainRealm(String proxyChainRealm) {
		this.proxyChainRealm = proxyChainRealm.trim();
		setValue(PATH_PROXY_CHAIN_REALM, this.proxyChainRealm);
	}

	public String getProxyChainUserName() {
		return proxyChainUserName;
	}
	
	public void setProxyChainUserName(String proxyChainUserName) {
		this.proxyChainUserName = proxyChainUserName.trim();
		setValue(PATH_PROXY_CHAIN_USER_NAME, this.proxyChainUserName);
	}
	
	public String getProxyChainPassword() {
		return proxyChainPassword.trim();
	}
	
	public void setProxyChainPassword(String proxyChainPassword) {
		this.proxyChainPassword = proxyChainPassword;
		setValue(PATH_PROXY_CHAIN_PASSWORD, this.proxyChainPassword);
	}
	
	/**
	Check if via proxy chain.
	@return	True = use proxy chain
	*/
	private boolean isUseProxyChain() {
		if (getProxyChainName().equals("")) {
			return false;
		} else {
			return true;
		}
	}
	
	/**
	Check if the given host name is in the proxy chain skip list
	@param	hostName	Host name to be checked.
	*/
	private boolean isSkipProxyChain(String hostName) {
		if (patternSkip == null || hostName == null) {
			return false;
		}
		
		return patternSkip.matcher(hostName).find();
	}
	
	/**
	Check if given host name need to send using proxy.
	@param	hostName	host name to be checked.
	@return	true = need to send via proxy.
	*/
	public boolean isUseProxy(String hostName) {
		if (!isUseProxyChain() || isSkipProxyChain(hostName)) {
			return false;
		} else {
			return true;
		}
	}
	
	/**
	Parse the proxy chain skip text string and build the regex pattern.
	*/
	private void parseProxyChainSkip(String skipName) {
		patternSkip = null;

		if (skipName == null || skipName.equals("")) {
			return;
		}
		
		skipName = skipName.replaceAll("\\.", "\\\\.");
		skipName = skipName.replaceAll("\\*",".*?").replaceAll("(;+$)|(^;+)", "");
		skipName = "(" + skipName.replaceAll(";+", "|") + ")$";
		patternSkip = Pattern.compile(skipName, Pattern.CASE_INSENSITIVE);
	}

    /**
     * @return Returns the listAuth.
     */
    public Vector getListAuth() {
        return listAuth;
    }
    /**
     * @param listAuth The listAuth to set.
     */
    public void setListAuth(Vector listAuth) {
        this.listAuth = listAuth;
        HostAuthentication auth = null;
        Element root = getElement(CONNECTION);
        removeElement(root, AUTH);
        for (int i=0; i<listAuth.size(); i++) {
            auth = (HostAuthentication) listAuth.get(i);
            Element base = addElement(root, AUTH);
            addElement(base, AUTH_HOST_NAME, auth.getHostName());
            addElement(base, AUTH_PORT, Integer.toString(auth.getPort()));
            addElement(base, AUTH_USER_NAME, auth.getUserName());
            addElement(base, AUTH_PASSWORD, auth.getPassword());
            addElement(base, AUTH_REALM, auth.getRealm());
        }
    }
    
    private static final String AUTH = "auth";
    private static final String AUTH_HOST_NAME = "authHostName";
    private static final String AUTH_PORT = "authPort";
    private static final String AUTH_USER_NAME = "authUserName";
    private static final String AUTH_PASSWORD = "authPassword";
    private static final String AUTH_REALM = "authRealm";
    
    private void parseAuthentication() {
        listAuth.clear();
        Element[] elements = getElements(AUTH);
        Element element = null;
        if (elements == null || elements.length == 0) {
            return;
        }
        
        for (int i=0; i<elements.length; i++) {
            element = elements[i];
            if (getValue(element, AUTH_HOST_NAME).equals("")) {
                continue;
            }
            HostAuthentication auth = new HostAuthentication(
                    getValue(element, AUTH_HOST_NAME),
                    Integer.parseInt(getValue(element, AUTH_PORT)),
                    getValue(element, AUTH_USER_NAME),
                    getValue(element, AUTH_PASSWORD),
                    getValue(element, AUTH_REALM)
                    );
            listAuth.add(auth);
        }
    }
    
}
