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