View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.repository;
20  
21  import java.net.InetAddress;
22  import java.net.MalformedURLException;
23  import java.net.URL;
24  import java.net.UnknownHostException;
25  import java.util.List;
26  import java.util.regex.Pattern;
27  
28  import org.apache.maven.RepositoryUtils;
29  import org.apache.maven.artifact.repository.ArtifactRepository;
30  import org.apache.maven.settings.Mirror;
31  import org.codehaus.plexus.component.annotations.Component;
32  import org.codehaus.plexus.util.StringUtils;
33  
34  /**
35   * DefaultMirrorSelector
36   */
37  @Component(role = MirrorSelector.class)
38  public class DefaultMirrorSelector implements MirrorSelector {
39  
40      private static final String WILDCARD = "*";
41  
42      private static final String EXTERNAL_WILDCARD = "external:*";
43  
44      private static final String EXTERNAL_HTTP_WILDCARD = "external:http:*";
45  
46      public Mirror getMirror(ArtifactRepository repository, List<Mirror> mirrors) {
47          String repoId = repository.getId();
48  
49          if (repoId != null && mirrors != null) {
50              for (Mirror mirror : mirrors) {
51                  if (repoId.equals(mirror.getMirrorOf()) && matchesLayout(repository, mirror)) {
52                      return mirror;
53                  }
54              }
55  
56              for (Mirror mirror : mirrors) {
57                  if (matchPattern(repository, mirror.getMirrorOf()) && matchesLayout(repository, mirror)) {
58                      return mirror;
59                  }
60              }
61          }
62  
63          return null;
64      }
65  
66      /**
67       * This method checks if the pattern matches the originalRepository. Valid patterns:
68       * <ul>
69       * <li>{@code *} = everything,</li>
70       * <li>{@code external:*} = everything not on the localhost and not file based,</li>
71       * <li>{@code external:http:*} = any repository not on the localhost using HTTP,</li>
72       * <li>{@code repo,repo1} = {@code repo} or {@code repo1},</li>
73       * <li>{@code *,!repo1} = everything except {@code repo1}.</li>
74       * </ul>
75       *
76       * @param originalRepository to compare for a match.
77       * @param pattern used for match. Currently only '*' is supported.
78       * @return true if the repository is a match to this pattern.
79       */
80      static boolean matchPattern(ArtifactRepository originalRepository, String pattern) {
81          boolean result = false;
82          String originalId = originalRepository.getId();
83  
84          // simple checks first to short circuit processing below.
85          if (WILDCARD.equals(pattern) || pattern.equals(originalId)) {
86              result = true;
87          } else {
88              // process the list
89              String[] repos = pattern.split(",");
90              for (String repo : repos) {
91                  repo = repo.trim();
92                  // see if this is a negative match
93                  if (repo.length() > 1 && repo.startsWith("!")) {
94                      if (repo.substring(1).equals(originalId)) {
95                          // explicitly exclude. Set result and stop processing.
96                          result = false;
97                          break;
98                      }
99                  }
100                 // check for exact match
101                 else if (repo.equals(originalId)) {
102                     result = true;
103                     break;
104                 }
105                 // check for external:*
106                 else if (EXTERNAL_WILDCARD.equals(repo) && isExternalRepo(originalRepository)) {
107                     result = true;
108                     // don't stop processing in case a future segment explicitly excludes this repo
109                 }
110                 // check for external:http:*
111                 else if (EXTERNAL_HTTP_WILDCARD.equals(repo) && isExternalHttpRepo(originalRepository)) {
112                     result = true;
113                     // don't stop processing in case a future segment explicitly excludes this repo
114                 } else if (WILDCARD.equals(repo)) {
115                     result = true;
116                     // don't stop processing in case a future segment explicitly excludes this repo
117                 }
118             }
119         }
120         return result;
121     }
122 
123     /**
124      * Checks the URL to see if this repository refers to an external repository
125      *
126      * @param originalRepository
127      * @return true if external.
128      */
129     static boolean isExternalRepo(ArtifactRepository originalRepository) {
130         try {
131             URL url = new URL(originalRepository.getUrl());
132             return !(isLocal(url.getHost()) || url.getProtocol().equals("file"));
133         } catch (MalformedURLException e) {
134             // bad url just skip it here. It should have been validated already, but the wagon lookup will deal with it
135             return false;
136         }
137     }
138 
139     /** An IPv4 address of the loopback range 127.0.0.0/8. */
140     private static final Pattern IPV4_LOOPBACK = Pattern.compile("127(\\.(25[0-5]|2[0-4]\\d|1?\\d?\\d)){3}");
141 
142     /**
143      * Checks whether a host names the local machine: {@code localhost}, an IPv4 address of the loopback
144      * range {@code 127.0.0.0/8} or an IPv6 loopback address in brackets. An IPv4-mapped IPv6 address is judged by its
145      * IPv4 address. The names are not resolved.
146      *
147      * @param host the host of a repository URL, may be {@code null}
148      * @return true if the host is local
149      */
150     private static boolean isLocal(String host) {
151         if (host == null) {
152             return false;
153         }
154         if ("localhost".equals(host) || IPV4_LOOPBACK.matcher(host).matches()) {
155             return true;
156         }
157         if (host.startsWith("[") && host.endsWith("]")) {
158             try {
159                 // an IP literal is parsed without any name lookup
160                 return InetAddress.getByName(host).isLoopbackAddress();
161             } catch (UnknownHostException e) {
162                 return false;
163             }
164         }
165         return false;
166     }
167 
168     /**
169      * Checks the URL to see if this repository refers to a non-localhost repository using HTTP.
170      *
171      * @param originalRepository
172      * @return true if external.
173      */
174     static boolean isExternalHttpRepo(ArtifactRepository originalRepository) {
175         try {
176             URL url = new URL(originalRepository.getUrl());
177             return ("http".equalsIgnoreCase(url.getProtocol())
178                             || "dav".equalsIgnoreCase(url.getProtocol())
179                             || "dav:http".equalsIgnoreCase(url.getProtocol())
180                             || "dav+http".equalsIgnoreCase(url.getProtocol()))
181                     && !isLocal(url.getHost());
182         } catch (MalformedURLException e) {
183             // bad url just skip it here. It should have been validated already, but the wagon lookup will deal with it
184             return false;
185         }
186     }
187 
188     static boolean matchesLayout(ArtifactRepository repository, Mirror mirror) {
189         return matchesLayout(RepositoryUtils.getLayout(repository), mirror.getMirrorOfLayouts());
190     }
191 
192     /**
193      * Checks whether the layouts configured for a mirror match with the layout of the repository.
194      *
195      * @param repoLayout The layout of the repository, may be {@code null}.
196      * @param mirrorLayout The layouts supported by the mirror, may be {@code null}.
197      * @return {@code true} if the layouts associated with the mirror match the layout of the original repository,
198      *         {@code false} otherwise.
199      */
200     static boolean matchesLayout(String repoLayout, String mirrorLayout) {
201         boolean result = false;
202 
203         // simple checks first to short circuit processing below.
204         if (StringUtils.isEmpty(mirrorLayout) || WILDCARD.equals(mirrorLayout)) {
205             result = true;
206         } else if (mirrorLayout.equals(repoLayout)) {
207             result = true;
208         } else {
209             // process the list
210             String[] layouts = mirrorLayout.split(",");
211             for (String layout : layouts) {
212                 // see if this is a negative match
213                 if (layout.length() > 1 && layout.startsWith("!")) {
214                     if (layout.substring(1).equals(repoLayout)) {
215                         // explicitly exclude. Set result and stop processing.
216                         result = false;
217                         break;
218                     }
219                 }
220                 // check for exact match
221                 else if (layout.equals(repoLayout)) {
222                     result = true;
223                     break;
224                 } else if (WILDCARD.equals(layout)) {
225                     result = true;
226                     // don't stop processing in case a future segment explicitly excludes this repo
227                 }
228             }
229         }
230 
231         return result;
232     }
233 }