View Javadoc
1   /*
2    * Copyright (c) 2002-2017 Gargoyle Software Inc.
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    * http://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package com.gargoylesoftware.htmlunit;
16  
17  import java.lang.reflect.Method;
18  import java.net.InetAddress;
19  import java.net.URL;
20  import java.text.SimpleDateFormat;
21  import java.util.Calendar;
22  import java.util.Locale;
23  import java.util.TimeZone;
24  
25  import org.apache.commons.net.util.SubnetUtils;
26  
27  import net.sourceforge.htmlunit.corejs.javascript.Context;
28  import net.sourceforge.htmlunit.corejs.javascript.FunctionObject;
29  import net.sourceforge.htmlunit.corejs.javascript.NativeFunction;
30  import net.sourceforge.htmlunit.corejs.javascript.Scriptable;
31  import net.sourceforge.htmlunit.corejs.javascript.ScriptableObject;
32  import net.sourceforge.htmlunit.corejs.javascript.Undefined;
33  
34  /**
35   * Provides an implementation of Proxy Auto-Config (PAC).
36   *
37   * @see <a href="http://lib.ru/WEBMASTER/proxy-live.txt">PAC file format</a>
38   *
39   * @author Ahmed Ashour
40   */
41  public final class ProxyAutoConfig {
42  
43      private ProxyAutoConfig() {
44      }
45  
46      /**
47       * Evaluates the <tt>FindProxyForURL</tt> method of the specified content.
48       * @param content the JavaScript content
49       * @param url the URL to be retrieved
50       * @return semicolon-separated result
51       */
52      public static String evaluate(final String content, final URL url) {
53          final Context cx = Context.enter();
54          try {
55              final ProxyAutoConfig config = new ProxyAutoConfig();
56              final Scriptable scope = cx.initStandardObjects();
57  
58              config.defineMethod("isPlainHostName", scope);
59              config.defineMethod("dnsDomainIs", scope);
60              config.defineMethod("localHostOrDomainIs", scope);
61              config.defineMethod("isResolvable", scope);
62              config.defineMethod("isInNet", scope);
63              config.defineMethod("dnsResolve", scope);
64              config.defineMethod("myIpAddress", scope);
65              config.defineMethod("dnsDomainLevels", scope);
66              config.defineMethod("shExpMatch", scope);
67              config.defineMethod("weekdayRange", scope);
68              config.defineMethod("dateRange", scope);
69              config.defineMethod("timeRange", scope);
70  
71              cx.evaluateString(scope, "var ProxyConfig = function() {}; ProxyConfig.bindings = {}", "<init>", 1, null);
72              cx.evaluateString(scope, content, "<Proxy Auto-Config>", 1, null);
73              final Object[] functionArgs = {url.toExternalForm(), url.getHost()};
74              final Object fObj = scope.get("FindProxyForURL", scope);
75  
76              final NativeFunction f = (NativeFunction) fObj;
77              final Object result = f.call(cx, scope, scope, functionArgs);
78              return Context.toString(result);
79          }
80          finally {
81              Context.exit();
82          }
83      }
84  
85      private void defineMethod(final String methodName, final Scriptable scope) {
86          for (Method method : getClass().getMethods()) {
87              if (method.getName().equals(methodName)) {
88                  final FunctionObject functionObject = new FunctionObject(methodName, method, scope);
89                  ((ScriptableObject) scope).defineProperty(methodName, functionObject, ScriptableObject.EMPTY);
90              }
91          }
92      }
93  
94      /**
95       * Returns true if there is no domain name in the hostname (no dots).
96       * @param host the hostname from the URL (excluding port number).
97       * @return true if there is no domain name in the hostname (no dots).
98       */
99      public static boolean isPlainHostName(final String host) {
100         return host.indexOf('.') == -1;
101     }
102 
103     /**
104      * Returns true if the domain of hostname matches.
105      * @param host the hostname from the URL
106      * @param domain the domain name to test the hostname against
107      * @return true if the domain of hostname matches.
108      */
109     public static boolean dnsDomainIs(final String host, final String domain) {
110         return host.endsWith(domain);
111     }
112 
113     /**
114      * Returns true if the hostname matches exactly the specified hostname,
115      * or if there is no domain name part in the hostname, but the unqualified hostname matches.
116      * @param host the hostname from the URL
117      * @param hostdom fully qualified hostname to match against
118      * @return true if the hostname matches exactly the specified hostname,
119      * or if there is no domain name part in the hostname, but the unqualified hostname matches.
120      */
121     public static boolean localHostOrDomainIs(final String host, final String hostdom) {
122         return host.length() > 1 && host.equals(hostdom) || host.indexOf('.') == -1 && hostdom.startsWith(host);
123     }
124 
125     /**
126      * Tries to resolve the hostname. Returns true if succeeds.
127      * @param host the hostname from the URL.
128      * @return true if the specific hostname is resolvable.
129      */
130     public static boolean isResolvable(final String host) {
131         return dnsResolve(host) != null;
132     }
133 
134     /**
135      * Returns true if the IP address of the host matches the specified IP address pattern.
136      * @param host a DNS hostname, or IP address.
137      * If a hostname is passed, it will be resolved into an IP address by this function.
138      * @param pattern an IP address pattern in the dot-separated format
139      * @param mask mask for the IP address pattern informing which parts of the IP address should be matched against.
140      * 0 means ignore, 255 means match
141      * @return true if the IP address of the host matches the specified IP address pattern.
142      */
143     public static boolean isInNet(final String host, final String pattern, final String mask) {
144         final String dnsResolve = dnsResolve(host);
145         if (null == dnsResolve) {
146             return false;
147         }
148 
149         final SubnetUtils subnetUtils = new SubnetUtils(pattern, mask);
150         return subnetUtils.getInfo().isInRange(dnsResolve);
151     }
152 
153     /**
154      * Resolves the given DNS hostname into an IP address, and returns it in the dot separated format as a string.
155      * @param host the hostname to resolve
156      * @return the resolved IP address
157      */
158     public static String dnsResolve(final String host) {
159         try {
160             return InetAddress.getByName(host).getHostAddress();
161         }
162         catch (final Exception e) {
163             return null;
164         }
165     }
166 
167     /**
168      * Returns the IP address of the local host, as a string in the dot-separated integer format.
169      * @return the IP address of the local host, as a string in the dot-separated integer format.
170      */
171     public static String myIpAddress() {
172         try {
173             return InetAddress.getLocalHost().getHostAddress();
174         }
175         catch (final Exception e) {
176             throw Context.throwAsScriptRuntimeEx(e);
177         }
178     }
179 
180     /**
181      * Returns the number (integer) of DNS domain levels (number of dots) in the hostname.
182      * @param host the hostname from the URL
183      * @return the number (integer) of DNS domain levels (number of dots) in the hostname.
184      */
185     public static int dnsDomainLevels(final String host) {
186         int levels = 0;
187         for (int i = host.length() - 1; i >= 0; i--) {
188             if (host.charAt(i) == '.') {
189                 levels++;
190             }
191         }
192         return levels;
193     }
194 
195     /**
196      * Matches the specified string against a shell expression, not regular expression.
197      * @param str a string to match
198      * @param shexp the shell expression
199      * @return if the string matches
200      */
201     public static boolean shExpMatch(final String str, final String shexp) {
202         final String regexp = shexp.replace(".", "\\.").replace("*", ".*").replace("?", ".");
203         return str.matches(regexp);
204     }
205 
206     /**
207      * Checks if today is included in the specified range.
208      * @param wd1 week day 1
209      * @param wd2 week day 2, optional
210      * @param gmt string of "GMT", or not specified
211      * @return if today is in range
212      */
213     public static boolean weekdayRange(final String wd1, Object wd2, final Object gmt) {
214         TimeZone timezone = TimeZone.getDefault();
215         if ("GMT".equals(Context.toString(gmt)) || "GMT".equals(Context.toString(wd2))) {
216             timezone = TimeZone.getTimeZone("GMT");
217         }
218         if (wd2 == Undefined.instance || "GMT".equals(Context.toString(wd2))) {
219             wd2 = wd1;
220         }
221         final Calendar calendar = Calendar.getInstance(timezone);
222         for (int i = 0; i < 7; i++) {
223             final String day = new SimpleDateFormat("EEE", Locale.ROOT)
224                     .format(calendar.getTime()).toUpperCase(Locale.ROOT);
225             if (day.equals(wd2)) {
226                 return true;
227             }
228             if (day.equals(wd1)) {
229                 return i == 0;
230             }
231             calendar.add(Calendar.DAY_OF_WEEK, 1);
232         }
233         return false;
234     }
235 
236     /**
237      * Checks if today is included in the specified range.
238      * @param value1 the value 1
239      * @param value2 the value 2
240      * @param value3 the value 3
241      * @param value4 the value 4
242      * @param value5 the value 5
243      * @param value6 the value 6
244      * @param value7 the value 7
245      * @return if today is in range
246      */
247     public static boolean dateRange(final String value1, final Object value2, final Object value3,
248             final Object value4, final Object value5, final Object value6, final Object value7) {
249         final Object[] values = {value1, value2, value3, value4, value5, value6, value7};
250         TimeZone timezone = TimeZone.getDefault();
251 
252         //actual values length
253         int length;
254         for (length = values.length - 1; length >= 0; length--) {
255             if ("GMT".equals(Context.toString(values[length]))) {
256                 timezone = TimeZone.getTimeZone("GMT");
257                 break;
258             }
259             else if (values[length] != Undefined.instance) {
260                 length++;
261                 break;
262             }
263         }
264 
265         final int day1, day2, month1, month2, year1, year2;
266         final Calendar cal1;
267         final Calendar cal2;
268         switch (length) {
269             case 1:
270                 final int day = getSmallInt(value1);
271                 final int month = dateRange_getMonth(value1);
272                 final int year = dateRange_getYear(value1);
273                 cal1 = dateRange_createCalendar(timezone, day, month, year);
274                 cal2 = (Calendar) cal1.clone();
275                 break;
276 
277             case 2:
278                 day1 = getSmallInt(value1);
279                 month1 = dateRange_getMonth(value1);
280                 year1 = dateRange_getYear(value1);
281                 cal1 = dateRange_createCalendar(timezone, day1, month1, year1);
282                 day2 = getSmallInt(value2);
283                 month2 = dateRange_getMonth(value2);
284                 year2 = dateRange_getYear(value2);
285                 cal2 = dateRange_createCalendar(timezone, day2, month2, year2);
286                 break;
287 
288             case 4:
289                 day1 = getSmallInt(value1);
290                 if (day1 != -1) {
291                     month1 = dateRange_getMonth(value2);
292                     day2 = getSmallInt(value3);
293                     month2 = dateRange_getMonth(value4);
294                     cal1 = dateRange_createCalendar(timezone, day1, month1, -1);
295                     cal2 = dateRange_createCalendar(timezone, day2, month2, -1);
296                 }
297                 else {
298                     month1 = dateRange_getMonth(value1);
299                     year1 = dateRange_getMonth(value2);
300                     month2 = getSmallInt(value3);
301                     year2 = dateRange_getMonth(value4);
302                     cal1 = dateRange_createCalendar(timezone, -1, month1, year1);
303                     cal2 = dateRange_createCalendar(timezone, -1, month2, year2);
304                 }
305                 break;
306 
307             default:
308                 day1 = getSmallInt(value1);
309                 month1 = dateRange_getMonth(value2);
310                 year1 = dateRange_getYear(value3);
311                 day2 = getSmallInt(value4);
312                 month2 = dateRange_getMonth(value5);
313                 year2 = dateRange_getYear(value6);
314                 cal1 = dateRange_createCalendar(timezone, day1, month1, year1);
315                 cal2 = dateRange_createCalendar(timezone, day2, month2, year2);
316         }
317 
318         final Calendar today = Calendar.getInstance(timezone);
319         today.set(Calendar.MILLISECOND, 0);
320         today.set(Calendar.SECOND, 0);
321         cal1.set(Calendar.MILLISECOND, 0);
322         cal1.set(Calendar.SECOND, 0);
323         cal2.set(Calendar.MILLISECOND, 0);
324         cal2.set(Calendar.SECOND, 0);
325         return today.equals(cal1) || (today.after(cal1) && today.before(cal2)) || today.equals(cal2);
326     }
327 
328     private static Calendar dateRange_createCalendar(final TimeZone timezone,
329             final int day, final int month, final int year) {
330         final Calendar calendar = Calendar.getInstance(timezone);
331         if (day != -1) {
332             calendar.set(Calendar.DAY_OF_MONTH, day);
333         }
334         if (month != -1) {
335             calendar.set(Calendar.MONTH, month);
336         }
337         if (year != -1) {
338             calendar.set(Calendar.YEAR, year);
339         }
340         return calendar;
341     }
342 
343     private static int getSmallInt(final Object object) {
344         final String s = Context.toString(object);
345         if (Character.isDigit(s.charAt(0))) {
346             final int i = Integer.parseInt(s);
347             if (i < 70) {
348                 return i;
349             }
350         }
351         return -1;
352     }
353 
354     private static int dateRange_getMonth(final Object object) {
355         final String s = Context.toString(object);
356         if (Character.isLetter(s.charAt(0))) {
357             try {
358                 final Calendar cal = Calendar.getInstance(Locale.ROOT);
359                 cal.clear();
360                 cal.setTime(new SimpleDateFormat("MMM", Locale.ROOT).parse(s));
361                 return cal.get(Calendar.MONTH);
362             }
363             catch (final Exception e) {
364                 //empty
365             }
366         }
367         return -1;
368     }
369 
370     private static int dateRange_getYear(final Object object) {
371         final String s = Context.toString(object);
372         if (Character.isDigit(s.charAt(0))) {
373             final int i = Integer.parseInt(s);
374             if (i > 1000) {
375                 return i;
376             }
377         }
378         return -1;
379     }
380 
381     /**
382      * Checks if the time now is included in the specified range.
383      * @param value1 the value 1
384      * @param value2 the value 2
385      * @param value3 the value 3
386      * @param value4 the value 4
387      * @param value5 the value 5
388      * @param value6 the value 6
389      * @param value7 the value 7
390      * @return if the time now is in the range
391      */
392     public static boolean timeRange(final String value1, final Object value2, final Object value3,
393             final Object value4, final Object value5, final Object value6, final Object value7) {
394         final Object[] values = {value1, value2, value3, value4, value5, value6, value7};
395         TimeZone timezone = TimeZone.getDefault();
396 
397         //actual values length
398         int length;
399         for (length = values.length - 1; length >= 0; length--) {
400             if ("GMT".equals(Context.toString(values[length]))) {
401                 timezone = TimeZone.getTimeZone("GMT");
402                 break;
403             }
404             else if (values[length] != Undefined.instance) {
405                 length++;
406                 break;
407             }
408         }
409 
410         final int hour1, hour2, min1, min2, second1, second2;
411         final Calendar cal1;
412         final Calendar cal2;
413         switch (length) {
414             case 1:
415                 hour1 = getSmallInt(value1);
416                 cal1 = timeRange_createCalendar(timezone, hour1, -1, -1);
417                 cal2 = (Calendar) cal1.clone();
418                 cal2.add(Calendar.HOUR_OF_DAY, 1);
419                 break;
420 
421             case 2:
422                 hour1 = getSmallInt(value1);
423                 cal1 = timeRange_createCalendar(timezone, hour1, -1, -1);
424                 hour2 = getSmallInt(value2);
425                 cal2 = timeRange_createCalendar(timezone, hour2, -1, -1);
426                 break;
427 
428             case 4:
429                 hour1 = getSmallInt(value1);
430                 min1 = getSmallInt(value2);
431                 hour2 = getSmallInt(value3);
432                 min2 = getSmallInt(value4);
433                 cal1 = dateRange_createCalendar(timezone, hour1, min1, -1);
434                 cal2 = dateRange_createCalendar(timezone, hour2, min2, -1);
435                 break;
436 
437             default:
438                 hour1 = getSmallInt(value1);
439                 min1 = getSmallInt(value2);
440                 second1 = getSmallInt(value3);
441                 hour2 = getSmallInt(value4);
442                 min2 = getSmallInt(value5);
443                 second2 = getSmallInt(value6);
444                 cal1 = dateRange_createCalendar(timezone, hour1, min1, second1);
445                 cal2 = dateRange_createCalendar(timezone, hour2, min2, second2);
446         }
447 
448         final Calendar now = Calendar.getInstance(timezone);
449         return now.equals(cal1) || now.after(cal1) && now.before(cal2) || now.equals(cal2);
450     }
451 
452     private static Calendar timeRange_createCalendar(final TimeZone timezone,
453             final int hour, final int minute, final int second) {
454         final Calendar calendar = Calendar.getInstance(timezone);
455         if (hour != -1) {
456             calendar.set(Calendar.HOUR_OF_DAY, hour);
457         }
458         if (minute != -1) {
459             calendar.set(Calendar.MINUTE, minute);
460         }
461         if (second != -1) {
462             calendar.set(Calendar.SECOND, second);
463         }
464         return calendar;
465     }
466 }