URLUtil.java revision 42bc2ff5d2e3a10ab6c1fb1e716a124f2b446dbc
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 (WebView.LOGV_ENABLED) {
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    private static int parseHex(byte b) {
130        if (b >= '0' && b <= '9') return (b - '0');
131        if (b >= 'A' && b <= 'F') return (b - 'A' + 10);
132        if (b >= 'a' && b <= 'f') return (b - 'a' + 10);
133
134        throw new IllegalArgumentException("Invalid hex char '" + b + "'");
135    }
136
137    /**
138     * @return True iff the url is an asset file.
139     */
140    public static boolean isAssetUrl(String url) {
141        return (null != url) && url.startsWith(ASSET_BASE);
142    }
143
144    /**
145     * @return True iff the url is an proxy url to allow cookieless network
146     * requests from a file url.
147     * @deprecated Cookieless proxy is no longer supported.
148     */
149    public static boolean isCookielessProxyUrl(String url) {
150        return (null != url) && url.startsWith(PROXY_BASE);
151    }
152
153    /**
154     * @return True iff the url is a local file.
155     */
156    public static boolean isFileUrl(String url) {
157        return (null != url) && (url.startsWith(FILE_BASE) &&
158                                 !url.startsWith(ASSET_BASE) &&
159                                 !url.startsWith(PROXY_BASE));
160    }
161
162    /**
163     * @return True iff the url is an about: url.
164     */
165    public static boolean isAboutUrl(String url) {
166        return (null != url) && url.startsWith("about:");
167    }
168
169    /**
170     * @return True iff the url is a data: url.
171     */
172    public static boolean isDataUrl(String url) {
173        return (null != url) && url.startsWith("data:");
174    }
175
176    /**
177     * @return True iff the url is a javascript: url.
178     */
179    public static boolean isJavaScriptUrl(String url) {
180        return (null != url) && url.startsWith("javascript:");
181    }
182
183    /**
184     * @return True iff the url is an http: url.
185     */
186    public static boolean isHttpUrl(String url) {
187        return (null != url) &&
188               (url.length() > 6) &&
189               url.substring(0, 7).equalsIgnoreCase("http://");
190    }
191
192    /**
193     * @return True iff the url is an https: url.
194     */
195    public static boolean isHttpsUrl(String url) {
196        return (null != url) &&
197               (url.length() > 7) &&
198               url.substring(0, 8).equalsIgnoreCase("https://");
199    }
200
201    /**
202     * @return True iff the url is a network url.
203     */
204    public static boolean isNetworkUrl(String url) {
205        if (url == null || url.length() == 0) {
206            return false;
207        }
208        return isHttpUrl(url) || isHttpsUrl(url);
209    }
210
211    /**
212     * @return True iff the url is a content: url.
213     */
214    public static boolean isContentUrl(String url) {
215        return (null != url) && url.startsWith("content:");
216    }
217
218    /**
219     * @return True iff the url is valid.
220     */
221    public static boolean isValidUrl(String url) {
222        if (url == null || url.length() == 0) {
223            return false;
224        }
225
226        return (isAssetUrl(url) ||
227                isFileUrl(url) ||
228                isAboutUrl(url) ||
229                isHttpUrl(url) ||
230                isHttpsUrl(url) ||
231                isJavaScriptUrl(url) ||
232                isContentUrl(url));
233    }
234
235    /**
236     * Strips the url of the anchor.
237     */
238    public static String stripAnchor(String url) {
239        int anchorIndex = url.indexOf('#');
240        if (anchorIndex != -1) {
241            return url.substring(0, anchorIndex);
242        }
243        return url;
244    }
245
246    /**
247     * Guesses canonical filename that a download would have, using
248     * the URL and contentDisposition. File extension, if not defined,
249     * is added based on the mimetype
250     * @param url Url to the content
251     * @param contentDisposition Content-Disposition HTTP header or null
252     * @param mimeType Mime-type of the content or null
253     *
254     * @return suggested filename
255     */
256    public static final String guessFileName(
257            String url,
258            String contentDisposition,
259            String mimeType) {
260        String filename = null;
261        String extension = null;
262
263        // If we couldn't do anything with the hint, move toward the content disposition
264        if (filename == null && contentDisposition != null) {
265            filename = parseContentDisposition(contentDisposition);
266            if (filename != null) {
267                int index = filename.lastIndexOf('/') + 1;
268                if (index > 0) {
269                    filename = filename.substring(index);
270                }
271            }
272        }
273
274        // If all the other http-related approaches failed, use the plain uri
275        if (filename == null) {
276            String decodedUrl = Uri.decode(url);
277            if (decodedUrl != null) {
278                int queryIndex = decodedUrl.indexOf('?');
279                // If there is a query string strip it, same as desktop browsers
280                if (queryIndex > 0) {
281                    decodedUrl = decodedUrl.substring(0, queryIndex);
282                }
283                if (!decodedUrl.endsWith("/")) {
284                    int index = decodedUrl.lastIndexOf('/') + 1;
285                    if (index > 0) {
286                        filename = decodedUrl.substring(index);
287                    }
288                }
289            }
290        }
291
292        // Finally, if couldn't get filename from URI, get a generic filename
293        if (filename == null) {
294            filename = "downloadfile";
295        }
296
297        // Split filename between base and extension
298        // Add an extension if filename does not have one
299        int dotIndex = filename.indexOf('.');
300        if (dotIndex < 0) {
301            if (mimeType != null) {
302                extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType);
303                if (extension != null) {
304                    extension = "." + extension;
305                }
306            }
307            if (extension == null) {
308                if (mimeType != null && mimeType.toLowerCase().startsWith("text/")) {
309                    if (mimeType.equalsIgnoreCase("text/html")) {
310                        extension = ".html";
311                    } else {
312                        extension = ".txt";
313                    }
314                } else {
315                    extension = ".bin";
316                }
317            }
318        } else {
319            if (mimeType != null) {
320                // Compare the last segment of the extension against the mime type.
321                // If there's a mismatch, discard the entire extension.
322                int lastDotIndex = filename.lastIndexOf('.');
323                String typeFromExt = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
324                        filename.substring(lastDotIndex + 1));
325                if (typeFromExt != null && !typeFromExt.equalsIgnoreCase(mimeType)) {
326                    extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType);
327                    if (extension != null) {
328                        extension = "." + extension;
329                    }
330                }
331            }
332            if (extension == null) {
333                extension = filename.substring(dotIndex);
334            }
335            filename = filename.substring(0, dotIndex);
336        }
337
338        return filename + extension;
339    }
340
341    /** Regex used to parse content-disposition headers */
342    private static final Pattern CONTENT_DISPOSITION_PATTERN =
343            Pattern.compile("attachment;\\s*filename\\s*=\\s*\"([^\"]*)\"");
344
345    /*
346     * Parse the Content-Disposition HTTP Header. The format of the header
347     * is defined here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html
348     * This header provides a filename for content that is going to be
349     * downloaded to the file system. We only support the attachment type.
350     */
351    private static String parseContentDisposition(String contentDisposition) {
352        try {
353            Matcher m = CONTENT_DISPOSITION_PATTERN.matcher(contentDisposition);
354            if (m.find()) {
355                return m.group(1);
356            }
357        } catch (IllegalStateException ex) {
358             // This function is defined as returning null when it can't parse the header
359        }
360        return null;
361    }
362}
363