blob: 03b07e080add69cc682f06118c6a3fc6060cd322 [file] [log] [blame]
Remi NGUYEN VAN0f8f6302021-01-15 18:08:24 +09001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.net;
18
19import android.annotation.SdkConstant;
20import android.annotation.SdkConstant.SdkConstantType;
21import android.compat.annotation.UnsupportedAppUsage;
22import android.content.Context;
23import android.os.Build;
24import android.text.TextUtils;
25import android.util.Log;
26
27import com.android.net.module.util.ProxyUtils;
28
29import java.net.InetSocketAddress;
30import java.net.ProxySelector;
31import java.net.URI;
32import java.util.List;
33import java.util.regex.Matcher;
34import java.util.regex.Pattern;
35
36/**
37 * A convenience class for accessing the user and default proxy
38 * settings.
39 */
40public final class Proxy {
41
42 private static final String TAG = "Proxy";
43
44 private static final ProxySelector sDefaultProxySelector;
45
46 /**
47 * Used to notify an app that's caching the proxy that either the default
48 * connection has changed or any connection's proxy has changed. The new
49 * proxy should be queried using {@link ConnectivityManager#getDefaultProxy()}.
50 *
51 * <p class="note">This is a protected intent that can only be sent by the system
52 */
53 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
54 public static final String PROXY_CHANGE_ACTION = "android.intent.action.PROXY_CHANGE";
55 /**
56 * Intent extra included with {@link #PROXY_CHANGE_ACTION} intents.
57 * It describes the new proxy being used (as a {@link ProxyInfo} object).
58 * @deprecated Because {@code PROXY_CHANGE_ACTION} is sent whenever the proxy
59 * for any network on the system changes, applications should always use
60 * {@link ConnectivityManager#getDefaultProxy()} or
61 * {@link ConnectivityManager#getLinkProperties(Network)}.{@link LinkProperties#getHttpProxy()}
62 * to get the proxy for the Network(s) they are using.
63 */
64 @Deprecated
65 public static final String EXTRA_PROXY_INFO = "android.intent.extra.PROXY_INFO";
66
67 /** @hide */
68 public static final int PROXY_VALID = 0;
69 /** @hide */
70 public static final int PROXY_HOSTNAME_EMPTY = 1;
71 /** @hide */
72 public static final int PROXY_HOSTNAME_INVALID = 2;
73 /** @hide */
74 public static final int PROXY_PORT_EMPTY = 3;
75 /** @hide */
76 public static final int PROXY_PORT_INVALID = 4;
77 /** @hide */
78 public static final int PROXY_EXCLLIST_INVALID = 5;
79
80 private static ConnectivityManager sConnectivityManager = null;
81
82 // Hostname / IP REGEX validation
83 // Matches blank input, ips, and domain names
84 private static final String NAME_IP_REGEX =
85 "[a-zA-Z0-9]+(\\-[a-zA-Z0-9]+)*(\\.[a-zA-Z0-9]+(\\-[a-zA-Z0-9]+)*)*";
86
87 private static final String HOSTNAME_REGEXP = "^$|^" + NAME_IP_REGEX + "$";
88
89 private static final Pattern HOSTNAME_PATTERN;
90
91 private static final String EXCL_REGEX =
92 "[a-zA-Z0-9*]+(\\-[a-zA-Z0-9*]+)*(\\.[a-zA-Z0-9*]+(\\-[a-zA-Z0-9*]+)*)*";
93
94 private static final String EXCLLIST_REGEXP = "^$|^" + EXCL_REGEX + "(," + EXCL_REGEX + ")*$";
95
96 private static final Pattern EXCLLIST_PATTERN;
97
98 static {
99 HOSTNAME_PATTERN = Pattern.compile(HOSTNAME_REGEXP);
100 EXCLLIST_PATTERN = Pattern.compile(EXCLLIST_REGEXP);
101 sDefaultProxySelector = ProxySelector.getDefault();
102 }
103
104 /**
105 * Return the proxy object to be used for the URL given as parameter.
106 * @param ctx A Context used to get the settings for the proxy host.
107 * @param url A URL to be accessed. Used to evaluate exclusion list.
108 * @return Proxy (java.net) object containing the host name. If the
109 * user did not set a hostname it returns the default host.
110 * A null value means that no host is to be used.
111 * {@hide}
112 */
113 @UnsupportedAppUsage
114 public static final java.net.Proxy getProxy(Context ctx, String url) {
115 String host = "";
116 if ((url != null) && !isLocalHost(host)) {
117 URI uri = URI.create(url);
118 ProxySelector proxySelector = ProxySelector.getDefault();
119
120 List<java.net.Proxy> proxyList = proxySelector.select(uri);
121
122 if (proxyList.size() > 0) {
123 return proxyList.get(0);
124 }
125 }
126 return java.net.Proxy.NO_PROXY;
127 }
128
129
130 /**
131 * Return the proxy host set by the user.
132 * @param ctx A Context used to get the settings for the proxy host.
133 * @return String containing the host name. If the user did not set a host
134 * name it returns the default host. A null value means that no
135 * host is to be used.
136 * @deprecated Use standard java vm proxy values to find the host, port
137 * and exclusion list. This call ignores the exclusion list.
138 */
139 @Deprecated
140 public static final String getHost(Context ctx) {
141 java.net.Proxy proxy = getProxy(ctx, null);
142 if (proxy == java.net.Proxy.NO_PROXY) return null;
143 try {
144 return ((InetSocketAddress)(proxy.address())).getHostName();
145 } catch (Exception e) {
146 return null;
147 }
148 }
149
150 /**
151 * Return the proxy port set by the user.
152 * @param ctx A Context used to get the settings for the proxy port.
153 * @return The port number to use or -1 if no proxy is to be used.
154 * @deprecated Use standard java vm proxy values to find the host, port
155 * and exclusion list. This call ignores the exclusion list.
156 */
157 @Deprecated
158 public static final int getPort(Context ctx) {
159 java.net.Proxy proxy = getProxy(ctx, null);
160 if (proxy == java.net.Proxy.NO_PROXY) return -1;
161 try {
162 return ((InetSocketAddress)(proxy.address())).getPort();
163 } catch (Exception e) {
164 return -1;
165 }
166 }
167
168 /**
169 * Return the default proxy host specified by the carrier.
170 * @return String containing the host name or null if there is no proxy for
171 * this carrier.
172 * @deprecated Use standard java vm proxy values to find the host, port and
173 * exclusion list. This call ignores the exclusion list and no
174 * longer reports only mobile-data apn-based proxy values.
175 */
176 @Deprecated
177 public static final String getDefaultHost() {
178 String host = System.getProperty("http.proxyHost");
179 if (TextUtils.isEmpty(host)) return null;
180 return host;
181 }
182
183 /**
184 * Return the default proxy port specified by the carrier.
185 * @return The port number to be used with the proxy host or -1 if there is
186 * no proxy for this carrier.
187 * @deprecated Use standard java vm proxy values to find the host, port and
188 * exclusion list. This call ignores the exclusion list and no
189 * longer reports only mobile-data apn-based proxy values.
190 */
191 @Deprecated
192 public static final int getDefaultPort() {
193 if (getDefaultHost() == null) return -1;
194 try {
195 return Integer.parseInt(System.getProperty("http.proxyPort"));
196 } catch (NumberFormatException e) {
197 return -1;
198 }
199 }
200
201 private static final boolean isLocalHost(String host) {
202 if (host == null) {
203 return false;
204 }
205 try {
206 if (host != null) {
207 if (host.equalsIgnoreCase("localhost")) {
208 return true;
209 }
210 if (InetAddresses.parseNumericAddress(host).isLoopbackAddress()) {
211 return true;
212 }
213 }
214 } catch (IllegalArgumentException iex) {
215 }
216 return false;
217 }
218
219 /**
220 * Validate syntax of hostname, port and exclusion list entries
221 * {@hide}
222 */
223 public static int validate(String hostname, String port, String exclList) {
224 Matcher match = HOSTNAME_PATTERN.matcher(hostname);
225 Matcher listMatch = EXCLLIST_PATTERN.matcher(exclList);
226
227 if (!match.matches()) return PROXY_HOSTNAME_INVALID;
228
229 if (!listMatch.matches()) return PROXY_EXCLLIST_INVALID;
230
231 if (hostname.length() > 0 && port.length() == 0) return PROXY_PORT_EMPTY;
232
233 if (port.length() > 0) {
234 if (hostname.length() == 0) return PROXY_HOSTNAME_EMPTY;
235 int portVal = -1;
236 try {
237 portVal = Integer.parseInt(port);
238 } catch (NumberFormatException ex) {
239 return PROXY_PORT_INVALID;
240 }
241 if (portVal <= 0 || portVal > 0xFFFF) return PROXY_PORT_INVALID;
242 }
243 return PROXY_VALID;
244 }
245
246 /** @hide */
247 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
248 public static final void setHttpProxySystemProperty(ProxyInfo p) {
249 String host = null;
250 String port = null;
251 String exclList = null;
252 Uri pacFileUrl = Uri.EMPTY;
253 if (p != null) {
254 host = p.getHost();
255 port = Integer.toString(p.getPort());
256 exclList = ProxyUtils.exclusionListAsString(p.getExclusionList());
257 pacFileUrl = p.getPacFileUrl();
258 }
259 setHttpProxySystemProperty(host, port, exclList, pacFileUrl);
260 }
261
262 /** @hide */
263 public static final void setHttpProxySystemProperty(String host, String port, String exclList,
264 Uri pacFileUrl) {
265 if (exclList != null) exclList = exclList.replace(",", "|");
266 if (false) Log.d(TAG, "setHttpProxySystemProperty :"+host+":"+port+" - "+exclList);
267 if (host != null) {
268 System.setProperty("http.proxyHost", host);
269 System.setProperty("https.proxyHost", host);
270 } else {
271 System.clearProperty("http.proxyHost");
272 System.clearProperty("https.proxyHost");
273 }
274 if (port != null) {
275 System.setProperty("http.proxyPort", port);
276 System.setProperty("https.proxyPort", port);
277 } else {
278 System.clearProperty("http.proxyPort");
279 System.clearProperty("https.proxyPort");
280 }
281 if (exclList != null) {
282 System.setProperty("http.nonProxyHosts", exclList);
283 System.setProperty("https.nonProxyHosts", exclList);
284 } else {
285 System.clearProperty("http.nonProxyHosts");
286 System.clearProperty("https.nonProxyHosts");
287 }
288 if (!Uri.EMPTY.equals(pacFileUrl)) {
289 ProxySelector.setDefault(new PacProxySelector());
290 } else {
291 ProxySelector.setDefault(sDefaultProxySelector);
292 }
293 }
294}