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.eclipse.aether.util.repository;
20  
21  import java.net.Authenticator;
22  import java.net.InetSocketAddress;
23  import java.net.PasswordAuthentication;
24  import java.net.SocketAddress;
25  import java.net.URI;
26  import java.net.URL;
27  import java.util.List;
28  import java.util.Map;
29  import java.util.UUID;
30  
31  import org.eclipse.aether.repository.Authentication;
32  import org.eclipse.aether.repository.AuthenticationContext;
33  import org.eclipse.aether.repository.AuthenticationDigest;
34  import org.eclipse.aether.repository.Proxy;
35  import org.eclipse.aether.repository.ProxySelector;
36  import org.eclipse.aether.repository.RemoteRepository;
37  
38  import static java.util.Objects.requireNonNull;
39  
40  /**
41   * A proxy selector that uses the {@link java.net.ProxySelector#getDefault() JRE's global proxy selector}. In
42   * combination with the system property {@code java.net.useSystemProxies}, this proxy selector can be employed to pick
43   * up the proxy configuration from the operating system, see <a
44   * href="http://docs.oracle.com/javase/6/docs/technotes/guides/net/proxies.html">Java Networking and Proxies</a> for
45   * details. The {@link java.net.Authenticator JRE's global authenticator} is used to look up credentials for a proxy
46   * when needed.
47   */
48  public final class JreProxySelector implements ProxySelector {
49  
50      /**
51       * Creates a new proxy selector that delegates to {@link java.net.ProxySelector#getDefault()}.
52       */
53      public JreProxySelector() {}
54  
55      public Proxy getProxy(RemoteRepository repository) {
56          requireNonNull(repository, "repository cannot be null");
57          List<java.net.Proxy> proxies = null;
58          try {
59              URI uri = new URI(repository.getUrl()).parseServerAuthority();
60              proxies = java.net.ProxySelector.getDefault().select(uri);
61          } catch (Exception e) {
62              // URL invalid or not accepted by selector or no selector at all, simply use no proxy
63          }
64          if (proxies != null) {
65              for (java.net.Proxy proxy : proxies) {
66                  if (java.net.Proxy.Type.DIRECT.equals(proxy.type())) {
67                      break;
68                  }
69                  if (java.net.Proxy.Type.HTTP.equals(proxy.type()) && isValid(proxy.address())) {
70                      InetSocketAddress addr = (InetSocketAddress) proxy.address();
71                      return new Proxy(
72                              Proxy.TYPE_HTTP, addr.getHostName(), addr.getPort(), JreProxyAuthentication.INSTANCE);
73                  }
74              }
75          }
76          return null;
77      }
78  
79      private static boolean isValid(SocketAddress address) {
80          if (address instanceof InetSocketAddress) {
81              /*
82               * NOTE: On some platforms with java.net.useSystemProxies=true, unconfigured proxies show up as proxy
83               * objects with empty host and port 0.
84               */
85              InetSocketAddress addr = (InetSocketAddress) address;
86              if (addr.getPort() <= 0) {
87                  return false;
88              }
89              if (addr.getHostName() == null || addr.getHostName().isEmpty()) {
90                  return false;
91              }
92              return true;
93          }
94          return false;
95      }
96  
97      private static final class JreProxyAuthentication implements Authentication {
98  
99          public static final Authentication INSTANCE = new JreProxyAuthentication();
100 
101         public void fill(AuthenticationContext context, String key, Map<String, String> data) {
102             requireNonNull(context, "context cannot be null");
103             Proxy proxy = context.getProxy();
104             if (proxy == null) {
105                 return;
106             }
107             if (!AuthenticationContext.USERNAME.equals(key) && !AuthenticationContext.PASSWORD.equals(key)) {
108                 return;
109             }
110 
111             try {
112                 URL url;
113                 try {
114                     url = new URL(context.getRepository().getUrl());
115                 } catch (Exception e) {
116                     url = null;
117                 }
118 
119                 PasswordAuthentication auth = Authenticator.requestPasswordAuthentication(
120                         proxy.getHost(),
121                         null,
122                         proxy.getPort(),
123                         "http",
124                         "Credentials for proxy " + proxy,
125                         null,
126                         url,
127                         Authenticator.RequestorType.PROXY);
128                 if (auth != null) {
129                     context.put(AuthenticationContext.USERNAME, auth.getUserName());
130                     context.put(AuthenticationContext.PASSWORD, auth.getPassword());
131                 } else {
132                     context.put(AuthenticationContext.USERNAME, System.getProperty("http.proxyUser"));
133                     context.put(AuthenticationContext.PASSWORD, System.getProperty("http.proxyPassword"));
134                 }
135             } catch (SecurityException e) {
136                 // oh well, let's hope the proxy can do without auth
137             }
138         }
139 
140         public void digest(AuthenticationDigest digest) {
141             requireNonNull(digest, "digest cannot be null");
142             // we don't know anything about the JRE's current authenticator, assume the worst (i.e. interactive)
143             digest.update(UUID.randomUUID().toString());
144         }
145 
146         @Override
147         public boolean equals(Object obj) {
148             return this == obj || (obj != null && getClass().equals(obj.getClass()));
149         }
150 
151         @Override
152         public int hashCode() {
153             return getClass().hashCode();
154         }
155     }
156 }