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