001package org.apache.maven.wagon.shared.http;
002
003/*
004 * Licensed to the Apache Software Foundation (ASF) under one
005 * or more contributor license agreements.  See the NOTICE file
006 * distributed with this work for additional information
007 * regarding copyright ownership.  The ASF licenses this file
008 * to you under the Apache License, Version 2.0 (the
009 * "License"); you may not use this file except in compliance
010 * with the License.  You may obtain a copy of the License at
011 *
012 *   http://www.apache.org/licenses/LICENSE-2.0
013 *
014 * Unless required by applicable law or agreed to in writing,
015 * software distributed under the License is distributed on an
016 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
017 * KIND, either express or implied.  See the License for the
018 * specific language governing permissions and limitations
019 * under the License.
020 */
021
022import org.apache.commons.io.IOUtils;
023import org.apache.commons.lang.StringUtils;
024import org.apache.maven.wagon.TransferFailedException;
025import org.jsoup.Jsoup;
026import org.jsoup.nodes.Document;
027import org.jsoup.nodes.Element;
028import org.jsoup.select.Elements;
029
030import java.io.IOException;
031import java.io.InputStream;
032import java.io.UnsupportedEncodingException;
033import java.net.URI;
034import java.net.URISyntaxException;
035import java.net.URLDecoder;
036import java.util.ArrayList;
037import java.util.HashSet;
038import java.util.List;
039import java.util.Set;
040import java.util.regex.Pattern;
041
042/**
043 * Html File List Parser.
044 */
045public class HtmlFileListParser
046{
047    // Apache Fancy Index Sort Headers
048    private static final Pattern APACHE_INDEX_SKIP = Pattern.compile( "\\?[CDMNS]=.*" );
049
050    // URLs with excessive paths.
051    private static final Pattern URLS_WITH_PATHS = Pattern.compile( "/[^/]*/" );
052
053    // URLs that to a parent directory.
054    private static final Pattern URLS_TO_PARENT = Pattern.compile( "\\.\\./" );
055
056    // mailto urls
057    private static final Pattern MAILTO_URLS = Pattern.compile( "mailto:.*" );
058
059    private static final Pattern[] SKIPS =
060        new Pattern[]{ APACHE_INDEX_SKIP, URLS_WITH_PATHS, URLS_TO_PARENT, MAILTO_URLS };
061
062    /**
063     * Fetches a raw HTML from a provided InputStream, parses it, and returns the file list.
064     *
065     * @param stream the input stream.
066     * @return the file list.
067     * @throws TransferFailedException if there was a problem fetching the raw html.
068     */
069    public static List<String> parseFileList( String baseurl, InputStream stream )
070        throws TransferFailedException
071    {
072        try
073        {
074            URI baseURI = new URI( baseurl );
075            // to make debugging easier, start with a string. This is assuming UTF-8, which might not be a safe
076            // assumption.
077            String content = IOUtils.toString( stream, "utf-8" );
078            Document doc = Jsoup.parse( content, baseurl );
079            Elements links = doc.select( "a[href]" );
080            Set<String> results = new HashSet<String>();
081            for ( Element link : links )
082            {
083                /*
084                 * The abs:href loses directories, so we deal with absolute paths ourselves below in cleanLink
085                 */
086                String target = link.attr( "href" );
087                if ( target != null )
088                {
089                    String clean = cleanLink( baseURI, target );
090                    if ( isAcceptableLink( clean ) )
091                    {
092                        results.add( clean );
093                    }
094                }
095
096            }
097
098            return new ArrayList<String>( results );
099        }
100        catch ( URISyntaxException e )
101        {
102            throw new TransferFailedException( "Unable to parse as base URI: " + baseurl, e );
103        }
104        catch ( IOException e )
105        {
106            throw new TransferFailedException( "I/O error reading HTML listing of artifacts: " + e.getMessage(), e );
107        }
108    }
109
110    private static String cleanLink( URI baseURI, String link )
111    {
112        if ( StringUtils.isEmpty( link ) )
113        {
114            return "";
115        }
116
117        String ret = link;
118
119        try
120        {
121            URI linkuri = new URI( ret );
122            if ( link.startsWith( "/" ) )
123            {
124                linkuri = baseURI.resolve( linkuri );
125            }
126            URI relativeURI = baseURI.relativize( linkuri ).normalize();
127            ret = relativeURI.toASCIIString();
128            if ( ret.startsWith( baseURI.getPath() ) )
129            {
130                ret = ret.substring( baseURI.getPath().length() );
131            }
132
133            ret = URLDecoder.decode( ret, "UTF-8" );
134        }
135        catch ( URISyntaxException e )
136        {
137            // ignore
138        }
139        catch ( UnsupportedEncodingException e )
140        {
141            // ignore
142        }
143
144        return ret;
145    }
146
147    private static boolean isAcceptableLink( String link )
148    {
149        if ( StringUtils.isEmpty( link ) )
150        {
151            return false;
152        }
153
154        for ( Pattern pattern : SKIPS )
155        {
156            if ( pattern.matcher( link ).find() )
157            {
158                return false;
159            }
160        }
161
162        return true;
163    }
164
165}