Debian Codegraph @

src/main/java/com/github/markusbernhardt/proxy/selector/pac/UrlPacScriptSource.java

raw symbols SCIP
1 package com.github.markusbernhardt.proxy.selector.pac;
2
3 import java.io.BufferedReader;
4 import java.io.File;
5 import java.io.FileReader;
6 import java.io.IOException;
7 import java.io.InputStreamReader;
8 import java.io.UnsupportedEncodingException;
9 import java.net.HttpURLConnection;
10 import java.net.MalformedURLException;
11 import java.net.Proxy;
12 import java.net.URISyntaxException;
13 import java.net.URL;
14
15 import com.github.markusbernhardt.proxy.util.Logger;
16 import com.github.markusbernhardt.proxy.util.Logger.LogLevel;
17
18 /*****************************************************************************
19 * Script source that will load the content of a PAC file from an webserver. The
20 * script content is cached once it was downloaded.
21 *
22 * @author Markus Bernhardt, Copyright 2016
23 * @author Bernd Rosstauscher, Copyright 2009
24 ****************************************************************************/
25
26 public class UrlPacScriptSource implements PacScriptSource {
27
28 private static final int DEFAULT_CONNECT_TIMEOUT = 15 * 1000; // seconds
29 private static final int DEFAULT_READ_TIMEOUT = 20 * 1000; // seconds
30 public static final String OVERRIDE_CONNECT_TIMEOUT = "com.btr.proxy.url.connectTimeout";
31 public static final String OVERRIDE_READ_TIMEOUT = "com.btr.proxy.url.readTimeout";
32
33 private final String scriptUrl;
34 private String scriptContent;
35 private long expireAtMillis;
36
37 /*************************************************************************
38 * Constructor
39 *
40 * @param url
41 * the URL to download the script from.
42 ************************************************************************/
43
44 public UrlPacScriptSource(String url) {
45 super();
46 this.expireAtMillis = 0;
47 this.scriptUrl = url;
48 }
49
50 /*************************************************************************
51 * getScriptContent
52 *
53 * @see com.github.markusbernhardt.proxy.selector.pac.PacScriptSource#getScriptContent()
54 ************************************************************************/
55
56 public synchronized String getScriptContent() throws IOException {
57 if (this.scriptContent == null
58 || (this.expireAtMillis > 0 && this.expireAtMillis < System.currentTimeMillis())) {
59 try {
60 // Reset it again with next download we should get a new expire
61 // info
62 this.expireAtMillis = 0;
63
64 if (this.scriptUrl.startsWith("file:/") || this.scriptUrl.indexOf(":/") == -1) {
65 this.scriptContent = readPacFileContent(this.scriptUrl);
66 } else {
67 this.scriptContent = downloadPacContent(this.scriptUrl);
68 }
69 } catch (IOException e) {
70 Logger.log(getClass(), LogLevel.ERROR, "Loading script failed from: {0} with error {1}", this.scriptUrl,
71 e);
72 this.scriptContent = "";
73 throw e;
74 }
75 }
76 return this.scriptContent;
77 }
78
79 /*************************************************************************
80 * Reads a PAC script from a local file.
81 *
82 * @param scriptUrl
83 * @return the content of the script file.
84 * @throws IOException
85 * @throws URISyntaxException
86 ************************************************************************/
87
88 private String readPacFileContent(String scriptUrl) throws IOException {
89 try {
90 File file = null;
91 if (scriptUrl.indexOf(":/") == -1) {
92 file = new File(scriptUrl);
93 } else {
94 file = new File(new URL(scriptUrl).toURI());
95 }
96 BufferedReader r = new BufferedReader(new FileReader(file));
97 StringBuilder result = new StringBuilder();
98 try {
99 String line;
100 while ((line = r.readLine()) != null) {
101 result.append(line).append("\n");
102 }
103 } finally {
104 r.close();
105 }
106 return result.toString();
107 } catch (Exception e) {
108 System.out.println(System.getProperty("user.dir"));
109 Logger.log(getClass(), LogLevel.ERROR, "File reading error.", e);
110 throw new IOException(e.getMessage());
111 }
112 }
113
114 /*************************************************************************
115 * Downloads the script from a webserver.
116 *
117 * @param url
118 * the URL to the script file.
119 * @return the script content.
120 * @throws IOException
121 * on read error.
122 ************************************************************************/
123
124 private String downloadPacContent(String url) throws IOException {
125 if (url == null) {
126 throw new IOException("Invalid PAC script URL: null");
127 }
128
129 setPacProxySelectorEnabled(false);
130
131 HttpURLConnection con = null;
132 try {
133 con = setupHTTPConnection(url);
134 if (con.getResponseCode() != 200) {
135 throw new IOException("Server returned: " + con.getResponseCode() + " " + con.getResponseMessage());
136 }
137 // Read expire date.
138 this.expireAtMillis = con.getExpiration();
139
140 BufferedReader r = getReader(con);
141 String result = readAllContent(r);
142 r.close();
143 return result;
144 } finally {
145 setPacProxySelectorEnabled(true);
146 if (con != null) {
147 con.disconnect();
148 }
149 }
150 }
151
152 /*************************************************************************
153 * Enables/disables the PAC proxy selector while we download to prevent
154 * recursion. See issue: 26 in the change tracker.
155 ************************************************************************/
156
157 private void setPacProxySelectorEnabled(boolean enable) {
158 PacProxySelector.setEnabled(enable);
159 }
160
161 /*************************************************************************
162 * Reads the whole content available into a String.
163 *
164 * @param r
165 * to read from.
166 * @return the complete PAC file content.
167 * @throws IOException
168 ************************************************************************/
169
170 private String readAllContent(BufferedReader r) throws IOException {
171 StringBuilder result = new StringBuilder();
172 String line;
173 while ((line = r.readLine()) != null) {
174 result.append(line).append("\n");
175 }
176 return result.toString();
177 }
178
179 /*************************************************************************
180 * Build a BufferedReader around the open HTTP connection.
181 *
182 * @param con
183 * to read from
184 * @return the BufferedReader.
185 * @throws UnsupportedEncodingException
186 * @throws IOException
187 ************************************************************************/
188
189 private BufferedReader getReader(HttpURLConnection con) throws UnsupportedEncodingException, IOException {
190 String charsetName = parseCharsetFromHeader(con.getContentType());
191 BufferedReader r = new BufferedReader(new InputStreamReader(con.getInputStream(), charsetName));
192 return r;
193 }
194
195 /*************************************************************************
196 * Configure the connection to download from.
197 *
198 * @param url
199 * to get the pac file content from
200 * @return a HTTPUrlConnecion to this url.
201 * @throws IOException
202 * @throws MalformedURLException
203 ************************************************************************/
204
205 private HttpURLConnection setupHTTPConnection(String url) throws IOException, MalformedURLException {
206 HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(Proxy.NO_PROXY);
207 con.setConnectTimeout(getTimeOut(OVERRIDE_CONNECT_TIMEOUT, DEFAULT_CONNECT_TIMEOUT));
208 con.setReadTimeout(getTimeOut(OVERRIDE_READ_TIMEOUT, DEFAULT_READ_TIMEOUT));
209 con.setInstanceFollowRedirects(true);
210 con.setRequestProperty("accept", "application/x-ns-proxy-autoconfig, */*;q=0.8");
211 return con;
212 }
213
214 /*************************************************************************
215 * Gets the timeout value from a property or uses the given default value if
216 * the property cannot be parsed.
217 *
218 * @param overrideProperty
219 * the property to define the timeout value in milliseconds
220 * @param defaultValue
221 * the default timeout value in milliseconds.
222 * @return the value to use.
223 ************************************************************************/
224
225 protected int getTimeOut(String overrideProperty, int defaultValue) {
226 int timeout = defaultValue;
227 String prop = System.getProperty(overrideProperty);
228 if (prop != null && prop.trim().length() > 0) {
229 try {
230 timeout = Integer.parseInt(prop.trim());
231 } catch (NumberFormatException e) {
232 Logger.log(getClass(), LogLevel.DEBUG, "Invalid override property : {0}={1}", overrideProperty, prop);
233 // In this case use the default value.
234 }
235 }
236 return timeout;
237 }
238
239 /*************************************************************************
240 * Response Content-Type could be something like this:
241 * application/x-ns-proxy-autoconfig; charset=UTF-8
242 *
243 * @param contentType
244 * header field.
245 * @return the extracted charset if set else a default charset.
246 ************************************************************************/
247
248 String parseCharsetFromHeader(String contentType) {
249 String result = "ISO-8859-1";
250 if (contentType != null) {
251 String[] paramList = contentType.split(";");
252 for (String param : paramList) {
253 if (param.toLowerCase().trim().startsWith("charset") && param.indexOf("=") != -1) {
254 result = param.substring(param.indexOf("=") + 1).trim();
255 }
256 }
257 }
258 return result;
259 }
260
261 /***************************************************************************
262 * @see java.lang.Object#toString()
263 **************************************************************************/
264 @Override
265 public String toString() {
266 return this.scriptUrl;
267 }
268
269 /*************************************************************************
270 * isScriptValid
271 *
272 * @see com.github.markusbernhardt.proxy.selector.pac.PacScriptSource#isScriptValid()
273 ************************************************************************/
274
275 public boolean isScriptValid() {
276 try {
277 String script = getScriptContent();
278 if (script == null || script.trim().length() == 0) {
279 Logger.log(getClass(), LogLevel.DEBUG, "PAC script is empty. Skipping script!");
280 return false;
281 }
282 if (script.indexOf("FindProxyForURL") == -1) {
283 Logger.log(getClass(), LogLevel.DEBUG,
284 "PAC script entry point FindProxyForURL not found. Skipping script!");
285 return false;
286 }
287 return true;
288 } catch (IOException e) {
289 Logger.log(getClass(), LogLevel.DEBUG, "File reading error: {0}", e);
290 return false;
291 }
292 }
293
294 }