head	1.4;
access;
symbols;
locks; strict;
comment	@# @;


1.4
date	2001.07.24.04.50.20;	author elicia;	state Exp;
branches;
next	1.3;

1.3
date	2001.07.19.19.08.43;	author dlr;	state Exp;
branches;
next	1.2;

1.2
date	2001.07.19.18.42.23;	author dlr;	state Exp;
branches;
next	1.1;

1.1
date	2001.06.13.19.09.59;	author elicia;	state Exp;
branches;
next	;


desc
@@


1.4
log
@writing only one document to each .htAccess file.
@
text
@/* ================================================================
 * Copyright (c) 2000-2001 CollabNet.  All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 * 
 * 1. Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * 
 * 2. Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * 
 * 3. The end-user documentation included with the redistribution, if
 * any, must include the following acknowlegement: "This product includes
 * software developed by Collab.Net (http://www.collab.net/)."
 * Alternately, this acknowlegement may appear in the software itself, if
 * and wherever such third-party acknowlegements normally appear.
 * 
 * 4. The hosted project names must not be used to endorse or promote
 * products derived from this software without prior written
 * permission. For written permission, please contact info@@collab.net.
 * 
 * 5. Products derived from this software may not use the "Tigris" name
 * nor may "Tigris" appear in their names without prior written
 * permission of Collab.Net.
 * 
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL COLLAB.NET OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ====================================================================
 * 
 * This software consists of voluntary contributions made by many
 * individuals on behalf of CollabNet.
 */


package org.tigris.helm.tool;

import java.io.*;
import java.util.*;
import java.math.BigInteger;
import java.text.ParseException;
import java.net.InetAddress;

import org.tigris.helm.tool.HelmProperties;
import org.tigris.helm.util.URL;

import org.apache.turbine.util.Log; 
import org.tigris.helm.om.*;

/**
 * Computes MDA using the Cryptix libs.  Direct port of
 * <a href="http://frogdot.de/mod_auth_mda/">Frogdot's mod_auth_mda</a> code.
 *
 * @@author <a href="heinz.richter@@frogdot.de">Heinz Richter</a>
 * @@author <a href="mailto:dlr@@collab.net">Daniel Rall</a>
 * @@author <a href="mailto:elicia@@collab.net">Elicia David</a>
 * @@version $Id: HtAccess.java,v 1.3 2001/07/19 19:08:43 dlr Exp $
 */
public class HtAccess
{
    /**
     * A hash of mutex objects for handling file write locking to 
     * .htaccess files, keyed by file name.
     */
    private static Map htaccessLocks = new HashMap();

    /**
     * The full path to the program used to write .htaccess files.
     */
    private static final String HTACCESS_WRITER =
        HelmProperties.getProperty("SANDBOX") +
        "/helm/perl/cgi/writeHtaccessFile";

    /**
     * Key for IS_VHOSTING.
     */
    private static final String IS_VHOSTING_KEY = "IS_VHOSTING";

    /**
     * Flag indicating whether in debug mode.
     */
    private static final boolean DEBUG = false;


    /**
     * Gets the full path to the <code>.htaccess</code> file for a protected
     * file's path.
     *
     * @@param path The path to the secured file.
     * @@return     The full path to the <code>.htaccess</code> file.
     */
    public static final String getHtaccess(ProposableFileArtifact artifact)
        throws ParseException, Exception
    {
        String path = artifact.getLocation();
        // HELP: This is suspect...why do we trim the last dir?
        int dirSepPos = indexOfLastElement(path) - 1;
        String fileServPath = path.substring(0, dirSepPos);
        if (DEBUG)
        {
            Log.debug("Project.getHtaccess: fileServPath=" + fileServPath);
        }
        return (fileServPath + File.separatorChar + artifact.getID() +
                File.separatorChar + ".htaccess");
    }

    /**
     * Finds the index of the last element in the supplied directory path.
     *
     * @@exception ParseException The supplied path doesn't parse.
     */
    private static int indexOfLastElement(String path)
        throws ParseException
    {
        int dirSepPos = path.lastIndexOf(File.separatorChar);
        if (dirSepPos == path.length() - 1)
        {
            // The provided path ended in the directory separator.
            dirSepPos = path.lastIndexOf(File.separatorChar, dirSepPos);
        }
        if (dirSepPos != -1)
        {
            return (dirSepPos + 1);
        }
        else
        {
            throw new ParseException("Project.indexOfLastElement(): Invalid  "
                                     + "file path: " + path, dirSepPos);
        }
    }

