URLUtil.java revision 758bf410843724d31f4ab48e8d7dd6b7c1240f23
1/*
2 * Copyright (C) 2006 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.webkit;
18
19import java.io.UnsupportedEncodingException;
20import java.util.regex.Matcher;
21import java.util.regex.Pattern;
22
23import android.net.Uri;
24import android.net.ParseException;
25import android.net.WebAddress;
26import android.util.Log;
27
28public final class URLUtil {
29
30    private static final String LOGTAG = "webkit";
31
32    static final String ASSET_BASE = "file:///android_asset/";
33    static final String FILE_BASE = "file://";
34    static final String PROXY_BASE = "file:///cookieless_proxy/";
35
36    /**
37     * Cleans up (if possible) user-entered web addresses
38     */
39    public static String guessUrl(String inUrl) {
40
41        String retVal = inUrl;
42        WebAddress webAddress;
43
44        Log.v(LOGTAG, "guessURL before queueRequest: " + inUrl);
45
46        if (inUrl.length() == 0) return inUrl;
47        if (inUrl.startsWith("about:")) return inUrl;
48        // Do not try to interpret data scheme URLs
49        if (inUrl.startsWith("data:")) return inUrl;
50        // Do not try to interpret file scheme URLs
51        if (inUrl.startsWith("file:")) return inUrl;
52        // Do not try to interpret javascript scheme URLs
53        if (inUrl.startsWith("javascript:")) return inUrl;
54
55        // bug 762454: strip period off end of url
56        if (inUrl.endsWith(".") == true) {
57            inUrl = inUrl.substring(0, inUrl.length() - 1);
58        }
59
60        try {
61            webAddress = new WebAddress(inUrl);
62        } catch (ParseException ex) {
63
64            if (DebugFlags.URL_UTIL) {
65                Log.v(LOGTAG, "smartUrlFilter: failed to parse url = " + inUrl);
66            }
67            return retVal;
68        }
69
70        // Check host
71        if (webAddress.mHost.indexOf('.') == -1) {
72            // no dot: user probably entered a bare domain.  try .com
73            webAddress.mHost = "www." + webAddress.mHost + ".com";
74        }
75        return webAddress.toString();
76    }
77
78    public static String composeSearchUrl(String inQuery, String template,
79                                          String queryPlaceHolder) {
80        int placeHolderIndex = template.indexOf(queryPlaceHolder);
81        if (placeHolderIndex < 0) {
82            return null;
83        }
84
85        String query;
86        StringBuilder buffer = new StringBuilder();
87        buffer.append(template.substring(0, placeHolderIndex));
88
89        try {
90            query = java.net.URLEncoder.encode(inQuery, "utf-8");
91            buffer.append(query);
92        } catch (UnsupportedEncodingException ex) {
93            return null;
94        }
95
96        buffer.append(template.substring(
97                placeHolderIndex + queryPlaceHolder.length()));
98
99        return buffer.toString();
100    }
101
102    public static byte[] decode(byte[] url) throws IllegalArgumentException {
103        if (url.length == 0) {
104            return new byte[0];
105        }
106
107        // Create a new byte array with the same length to ensure capacity
108        byte[] tempData = new byte[url.length];
109
110        int tempCount = 0;
111        for (int i = 0; i < url.length; i++) {
112            byte b = url[i];
113            if (b == '%') {
114                if (url.length - i > 2) {
115                    b = (byte) (parseHex(url[i + 1]) * 16
116                            + parseHex(url[i + 2]));
117                    i += 2;
118                } else {
119                    throw new IllegalArgumentException("Invalid format");
120                }
121            }
122            tempData[tempCount++] = b;
123        }
124        byte[] retData = new byte[tempCount];
125        System.arraycopy(tempData, 0, retData, 0, tempCount);
126        return retData;
127    }
128
129    /**
130     * @return True iff the url is correctly URL encoded
131     */
132    static boolean verifyURLEncoding(String url) {
133        int count = url.length();
134        if (count == 0) {
135            return false;
136        }
137
138        int index = url.indexOf('%');
139        while (index >= 0 && index < count) {
140            if (index < count - 2) {
141                try {
142                    parseHex((byte) url.charAt(++index));
143                    parseHex((byte) url.charAt(++index));
144                } catch (IllegalArgumentException e) {
145                    return false;
146                }
147            } else {
148                return false;
149            }
150            index = url.indexOf('%', index + 1);
151        }
152        return true;
153    }
154
155    private static int parseHex(byte b) {
156        if (b >= '0' && b <= '9') return (b - '0');
157        if (b >= 'A' && b <= 'F') return (b - 'A' + 10);
158        if (b >= 'a' && b <= 'f') return (b - 'a' + 10);
159
160        throw new IllegalArgumentException("Invalid hex char '" + b + "'");
161    }
162
163    /**
164     * @return True iff the url is an asset file.
165     */
166    public static boolean isAssetUrl(String url) {
167        return (null != url) && url.startsWith(ASSET_BASE);
168    }
169
170    /**
171     * @return True iff the url is an proxy url to allow cookieless network
172     * requests from a file url.
173     * @deprecated Cookieless proxy is no longer supported.
174     */
175    public static boolean isCookielessProxyUrl(String url) {
176        return (null != url) && url.startsWith(PROXY_BASE);
177    }
178
179    /**
180     * @return True iff the url is a local file.
181     */
182    public static boolean isFileUrl(String url) {
183        return (null != url) && (url.startsWith(FILE_BASE) &&
184                                 !url.startsWith(ASSET_BASE) &&
185                                 !url.startsWith(PROXY_BASE));
186    }
187
188    /**
189     * @return True iff the url is an about: url.
190     */
191    public static boolean isAboutUrl(String url) {
192        return (null != url) && url.startsWith("about:");
193    }
194
195    /**
196     * @return True iff the url is a data: url.
197     */
198    public static boolean isDataUrl(String url) {
199        return (null != url) && url.startsWith("data:");
200    }
201
202    /**
203     * @return True iff the url is a javascript: url.
204     */
205    public static boolean isJavaScriptUrl(String url) {
206        return (null != url) && url.startsWith("javascript:");
207    }
208
209    /**
210     * @return True iff the url is an http: url.
211     */
212    public static boolean isHttpUrl(String url) {
213        return (null != url) &&
214               (url.length() > 6) &&
215               url.substring(0, 7).equalsIgnoreCase("http://");
216    }
217
218    /**
219     * @return True iff the url is an https: url.
220     */
221    public static boolean isHttpsUrl(String url) {
222        return (null != url) &&
223               (url.length() > 7) &&
224               url.substring(0, 8).equalsIgnoreCase("https://");
225    }
226
227    /**
228     * @return True iff the url is a network url.
229     */
230    public static boolean isNetworkUrl(String url) {
231        if (url == null || url.length() == 0) {
232            return false;
233        }
234        return isHttpUrl(url) || isHttpsUrl(url);
235    }
236
237    /**
238     * @return True iff the url is a content: url.
239     */
240    public static boolean isContentUrl(String url) {
241        return (null != url) && url.startsWith("content:");
242    }
243
244    /**
245     * @return True iff the url is valid.
246     */
247    public static boolean isValidUrl(String url) {
248        if (url == null || url.length() == 0) {
249            return false;
250        }
251
252        return (isAssetUrl(url) ||
253                isFileUrl(url) ||
254                isAboutUrl(url) ||
255                isHttpUrl(url) ||
256                isHttpsUrl(url) ||
257                isJavaScriptUrl(url) ||
258                isContentUrl(url));
259    }
260
261    /**
262     * Strips the url of the anchor.
263     */
264    public static String stripAnchor(String url) {
265        int anchorIndex = url.indexOf('#');
266        if (anchorIndex != -1) {
267            return url.substring(0, anchorIndex);
268        }
269        return url;
270    }
271
272    /**
273     * Guesses canonical filename that a download would have, using
274     * the URL and contentDisposition. File extension, if not defined,
275     * is added based on the mimetype
276     * @param url Url to the content
277     * @param contentDisposition Content-Disposition HTTP header or null
278     * @param mimeType Mime-type of the content or null
279     *
280     * @return suggested filename
281     */
282    public static final String guessFileName(
283            String url,
284            String contentDisposition,
285            String mimeType) {
286        String filename = null;
287        String extension = null;
288
289        // If we couldn't do anything with the hint, move toward the content disposition
290        if (filename == null && contentDisposition != null) {
291            filename = parseContentDisposition(contentDisposition);
292            if (filename != null) {
293                int index = filename.lastIndexOf('/') + 1;
294                if (index > 0) {
295                    filename = filename.substring(index);
296                }
297            }
298        }
299
300        // If all the other http-related approaches failed, use the plain uri
301        if (filename == null) {
302            String decodedUrl = Uri.decode(url);
303            if (decodedUrl != null) {
304                int queryIndex = decodedUrl.indexOf('?');
305                // If there is a query string strip it, same as desktop browsers
306                if (queryIndex > 0) {
307                    decodedUrl = decodedUrl.substring(0, queryIndex);
308                }
309                if (!decodedUrl.endsWith("/")) {
310                    int index = decodedUrl.lastIndexOf('/') + 1;
311                    if (index > 0) {
312                        filename = decodedUrl.substring(index);
313                    }
314                }
315            }
316        }
317
318        // Finally, if couldn't get filename from URI, get a generic filename
319        if (filename == null) {
320            filename = "downloadfile";
321        }
322
323        // Split filename between base and extension
324        // Add an extension if filename does not have one
325        int dotIndex = filename.indexOf('.');
326        if (dotIndex < 0) {
327            if (mimeType != null) {
328                extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType);
329                if (extension != null) {
330                    extension = "." + extension;
331                }
332            }
333            if (extension == null) {
334                if (mimeType != null && mimeType.toLowerCase().startsWith("text/")) {
335                    if (mimeType.equalsIgnoreCase("text/html")) {
336                        extension = ".html";
337                    } else {
338                        extension = ".txt";
339                    }
340                } else {
341                    extension = ".bin";
342                }
343            }
344        } else {
345            if (mimeType != null) {
346                // Compare the last segment of the extension against the mime type.
347                // If there's a mismatch, discard the entire extension.
348                int lastDotIndex = filename.lastIndexOf('.');
349                String typeFromExt = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
350                        filename.substring(lastDotIndex + 1));
351                if (typeFromExt != null && !typeFromExt.equalsIgnoreCase(mimeType)) {
352                    extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType);
353                    if (extension != null) {
354                        extension = "." + extension;
355                    }
356                }
357            }
358            if (extension == null) {
359                extension = filename.substring(dotIndex);
360            }
361            filename = filename.substring(0, dotIndex);
362        }
363
364        return filename + extension;
365    }
366
367    /** Regex used to parse content-disposition headers */
368    private static final Pattern CONTENT_DISPOSITION_PATTERN =
369            Pattern.compile("attachment;\\s*filename\\s*=\\s*\"([^\"]*)\"");
370
371    /*
372     * Parse the Content-Disposition HTTP Header. The format of the header
373     * is defined here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html
374     * This header provides a filename for content that is going to be
375     * downloaded to the file system. We only support the attachment type.
376     */
377    static String parseContentDisposition(String contentDisposition) {
378        try {
379            Matcher m = CONTENT_DISPOSITION_PATTERN.matcher(contentDisposition);
380            if (m.find()) {
381                return m.group(1);
382            }
383        } catch (IllegalStateException ex) {
384             // This function is defined as returning null when it can't parse the header
385        }
386        return null;
387    }
388}
389