001/*
002    Licensed to the Apache Software Foundation (ASF) under one
003    or more contributor license agreements.  See the NOTICE file
004    distributed with this work for additional information
005    regarding copyright ownership.  The ASF licenses this file
006    to you under the Apache License, Version 2.0 (the
007    "License"); you may not use this file except in compliance
008    with the License.  You may obtain a copy of the License at
009
010       http://www.apache.org/licenses/LICENSE-2.0
011
012    Unless required by applicable law or agreed to in writing,
013    software distributed under the License is distributed on an
014    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015    KIND, either express or implied.  See the License for the
016    specific language governing permissions and limitations
017    under the License.    
018 */
019package org.apache.wiki.util;
020
021import org.apache.commons.lang3.StringUtils;
022import org.apache.commons.lang3.Validate;
023import org.apache.logging.log4j.LogManager;
024import org.apache.logging.log4j.Logger;
025
026import javax.servlet.ServletContext;
027import java.io.*;
028import java.nio.file.Paths;
029import java.util.*;
030import java.util.function.Function;
031import java.util.stream.Collectors;
032import java.nio.file.Files;
033
034
035/**
036 * Property Reader for the WikiEngine. Reads the properties for the WikiEngine
037 * and implements the feature of cascading properties and variable substitution,
038 * which come in handy in a multi wiki installation environment: It reduces the
039 * need for (shell) scripting in order to generate different jspwiki.properties
040 * to a minimum.
041 *
042 * @since 2.5.x
043 */
044public final class PropertyReader {
045
046    private static final Logger LOG = LogManager.getLogger( PropertyReader.class );
047
048    /**
049     * Path to the base property file, {@value}, usually overridden by values provided in
050     * a jspwiki-custom.properties file.
051     */
052    public static final String DEFAULT_JSPWIKI_CONFIG = "/ini/jspwiki.properties";
053
054    /**
055     * The servlet context parameter (from web.xml)  that defines where the config file is to be found. If it is not defined, checks
056     * the Java System Property, if that is not defined either, uses the default as defined by DEFAULT_PROPERTYFILE.
057     * {@value #DEFAULT_JSPWIKI_CONFIG}
058     */
059    public static final String PARAM_CUSTOMCONFIG = "jspwiki.custom.config";
060
061    /**
062     *  The prefix when you are cascading properties.
063     *
064     *  @see #loadWebAppProps(ServletContext)
065     */
066    public static final String PARAM_CUSTOMCONFIG_CASCADEPREFIX = "jspwiki.custom.cascade.";
067
068    public static final String  CUSTOM_JSPWIKI_CONFIG = "/jspwiki-custom.properties";
069
070    private static final String PARAM_VAR_DECLARATION = "var.";
071    private static final String PARAM_VAR_IDENTIFIER  = "$";
072
073    /**
074     *  Private constructor to prevent instantiation.
075     */
076    private PropertyReader()
077    {}
078
079    /**
080     *  Loads the webapp properties based on servlet context information, or
081     *  (if absent) based on the Java System Property {@value #PARAM_CUSTOMCONFIG}.
082     *  Returns a Properties object containing the settings, or null if unable
083     *  to load it. (The default file is ini/jspwiki.properties, and can be
084     *  customized by setting {@value #PARAM_CUSTOMCONFIG} in the server or webapp
085     *  configuration.)
086     *
087     *  <h3>Properties sources</h3>
088     *  The following properties sources are taken into account:
089     *  <ol>
090     *      <li>JSPWiki default properties</li>
091     *      <li>System environment</li>
092     *      <li>JSPWiki custom property files</li>
093     *      <li>JSPWiki cascading properties</li>
094     *      <li>System properties</li>
095     *  </ol>
096     *  With later sources taking precedence over the previous ones. To avoid leaking system information,
097     *  only System environment and properties beginning with {@code jspwiki} (case unsensitive) are taken into account.
098     *  Also, to ease docker integration, System env properties containing "_" are turned into ".". Thus,
099     *  {@code ENV jspwiki_fileSystemProvider_pageDir} is loaded as {@code jspwiki.fileSystemProvider.pageDir}.
100     *
101     *  <h3>Cascading Properties</h3>
102     *  <p>
103     *  You can define additional property files and merge them into the default
104     *  properties file in a similar process to how you define cascading style
105     *  sheets; hence we call this <i>cascading property files</i>. This way you
106     *  can overwrite the default values and only specify the properties you
107     *  need to change in a multiple wiki environment.
108     *  <p>
109     *  You define a cascade in the context mapping of your servlet container.
110     *  <pre>
111     *  jspwiki.custom.cascade.1
112     *  jspwiki.custom.cascade.2
113     *  jspwiki.custom.cascade.3
114     *  </pre>
115     *  and so on. You have to number your cascade in a descending way starting
116     *  with "1". This means you cannot leave out numbers in your cascade. This
117     *  method is based on an idea by Olaf Kaus, see [JSPWiki:MultipleWikis].
118     *
119     *  @param context A Servlet Context which is used to find the properties
120     *  @return A filled Properties object with all the cascaded properties in place
121     */
122    public static Properties loadWebAppProps( final ServletContext context ) {
123        final String propertyFile = getInitParameter( context, PARAM_CUSTOMCONFIG );
124        try( final InputStream propertyStream = loadCustomPropertiesFile(context, propertyFile) ) {
125            final Properties props = getDefaultProperties();
126
127            // add system env properties beginning with jspwiki...
128            final Map< String, String > env = collectPropertiesFrom( System.getenv() );
129            props.putAll( env );
130
131            if( propertyStream == null ) {
132                LOG.debug( "No custom property file found, relying on JSPWiki defaults." );
133            } else {
134                props.load( propertyStream );
135            }
136
137            // this will add additional properties to the default ones:
138            LOG.debug( "Loading cascading properties..." );
139
140            // now load the cascade (new in 2.5)
141            loadWebAppPropsCascade( context, props );
142
143            // property expansion so we can resolve things like ${TOMCAT_HOME}
144            propertyExpansion( props );
145
146            // sets the JSPWiki working directory (jspwiki.workDir)
147            setWorkDir( context, props );
148
149            // add system properties beginning with jspwiki...
150            final Map< String, String > sysprops = collectPropertiesFrom( System.getProperties().stringPropertyNames().stream()
151                                                                                .collect( Collectors.toMap( Function.identity(), System::getProperty ) ) );
152            props.putAll( sysprops );
153
154            // finally, expand the variables (new in 2.5)
155            expandVars( props );
156
157            return props;
158        } catch( final Exception e ) {
159            LOG.error( "JSPWiki: Unable to load and setup properties from jspwiki.properties. " + e.getMessage(), e );
160        }
161
162        return null;
163    }
164
165    static Map< String, String > collectPropertiesFrom( final Map< String, String > map ) {
166        return map.entrySet().stream()
167                  .filter( entry -> entry.getKey().toLowerCase().startsWith( "jspwiki" ) )
168                  .map( entry -> new AbstractMap.SimpleEntry<>( entry.getKey().replace( "_", "." ), entry.getValue() ) )
169                  .collect( Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue ) );
170    }
171
172    /**
173     * Figure out where our properties lie.
174     *
175     * @param context servlet context
176     * @param propertyFile property file
177     * @return InputStream holding the properties file
178     * @throws FileNotFoundException properties file not found
179     */
180    static InputStream loadCustomPropertiesFile( final ServletContext context, final String propertyFile ) throws IOException {
181        final InputStream propertyStream;
182        if( propertyFile == null ) {
183            LOG.debug( "No " + PARAM_CUSTOMCONFIG + " defined for this context, looking for custom properties file with default name of: " + CUSTOM_JSPWIKI_CONFIG );
184            //  Use the custom property file at the default location
185            propertyStream =  locateClassPathResource(context, CUSTOM_JSPWIKI_CONFIG);
186        } else {
187            LOG.debug( PARAM_CUSTOMCONFIG + " defined, using " + propertyFile + " as the custom properties file." );
188            propertyStream = Files.newInputStream( new File(propertyFile).toPath() );
189        }
190        return propertyStream;
191    }
192
193
194    /**
195     *  Returns the property set as a Properties object.
196     *
197     *  @return A property set.
198     */
199    public static Properties getDefaultProperties() {
200        final Properties props = new Properties();
201        try( final InputStream in = PropertyReader.class.getResourceAsStream( DEFAULT_JSPWIKI_CONFIG ) ) {
202            if( in != null ) {
203                props.load( in );
204            }
205        } catch( final IOException e ) {
206            LOG.error( "Unable to load default propertyfile '{}' {}", DEFAULT_JSPWIKI_CONFIG, e.getMessage(), e );
207        }
208
209        return props;
210    }
211
212    /**
213     *  Returns a property set consisting of the default Property Set overlaid with a custom property set
214     *
215     *  @param fileName Reference to the custom override file
216     *  @return A property set consisting of the default property set and custom property set, with
217     *          the latter's properties replacing the former for any common values
218     */
219    public static Properties getCombinedProperties( final String fileName ) {
220        final Properties newPropertySet = getDefaultProperties();
221        try( final InputStream in = PropertyReader.class.getResourceAsStream( fileName ) ) {
222            if( in != null ) {
223                newPropertySet.load( in );
224            } else {
225                LOG.error( "*** Custom property file \"" + fileName + "\" not found, relying on default file alone." );
226            }
227        } catch( final IOException e ) {
228            LOG.error( "Unable to load propertyfile '" + fileName + "'" + e.getMessage(), e );
229        }
230
231        return newPropertySet;
232    }
233
234    /**
235     * Returns the ServletContext Init parameter if has been set, otherwise checks for a System property of the same name. If neither are
236     * defined, returns null. This permits both Servlet- and System-defined cascading properties.
237     */
238    private static String getInitParameter( final ServletContext context, final String name ) {
239        final String value = context.getInitParameter( name );
240        return value != null ? value : System.getProperty( name ) ;
241    }
242
243
244    /**
245     *  Implement the cascade functionality.
246     *
247     * @param context             where to read the cascade from
248     * @param defaultProperties   properties to merge the cascading properties to
249     * @since 2.5.x
250     */
251    private static void loadWebAppPropsCascade( final ServletContext context, final Properties defaultProperties ) {
252        if( getInitParameter( context, PARAM_CUSTOMCONFIG_CASCADEPREFIX + "1" ) == null ) {
253            LOG.debug( " No cascading properties defined for this context" );
254            return;
255        }
256
257        // get into cascade...
258        int depth = 0;
259        while( true ) {
260            depth++;
261            final String propertyFile = getInitParameter( context, PARAM_CUSTOMCONFIG_CASCADEPREFIX + depth );
262            if( propertyFile == null ) {
263                break;
264            }
265
266            try( final InputStream propertyStream = Files.newInputStream(Paths.get(( propertyFile ) ))) {
267                LOG.info( " Reading additional properties from {} and merge to cascade.", propertyFile );
268                final Properties additionalProps = new Properties();
269                additionalProps.load( propertyStream );
270                defaultProperties.putAll( additionalProps );
271            } catch( final Exception e ) {
272                LOG.error( "JSPWiki: Unable to load and setup properties from {}. {}", propertyFile, e.getMessage() );
273            }
274        }
275    }
276
277    /**
278     * <p>Try to resolve properties whose value is something like {@code ${SOME_VALUE}} from a system property first and,
279     * if not found, from a system environment variable. If not found on neither, the property value will remain as
280     * {@code ${SOME_VALUE}}, and no more expansions will be processed.</p>
281     *
282     * <p>Several expansions per property is OK, but no we're not supporting fancy things like recursion. Reference to
283     * other properties is achieved through {@link #expandVars(Properties)}. More than one property expansion per entry
284     * is allowed.</p>
285     *
286     * @param properties properties to expand;
287     */
288    public static void propertyExpansion( final Properties properties ) {
289        final Enumeration< ? > propertyList = properties.propertyNames();
290        while( propertyList.hasMoreElements() ) {
291            final String propertyName = ( String )propertyList.nextElement();
292            String propertyValue = properties.getProperty( propertyName );
293            while( propertyValue.contains( "${" ) && propertyValue.contains( "}" ) ) {
294                final int start = propertyValue.indexOf( "${" );
295                final int end = propertyValue.indexOf( "}", start );
296                if( start >= 0 && end >= 0 && end > start ) {
297                    final String substring = propertyValue.substring( start, end ).replace( "${", "" ).replace( "}", "" );
298                    final String expansion = Objects.toString( System.getProperty( substring ), System.getenv( substring ) );
299                    if( expansion != null ) {
300                        propertyValue =  propertyValue.replace( "${" + substring + "}", expansion );
301                        properties.setProperty( propertyName, propertyValue );
302                    } else {
303                        LOG.warn( "{} referenced on {} ({}) but not found on System props or env", substring, propertyName, propertyValue );
304                        break;
305                    }
306                } else {
307                    // no more matches or value like foo}${bar
308                    break;
309                }
310            }
311        }
312    }
313
314    /**
315     *  <p>You define a property variable by using the prefix {@code var.x} as a property. In property values you can then use the "$x" identifier
316     *  to use this variable.</p>
317     *
318     *  <p>For example, you could declare a base directory for all your files like this and use it in all your other property definitions with
319     *  a {@code $basedir}. Note that it does not matter if you define the variable before its usage.
320     *  <pre>
321     *  var.basedir = /p/mywiki; # var.basedir = ${TOMCAT_HOME} would also be fine
322     *  jspwiki.fileSystemProvider.pageDir =         $basedir/www/
323     *  jspwiki.basicAttachmentProvider.storageDir = $basedir/www/
324     *  jspwiki.workDir =                            $basedir/wrk/
325     *  </pre></p>
326     *
327     * @param properties - properties to expand;
328     */
329    public static void expandVars( final Properties properties ) {
330        //get variable name/values from properties...
331        final Map< String, String > vars = new HashMap<>();
332        Enumeration< ? > propertyList = properties.propertyNames();
333        while( propertyList.hasMoreElements() ) {
334            final String propertyName = ( String )propertyList.nextElement();
335            final String propertyValue = properties.getProperty( propertyName );
336
337            if ( propertyName.startsWith( PARAM_VAR_DECLARATION ) ) {
338                final String varName = propertyName.substring( 4 ).trim();
339                final String varValue = propertyValue.trim();
340                vars.put( varName, varValue );
341            }
342        }
343
344        //now, substitute $ values in property values with vars...
345        propertyList = properties.propertyNames();
346        while( propertyList.hasMoreElements() ) {
347            final String propertyName = ( String )propertyList.nextElement();
348            String propertyValue = properties.getProperty( propertyName );
349
350            //skip var properties itself...
351            if( propertyName.startsWith( PARAM_VAR_DECLARATION ) ) {
352                continue;
353            }
354
355            for( final Map.Entry< String, String > entry : vars.entrySet() ) {
356                final String varName = entry.getKey();
357                final String varValue = entry.getValue();
358
359                //replace old property value, using the same variabe. If we don't overwrite
360                //the same one the next loop works with the original one again and
361                //multiple var expansion won't work...
362                propertyValue = TextUtil.replaceString( propertyValue, PARAM_VAR_IDENTIFIER + varName, varValue );
363
364                //add the new PropertyValue to the properties
365                properties.put( propertyName, propertyValue );
366            }
367        }
368    }
369
370    /**
371     * Locate a resource stored in the class path. Try first with "WEB-INF/classes"
372     * from the web app and fallback to "resourceName".
373     *
374     * @param context the servlet context
375     * @param resourceName the name of the resource
376     * @return the input stream of the resource or <b>null</b> if the resource was not found
377     */
378    public static InputStream locateClassPathResource( final ServletContext context, final String resourceName ) {
379        InputStream result;
380        String currResourceLocation;
381
382        // garbage in - garbage out
383        if( StringUtils.isEmpty( resourceName ) ) {
384            return null;
385        }
386
387        // try with web app class loader searching in "WEB-INF/classes"
388        currResourceLocation = createResourceLocation( "/WEB-INF/classes", resourceName );
389        result = context.getResourceAsStream( currResourceLocation );
390        if( result != null ) {
391            LOG.debug( " Successfully located the following classpath resource : " + currResourceLocation );
392            return result;
393        }
394
395        // if not found - try with the current class loader and the given name
396        currResourceLocation = createResourceLocation( "", resourceName );
397        result = PropertyReader.class.getResourceAsStream( currResourceLocation );
398        if( result != null ) {
399            LOG.debug( " Successfully located the following classpath resource : " + currResourceLocation );
400            return result;
401        }
402
403        LOG.debug( " Unable to resolve the following classpath resource : " + resourceName );
404
405        return result;
406    }
407
408    /**
409     * Create a resource location with proper usage of "/".
410     *
411     * @param path a path
412     * @param name a resource name
413     * @return a resource location
414     */
415    static String createResourceLocation( final String path, final String name ) {
416        Validate.notEmpty( name, "name is empty" );
417        final StringBuilder result = new StringBuilder();
418
419        // strip an ending "/"
420        final String sanitizedPath = ( path != null && !path.isEmpty() && path.endsWith( "/" ) ? path.substring( 0, path.length() - 1 ) : path );
421
422        // strip leading "/"
423        final String sanitizedName = ( name.startsWith( "/" ) ? name.substring( 1 ) : name );
424
425        // append the optional path
426        if( sanitizedPath != null && !sanitizedPath.isEmpty() ) {
427            if( !sanitizedPath.startsWith( "/" ) ) {
428                result.append( "/" );
429            }
430            result.append( sanitizedPath );
431        }
432        result.append( "/" );
433
434        // append the name
435        result.append( sanitizedName );
436        return result.toString();
437    }
438
439    /**
440     * This method sets the JSPWiki working directory (jspwiki.workDir). It first checks if this property
441     * is already set. If it isn't, it attempts to use the servlet container's temporary directory
442     * (javax.servlet.context.tempdir). If that is also unavailable, it defaults to the system's temporary
443     * directory (java.io.tmpdir).
444     * <p>
445     * This method is package-private to allow for unit testing.
446     *
447     * @param properties     the JSPWiki properties
448     * @param servletContext the Servlet context from which to fetch the tempdir if needed
449     * @since JSPWiki 2.11.1
450     */
451    static void setWorkDir( final ServletContext servletContext, final Properties properties ) {
452        final String workDir = TextUtil.getStringProperty(properties, "jspwiki.workDir", null);
453        if (workDir == null) {
454            final File tempDir = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
455            if (tempDir != null) {
456                properties.setProperty("jspwiki.workDir", tempDir.getAbsolutePath());
457                LOG.info("Setting jspwiki.workDir to ServletContext's temporary directory: {}", tempDir.getAbsolutePath());
458            } else {
459                final String defaultTmpDir = System.getProperty("java.io.tmpdir");
460                properties.setProperty("jspwiki.workDir", defaultTmpDir);
461                LOG.info("ServletContext's temporary directory not found. Setting jspwiki.workDir to system's temporary directory: {}", defaultTmpDir);
462            }
463        } else {
464            LOG.debug("jspwiki.workDir is already set to: {}", workDir);
465        }
466    }
467
468}