Proxy.java revision 3dce5af6abc9c8d41d24d9499410b33ec76b1f08
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
17package android.net;
18
19import android.annotation.SdkConstant;
20import android.annotation.SdkConstant.SdkConstantType;
21import android.content.Context;
22import android.text.TextUtils;
23import android.util.Log;
24
25
26import org.apache.http.HttpHost;
27import org.apache.http.HttpRequest;
28import org.apache.http.conn.routing.HttpRoute;
29import org.apache.http.conn.routing.HttpRoutePlanner;
30import org.apache.http.conn.scheme.SchemeRegistry;
31import org.apache.http.protocol.HttpContext;
32
33import java.net.InetSocketAddress;
34import java.net.ProxySelector;
35import java.net.URI;
36import java.util.List;
37import java.util.regex.Matcher;
38import java.util.regex.Pattern;
39
40/**
41 * A convenience class for accessing the user and default proxy
42 * settings.
43 */
44public final class Proxy {
45
46    // Set to true to enable extra debugging.
47    private static final boolean DEBUG = false;
48    private static final String TAG = "Proxy";
49
50    private static final ProxySelector sDefaultProxySelector;
51
52    /**
53     * Used to notify an app that's caching the default connection proxy
54     * that either the default connection or its proxy has changed.
55     * The intent will have the following extra value:</p>
56     * <ul>
57     *   <li><em>EXTRA_PROXY_INFO</em> - The ProxyProperties for the proxy.  Non-null,
58     *                                   though if the proxy is undefined the host string
59     *                                   will be empty.
60     * </ul>
61     *
62     * <p class="note">This is a protected intent that can only be sent by the system
63     */
64    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
65    public static final String PROXY_CHANGE_ACTION = "android.intent.action.PROXY_CHANGE";
66    /** {@hide} **/
67    public static final String EXTRA_PROXY_INFO = "proxy";
68
69    private static ConnectivityManager sConnectivityManager = null;
70
71    // Hostname / IP REGEX validation
72    // Matches blank input, ips, and domain names
73    private static final String NAME_IP_REGEX =
74        "[a-zA-Z0-9]+(\\-[a-zA-Z0-9]+)*(\\.[a-zA-Z0-9]+(\\-[a-zA-Z0-9]+)*)*";
75
76    private static final String HOSTNAME_REGEXP = "^$|^" + NAME_IP_REGEX + "$";
77
78    private static final Pattern HOSTNAME_PATTERN;
79
80    private static final String EXCL_REGEX =
81        "[a-zA-Z0-9*]+(\\-[a-zA-Z0-9*]+)*(\\.[a-zA-Z0-9*]+(\\-[a-zA-Z0-9*]+)*)*";
82
83    private static final String EXCLLIST_REGEXP = "^$|^" + EXCL_REGEX + "(," + EXCL_REGEX + ")*$";
84
85    private static final Pattern EXCLLIST_PATTERN;
86
87    static {
88        HOSTNAME_PATTERN = Pattern.compile(HOSTNAME_REGEXP);
89        EXCLLIST_PATTERN = Pattern.compile(EXCLLIST_REGEXP);
90        sDefaultProxySelector = ProxySelector.getDefault();
91    }
92
93    /**
94     * Return the proxy object to be used for the URL given as parameter.
95     * @param ctx A Context used to get the settings for the proxy host.
96     * @param url A URL to be accessed. Used to evaluate exclusion list.
97     * @return Proxy (java.net) object containing the host name. If the
98     *         user did not set a hostname it returns the default host.
99     *         A null value means that no host is to be used.
100     * {@hide}
101     */
102    public static final java.net.Proxy getProxy(Context ctx, String url) {
103        String host = "";
104        if (url != null) {
105            URI uri = URI.create(url);
106            host = uri.getHost();
107        }
108
109        if (!isLocalHost(host)) {
110            if (sConnectivityManager == null) {
111                sConnectivityManager = (ConnectivityManager)ctx.getSystemService(
112                        Context.CONNECTIVITY_SERVICE);
113            }
114            if (sConnectivityManager == null) return java.net.Proxy.NO_PROXY;
115
116            ProxyProperties proxyProperties = sConnectivityManager.getProxy();
117
118            if (proxyProperties != null) {
119                if (!proxyProperties.isExcluded(host)) {
120                    return proxyProperties.makeProxy();
121                }
122            }
123        }
124        return java.net.Proxy.NO_PROXY;
125    }
126
127
128    /**
129     * Return the proxy host set by the user.
130     * @param ctx A Context used to get the settings for the proxy host.
131     * @return String containing the host name. If the user did not set a host
132     *         name it returns the default host. A null value means that no
133     *         host is to be used.
134     * @deprecated Use standard java vm proxy values to find the host, port
135     *         and exclusion list.  This call ignores the exclusion list.
136     */
137    public static final String getHost(Context ctx) {
138        java.net.Proxy proxy = getProxy(ctx, null);
139        if (proxy == java.net.Proxy.NO_PROXY) return null;
140        try {
141            return ((InetSocketAddress)(proxy.address())).getHostName();
142        } catch (Exception e) {
143            return null;
144        }
145    }
146
147    /**
148     * Return the proxy port set by the user.
149     * @param ctx A Context used to get the settings for the proxy port.
150     * @return The port number to use or -1 if no proxy is to be used.
151     * @deprecated Use standard java vm proxy values to find the host, port
152     *         and exclusion list.  This call ignores the exclusion list.
153     */
154    public static final int getPort(Context ctx) {
155        java.net.Proxy proxy = getProxy(ctx, null);
156        if (proxy == java.net.Proxy.NO_PROXY) return -1;
157        try {
158            return ((InetSocketAddress)(proxy.address())).getPort();
159        } catch (Exception e) {
160            return -1;
161        }
162    }
163
164    /**
165     * Return the default proxy host specified by the carrier.
166     * @return String containing the host name or null if there is no proxy for
167     * this carrier.
168     * @deprecated Use standard java vm proxy values to find the host, port and
169     *         exclusion list.  This call ignores the exclusion list and no
170     *         longer reports only mobile-data apn-based proxy values.
171     */
172    public static final String getDefaultHost() {
173        String host = System.getProperty("http.proxyHost");
174        if (TextUtils.isEmpty(host)) return null;
175        return host;
176    }
177
178    /**
179     * Return the default proxy port specified by the carrier.
180     * @return The port number to be used with the proxy host or -1 if there is
181     * no proxy for this carrier.
182     * @deprecated Use standard java vm proxy values to find the host, port and
183     *         exclusion list.  This call ignores the exclusion list and no
184     *         longer reports only mobile-data apn-based proxy values.
185     */
186    public static final int getDefaultPort() {
187        if (getDefaultHost() == null) return -1;
188        try {
189            return Integer.parseInt(System.getProperty("http.proxyPort"));
190        } catch (NumberFormatException e) {
191            return -1;
192        }
193    }
194
195    /**
196     * Returns the preferred proxy to be used by clients. This is a wrapper
197     * around {@link android.net.Proxy#getHost()}.
198     *
199     * @param context the context which will be passed to
200     * {@link android.net.Proxy#getHost()}
201     * @param url the target URL for the request
202     * @note Calling this method requires permission
203     * android.permission.ACCESS_NETWORK_STATE
204     * @return The preferred proxy to be used by clients, or null if there
205     * is no proxy.
206     * {@hide}
207     */
208    public static final HttpHost getPreferredHttpHost(Context context,
209            String url) {
210        java.net.Proxy prefProxy = getProxy(context, url);
211        if (prefProxy.equals(java.net.Proxy.NO_PROXY)) {
212            return null;
213        } else {
214            InetSocketAddress sa = (InetSocketAddress)prefProxy.address();
215            return new HttpHost(sa.getHostName(), sa.getPort(), "http");
216        }
217    }
218
219    private static final boolean isLocalHost(String host) {
220        if (host == null) {
221            return false;
222        }
223        try {
224            if (host != null) {
225                if (host.equalsIgnoreCase("localhost")) {
226                    return true;
227                }
228                if (NetworkUtils.numericToInetAddress(host).isLoopbackAddress()) {
229                    return true;
230                }
231            }
232        } catch (IllegalArgumentException iex) {
233        }
234        return false;
235    }
236
237    /**
238     * Validate syntax of hostname, port and exclusion list entries
239     * {@hide}
240     */
241    public static void validate(String hostname, String port, String exclList) {
242        Matcher match = HOSTNAME_PATTERN.matcher(hostname);
243        Matcher listMatch = EXCLLIST_PATTERN.matcher(exclList);
244
245        if (!match.matches()) {
246            throw new IllegalArgumentException();
247        }
248
249        if (!listMatch.matches()) {
250            throw new IllegalArgumentException();
251        }
252
253        if (hostname.length() > 0 && port.length() == 0) {
254            throw new IllegalArgumentException();
255        }
256
257        if (port.length() > 0) {
258            if (hostname.length() == 0) {
259                throw new IllegalArgumentException();
260            }
261            int portVal = -1;
262            try {
263                portVal = Integer.parseInt(port);
264            } catch (NumberFormatException ex) {
265                throw new IllegalArgumentException();
266            }
267            if (portVal <= 0 || portVal > 0xFFFF) {
268                throw new IllegalArgumentException();
269            }
270        }
271    }
272
273    static class AndroidProxySelectorRoutePlanner
274            extends org.apache.http.impl.conn.ProxySelectorRoutePlanner {
275
276        private Context mContext;
277
278        public AndroidProxySelectorRoutePlanner(SchemeRegistry schreg, ProxySelector prosel,
279                Context context) {
280            super(schreg, prosel);
281            mContext = context;
282        }
283
284        @Override
285        protected java.net.Proxy chooseProxy(List<java.net.Proxy> proxies, HttpHost target,
286                HttpRequest request, HttpContext context) {
287            return getProxy(mContext, target.getHostName());
288        }
289
290        @Override
291        protected HttpHost determineProxy(HttpHost target, HttpRequest request,
292                HttpContext context) {
293            return getPreferredHttpHost(mContext, target.getHostName());
294        }
295
296        @Override
297        public HttpRoute determineRoute(HttpHost target, HttpRequest request,
298                HttpContext context) {
299            HttpHost proxy = getPreferredHttpHost(mContext, target.getHostName());
300            if (proxy == null) {
301                return new HttpRoute(target);
302            } else {
303                return new HttpRoute(target, null, proxy, false);
304            }
305        }
306    }
307
308    /** @hide */
309    public static final HttpRoutePlanner getAndroidProxySelectorRoutePlanner(Context context) {
310        AndroidProxySelectorRoutePlanner ret = new AndroidProxySelectorRoutePlanner(
311                new SchemeRegistry(), ProxySelector.getDefault(), context);
312        return ret;
313    }
314
315    /** @hide */
316    public static final void setHttpProxySystemProperty(ProxyProperties p) {
317        String host = null;
318        String port = null;
319        String exclList = null;
320        String pacFileUrl = null;
321        if (p != null) {
322            host = p.getHost();
323            port = Integer.toString(p.getPort());
324            exclList = p.getExclusionList();
325            pacFileUrl = p.getPacFileUrl();
326        }
327        setHttpProxySystemProperty(host, port, exclList, pacFileUrl);
328    }
329
330    /** @hide */
331    public static final void setHttpProxySystemProperty(String host, String port, String exclList,
332            String pacFileUrl) {
333        if (exclList != null) exclList = exclList.replace(",", "|");
334        if (false) Log.d(TAG, "setHttpProxySystemProperty :"+host+":"+port+" - "+exclList);
335        if (host != null) {
336            System.setProperty("http.proxyHost", host);
337            System.setProperty("https.proxyHost", host);
338        } else {
339            System.clearProperty("http.proxyHost");
340            System.clearProperty("https.proxyHost");
341        }
342        if (port != null) {
343            System.setProperty("http.proxyPort", port);
344            System.setProperty("https.proxyPort", port);
345        } else {
346            System.clearProperty("http.proxyPort");
347            System.clearProperty("https.proxyPort");
348        }
349        if (exclList != null) {
350            System.setProperty("http.nonProxyHosts", exclList);
351            System.setProperty("https.nonProxyHosts", exclList);
352        } else {
353            System.clearProperty("http.nonProxyHosts");
354            System.clearProperty("https.nonProxyHosts");
355        }
356        if (!TextUtils.isEmpty(pacFileUrl)) {
357            ProxySelector.setDefault(new PacProxySelector());
358        } else {
359            ProxySelector.setDefault(sDefaultProxySelector);
360        }
361    }
362}
363