/*
 * The contents of this file are subject to the terms
 * of the Common Development and Distribution License
 * (the License).  You may not use this file except in
 * compliance with the License.
 *
 * You can obtain a copy of the license at
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing
 * permissions and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL
 * Header Notice in each file and include the License file
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.
 * If applicable, add the following below the CDDL Header,
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information:
 * "Portions Copyrighted [year] [name of copyright owner]"
 *
 * Copyright (c) Ericsson AB, 2004-2007. All rights reserved.
 */
package com.ericsson.ssa.sip;


/**
 * Validation of Via header.
 *
 * @author qmaghes
 */
public class ViaHeaderValidator extends BasicMandatoryHeaderValidator {
    public ViaHeaderValidator() {
        super(Header.VIA);
    }

    public boolean validate(SipServletMessageImpl message) {
        Header header = message.getRawHeader(Header.VIA);

        if ((header == null) || (header.getValue() == null) ||
                (header.getValue().length() == 0)) {
            return false;
        }

        String headerValue = header.getValue();
        String[] viaParts = headerValue.split(",");

        // A via header may contain several comma separate such
        if (viaParts.length < 1) {
            return false;
        }

        // Validate parts
        for (String part : viaParts) {
            if (!validatePart(message.getMethod(), part)) {
                return false;
            }
        }

        return true;
    }

    private boolean validatePart(String method, String part) {
        try {
            // Delegate to ViaImpl for validation
            ViaImpl impl = new ViaImpl(part);

            return validateTransport(impl.getTransport()) &&
            validateHost(impl.getHost()) &&
            validateBranchParameter(method, impl.getParameter("branch"));
        } catch (StringIndexOutOfBoundsException e) {
            return false;
        }
    }

    private boolean validateTransport(String transport) {
        // Transport should be rfc3261 token.
        return isToken(transport);
    }

    private boolean validateHost(String host) {
        // FIXME, more strict.
        return host != null;
    }

    private boolean validateBranchParameter(String method, String branch) {
        // branch parameter MUST start with magic number z9hG4bK
        // FIXME HH18816, test tools have problems with ACK, should
        // change this and remove special handling of branch for ACK
        // in later release
        return (branch != null) &&
        (branch.startsWith("z9hG4bK") || method.equals("ACK"));
    }
}
