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