1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.htmlunit.javascript.host;
16
17 import static org.htmlunit.BrowserVersionFeatures.JS_LOCATION_PROTOCOL_UNCHANGED_NO_NAVIGATION;
18 import static org.htmlunit.BrowserVersionFeatures.JS_LOCATION_RELOAD_REFERRER;
19
20 import java.io.IOException;
21 import java.lang.reflect.Method;
22 import java.net.MalformedURLException;
23 import java.net.URL;
24
25 import org.apache.commons.logging.Log;
26 import org.apache.commons.logging.LogFactory;
27 import org.htmlunit.BrowserVersion;
28 import org.htmlunit.Page;
29 import org.htmlunit.WebClient;
30 import org.htmlunit.WebRequest;
31 import org.htmlunit.WebWindow;
32 import org.htmlunit.corejs.javascript.Context;
33 import org.htmlunit.corejs.javascript.Function;
34 import org.htmlunit.corejs.javascript.FunctionObject;
35 import org.htmlunit.corejs.javascript.ScriptableObject;
36 import org.htmlunit.corejs.javascript.VarScope;
37 import org.htmlunit.html.FrameWindow;
38 import org.htmlunit.html.HtmlPage;
39 import org.htmlunit.html.csp.ContentSecurityPolicy;
40 import org.htmlunit.javascript.HtmlUnitScriptable;
41 import org.htmlunit.javascript.JavaScriptEngine;
42 import org.htmlunit.javascript.configuration.JsxClass;
43 import org.htmlunit.javascript.configuration.JsxConstructor;
44 import org.htmlunit.javascript.host.dom.DOMException;
45 import org.htmlunit.javascript.host.event.Event;
46 import org.htmlunit.javascript.host.event.HashChangeEvent;
47 import org.htmlunit.protocol.javascript.JavaScriptURLConnection;
48 import org.htmlunit.util.StringUtils;
49 import org.htmlunit.util.UrlUtils;
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70 @JsxClass
71 public class Location extends HtmlUnitScriptable {
72
73 private static final Log LOG = LogFactory.getLog(Location.class);
74 private static final String UNKNOWN = "null";
75
76
77
78
79 private Window window_;
80
81 private static final Method METHOD_ASSIGN;
82 private static final Method METHOD_RELOAD;
83 private static final Method METHOD_REPLACE;
84 private static final Method METHOD_TO_STRING;
85
86 private static final Method GETTER_HASH;
87 private static final Method SETTER_HASH;
88
89 private static final Method GETTER_HOST;
90 private static final Method SETTER_HOST;
91
92 private static final Method GETTER_HOSTNAME;
93 private static final Method SETTER_HOSTNAME;
94
95 private static final Method GETTER_HREF;
96 private static final Method SETTER_HREF;
97
98 private static final Method GETTER_ORIGIN;
99
100 private static final Method GETTER_PATHNAME;
101 private static final Method SETTER_PATHNAME;
102
103 private static final Method GETTER_PORT;
104 private static final Method SETTER_PORT;
105
106 private static final Method GETTER_PROTOCOL;
107 private static final Method SETTER_PROTOCOL;
108
109 private static final Method GETTER_SEARCH;
110 private static final Method SETTER_SEARCH;
111
112 static {
113 try {
114 METHOD_ASSIGN = Location.class.getDeclaredMethod("assign", String.class);
115 METHOD_RELOAD = Location.class.getDeclaredMethod("reload", boolean.class);
116 METHOD_REPLACE = Location.class.getDeclaredMethod("replace", String.class);
117 METHOD_TO_STRING = Location.class.getDeclaredMethod("jsToString");
118
119 GETTER_HASH = Location.class.getDeclaredMethod("getHash");
120 SETTER_HASH = Location.class.getDeclaredMethod("setHash", String.class);
121
122 GETTER_HOST = Location.class.getDeclaredMethod("getHost");
123 SETTER_HOST = Location.class.getDeclaredMethod("setHost", String.class);
124
125 GETTER_HOSTNAME = Location.class.getDeclaredMethod("getHostname");
126 SETTER_HOSTNAME = Location.class.getDeclaredMethod("setHostname", String.class);
127
128 GETTER_HREF = Location.class.getDeclaredMethod("getHref");
129 SETTER_HREF = Location.class.getDeclaredMethod("setHref", String.class);
130
131 GETTER_ORIGIN = Location.class.getDeclaredMethod("getOrigin");
132
133 GETTER_PATHNAME = Location.class.getDeclaredMethod("getPathname");
134 SETTER_PATHNAME = Location.class.getDeclaredMethod("setPathname", String.class);
135
136 GETTER_PORT = Location.class.getDeclaredMethod("getPort");
137 SETTER_PORT = Location.class.getDeclaredMethod("setPort", String.class);
138
139 GETTER_PROTOCOL = Location.class.getDeclaredMethod("getProtocol");
140 SETTER_PROTOCOL = Location.class.getDeclaredMethod("setProtocol", String.class);
141
142 GETTER_SEARCH = Location.class.getDeclaredMethod("getSearch");
143 SETTER_SEARCH = Location.class.getDeclaredMethod("setSearch", String.class);
144 }
145 catch (NoSuchMethodException | SecurityException e) {
146 throw new RuntimeException(e);
147 }
148 }
149
150
151
152
153
154 private String hash_;
155
156
157
158
159
160
161
162
163
164
165
166 @JsxConstructor
167 public static Location jsConstructor(final Context cx, final VarScope scope,
168 final Object[] args, final Function ctorObj, final boolean inNewExpr) {
169
170 final Location location = new Location();
171 location.setParentScope(scope);
172 location.setPrototype(((FunctionObject) ctorObj).getClassPrototype());
173
174 location.initialize(scope, null, null);
175
176 return location;
177 }
178
179
180
181
182
183
184
185
186 public void initialize(final VarScope scope, final Window window, final Page page) {
187 final int attributes = ScriptableObject.PERMANENT | ScriptableObject.READONLY;
188
189 FunctionObject functionObject = new FunctionObject(METHOD_ASSIGN.getName(), METHOD_ASSIGN, scope);
190 defineProperty(METHOD_ASSIGN.getName(), functionObject, attributes);
191
192 functionObject = new FunctionObject(METHOD_RELOAD.getName(), METHOD_RELOAD, scope);
193 defineProperty(METHOD_RELOAD.getName(), functionObject, attributes);
194
195 functionObject = new FunctionObject(METHOD_REPLACE.getName(), METHOD_REPLACE, scope);
196 defineProperty(METHOD_REPLACE.getName(), functionObject, attributes);
197
198 functionObject = new FunctionObject(METHOD_TO_STRING.getName(), METHOD_TO_STRING, scope);
199 defineProperty("toString", functionObject, attributes);
200
201 defineProperty(scope, "hash", null, GETTER_HASH, SETTER_HASH, attributes);
202 defineProperty(scope, "host", null, GETTER_HOST, SETTER_HOST, attributes);
203 defineProperty(scope, "hostname", null, GETTER_HOSTNAME, SETTER_HOSTNAME, attributes);
204 defineProperty(scope, "href", null, GETTER_HREF, SETTER_HREF, attributes);
205 defineProperty(scope, "origin", null, GETTER_ORIGIN, null, attributes);
206 defineProperty(scope, "pathname", null, GETTER_PATHNAME, SETTER_PATHNAME, attributes);
207 defineProperty(scope, "port", null, GETTER_PORT, SETTER_PORT, attributes);
208 defineProperty(scope, "protocol", null, GETTER_PROTOCOL, SETTER_PROTOCOL, attributes);
209 defineProperty(scope, "search", null, GETTER_SEARCH, SETTER_SEARCH, attributes);
210
211 window_ = window;
212 if (window_ != null && page != null) {
213 setHash(null, page.getUrl().getRef());
214 }
215 }
216
217
218
219
220 @Override
221 public Object getDefaultValue(final Class<?> hint) {
222 if (getPrototype() != null
223 && window_ != null
224 && (hint == null || String.class.equals(hint))) {
225 return getHref();
226 }
227 return super.getDefaultValue(hint);
228 }
229
230
231
232
233
234
235
236
237 public void assign(final String url) throws IOException {
238 setHref(url);
239 }
240
241
242
243
244
245
246
247
248
249 public void reload(final boolean force) throws IOException {
250 final WebWindow webWindow = window_.getWebWindow();
251 final HtmlPage htmlPage = (HtmlPage) webWindow.getEnclosedPage();
252 final WebRequest request = htmlPage.getWebResponse().getWebRequest();
253
254
255
256 request.setUrl(UrlUtils.toUrlUnsafe(getHref()));
257 if (getBrowserVersion().hasFeature(JS_LOCATION_RELOAD_REFERRER)) {
258 request.setRefererHeader(htmlPage.getUrl());
259 request.setReferrerPolicy(htmlPage.getReferrerPolicy());
260 }
261
262 webWindow.getWebClient().download(webWindow, "", request, false, null, "JS location.reload");
263 }
264
265
266
267
268
269
270
271
272
273 public void replace(final String url) throws IOException {
274 window_.getWebWindow().getHistory().removeCurrent();
275 setHref(url);
276 }
277
278
279
280
281
282
283 public String jsToString() {
284 if (window_ != null) {
285 return getHref();
286 }
287 return "";
288 }
289
290
291
292
293
294
295
296 public String getHref() {
297 final WebWindow webWindow = window_.getWebWindow();
298 final Page page = webWindow.getEnclosedPage();
299 if (page == null) {
300 return UNKNOWN;
301 }
302 try {
303 URL url = page.getUrl();
304 if (url.getUserInfo() != null) {
305
306 url = UrlUtils.getUrlWithoutUserInfo(url);
307 }
308 final String hash = getHash(true);
309 if (hash != null) {
310 url = UrlUtils.getUrlWithNewRef(url, hash);
311 }
312 String s = url.toExternalForm();
313 if (s.startsWith("file:/") && !s.startsWith("file:///")) {
314
315
316 s = "file:///" + s.substring("file:/".length());
317 }
318 return s;
319 }
320 catch (final MalformedURLException e) {
321 if (LOG.isErrorEnabled()) {
322 LOG.error(e.getMessage(), e);
323 }
324 return page.getUrl().toExternalForm();
325 }
326 }
327
328
329
330
331
332
333
334
335 public void setHref(final String newLocation) throws IOException {
336 if (newLocation.startsWith(JavaScriptURLConnection.JAVASCRIPT_PREFIX)) {
337 final String script = newLocation.substring(11);
338 final HtmlPage page = (HtmlPage) window_.getWebWindow().getEnclosedPage();
339 if (ContentSecurityPolicy.allowsJavaScriptUrl(page, null, newLocation)) {
340 page.executeJavaScript(script, "new location value", 1);
341 }
342 return;
343 }
344
345 try {
346
347 WebWindow webWindow = ((Window) JavaScriptEngine.getTopCallScope().getGlobalThis()).getWebWindow();
348 final HtmlPage callingPage = (HtmlPage) webWindow.getEnclosedPage();
349 checkSandboxedNavigation(callingPage, webWindow, window_.getWebWindow());
350
351 final BrowserVersion browserVersion = webWindow.getWebClient().getBrowserVersion();
352
353 URL url = callingPage.getFullyQualifiedUrl(newLocation);
354
355 if (StringUtils.isEmptyOrNull(newLocation)) {
356 url = UrlUtils.getUrlWithNewRef(url, null);
357 }
358 url = upgradeInsecureRequest(callingPage, window_.getWebWindow(), url);
359
360
361 if (!callingPage.isLocalResourceAccessAllowed(url)) {
362 webWindow.getWebClient().getIncorrectnessListener()
363 .notify("Not allowed to load local resource: " + url, this);
364 return;
365 }
366
367 final WebRequest webRequest = new WebRequest(url,
368 browserVersion.getHtmlAcceptHeader(), browserVersion.getAcceptEncodingHeader());
369 webRequest.setRefererHeader(callingPage.getUrl());
370 webRequest.setReferrerPolicy(callingPage.getReferrerPolicy());
371
372 webRequest.markAsNavigation(getUrl(), false);
373 webRequest.setFetchModeOverride(WebRequest.FetchMode.NAVIGATE);
374 upgradeInsecureRedirects(callingPage, window_.getWebWindow(), webRequest);
375
376 webWindow = window_.getWebWindow();
377 webWindow.getWebClient().download(webWindow, "", webRequest, true, null, "JS set location");
378 }
379 catch (final MalformedURLException e) {
380 if (LOG.isErrorEnabled()) {
381 LOG.error("setHref('" + newLocation + "') got MalformedURLException", e);
382 }
383 throw e;
384 }
385 }
386
387
388
389
390
391
392
393
394
395 private void checkSandboxedNavigation(final HtmlPage callingPage, final WebWindow callingWindow,
396 final WebWindow targetWindow) {
397 if (callingPage.getSandboxTokens() == null) {
398 return;
399 }
400
401
402 WebWindow window = targetWindow;
403 while (true) {
404 if (window == callingWindow) {
405 return;
406 }
407 final WebWindow parent = window.getParentWindow();
408 if (parent == null || parent == window) {
409 break;
410 }
411 window = parent;
412 }
413
414 if (targetWindow == callingWindow.getTopWindow()
415 && callingPage.isSandboxAllowed("allow-top-navigation")) {
416 return;
417 }
418
419 throw JavaScriptEngine.asJavaScriptException(window_,
420 "The document is sandboxed and lacks the 'allow-top-navigation' flag.",
421 DOMException.SECURITY_ERR);
422 }
423
424
425
426
427
428
429
430 public String getSearch() {
431 final URL url = getUrl();
432 final String search = url.getQuery();
433 if (StringUtils.isEmptyOrNull(search)) {
434 return "";
435 }
436 return "?" + search;
437 }
438
439
440
441
442
443
444
445
446 public void setSearch(final String search) throws Exception {
447 setUrl(UrlUtils.getUrlWithNewQuery(getUrl(), search));
448 }
449
450
451
452
453
454
455
456 public String getHash() {
457 if (StringUtils.isEmptyOrNull(hash_)) {
458 return "";
459 }
460
461 if (hash_.indexOf('%') == -1) {
462 return "#" + UrlUtils.encodeHash(hash_);
463 }
464 return "#" + UrlUtils.encodeHash(UrlUtils.decode(hash_));
465 }
466
467 private String getHash(final boolean encoded) {
468 if (hash_ == null || hash_.isEmpty()) {
469 return null;
470 }
471 if (encoded) {
472 return UrlUtils.encodeHash(hash_);
473 }
474 return hash_;
475 }
476
477
478
479
480
481
482
483
484 public void setHash(final String hash) {
485
486
487 setHash(getHref(), hash, true);
488 }
489
490
491
492
493
494
495
496 public void setHash(final String oldURL, final String hash) {
497 setHash(oldURL, hash, true);
498 }
499
500
501
502
503
504
505
506
507
508
509 public void setHash(final String oldURL, final String hash, final boolean triggerHashChanged) {
510
511
512 final String newHash = hash != null && !hash.isEmpty() && hash.charAt(0) == '#'
513 ? hash.substring(1)
514 : hash;
515 final boolean hasChanged = newHash != null && !newHash.equals(hash_);
516 hash_ = newHash;
517
518 if (hasChanged) {
519 final Window w = getWindow();
520 final Page page = w.getWebWindow().getEnclosedPage();
521 if (page != null) {
522 final WebRequest request = page.getWebResponse().getWebRequest();
523 request.setUrl(UrlUtils.toUrlSafe(getHref()));
524 }
525
526 if (triggerHashChanged) {
527 final Event event = new HashChangeEvent(w, Event.TYPE_HASH_CHANGE, oldURL, getHref());
528 w.executeEventLocally(event);
529 }
530 }
531 }
532
533
534
535
536
537
538
539 public String getHostname() {
540 return getUrl().getHost();
541 }
542
543
544
545
546
547
548
549
550 public void setHostname(final String hostname) throws Exception {
551 setUrl(UrlUtils.getUrlWithNewHost(getUrl(), hostname));
552 }
553
554
555
556
557
558
559
560 public String getHost() {
561 final URL url = getUrl();
562 final int port = url.getPort();
563 final String host = url.getHost();
564
565 if (port == -1) {
566 return host;
567 }
568 return host + ":" + port;
569 }
570
571
572
573
574
575
576
577
578 public void setHost(final String host) throws Exception {
579 final String hostname;
580 final int port;
581 final int index = host.indexOf(':');
582 if (index == -1) {
583 hostname = host;
584 port = -1;
585 }
586 else {
587 hostname = host.substring(0, index);
588 port = Integer.parseInt(host.substring(index + 1));
589 }
590 final URL url = UrlUtils.getUrlWithNewHostAndPort(getUrl(), hostname, port);
591 setUrl(url);
592 }
593
594
595
596
597
598
599
600 public String getPathname() {
601 if (UrlUtils.URL_ABOUT_BLANK == getUrl()) {
602 return "blank";
603 }
604 return getUrl().getPath();
605 }
606
607
608
609
610
611
612
613
614 public void setPathname(final String pathname) throws Exception {
615 setUrl(UrlUtils.getUrlWithNewPath(getUrl(), pathname));
616 }
617
618
619
620
621
622
623
624 public String getPort() {
625 final int port = getUrl().getPort();
626 if (port == -1) {
627 return "";
628 }
629 return Integer.toString(port);
630 }
631
632
633
634
635
636
637
638
639 public void setPort(final String port) throws Exception {
640 setUrl(UrlUtils.getUrlWithNewPort(getUrl(), Integer.parseInt(port)));
641 }
642
643
644
645
646
647
648
649 public String getProtocol() {
650 return getUrl().getProtocol() + ":";
651 }
652
653
654
655
656
657
658
659
660
661
662
663
664 public void setProtocol(final String protocol) throws Exception {
665 final URL url = getUrl();
666 final URL newUrl = UrlUtils.getUrlWithNewProtocolLikeSetter(url, protocol);
667 if (newUrl == null) {
668 throw JavaScriptEngine.asJavaScriptException(this,
669 "Failed to set the 'protocol' property on 'Location': '" + protocol
670 + "' is an invalid scheme.", DOMException.SYNTAX_ERR);
671 }
672 final String scheme = newUrl.getProtocol();
673 if (!"http".equals(scheme) && !"https".equals(scheme)) {
674 return;
675 }
676 if (newUrl == url
677 && window_.getWebWindow().getWebClient().getBrowserVersion()
678 .hasFeature(JS_LOCATION_PROTOCOL_UNCHANGED_NO_NAVIGATION)) {
679
680 return;
681 }
682 setUrl(newUrl);
683 }
684
685
686
687
688
689
690 private URL getUrl() {
691 return window_.getWebWindow().getEnclosedPage().getUrl();
692 }
693
694
695
696
697
698 private static URL upgradeInsecureRequest(final HtmlPage page, final WebWindow targetWindow, final URL url) {
699 if (targetWindow instanceof FrameWindow) {
700 return ContentSecurityPolicy.upgradeInsecureRequest(page, url);
701 }
702 return ContentSecurityPolicy.upgradeInsecureNavigation(page, url);
703 }
704
705 private static void upgradeInsecureRedirects(final HtmlPage page, final WebWindow targetWindow,
706 final WebRequest webRequest) {
707 if (targetWindow instanceof FrameWindow) {
708 ContentSecurityPolicy.upgradeInsecureRedirects(page, webRequest);
709 }
710 else {
711 ContentSecurityPolicy.upgradeInsecureNavigationRedirects(page, webRequest);
712 }
713 }
714
715
716
717
718
719
720
721
722 private void setUrl(final URL url) throws IOException {
723 final WebWindow webWindow = window_.getWebWindow();
724 final WebClient webClient = webWindow.getWebClient();
725 final BrowserVersion browserVersion = webClient.getBrowserVersion();
726
727 URL requestUrl = url;
728 if (webWindow.getEnclosedPage() instanceof HtmlPage page) {
729 requestUrl = upgradeInsecureRequest(page, webWindow, url);
730 }
731
732
733
734 final WebWindow callingWindow = ((Window) JavaScriptEngine.getTopCallScope().getGlobalThis()).getWebWindow();
735 final boolean allowed;
736 if (callingWindow.getEnclosedPage() instanceof HtmlPage callingPage) {
737 allowed = callingPage.isLocalResourceAccessAllowed(requestUrl);
738 }
739 else {
740 allowed = webClient.getOptions().isLocalFileAccessFromRemotePagesAllowed()
741 || UrlUtils.isLocalResourceAccessAllowed(callingWindow.getEnclosedPage().getUrl(), requestUrl);
742 }
743 if (!allowed) {
744 webClient.getIncorrectnessListener().notify("Not allowed to load local resource: " + requestUrl, this);
745 return;
746 }
747
748 final WebRequest webRequest = new WebRequest(requestUrl,
749 browserVersion.getHtmlAcceptHeader(), browserVersion.getAcceptEncodingHeader());
750
751 webRequest.markAsNavigation(getUrl(), false);
752 webRequest.setFetchModeOverride(WebRequest.FetchMode.NAVIGATE);
753
754 webRequest.setRefererHeader(getUrl());
755 if (webWindow.getEnclosedPage() instanceof HtmlPage referrerPage) {
756 webRequest.setReferrerPolicy(referrerPage.getReferrerPolicy());
757 }
758
759 if (webWindow.getEnclosedPage() instanceof HtmlPage page) {
760 upgradeInsecureRedirects(page, webWindow, webRequest);
761 }
762
763 webClient.getPage(webWindow, webRequest);
764 }
765
766
767
768
769
770
771 public String getOrigin() {
772 return getUrl().getProtocol() + "://" + getHost();
773 }
774 }