    /**
     * Writes the .htaccess file in the right directory for this project.
     *
     * @@param htaccess  The full path to the .htaccess file.
     * @@param url       The URL for auth and timeout (when <code>null</code>,
     *                  defaults to <code>http://[JVM host]/</code>).
     * @@param artifacts The {@@link org.tigris.helm.om.ProjectFileArtifact}
     *                  objects to provide access control for.
     */
    public static void writeHtaccessFile(String htaccess, String url,
                                         ProjectFileArtifact artifact,
                                         String projectID)
        throws Exception
    {
        if (url == null)
        {
            url = URL.DEFAULT_PROTOCOL + "://" +
                InetAddress.getLocalHost().getHostName() + '/';
        }

        // If not in vhosting mode, append projectID as CGI param.
        if (!isVhosting())
        {
            url = URL.appendCGIParam(url, "projectID", projectID);
        }

        // Get a mutex for the given .htaccess file.
        Object htaccessWriteLock = null;
        synchronized (htaccessLocks)
        {
            if (!htaccessLocks.containsKey(htaccess))
            {
                htaccessLocks.put(htaccess, new Object());
            }
            htaccessWriteLock = htaccessLocks.get(htaccess);
        }

        // Append each entry to the .htaccess file.
        synchronized (htaccessWriteLock)
        {
            // Format inputs for writeHtaccessFile script.
            StringBuffer fakedUrl = new StringBuffer(url).append("?null");
            String path;
            String fileName = artifact.getFileName();
            if (fileName != null)
            {
               path = artifact.getLocation();
               fakedUrl.append('&')
               .append(URL.encode(artifact.getFileName()))
               .append('=')
               .append(generateMDARealmMask(artifact.isPublic(),
                                            projectID));
            }

	        //Log.debug("Project.writeHtaccessFile: .htaccess file name=" +
	        //          htaccess);
            String[] cmd = { HTACCESS_WRITER, htaccess, fakedUrl.toString() };
            int exitValue = 0;
            try
            {
                Process proc = Runtime.getRuntime().exec(cmd);
                exitValue = proc.waitFor();
            }
            catch (RuntimeException e)
            {
                exitValue = 1;
            }

            if (exitValue != 0)
            {
                throw new Exception("Unable to write .htaccess file");
            }
        }
    }

    /**
     * All the .htaccess files within a specific projectID will share that
     * same realm.  The return value will be used in creation of an auth
     * ticket for file downloads.
     *
     * @@param isPublicFile Whether the download requires auth for a
     *                    <i>specific domain</i>.
     * @@return            The hexidecimal representation of the project's 
     *                    unique identifier.
     */
    public static String generateMDARealmMask(boolean isPublicFile, 
                                              String projectID)

    {
        // If the file requested is private, set the projectID bit.
        BigInteger i = (isPublicFile ?
                        BigInteger.ZERO : 
                        BigInteger.ZERO.setBit(Integer.parseInt(projectID)));
        // Return as hex (a la tohex(2 ^ projectID)).
        return i.toString(16);
    }

    /**
     * Test if vhosting is turned on.
     */
    private static boolean isVhosting()
    {
        String isVhosting = HelmProperties.getProperty(IS_VHOSTING_KEY);
        return (isVhosting != null &&
                new Boolean(isVhosting).booleanValue());
    }
}
@


1.3
log
@Updated to use Helm URL class (just ported from Joist).
@
text
@d69 1
a69 1
 * @@version $Id: HtAccess.java,v 1.2 2001/07/19 18:42:23 dlr Exp $
d154 2
a155 1
                                     List artifacts, String projectID)
d187 2
a188 1
            for (Iterator i = artifacts.iterator(); i.hasNext(); )
d190 6
a195 12
                ProjectFileArtifact artifact = (ProjectFileArtifact) i.next();
                String fileName = artifact.getFileName();
                Log.debug("fileName=" + fileName);
                if (fileName != null)
                {
                   path = artifact.getLocation();
                   fakedUrl.append('&')
                   .append(URL.encode(artifact.getFileName()))
                   .append('=')
                   .append(generateMDARealmMask(artifact.isPublic(),
                                                projectID));
                }
@


1.2
log
@Updated in light of the port of Joist JoistProperties class to Helm (as class HelmProperties).
@
text
@d57 1
a57 1
import org.joist.util.URL;
d69 1
a69 1
 * @@version $Id: HtAccess.java,v 1.1 2001/06/13 19:09:59 elicia Exp $
@


1.1
log
@abstracted out .htaccess methods (for file downloads) into this class
@
text
@d56 1
a56 1
import org.joist.util.JoistProperties;
d69 1
a69 1
 * @@version $Id: htAccess.java,v 1.16 2001/02/21 01:08:25 dlr Exp $
d83 1
a83 1
        JoistProperties.getProperty("SANDBOX") +
d250 1
a250 1
        String isVhosting = JoistProperties.getProperty(IS_VHOSTING_KEY);
@

