tomcat-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From billbar...@apache.org
Subject cvs commit: jakarta-tomcat-connectors/jk/java/org/apache/jk/config ApacheConfig.java BaseJkConfig.java IISConfig.java NSConfig.java
Date Thu, 01 Jan 2004 03:12:30 GMT
billbarker    2003/12/31 19:12:30

  Added:       jk/java/org/apache/jk/config ApacheConfig.java
                        BaseJkConfig.java IISConfig.java NSConfig.java
  Log:
  Repackaging ApacheConfig and friends for Tomcat 5.
  
  This is a straight re-packaging, no change in functionality.  I want to make it JMX-aware eventually (so you can do an all-in-one config al la TC 3.3).  However, it's not a reason to hold up a release.
  
  Addresses Bug #25838
  
  Revision  Changes    Path
  1.1                  jakarta-tomcat-connectors/jk/java/org/apache/jk/config/ApacheConfig.java
  
  Index: ApacheConfig.java
  ===================================================================
  /*
   * ====================================================================
   *
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 1999 The Apache Software Foundation.  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 the 
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowlegement may appear in the software itself,
   *    if and wherever such third-party acknowlegements normally appear.
   *
   * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
   *    Foundation" must not be used to endorse or promote products derived
   *    from this software without prior written permission. For written 
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache"
   *    nor may "Apache" appear in their names without prior written
   *    permission of the Apache Group.
   *
   * 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 THE APACHE SOFTWARE FOUNDATION 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 the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   *
   * [Additional notices, if required by prior licensing conditions]
   *
   */
  package org.apache.jk.config;
  
  import java.io.File;
  import java.io.FileWriter;
  import java.io.IOException;
  import java.io.PrintWriter;
  import java.util.Date;
  import java.util.Hashtable;
  
  import org.apache.catalina.Context;
  import org.apache.catalina.Host;
  
  /* The idea is to keep all configuration in server.xml and
     the normal apache config files. We don't want people to
     touch apache ( or IIS, NES ) config files unless they
     want to and know what they're doing ( better than we do :-).
  
     One nice feature ( if someone sends it ) would be to
     also edit httpd.conf to add the include.
  
     We'll generate a number of configuration files - this one
     is trying to generate a native apache config file.
  
     Some web.xml mappings do not "map" to server configuration - in
     this case we need to fallback to forward all requests to tomcat.
  
     Ajp14 will add to that the posibility to have tomcat and
     apache on different machines, and many other improvements -
     but this should also work for Ajp12, Ajp13 and Jni.
  
  */
  
  /**
      Generates automatic apache mod_jk configurations based on
      the Tomcat server.xml settings and the war contexts
      initialized during startup.
      <p>
      This config interceptor is enabled by inserting an ApacheConfig
      <code>Listener</code> in 
      the server.xml file like so:
      <pre>
      * < Server ... >
      *   ...
      *   <Listener className=<b>org.apache.ajp.tomcat4.config.ApacheConfig</b> 
      *       <i>options</i> />
      *   ...
      * < /Server >
      </pre>
      where <i>options</i> can include any of the following attributes:
      <ul>
       <li><b>configHome</b> - default parent directory for the following paths.
                              If not set, this defaults to TOMCAT_HOME. Ignored
                              whenever any of the following paths is absolute.
                               </li>
       <li><b>jkConfig</b> - path to use for writing Apache mod_jk conf file. If
                              not set, defaults to
                              "conf/auto/mod_jk.conf".</li>
       <li><b>workersConfig</b> - path to workers.properties file used by 
                              mod_jk. If not set, defaults to
                              "conf/jk/workers.properties".</li>
       <li><b>modJk</b> - path to Apache mod_jk plugin file.  If not set,
                          defaults to "modules/mod_jk.dll" on windows,
                          "modules/mod_jk.nlm" on netware, and
                          "libexec/mod_jk.so" everywhere else.</li>
       <li><b>jkLog</b> - path to log file to be used by mod_jk.</li>
       <li><b>jkDebug</b> - JK Loglevel setting.  May be debug, info, error, or emerg.
                            If not set, defaults to emerg.</li>
       <li><b>jkWorker</b> The desired worker.  Must be set to one of the workers
                           defined in the workers.properties file. "ajp12", "ajp13"
                           or "inprocess" are the workers found in the default
                           workers.properties file. If not specified, defaults
                           to "ajp13" if an Ajp13Interceptor is in use, otherwise
                           it defaults to "ajp12".</li>
       <li><b>forwardAll</b> - If true, forward all requests to Tomcat. This helps
                               insure that all the behavior configured in the web.xml
                               file functions correctly.  If false, let Apache serve
                               static resources. The default is true.
                               Warning: When false, some configuration in
                               the web.xml may not be duplicated in Apache.
                               Review the mod_jk conf file to see what
                               configuration is actually being set in Apache.</li>
       <li><b>noRoot</b> - If true, the root context is not mapped to
                           Tomcat.  If false and forwardAll is true, all requests
                           to the root context are mapped to Tomcat. If false and
                           forwardAll is false, only JSP and servlets requests to
                           the root context are mapped to Tomcat. When false,
                           to correctly serve Tomcat's root context you must also
                           modify the DocumentRoot setting in Apache's httpd.conf
                           file to point to Tomcat's root context directory.
                           Otherwise some content, such as Apache's index.html,
                           will be served by Apache before mod_jk gets a chance
                           to claim the request and pass it to Tomcat.
                           The default is true.</li>
      </ul>
      <p>
      @author Costin Manolache
      @author Larry Isaacs
      @author Mel Martinez
      @author Bill Barker
   */
  public class ApacheConfig  extends BaseJkConfig { 
      
      /** default path to mod_jk .conf location */
      public static final String MOD_JK_CONFIG = "conf/auto/mod_jk.conf";
      /** default path to workers.properties file
  	This should be also auto-generated from server.xml.
      */
      public static final String WORKERS_CONFIG = "conf/jk/workers.properties";
      /** default mod_jk log file location */
      public static final String JK_LOG_LOCATION = "logs/mod_jk.log";
      /** default location of mod_jk Apache plug-in. */
      public static final String MOD_JK;
      
      //set up some defaults based on OS type
      static{
          String os = System.getProperty("os.name").toLowerCase();
          if(os.indexOf("windows")>=0){ 
             MOD_JK = "modules/mod_jk.dll";
          }else if(os.indexOf("netware")>=0){
             MOD_JK = "modules/mod_jk.nlm";
          }else{
             MOD_JK = "libexec/mod_jk.so";
          }
      }
      
      private File jkConfig = null;
      private File modJk = null;
  
      // ssl settings 
      private boolean sslExtract=true;
      private String sslHttpsIndicator="HTTPS";
      private String sslSessionIndicator="SSL_SESSION_ID";
      private String sslCipherIndicator="SSL_CIPHER";
      private String sslCertsIndicator="SSL_CLIENT_CERT";
  
      Hashtable NamedVirtualHosts=null;
      
      public ApacheConfig() {
      }
  
      //-------------------- Properties --------------------
  
      /**
          set the path to the output file for the auto-generated
          mod_jk configuration file.  If this path is relative
          then it will be resolved absolutely against
          the getConfigHome() path.
          <p>
          @param <b>path</b> String path to a file
      */
      public void setJkConfig(String path){
  	jkConfig= (path==null)?null:new File(path);
      }
  
      /**
          set the path to the mod_jk Apache Module
          @param <b>path</b> String path to a file
      */
      public void setModJk(String path){
          modJk=( path==null?null:new File(path));
      }
  
      /** By default mod_jk is configured to collect SSL information from
  	the apache environment and send it to the Tomcat workers. The
  	problem is that there are many SSL solutions for Apache and as
  	a result the environment variable names may change.
  
  	The following JK related SSL configureation
  	can be used to customize mod_jk's SSL behaviour.
  
  	Should mod_jk send SSL information to Tomact (default is On)
      */
      public void setExtractSSL( boolean sslMode ) {
  	this.sslExtract=sslMode;
      }
  
      /** What is the indicator for SSL (default is HTTPS)
       */
      public void setHttpsIndicator( String s ) {
  	sslHttpsIndicator=s;
      }
  
      /**What is the indicator for SSL session (default is SSL_SESSION_ID)
       */
      public void setSessionIndicator( String s ) {
  	sslSessionIndicator=s;
      }
      
      /**What is the indicator for client SSL cipher suit (default is SSL_CIPHER)
       */
      public void setCipherIndicator( String s ) {
  	sslCipherIndicator=s;
      }
  
      /** What is the indicator for the client SSL certificated(default
  	is SSL_CLIENT_CERT
       */
      public void setCertsIndicator( String s ) {
  	sslCertsIndicator=s;
      }
  
      // -------------------- Initialize/guess defaults --------------------
  
      /** Initialize defaults for properties that are not set
  	explicitely
      */
      protected void initProperties() {
          super.initProperties();
  
  	jkConfig= getConfigFile( jkConfig, configHome, MOD_JK_CONFIG);
  	workersConfig=getConfigFile( workersConfig, configHome,
  				     WORKERS_CONFIG);
  	if( modJk == null )
  	    modJk=new File(MOD_JK);
  	else
  	    modJk=getConfigFile( modJk, configHome, MOD_JK );
  	jkLog=getConfigFile( jkLog, configHome, JK_LOG_LOCATION);
      }
      // -------------------- Generate config --------------------
      
      protected PrintWriter getWriter() throws IOException {
  	String abJkConfig = jkConfig.getAbsolutePath();
  	return new PrintWriter(new FileWriter(abJkConfig, append));
      }
  			       
  
      // -------------------- Config sections  --------------------
  
      /** Generate the loadModule and general options
       */
      protected boolean generateJkHead(PrintWriter mod_jk)
      {
  
  	mod_jk.println("########## Auto generated on " +  new Date() +
  		       "##########" );
  	mod_jk.println();
  
  	// Fail if mod_jk not found, let the user know the problem
  	// instead of running into problems later.
  	if( ! modJk.exists() ) {
  	    log( "mod_jk location: " + modJk );
  	    log( "Make sure it is installed corectly or " +
  		 " set the config location" );
  	    log( "Using <Listener className=\""+getClass().getName()+"\"  modJk=\"PATH_TO_MOD_JK.SO_OR_DLL\" />" );
  	}
              
  	// Verify the file exists !!
  	mod_jk.println("<IfModule !mod_jk.c>");
  	mod_jk.println("  LoadModule jk_module "+
  		       modJk.toString().replace('\\','/'));
  	mod_jk.println("</IfModule>");
  	mod_jk.println();                
  
  	
  	// Fail if workers file not found, let the user know the problem
  	// instead of running into problems later.
  	if( ! workersConfig.exists() ) {
  	    log( "Can't find workers.properties at " + workersConfig );
  	    log( "Please install it in the default location or " +
  		 " set the config location" );
  	    log( "Using <Listener className=\"" + getClass().getName() + "\"  workersConfig=\"FULL_PATH\" />" );
  	    return false;
  	}
              
  	mod_jk.println("JkWorkersFile \"" 
  		       + workersConfig.toString().replace('\\', '/') 
  		       + "\"");
  
  	mod_jk.println("JkLogFile \"" 
  		       + jkLog.toString().replace('\\', '/') 
  		       + "\"");
  	mod_jk.println();
  
  	if( jkDebug != null ) {
  	    mod_jk.println("JkLogLevel " + jkDebug);
  	    mod_jk.println();
  	}
  	return true;
      }
  
      protected void generateVhostHead(Host host, PrintWriter mod_jk) {
  
          mod_jk.println();
          String vhostip = host.getName();
  	String vhost = vhostip;
  	int ppos = vhost.indexOf(":");
  	if(ppos >= 0)
  	    vhost = vhost.substring(0,ppos);
  
          mod_jk.println("<VirtualHost "+ vhostip + ">");
          mod_jk.println("    ServerName " + vhost );
          String [] aliases=host.findAliases();
          if( aliases.length > 0 ) {
              mod_jk.print("    ServerAlias " );
              for( int ii=0; ii < aliases.length ; ii++) {
                  mod_jk.print( aliases[ii] + " " );
              }
              mod_jk.println();
          }
          indent="    ";
      }
  
      protected void generateVhostTail(Host host, PrintWriter mod_jk) {
          mod_jk.println("</VirtualHost>");
          indent="";
      }
      
      protected void generateSSLConfig(PrintWriter mod_jk) {
  	if( ! sslExtract ) {
  	    mod_jk.println("JkExtractSSL Off");        
  	}
  	if( ! "HTTPS".equalsIgnoreCase( sslHttpsIndicator ) ) {
  	    mod_jk.println("JkHTTPSIndicator " + sslHttpsIndicator);        
  	}
  	if( ! "SSL_SESSION_ID".equalsIgnoreCase( sslSessionIndicator )) {
  	    mod_jk.println("JkSESSIONIndicator " + sslSessionIndicator);
  	}
  	if( ! "SSL_CIPHER".equalsIgnoreCase( sslCipherIndicator )) {
  	    mod_jk.println("JkCIPHERIndicator " + sslCipherIndicator);
  	}
  	if( ! "SSL_CLIENT_CERT".equalsIgnoreCase( sslCertsIndicator )) {
  	    mod_jk.println("JkCERTSIndicator " + sslCertsIndicator);
  	}
  
  	mod_jk.println();
      }
  
      // -------------------- Forward all mode --------------------
      String indent="";
      
      /** Forward all requests for a context to tomcat.
  	The default.
       */
      protected void generateStupidMappings(Context context,
  					   PrintWriter mod_jk )
      {
  	String ctxPath  = context.getPath();
  	if(ctxPath == null)
  	    return;
  
  	String nPath=("".equals(ctxPath)) ? "/" : ctxPath;
  	
          mod_jk.println();
  	mod_jk.println(indent + "JkMount " +  nPath + " " + jkWorker );
  	if( "".equals(ctxPath) ) {
  	    mod_jk.println(indent + "JkMount " +  nPath + "* " + jkWorker );
              if ( context.getParent() instanceof Host ) {
                  mod_jk.println(indent + "DocumentRoot \"" +
                              getApacheDocBase(context) + "\"");
              } else {
                  mod_jk.println(indent +
                          "# To avoid Apache serving root welcome files from htdocs, update DocumentRoot");
                  mod_jk.println(indent +
                          "# to point to: \"" + getApacheDocBase(context) + "\"");
              }
  
  	} else {
  	    mod_jk.println(indent + "JkMount " +  nPath + "/* " + jkWorker );
  	}
      }    
  
      
      private void generateNameVirtualHost( PrintWriter mod_jk, String ip ) {
          if( !NamedVirtualHosts.containsKey(ip) ) {
              mod_jk.println("NameVirtualHost " + ip + "");
              NamedVirtualHosts.put(ip,ip);
          }
      }
      
      // -------------------- Apache serves static mode --------------------
      // This is not going to work for all apps. We fall back to stupid mode.
      
      protected void generateContextMappings(Context context, PrintWriter mod_jk )
      {
  	String ctxPath  = context.getPath();
  	Host vhost = getHost(context);
  
          if( noRoot &&  "".equals(ctxPath) ) {
              log("Ignoring root context in non-forward-all mode  ");
              return;
          }
  
  	mod_jk.println();
  	mod_jk.println(indent + "#################### " +
  		       ((vhost!=null ) ? vhost.getName() + ":" : "" ) +
  		       (("".equals(ctxPath)) ? "/" : ctxPath ) +
  		       " ####################" );
          mod_jk.println();
  	// Dynamic /servet pages go to Tomcat
   
  	generateStaticMappings( context, mod_jk );
  
  	// InvokerInterceptor - it doesn't have a container,
  	// but it's implemented using a special module.
  	
  	// XXX we need to better collect all mappings
  
  	if(context.getLoginConfig() != null) {
  	    String loginPage = context.getLoginConfig().getLoginPage();
  	    if(loginPage != null) {
  		int lpos = loginPage.lastIndexOf("/");
  		String jscurl = loginPage.substring(0,lpos+1) + "j_security_check";
  		addMapping( ctxPath, jscurl, mod_jk);
  	    }
  	}
  	String [] servletMaps = context.findServletMappings();
  	for(int ii=0; ii < servletMaps.length; ii++) {
  	      addMapping( ctxPath, servletMaps[ii] , mod_jk );
  	}
      }
  
      /** Add an Apache extension mapping.
       */
      protected boolean addExtensionMapping( String ctxPath, String ext,
  					 PrintWriter mod_jk )
      {
          if( debug > 0 )
              log( "Adding extension map for " + ctxPath + "/*." + ext );
  	mod_jk.println(indent + "JkMount " + ctxPath + "/*." + ext
  		       + " " + jkWorker);
  	return true;
      }
      
      
      /** Add a fulling specified Appache mapping.
       */
      protected boolean addMapping( String fullPath, PrintWriter mod_jk ) {
          if( debug > 0 )
              log( "Adding map for " + fullPath );
  	mod_jk.println(indent + "JkMount " + fullPath + "  " + jkWorker );
  	return true;
      }
      /** Add a partially specified Appache mapping.
       */
      protected boolean addMapping( String ctxP, String ext, PrintWriter mod_jk ) {
          if( debug > 0 )
              log( "Adding map for " + ext );
  	if(! ext.startsWith("/") )
  	    ext = "/" + ext;
  	if(ext.length() > 1)
  	    mod_jk.println(indent + "JkMount " + ctxP + ext+ "  " + jkWorker );
  	return true;
      }
  
      private void generateWelcomeFiles(Context context, PrintWriter mod_jk ) {
  	String wf[]=context.findWelcomeFiles();
  	if( wf==null || wf.length == 0 )
  	    return;
  	mod_jk.print(indent + "    DirectoryIndex ");
  	for( int i=0; i<wf.length ; i++ ) {
  	    mod_jk.print( wf[i] + " " );
  	}
  	mod_jk.println();
      }
  
      /** Mappings for static content. XXX need to add welcome files,
       *  mime mappings ( all will be handled by Mime and Static modules of
       *  apache ).
       */
      private void generateStaticMappings(Context context, PrintWriter mod_jk ) {
  	String ctxPath  = context.getPath();
  
  	// Calculate the absolute path of the document base
  	String docBase = getApacheDocBase(context);
  
          if( !"".equals(ctxPath) ) {
              // Static files will be served by Apache
              mod_jk.println(indent + "# Static files ");		    
              mod_jk.println(indent + "Alias " + ctxPath + " \"" + docBase + "\"");
              mod_jk.println();
          } else {
              if ( getHost(context) != null ) {
                  mod_jk.println(indent + "DocumentRoot \"" +
                              getApacheDocBase(context) + "\"");
              } else {
                  // For root context, ask user to update DocumentRoot setting.
                  // Using "Alias / " interferes with the Alias for other contexts.
                  mod_jk.println(indent +
                          "# Be sure to update DocumentRoot");
                  mod_jk.println(indent +
                          "# to point to: \"" + docBase + "\"");
              }
          }
  	mod_jk.println(indent + "<Directory \"" + docBase + "\">");
  	mod_jk.println(indent + "    Options Indexes FollowSymLinks");
  
  	generateWelcomeFiles(context, mod_jk);
  
  	// XXX XXX Here goes the Mime types and welcome files !!!!!!!!
  	mod_jk.println(indent + "</Directory>");
  	mod_jk.println();            
  	
  
  	// Deny serving any files from WEB-INF
  	mod_jk.println();            
  	mod_jk.println(indent +
  		       "# Deny direct access to WEB-INF and META-INF");
  	mod_jk.println(indent + "#");                        
  	mod_jk.println(indent + "<Location \"" + ctxPath + "/WEB-INF/*\">");
  	mod_jk.println(indent + "    AllowOverride None");
  	mod_jk.println(indent + "    deny from all");
  	mod_jk.println(indent + "</Location>");
  	// Deny serving any files from META-INF
  	mod_jk.println();            
  	mod_jk.println(indent + "<Location \"" + ctxPath + "/META-INF/*\">");
  	mod_jk.println(indent + "    AllowOverride None");
  	mod_jk.println(indent + "    deny from all");
  	mod_jk.println(indent + "</Location>");
  	if (File.separatorChar == '\\') {
  	    mod_jk.println(indent + "#");		    
  	    mod_jk.println(indent +
  			   "# Use Directory too. On Windows, Location doesn't"
  			   + " work unless case matches");
  	    mod_jk.println(indent + "#");                        
  	    mod_jk.println(indent +
  			   "<Directory \"" + docBase + "/WEB-INF/\">");
  	    mod_jk.println(indent + "    AllowOverride None");
  	    mod_jk.println(indent + "    deny from all");
  	    mod_jk.println(indent + "</Directory>");
  	    mod_jk.println();
  	    mod_jk.println(indent +
  			   "<Directory \"" + docBase + "/META-INF/\">");
  	    mod_jk.println(indent + "    AllowOverride None");
  	    mod_jk.println(indent + "    deny from all");
  	    mod_jk.println(indent + "</Directory>");
  	}
  	mod_jk.println();
      }    
  
      // -------------------- Utils --------------------
  
      private String getApacheDocBase(Context context)
      {
  	// Calculate the absolute path of the document base
  	String docBase = getAbsoluteDocBase(context);
  	if (File.separatorChar == '\\') {
  	    // use separator preferred by Apache
  	    docBase = docBase.replace('\\','/');
  	}
          return docBase;
      }
  
      private String getVirtualHostAddress(String vhost, String vhostip) {
          if( vhostip == null ) {
              if ( vhost != null && vhost.length() > 0 && Character.isDigit(vhost.charAt(0)) )
                  vhostip=vhost;
              else
                  vhostip="*";
          }
          return vhostip;
      }
  
  }
  
  
  
  1.1                  jakarta-tomcat-connectors/jk/java/org/apache/jk/config/BaseJkConfig.java
  
  Index: BaseJkConfig.java
  ===================================================================
  /*
   * ====================================================================
   *
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 1999 The Apache Software Foundation.  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 the 
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowlegement may appear in the software itself,
   *    if and wherever such third-party acknowlegements normally appear.
   *
   * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
   *    Foundation" must not be used to endorse or promote products derived
   *    from this software without prior written permission. For written 
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache"
   *    nor may "Apache" appear in their names without prior written
   *    permission of the Apache Group.
   *
   * 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 THE APACHE SOFTWARE FOUNDATION 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 the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   *
   * [Additional notices, if required by prior licensing conditions]
   *
   */
  package org.apache.jk.config;
  
  import java.io.File;
  import java.io.IOException;
  import java.io.PrintWriter;
  
  import org.apache.catalina.Container;
  import org.apache.catalina.Context;
  import org.apache.catalina.Engine;
  import org.apache.catalina.Host;
  import org.apache.catalina.Lifecycle;
  import org.apache.catalina.LifecycleEvent;
  import org.apache.catalina.LifecycleListener;
  import org.apache.catalina.Server;
  
  
  /**
      Base class for automatic jk based configurations based on
      the Tomcat server.xml settings and the war contexts
      initialized during startup.
      <p>
      This config interceptor is enabled by inserting a Config
      element in the <b>&lt;ContextManager&gt;</b> tag body inside
      the server.xml file like so:
      <pre>
      * < ContextManager ... >
      *   ...
      *   <<b>???Config</b> <i>options</i> />
      *   ...
      * < /ContextManager >
      </pre>
      where <i>options</i> can include any of the following attributes:
      <ul>
       <li><b>configHome</b> - default parent directory for the following paths.
                               If not set, this defaults to TOMCAT_HOME. Ignored
                               whenever any of the following paths is absolute.
                               </li>
       <li><b>workersConfig</b> - path to workers.properties file used by 
                                  jk connector. If not set, defaults to
                                  "conf/jk/workers.properties".</li>
       <li><b>jkLog</b> - path to log file to be used by jk connector.</li>
       <li><b>jkDebug</b> - Loglevel setting.  May be debug, info, error, or emerg.
                            If not set, defaults to emerg.</li>
       <li><b>jkWorker</b> The desired worker.  Must be set to one of the workers
                           defined in the workers.properties file. "ajp12", "ajp13"
                           or "inprocess" are the workers found in the default
                           workers.properties file. If not specified, defaults
                           to "ajp13" if an Ajp13Interceptor is in use, otherwise
                           it defaults to "ajp12".</li>
       <li><b>forwardAll</b> - If true, forward all requests to Tomcat. This helps
                               insure that all the behavior configured in the web.xml
                               file functions correctly.  If false, let Apache serve
                               static resources. The default is true.
                               Warning: When false, some configuration in
                               the web.xml may not be duplicated in Apache.
                               Review the mod_jk conf file to see what
                               configuration is actually being set in Apache.</li>
       <li><b>noRoot</b> - If true, the root context is not mapped to
                           Tomcat.  If false and forwardAll is true, all requests
                           to the root context are mapped to Tomcat. If false and
                           forwardAll is false, only JSP and servlets requests to
                           the root context are mapped to Tomcat. When false,
                           to correctly serve Tomcat's root context you may also
                           need to modify the web server to point it's home
                           directory to Tomcat's root context directory.
                           Otherwise some content, such as the root index.html,
                           may be served by the web server before the connector
                           gets a chance to claim the request and pass it to Tomcat.
                           The default is true.</li>
      </ul>
      <p>
      @author Costin Manolache
      @author Larry Isaacs
      @author Bill Barker
  	@version $Revision: 1.1 $
   */
  public class BaseJkConfig  implements LifecycleListener {
      protected int debug=0;
      protected File configHome = null;
      protected File workersConfig = null;
  
      protected File jkLog = null;
      protected String jkDebug="emerg";
      protected String jkWorker = "ajp13";
  
      protected boolean noRoot=true;
      protected boolean forwardAll=true;
  
      protected String tomcatHome;
      protected boolean regenerate=false;
      protected boolean append=false;
      protected boolean legacy=false;
  
      // -------------------- Tomcat callbacks --------------------
  
  
      // Auto-config should be able to react to dynamic config changes,
      // and regenerate the config.
  
      /** Generate the configuration - only when the server is
       *  completely initialized ( before starting )
       */
      public void lifecycleEvent(LifecycleEvent evt)
      {
  	if(Lifecycle.START_EVENT.equals(evt.getType())) {
  	   execute( evt );
  	}
      }
  
      /** Generate configuration files.  Override with method to generate
          web server specific configuration.
       */
      public void execute(LifecycleEvent evt)
      {
  	initProperties();
  	PrintWriter mod_jk = null;
  	try {
  	    mod_jk = getWriter();
  	} catch(IOException iex) {
  	    log("Unable to open config file");
  	    return;
  	}
  	Lifecycle who = evt.getLifecycle();
  	if( who instanceof Server ) {
  	    executeServer((Server)who, mod_jk);
  	} else if ( who instanceof Host ) {
  	    executeHost((Host)who, mod_jk);
  	} else if( who instanceof Context ) {
  	    executeContext((Context)who, mod_jk);
  	}
  	mod_jk.close();
      }
      /** Generate configuration files.  Override with method to generate
          web server specific configuration.
       */
      public void executeServer(Server svr, PrintWriter mod_jk) {
  	if(! append ) {
  	    if( ! generateJkHead(mod_jk) )
  		return;
  	    generateSSLConfig(mod_jk);
  	    generateJkTail(mod_jk);
  	}
      }
  
      /** Generate SSL options
       */
      protected void generateSSLConfig(PrintWriter mod_jk)
      {
      }
      /** Generate general options
       */
      protected boolean generateJkHead(PrintWriter mod_jk)
      {
  	return true;
      }
      /** Generate general options
       */
      protected void generateJkTail(PrintWriter mod_jk)
      {
      }
      /** Generate Virtual Host start
       */
      protected void generateVhostHead(Host host, PrintWriter mod_jk) {
      }
      /** Generate Virtual Host end
       */
      protected void generateVhostTail(Host host, PrintWriter mod_jk) {
      }
      /** Generate configuration files.  Override with method to generate
          web server specific configuration.
       */
      protected void executeEngine(Engine egn, PrintWriter mod_jk) {
  	Container [] children = egn.findChildren();
  	for(int ii=0; ii < children.length; ii++) {
  	    if( children[ii] instanceof Host ) {
  		executeHost((Host)children[ii], mod_jk);
  	    } else if( children[ii] instanceof Context ) {
  		executeContext((Context)children[ii], mod_jk);
  	    }
  	}
      }
      /** Generate configuration files.  Override with method to generate
          web server specific configuration.
       */
      protected void executeHost(Host hst, PrintWriter mod_jk) {
  	generateVhostHead(hst, mod_jk);
  	Container [] children = hst.findChildren();
  	for(int ii=0; ii < children.length; ii++) {
  	    if(children[ii] instanceof Context) {
  		executeContext((Context)children[ii],mod_jk);
  	    }
  	}
  	generateVhostTail(hst, mod_jk);
      }
      /**
          executes the ApacheConfig interceptor. This method generates apache
          configuration files for use with  mod_jk.
          <p>
          @param <b>context</b> a Context object.
  	@param <b>mod_jk</b> Writer for output.
      */
      public void executeContext(Context context, PrintWriter mod_jk){
  
  	if(context.getPath().length() > 0 || ! noRoot ) {
  	    String docRoot = context.getServletContext().getRealPath("/");
  	    if( forwardAll || docRoot == null)
  		generateStupidMappings( context, mod_jk );
  	    else
  		generateContextMappings( context, mod_jk);
  	}
      }
      protected void generateStupidMappings(Context context, PrintWriter mod_jk){
      }
      protected void generateContextMappings(Context context, PrintWriter mod_jk){
      }
      /** Get the output Writer.  Override with method to generate
          web server specific configuration.
       */
      protected PrintWriter getWriter() throws IOException {
  	return null;
      }
      /** Get the host associated with this Container (if any).
       */
      protected Host getHost(Container child) {
  	while(child != null && ! (child instanceof Host) ) {
  	    child = child.getParent();
  	}
  	return (Host)child;
      }
  
      //-------------------- Properties --------------------
  
      /** Append to config file.
       *  Set to <code>true</code> if the config information should be 
       *  appended.
       */
      public void setAppend(boolean apnd) {
  	append = apnd;
      }
      /** If false, we'll try to generate a config that will
       *  let apache serve static files.
       *  The default is true, forward all requests in a context
       *  to tomcat.
       */
      public void setForwardAll( boolean b ) {
          forwardAll=b;
      }
  
      /** Special option - do not generate mappings for the ROOT
          context. The default is true, and will not generate the mappings,
          not redirecting all pages to tomcat (since /* matches everything).
          This means that the web server's root remains intact but isn't
          completely servlet/JSP enabled. If the ROOT webapp can be configured
          with the web server serving static files, there's no problem setting
          this option to false. If not, then setting it true means the web
          server will be out of picture for all requests.
      */
      public void setNoRoot( boolean b ) {
          noRoot=b;
      }
      
      /**
          set a path to the parent directory of the
          conf folder.  That is, the parent directory
          within which path setters would be resolved against,
          if relative.  For example if ConfigHome is set to "/home/tomcat"
          and regConfig is set to "conf/mod_jk.conf" then the resulting 
          path used would be: 
          "/home/tomcat/conf/mod_jk.conf".</p>
          <p>
          However, if the path is set to an absolute path,
          this attribute is ignored.
          <p>
          If not set, execute() will set this to TOMCAT_HOME.
          <p>
          @param <b>dir</b> - path to a directory
      */
      public void setConfigHome(String dir){
          if( dir==null ) return;
          File f=new File(dir);
          if(!f.isDirectory()){
              throw new IllegalArgumentException(
                  "BaseConfig.setConfigHome(): "+
                  "Configuration Home must be a directory! : "+dir);
          }
          configHome = f;
      }
  
      /**
          set a path to the workers.properties file.
          @param <b>path</b> String path to workers.properties file
      */
      public void setWorkersConfig(String path){
          workersConfig= (path==null?null:new File(path));
      }
  
      /**
          set the path to the log file
          @param <b>path</b> String path to a file
      */
      public void setJkLog(String path){
          jkLog= ( path==null?null:new File(path));
      }
  
      /** Set the verbosity level
          ( use debug, error, etc. ) If not set, no log is written.
       */
      public void setJkDebug( String level ) {
          jkDebug=level;
      }
  
      /**
          set the Ajp protocal
          @param <b>protocal</b> String protocol, "ajp12" or "ajp13"
       */
      public void setJkWorker(String worker){
          jkWorker = worker;
      }
  
      public void setLegacy(boolean legacy) {
          this.legacy = legacy;
      }
  
      // -------------------- Initialize/guess defaults --------------------
  
      /** Initialize defaults for properties that are not set
          explicitely
      */
      protected void initProperties() {
          tomcatHome = System.getProperty("catalina.home");
          File tomcatDir = new File(tomcatHome);
          if(configHome==null){
              configHome=tomcatDir;
          }
      }
  
      // -------------------- Config Utils  --------------------
  
  
      /** Add an extension mapping. Override with method to generate
          web server specific configuration
       */
      protected boolean addExtensionMapping( String ctxPath, String ext,
  					 PrintWriter pw )
      {
  	return true;
      }
      
      
      /** Add a fulling specified mapping.  Override with method to generate
          web server specific configuration
       */
      protected boolean addMapping( String fullPath, PrintWriter pw ) {
  	return true;
      }
  
      // -------------------- General Utils --------------------
  
      protected String getAbsoluteDocBase(Context context)
      {
  	// Calculate the absolute path of the document base
  	String docBase = context.getServletContext().getRealPath("/");
  	docBase = docBase.substring(0,docBase.length()-1);
  	if (!isAbsolute(docBase)){
  	    docBase = tomcatHome + "/" + docBase;
  	}
  	docBase = patch(docBase);
          return docBase;
      }
  
      // ------------------ Grabbed from FileUtil -----------------
      public static File getConfigFile( File base, File configDir, String defaultF )
      {
          if( base==null )
              base=new File( defaultF );
          if( ! base.isAbsolute() ) {
              if( configDir != null )
                  base=new File( configDir, base.getPath());
              else
                  base=new File( base.getAbsolutePath()); //??
          }
          File parent=new File(base.getParent());
          if(!parent.exists()){
              if(!parent.mkdirs()){
                  throw new RuntimeException(
                      "Unable to create path to config file :"+
                      base.getAbsolutePath());
              }
          }
          return base;
      }
      public static String patch(String path) {
          String patchPath = path;
  
          // Move drive spec to the front of the path
          if (patchPath.length() >= 3 &&
              patchPath.charAt(0) == '/'  &&
              Character.isLetter(patchPath.charAt(1)) &&
              patchPath.charAt(2) == ':') {
              patchPath=patchPath.substring(1,3)+"/"+patchPath.substring(3);
          }
  
          // Eliminate consecutive slashes after the drive spec
  	if (patchPath.length() >= 2 &&
              Character.isLetter(patchPath.charAt(0)) &&
              patchPath.charAt(1) == ':') {
              char[] ca = patchPath.replace('/', '\\').toCharArray();
              char c;
              StringBuffer sb = new StringBuffer();
  
              for (int i = 0; i < ca.length; i++) {
                  if ((ca[i] != '\\') ||
                      (ca[i] == '\\' &&
                          i > 0 &&
                          ca[i - 1] != '\\')) {
                      if (i == 0 &&
                          Character.isLetter(ca[i]) &&
                          i < ca.length - 1 &&
                          ca[i + 1] == ':') {
                          c = Character.toUpperCase(ca[i]);
                      } else {
                          c = ca[i];
                      }
  
                      sb.append(c);
                  }
              }
  
              patchPath = sb.toString();
          }
  
  	// fix path on NetWare - all '/' become '\\' and remove duplicate '\\'
  	if (System.getProperty("os.name").startsWith("NetWare") &&
  	    path.length() >=3 &&
  	    path.indexOf(':') > 0) {
  	    char[] ca = patchPath.replace('/', '\\').toCharArray();
  	    StringBuffer sb = new StringBuffer();
  
  	    for (int i = 0; i < ca.length; i++) {
  		if ((ca[i] != '\\') ||
  		    (ca[i] == '\\' && i > 0 && ca[i - 1] != '\\')) {
  		    sb.append(ca[i]);
  		}
  	    }
  	    patchPath = sb.toString();
  	}
  
          return patchPath;
      }
  
      public static boolean isAbsolute( String path ) {
  	// normal file
  	if( path.startsWith("/" ) ) return true;
  
  	if( path.startsWith(File.separator ) ) return true;
  
  	// win c:
  	if (path.length() >= 3 &&
              Character.isLetter(path.charAt(0)) &&
              path.charAt(1) == ':')
  	    return true;
  
  	// NetWare volume:
  	if (System.getProperty("os.name").startsWith("NetWare") &&
  	    path.length() >=3 &&
  	    path.indexOf(':') > 0)
  	    return true;
  
  	return false;
      }
      protected void log(String msg) {
  	System.err.println(msg);
      }
  }
  
  
  
  1.1                  jakarta-tomcat-connectors/jk/java/org/apache/jk/config/IISConfig.java
  
  Index: IISConfig.java
  ===================================================================
  /*
   * ====================================================================
   *
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 1999 The Apache Software Foundation.  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 the 
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowlegement may appear in the software itself,
   *    if and wherever such third-party acknowlegements normally appear.
   *
   * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
   *    Foundation" must not be used to endorse or promote products derived
   *    from this software without prior written permission. For written 
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache"
   *    nor may "Apache" appear in their names without prior written
   *    permission of the Apache Group.
   *
   * 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 THE APACHE SOFTWARE FOUNDATION 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 the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   *
   * [Additional notices, if required by prior licensing conditions]
   *
   */
  package org.apache.jk.config;
  
  import java.io.File;
  import java.io.FileWriter;
  import java.io.IOException;
  import java.io.PrintWriter;
  import java.util.Date;
  
  import org.apache.catalina.Context;
  
  
  /**
      Generates automatic IIS isapi_redirect configurations based on
      the Tomcat server.xml settings and the war contexts
      initialized during startup.
      <p>
      This config interceptor is enabled by inserting an IISConfig
      element in the <b>&lt;ContextManager&gt;</b> tag body inside
      the server.xml file like so:
      <pre>
      * < ContextManager ... >
      *   ...
      *   <<b>IISConfig</b> <i>options</i> />
      *   ...
      * < /ContextManager >
      </pre>
      where <i>options</i> can include any of the following attributes:
      <ul>
       <li><b>configHome</b> - default parent directory for the following paths.
                              If not set, this defaults to TOMCAT_HOME. Ignored
                              whenever any of the following paths is absolute.
                               </li>
       <li><b>regConfig</b> - path to use for writing IIS isapi_redirect registry
                              file. If not set, defaults to
                              "conf/auto/iis_redirect.reg".</li>
       <li><b>workersConfig</b> - path to workers.properties file used by 
                                  isapi_redirect. If not set, defaults to
                                  "conf/jk/workers.properties".</li>
       <li><b>uriConfig</b> - path to use for writing IIS isapi_redirect uriworkermap
                              file. If not set, defaults to
                              "conf/auto/uriworkermap.properties".</li>
       <li><b>jkLog</b> - path to log file to be used by isapi_redirect.</li>
       <li><b>jkDebug</b> - Loglevel setting.  May be debug, info, error, or emerg.
                            If not set, defaults to emerg.</li>
       <li><b>jkWorker</b> The desired worker.  Must be set to one of the workers
                           defined in the workers.properties file. "ajp12", "ajp13"
                           or "inprocess" are the workers found in the default
                           workers.properties file. If not specified, defaults
                           to "ajp13" if an Ajp13Interceptor is in use, otherwise
                           it defaults to "ajp12".</li>
       <li><b>forwardAll</b> - If true, forward all requests to Tomcat. This helps
                               insure that all the behavior configured in the web.xml
                               file functions correctly.  If false, let IIS serve
                               static resources assuming it has been configured
                               to do so. The default is true.
                               Warning: When false, some configuration in
                               the web.xml may not be duplicated in IIS.
                               Review the uriworkermap file to see what
                               configuration is actually being set in IIS.</li>
       <li><b>noRoot</b> - If true, the root context is not mapped to
                           Tomcat.  If false and forwardAll is true, all requests
                           to the root context are mapped to Tomcat. If false and
                           forwardAll is false, only JSP and servlets requests to
                           the root context are mapped to Tomcat. When false,
                           to correctly serve Tomcat's root context you must also
                           modify the Home Directory setting in IIS
                           to point to Tomcat's root context directory.
                           Otherwise some content, such as the root index.html,
                           will be served by IIS before isapi_redirect gets a chance
                           to claim the request and pass it to Tomcat.
                           The default is true.</li>
      </ul>
    <p>
      @author Costin Manolache
      @author Larry Isaacs
      @author Gal Shachor
      @author Bill Barker
   */
  public class IISConfig extends BaseJkConfig  { 
  
      public static final String WORKERS_CONFIG = "/conf/jk/workers.properties";
      public static final String URI_WORKERS_MAP_CONFIG = "/conf/auto/uriworkermap.properties";
      public static final String ISAPI_LOG_LOCATION = "/logs/iis_redirect.log";
      public static final String ISAPI_REG_FILE = "/conf/auto/iis_redirect.reg";    
  
      private File regConfig = null;
      private File uriConfig = null;
  
      public IISConfig() 
      {
      }
  
      //-------------------- Properties --------------------
      
      /**
          set the path to the output file for the auto-generated
          isapi_redirect registry file.  If this path is relative
          then getRegConfig() will resolve it absolutely against
          the getConfigHome() path.
          <p>
          @param <b>path</b> String path to a file
      */
      public void setRegConfig(String path){
  	regConfig= (path==null)?null:new File(path);
      }
  
      /**
          set a path to the uriworkermap.properties file.
          @param <b>path</b> String path to uriworkermap.properties file
      */
      public void setUriConfig(String path){
          uriConfig= (path==null?null:new File(path));
      }
  
      // -------------------- Initialize/guess defaults --------------------
  
      /** Initialize defaults for properties that are not set
  	explicitely
      */
      protected void initProperties() {
          super.initProperties();
  
  	regConfig=getConfigFile( regConfig, configHome, ISAPI_REG_FILE);
  	workersConfig=getConfigFile( workersConfig, configHome, WORKERS_CONFIG);
  	uriConfig=getConfigFile( uriConfig, configHome, URI_WORKERS_MAP_CONFIG);
  	jkLog=getConfigFile( jkLog, configHome, ISAPI_LOG_LOCATION);
      }
  
      // -------------------- Generate config --------------------
  
      protected PrintWriter getWriter() throws IOException {
  	String abUriConfig = uriConfig.getAbsolutePath();
  	return new PrintWriter(new FileWriter(abUriConfig,append));        
      }
      protected boolean generateJkHead(PrintWriter mod_jk) {
  	try {
  	    PrintWriter regfile = new PrintWriter(new FileWriter(regConfig));
  	    log("Generating IIS registry file = "+regConfig );
  	    generateRegistrySettings(regfile);
  	    regfile.close();
  	} catch(IOException iex) {
  	    log("Unable to generate registry file " +regConfig);
  	    return false;
  	}
  	log("Generating IIS URI worker map file = "+uriConfig );
  	generateUriWorkerHeader(mod_jk);            
  	return true;
      }
  
      // -------------------- Config sections  --------------------
  
      /** Writes the registry settings required by the IIS connector
       */
      private void generateRegistrySettings(PrintWriter regfile)
      {
          regfile.println("REGEDIT4");
          regfile.println();
          regfile.println("[HKEY_LOCAL_MACHINE\\SOFTWARE\\Apache Software Foundation\\Jakarta Isapi Redirector\\1.0]");
          regfile.println("\"extension_uri\"=\"/jakarta/isapi_redirect.dll\"");
          regfile.println("\"log_file\"=\"" + dubleSlash(jkLog.toString()) +"\"");
          regfile.println("\"log_level\"=\"" + jkDebug + "\"");
          regfile.println("\"worker_file\"=\"" + dubleSlash(workersConfig.toString()) +"\"");
          regfile.println("\"worker_mount_file\"=\"" + dubleSlash(uriConfig.toString()) +"\"");
      }
  
      /** Writes the header information to the uriworkermap file
       */
      private void generateUriWorkerHeader(PrintWriter uri_worker)
      {
          uri_worker.println("###################################################################");		    
          uri_worker.println("# Auto generated configuration. Dated: " +  new Date());
          uri_worker.println("###################################################################");		    
          uri_worker.println();
  
          uri_worker.println("#");        
          uri_worker.println("# Default worker to be used through our mappings");
          uri_worker.println("#");        
          uri_worker.println("default.worker=" + jkWorker);        
          uri_worker.println();
      }
  
      /** Forward all requests for a context to tomcat.
  	The default.
       */
      protected void generateStupidMappings(Context context, PrintWriter uri_worker )
      {
          String ctxPath  = context.getPath();
  	String nPath=("".equals(ctxPath)) ? "/" : ctxPath;
  
          if( noRoot &&  "".equals(ctxPath) ) {
              log("Ignoring root context in forward-all mode  ");
              return;
          } 
  
          // map all requests for this context to Tomcat
          uri_worker.println(nPath +"=$(default.worker)");
          if( "".equals(ctxPath) ) {
              uri_worker.println(nPath +"*=$(default.worker)");
              uri_worker.println(
                      "# Note: To correctly serve the Tomcat's root context, IIS's Home Directory must");
              uri_worker.println(
                      "# must be set to: \"" + getAbsoluteDocBase(context) + "\"");
          }
          else
              uri_worker.println(nPath +"/*=$(default.worker)");
      }
  
      protected void generateContextMappings(Context context, PrintWriter uri_worker )
      {
          String ctxPath  = context.getPath();
  	String nPath=("".equals(ctxPath)) ? "/" : ctxPath;
  
          if( noRoot &&  "".equals(ctxPath) ) {
              log("Ignoring root context in forward-all mode  ");
              return;
          } 
  
          // Static files will be served by IIS
          uri_worker.println();
          uri_worker.println("#########################################################");		    
          uri_worker.println("# Auto configuration for the " + nPath + " context.");
          uri_worker.println("#########################################################");		    
          uri_worker.println();
  
          // Static mappings are not set in uriworkermap, but must be set with IIS admin.
  
  	// InvokerInterceptor - it doesn't have a container,
  	// but it's implemented using a special module.
  
  	// XXX we need to better collect all mappings
  
  	if(context.getLoginConfig() != null) {
  	    String loginPage = context.getLoginConfig().getLoginPage();
  	    if(loginPage != null) {
  		int lpos = loginPage.lastIndexOf("/");
  		String jscurl = loginPage.substring(0,lpos+1) + "j_security_check";
  		addMapping( ctxPath, jscurl, uri_worker);
  	    }
  	}
  		String [] servletMaps=context.findServletMappings();
  	for( int ii=0; ii < servletMaps.length ; ii++) {
  	    addMapping( ctxPath , servletMaps[ii] , uri_worker );
  	}
      }
  
      /** Add an IIS extension mapping.
       */
      protected boolean addMapping( String ctxPath, String ext,
  					 PrintWriter uri_worker )
      {
          if( debug > 0 )
              log( "Adding extension map for " + ctxPath + "/*." + ext );
  	if(! ext.startsWith("/") )
  	    ext = "/" + ext;
  	if(ext.length() > 1)
  	    uri_worker.println(ctxPath + "/*." + ext + "=$(default.worker)");
          return true;
      }
  
      /** Add a fulling specified IIS mapping.
       */
      protected boolean addMapping( String fullPath, PrintWriter uri_worker ) {
          if( debug > 0 )
              log( "Adding map for " + fullPath );
          uri_worker.println(fullPath + "=$(default.worker)" );
          return true;
      }
  
      // -------------------- Utils --------------------
  
      private String dubleSlash(String in) 
      {
          StringBuffer sb = new StringBuffer();
          
          for(int i = 0 ; i < in.length() ; i++) {
              char ch = in.charAt(i);
              if('\\' == ch) {
                  sb.append("\\\\");
              } else {
                  sb.append(ch);
              }
          }
          
          return sb.toString();
      }
  
  }
  
  
  
  1.1                  jakarta-tomcat-connectors/jk/java/org/apache/jk/config/NSConfig.java
  
  Index: NSConfig.java
  ===================================================================
  /*
   * ====================================================================
   *
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 1999 The Apache Software Foundation.  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 the 
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowlegement may appear in the software itself,
   *    if and wherever such third-party acknowlegements normally appear.
   *
   * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
   *    Foundation" must not be used to endorse or promote products derived
   *    from this software without prior written permission. For written 
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache"
   *    nor may "Apache" appear in their names without prior written
   *    permission of the Apache Group.
   *
   * 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 THE APACHE SOFTWARE FOUNDATION 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 the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   *
   * [Additional notices, if required by prior licensing conditions]
   *
   */
  package org.apache.jk.config;
  
  import java.io.File;
  import java.io.FileWriter;
  import java.io.IOException;
  import java.io.PrintWriter;
  import java.util.Date;
  
  import org.apache.catalina.Context;
  
  
  /**
      Generates automatic Netscape nsapi_redirect configurations based on
      the Tomcat server.xml settings and the war contexts
      initialized during startup.
      <p>
      This config interceptor is enabled by inserting an NSConfig
      element in the <b>&lt;ContextManager&gt;</b> tag body inside
      the server.xml file like so:
      <pre>
      * < ContextManager ... >
      *   ...
      *   <<b>NSConfig</b> <i>options</i> />
      *   ...
      * < /ContextManager >
      </pre>
      where <i>options</i> can include any of the following attributes:
      <ul>
       <li><b>configHome</b> - default parent directory for the following paths.
                              If not set, this defaults to TOMCAT_HOME. Ignored
                              whenever any of the following paths is absolute.
                               </li>
       <li><b>objConfig</b> - path to use for writing Netscape obj.conf
                              file. If not set, defaults to
                              "conf/auto/obj.conf".</li>
       <li><b>objectName</b> - Name of the Object to execute the requests.
                               Defaults to "servlet".</li>
       <li><b>workersConfig</b> - path to workers.properties file used by 
                                  nsapi_redirect. If not set, defaults to
                                  "conf/jk/workers.properties".</li>
       <li><b>nsapiJk</b> - path to Netscape mod_jk plugin file.  If not set,
                          defaults to "bin/nsapi_redirect.dll" on windows,
                          "bin/nsapi_rd.nlm" on netware, and
                          "bin/nsapi_redirector.so" everywhere else.</li>
       <li><b>jkLog</b> - path to log file to be used by nsapi_redirect.</li>
       <li><b>jkDebug</b> - Loglevel setting.  May be debug, info, error, or emerg.
                            If not set, defaults to emerg.</li>
       <li><b>jkWorker</b> The desired worker.  Must be set to one of the workers
                           defined in the workers.properties file. "ajp12", "ajp13"
                           or "inprocess" are the workers found in the default
                           workers.properties file. If not specified, defaults
                           to "ajp13" if an Ajp13Interceptor is in use, otherwise
                           it defaults to "ajp12".</li>
       <li><b>forwardAll</b> - If true, forward all requests to Tomcat. This helps
                               insure that all the behavior configured in the web.xml
                               file functions correctly.  If false, let Netscape serve
                               static resources assuming it has been configured
                               to do so. The default is true.
                               Warning: When false, some configuration in
                               the web.xml may not be duplicated in Netscape.
                               Review the uriworkermap file to see what
                               configuration is actually being set in Netscape.</li>
       <li><b>noRoot</b> - If true, the root context is not mapped to
                           Tomcat.  If false and forwardAll is true, all requests
                           to the root context are mapped to Tomcat. If false and
                           forwardAll is false, only JSP and servlets requests to
                           the root context are mapped to Tomcat. When false,
                           to correctly serve Tomcat's root context you must also
                           modify the Home Directory setting in Netscape
                           to point to Tomcat's root context directory.
                           Otherwise some content, such as the root index.html,
                           will be served by Netscape before nsapi_redirect gets a chance
                           to claim the request and pass it to Tomcat.
                           The default is true.</li>
      </ul>
    <p>
      @author Costin Manolache
      @author Larry Isaacs
      @author Gal Shachor
      @author Bill Barker
   */
  public class NSConfig  extends BaseJkConfig { 
  
      public static final String WORKERS_CONFIG = "/conf/jk/workers.properties";
      public static final String NS_CONFIG = "/conf/auto/obj.conf";
      public static final String NSAPI_LOG_LOCATION = "/logs/nsapi_redirect.log";
      /** default location of nsapi plug-in. */
      public static final String NSAPI_REDIRECTOR;
      
      //set up some defaults based on OS type
      static{
          String os = System.getProperty("os.name").toLowerCase();
          if(os.indexOf("windows")>=0){
             NSAPI_REDIRECTOR = "bin/nsapi_redirect.dll";
          }else if(os.indexOf("netware")>=0){
             NSAPI_REDIRECTOR = "bin/nsapi_rd.nlm";
          }else{
             NSAPI_REDIRECTOR = "bin/nsapi_redirector.so";
          }
      }
  
      private File objConfig = null;
      private File nsapiJk = null;
      private String objectName = "servlet";
  
      public NSConfig() 
      {
      }
  
      //-------------------- Properties --------------------
      
      /**
          set the path to the output file for the auto-generated
          isapi_redirect registry file.  If this path is relative
          then getRegConfig() will resolve it absolutely against
          the getConfigHome() path.
          <p>
          @param <b>path</b> String path to a file
      */
      public void setObjConfig(String path) {
  	objConfig= (path==null)?null:new File(path);
      }
  
      /**
          set the path to the nsapi plugin module
          @param <b>path</b> String path to a file
      */
      public void setNsapiJk(String path) {
          nsapiJk=( path==null?null:new File(path));
      }
  
      /**
          Set the name for the Object that implements the
          jk_service call.
          @param <b>name</b> Name of the obj.conf Object
      */
      public void setObjectName(String name) {
          objectName = name;
      }
  
      // -------------------- Initialize/guess defaults --------------------
  
      /** Initialize defaults for properties that are not set
  	explicitely
      */
      protected void initProperties() {
          super.initProperties();
  
  	objConfig=getConfigFile( objConfig, configHome, NS_CONFIG);
  	workersConfig=getConfigFile( workersConfig, configHome, WORKERS_CONFIG);
  
  	if( nsapiJk == null )
  	    nsapiJk=new File(NSAPI_REDIRECTOR);
  	else
  	    nsapiJk =getConfigFile( nsapiJk, configHome, NSAPI_REDIRECTOR );
  	jkLog=getConfigFile( jkLog, configHome, NSAPI_LOG_LOCATION);
      }
  
      // -------------------- Generate config --------------------
      protected PrintWriter getWriter() throws IOException {
  	String abObjConfig = objConfig.getAbsolutePath();
  	return new PrintWriter(new FileWriter(abObjConfig,append));
      }
      protected boolean generateJkHead(PrintWriter mod_jk) {
  	log("Generating netscape web server config = "+objConfig );
  	
  	generateNsapiHead( mod_jk );
  	
  	mod_jk.println("<Object name=default>");
  	return true;
      }
  
      private void generateNsapiHead(PrintWriter objfile)
      {
          objfile.println("###################################################################");		    
          objfile.println("# Auto generated configuration. Dated: " +  new Date());
          objfile.println("###################################################################");		    
          objfile.println();
  
          objfile.println("#");        
          objfile.println("# You will need to merge the content of this file with your ");
          objfile.println("# regular obj.conf and then restart (=stop + start) your Netscape server. ");
          objfile.println("#");        
          objfile.println();
              
          objfile.println("#");                    
          objfile.println("# Loading the redirector into your server");
          objfile.println("#");        
          objfile.println();            
          objfile.println("Init fn=\"load-modules\" funcs=\"jk_init,jk_service\" shlib=\"<put full path to the redirector here>\"");
          objfile.println("Init fn=\"jk_init\" worker_file=\"" + 
                          workersConfig.toString().replace('\\', '/') +  
                          "\" log_level=\"" + jkDebug + "\" log_file=\"" + 
                          jkLog.toString().replace('\\', '/') + 
                          "\"");
          objfile.println();
      }
  
      protected void generateJkTail(PrintWriter objfile)
      {
          objfile.println();
          objfile.println("#######################################################");		    
          objfile.println("# Protecting the WEB-INF and META-INF directories.");
          objfile.println("#######################################################");		    
          objfile.println("PathCheck fn=\"deny-existence\" path=\"*/WEB-INF/*\""); 
          objfile.println("PathCheck fn=\"deny-existence\" path=\"*/META-INF/*\""); 
          objfile.println();
  
          objfile.println("</Object>");            
          objfile.println();
  
          objfile.println("#######################################################");		    
          objfile.println("# New object to execute your servlet requests.");
          objfile.println("#######################################################");		    
          objfile.println("<Object name=" + objectName + ">");
          objfile.println("ObjectType fn=force-type type=text/html");
          objfile.println("Service fn=\"jk_service\" worker=\""+ jkWorker + "\" path=\"/*\"");
          objfile.println("</Object>");
          objfile.println();
      }
  
      // -------------------- Forward all mode --------------------
      
      /** Forward all requests for a context to tomcat.
  	The default.
       */
      protected void generateStupidMappings(Context context, PrintWriter objfile )
      {
          String ctxPath  = context.getPath();
  	String nPath=("".equals(ctxPath)) ? "/" : ctxPath;
  
          if( noRoot &&  "".equals(ctxPath) ) {
              log("Ignoring root context in forward-all mode  ");
              return;
          } 
  	objfile.println("<Object name=" + context.getName() + ">");
  
          objfile.println("NameTrans fn=\"assign-name\" from=\"" + ctxPath + "\" name=\"" + objectName + "\""); 
          objfile.println("NameTrans fn=\"assign-name\" from=\"" + ctxPath + "/*\" name=\"" + objectName + "\""); 
  	objfile.println("</Object>");
      }
  
  
      // -------------------- Netscape serves static mode --------------------
      // This is not going to work for all apps. We fall back to stupid mode.
      
      protected void generateContextMappings(Context context, PrintWriter objfile )
      {
          String ctxPath  = context.getPath();
  	String nPath=("".equals(ctxPath)) ? "/" : ctxPath;
  
          if( noRoot &&  "".equals(ctxPath) ) {
              log("Ignoring root context in non-forward-all mode  ");
              return;
          } 
  	objfile.println("<Object name=" + context.getName() + ">");
          // Static files will be served by Netscape
          objfile.println("#########################################################");		    
          objfile.println("# Auto configuration for the " + nPath + " context starts.");
          objfile.println("#########################################################");		    
          objfile.println();
  
          // XXX Need to determine what if/how static mappings are done
  
  	// InvokerInterceptor - it doesn't have a container,
  	// but it's implemented using a special module.
  	
  	// XXX we need to better collect all mappings
  	if(context.getLoginConfig() != null) {
  	    String loginPage = context.getLoginConfig().getLoginPage();
  	    if(loginPage != null) {
  		int lpos = loginPage.lastIndexOf("/");
  		String jscurl = loginPage.substring(0,lpos+1) + "j_security_check";
  		addMapping( ctxPath, jscurl, objfile);
  	    }
  	}
  	
  	String [] servletMaps=context.findServletMappings();
  	for(int ii=0; ii < servletMaps.length; ii++) {
  	    addMapping( ctxPath , servletMaps[ii] , objfile );
  	}
  	objfile.println("</Object>");
      }
  
      /** Add a Netscape extension mapping.
       */
      protected boolean addMapping( String ctxPath, String ext,
  					 PrintWriter objfile )
      {
          if( debug > 0 )
              log( "Adding extension map for " + ctxPath + "/*." + ext );
  	if(! ext.startsWith("/") )
  	    ext = "/" + ext;
  	if(ext.length() > 1)
  	    objfile.println("NameTrans fn=\"assign-name\" from=\"" +
                      ctxPath  + ext + "\" name=\"" + objectName + "\""); 
  	return true;
      }
  
      /** Add a fulling specified Netscape mapping.
       */
      protected boolean addMapping( String fullPath, PrintWriter objfile ) {
          if( debug > 0 )
              log( "Adding map for " + fullPath );
          objfile.println("NameTrans fn=\"assign-name\" from=\"" +
                          fullPath + "\" name=\"" + objectName + "\""); 
  	return true;
      }
  
  }
  
  
  

---------------------------------------------------------------------
To unsubscribe, e-mail: tomcat-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: tomcat-dev-help@jakarta.apache.org


Mime
View raw message