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.html;
16
17 import static org.htmlunit.BrowserVersionFeatures.HTMLIMAGE_BLANK_SRC_AS_EMPTY;
18 import static org.htmlunit.BrowserVersionFeatures.HTMLIMAGE_EMPTY_SRC_DISPLAY_FALSE;
19 import static org.htmlunit.BrowserVersionFeatures.HTMLIMAGE_HTMLELEMENT;
20 import static org.htmlunit.BrowserVersionFeatures.HTMLIMAGE_HTMLUNKNOWNELEMENT;
21 import static org.htmlunit.BrowserVersionFeatures.HTTP_HEADER_CH_UA;
22 import static org.htmlunit.BrowserVersionFeatures.JS_IMAGE_WIDTH_HEIGHT_RETURNS_16x16_0x0;
23 import static org.htmlunit.BrowserVersionFeatures.JS_IMAGE_WIDTH_HEIGHT_RETURNS_24x24_0x0;
24
25 import java.io.File;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.OutputStream;
29 import java.net.MalformedURLException;
30 import java.net.URL;
31 import java.nio.file.Files;
32 import java.util.Map;
33 import java.util.function.Predicate;
34
35 import org.apache.commons.io.IOUtils;
36 import org.apache.commons.logging.Log;
37 import org.apache.commons.logging.LogFactory;
38 import org.htmlunit.BrowserVersion;
39 import org.htmlunit.HttpHeader;
40 import org.htmlunit.Page;
41 import org.htmlunit.ScriptResult;
42 import org.htmlunit.SgmlPage;
43 import org.htmlunit.WebClient;
44 import org.htmlunit.WebRequest;
45 import org.htmlunit.WebResponse;
46 import org.htmlunit.html.csp.ContentSecurityPolicy;
47 import org.htmlunit.http.HttpStatus;
48 import org.htmlunit.javascript.AbstractJavaScriptEngine;
49 import org.htmlunit.javascript.PostponedAction;
50 import org.htmlunit.javascript.host.dom.Document;
51 import org.htmlunit.javascript.host.event.Event;
52 import org.htmlunit.javascript.host.event.MouseEvent;
53 import org.htmlunit.platform.Platform;
54 import org.htmlunit.platform.geom.IntDimension2D;
55 import org.htmlunit.platform.image.ImageData;
56 import org.htmlunit.util.StringUtils;
57 import org.htmlunit.util.UrlUtils;
58
59 /**
60 * Wrapper for the HTML element "img".
61 *
62 * @author Mike Bowler
63 * @author David K. Taylor
64 * @author Christian Sell
65 * @author Ahmed Ashour
66 * @author Knut Johannes Dahle
67 * @author Ronald Brill
68 * @author Frank Danek
69 * @author Carsten Steul
70 * @author Alex Gorbatovsky
71 */
72 public class HtmlImage extends HtmlElement {
73
74 private static final Log LOG = LogFactory.getLog(HtmlImage.class);
75
76 /** The HTML tag represented by this element. */
77 public static final String TAG_NAME = "img";
78 /** Another HTML tag represented by this element. */
79 public static final String TAG_NAME2 = "image";
80
81 private final String originalQualifiedName_;
82
83 private int lastClickX_ = -1;
84 private int lastClickY_ = -1;
85 private WebResponse imageWebResponse_;
86 private transient ImageData imageData_;
87 private int width_ = -1;
88 private int height_ = -1;
89 private boolean downloaded_;
90 // the url checked against the Content-Security-Policy (img-src) and the result
91 private String cspCheckedUrl_;
92 private boolean cspAllowed_ = true;
93 // Whether the image data of the current response is CORS-cross-origin (see isCorsCrossOrigin()).
94 // A canvas the image is drawn to loses its origin-clean flag, so script can't read back the pixels.
95 // The value has to be determined while downloading the image: the redirect targets are only known
96 // during the download (redirect filter); afterwards only the request url and the final url are left.
97 // It is reset with every download (a new src means a new response).
98 private boolean corsCrossOrigin_;
99 private boolean isComplete_;
100 private boolean onloadProcessed_;
101 private boolean createdByJavascript_;
102
103 /**
104 * Creates a new instance.
105 *
106 * @param qualifiedName the qualified name of the element type to instantiate
107 * @param page the page that contains this element
108 * @param attributes the initial attributes
109 */
110 HtmlImage(final String qualifiedName, final SgmlPage page, final Map<String, DomAttr> attributes) {
111 super(unifyLocalName(qualifiedName), page, attributes);
112 originalQualifiedName_ = qualifiedName;
113 if (page.getWebClient().getOptions().isDownloadImages()) {
114 try {
115 downloadImageIfNeeded();
116 }
117 catch (final IOException e) {
118 if (LOG.isDebugEnabled()) {
119 LOG.debug("Unable to download image for element " + this);
120 }
121 }
122 }
123 }
124
125 private static String unifyLocalName(final String qualifiedName) {
126 if (qualifiedName != null && qualifiedName.endsWith(TAG_NAME2)) {
127 final int pos = qualifiedName.lastIndexOf(TAG_NAME2);
128 return qualifiedName.substring(0, pos) + TAG_NAME;
129 }
130 return qualifiedName;
131 }
132
133 /**
134 * {@inheritDoc}
135 */
136 @Override
137 protected void onAddedToPage() {
138 doOnLoad();
139 super.onAddedToPage();
140 }
141
142 /**
143 * {@inheritDoc}
144 */
145 @Override
146 protected void setAttributeNS(final String namespaceURI, final String qualifiedName, final String value,
147 final boolean notifyAttributeChangeListeners, final boolean notifyMutationObservers) {
148
149 final HtmlPage htmlPage = getHtmlPageOrNull();
150 final String qualifiedNameLC = StringUtils.toRootLowerCase(qualifiedName);
151 if (SRC_ATTRIBUTE.equals(qualifiedNameLC) && value != ATTRIBUTE_NOT_DEFINED && htmlPage != null) {
152 final String oldValue = getAttributeNS(namespaceURI, qualifiedNameLC);
153 if (!oldValue.equals(value)) {
154 super.setAttributeNS(namespaceURI, qualifiedNameLC, value, notifyAttributeChangeListeners,
155 notifyMutationObservers);
156
157 // onload handlers may need to be invoked again, and a new image may need to be downloaded
158 onloadProcessed_ = false;
159 downloaded_ = false;
160 isComplete_ = false;
161 width_ = -1;
162 height_ = -1;
163 try {
164 closeImageData();
165 }
166 catch (final Exception e) {
167 LOG.error(e.getMessage(), e);
168 }
169
170 final String readyState = htmlPage.getReadyState();
171 if (READY_STATE_LOADING.equals(readyState)) {
172 final PostponedAction action = new PostponedAction(getPage(), "HtmlImage.setAttributeNS") {
173 @Override
174 public void execute() {
175 doOnLoad();
176 }
177 };
178 htmlPage.addAfterLoadAction(action);
179 return;
180 }
181 doOnLoad();
182 return;
183 }
184 }
185
186 super.setAttributeNS(namespaceURI, qualifiedNameLC, value, notifyAttributeChangeListeners,
187 notifyMutationObservers);
188 }
189
190 /**
191 * {@inheritDoc}
192 */
193 @Override
194 public void processImportNode(final Document doc) {
195 URL oldUrl = null;
196 final String src = getSrcAttribute();
197 HtmlPage htmlPage = getHtmlPageOrNull();
198 try {
199 if (htmlPage != null) {
200 oldUrl = htmlPage.getFullyQualifiedUrl(src);
201 }
202 }
203 catch (final MalformedURLException ignored) {
204 // ignore
205 }
206
207 super.processImportNode(doc);
208
209 URL url = null;
210 htmlPage = getHtmlPageOrNull();
211 try {
212 if (htmlPage != null) {
213 url = htmlPage.getFullyQualifiedUrl(src);
214 }
215 }
216 catch (final MalformedURLException ignored) {
217 // ignore
218 }
219
220 if (oldUrl == null || !UrlUtils.sameFile(oldUrl, url)) {
221 // image has to be reloaded
222 lastClickX_ = -1;
223 lastClickY_ = -1;
224 imageWebResponse_ = null;
225 imageData_ = null;
226 width_ = -1;
227 height_ = -1;
228 downloaded_ = false;
229 isComplete_ = false;
230 onloadProcessed_ = false;
231 createdByJavascript_ = true;
232 }
233
234 if (htmlPage == null) {
235 return; // nothing to do if embedded in XML code
236 }
237
238 if (htmlPage.getWebClient().getOptions().isDownloadImages()) {
239 try {
240 downloadImageIfNeeded();
241 }
242 catch (final IOException e) {
243 if (LOG.isDebugEnabled()) {
244 LOG.debug("Unable to download image for element " + this);
245 }
246 }
247 }
248 }
249
250 /**
251 * <p><span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span></p>
252 *
253 * <p>Executes this element's <code>onload</code> or <code>onerror</code> handler. This method downloads the image
254 * if either of these handlers are present (prior to invoking the resulting handler), because applications
255 * sometimes use images to send information to the server and use these handlers to get notified when the
256 * information has been received by the server.</p>
257 *
258 * <p>See <a href="http://www.nabble.com/How-should-we-handle-image.onload--tt9850876.html">here</a> and
259 * <a href="http://www.nabble.com/Image-Onload-Support-td18895781.html">here</a> for the discussion which
260 * lead up to this method.</p>
261 *
262 * <p>This method may be called multiple times, but will only attempt to execute the <code>onload</code> or
263 * <code>onerror</code> handler the first time it is invoked.</p>
264 */
265 public void doOnLoad() {
266 if (onloadProcessed_) {
267 return;
268 }
269
270 final HtmlPage htmlPage = getHtmlPageOrNull();
271 if (htmlPage == null) {
272 return; // nothing to do if embedded in XML code
273 }
274 if (isInDocumentWithoutBrowsingContext()) {
275 // nothing is loaded and no event is fired; this happens if the image
276 // is imported into a document with browsing context
277 return;
278 }
279
280 // like the browsers, the image url is checked against the Content-Security-Policy
281 // also if HtmlUnit does not download the image
282 isAllowedByContentSecurityPolicy(htmlPage);
283
284 final WebClient client = htmlPage.getWebClient();
285
286 final boolean hasEventHandler = hasEventHandlers("onload") || hasEventHandlers("onerror");
287 if (((hasEventHandler && client.isJavaScriptEnabled())
288 || client.getOptions().isDownloadImages()) && hasAttribute(SRC_ATTRIBUTE)) {
289 boolean loadSuccessful = false;
290 final boolean tryDownload;
291 if (hasFeature(HTMLIMAGE_BLANK_SRC_AS_EMPTY)) {
292 tryDownload = !StringUtils.isBlank(getSrcAttribute());
293 }
294 else {
295 tryDownload = !getSrcAttribute().isEmpty();
296 }
297 if (tryDownload) {
298 // We need to download the image and then call the resulting handler.
299 try {
300 downloadImageIfNeeded();
301 // if the download was a success
302 if (imageWebResponse_ != null && imageWebResponse_.isSuccess()) {
303 if (imageWebResponse_.getStatusCode() != HttpStatus.NO_CONTENT_204) {
304 loadSuccessful = true; // Trigger the onload handler
305 }
306 }
307 }
308 catch (final IOException e) {
309 if (LOG.isDebugEnabled()) {
310 LOG.debug("IOException while downloading image for '" + this + "'", e);
311 }
312 }
313 }
314
315 if (!client.isJavaScriptEnabled()) {
316 onloadProcessed_ = true;
317 return;
318 }
319
320 if (!hasEventHandler) {
321 return;
322 }
323
324 onloadProcessed_ = true;
325 final Event event = new Event(this, loadSuccessful ? Event.TYPE_LOAD : Event.TYPE_ERROR);
326 if (LOG.isDebugEnabled()) {
327 LOG.debug("Firing the " + event.getType() + " event for '" + this + "'.");
328 }
329
330 if (READY_STATE_LOADING.equals(htmlPage.getReadyState())) {
331 final PostponedAction action = new PostponedAction(getPage(), "HtmlImage.doOnLoad") {
332 @Override
333 public void execute() {
334 HtmlImage.this.fireEvent(event);
335 }
336 };
337 htmlPage.addAfterLoadAction(action);
338 }
339 else {
340 final AbstractJavaScriptEngine<?> jsEngine = client.getJavaScriptEngine();
341 if (jsEngine.isScriptRunning()) {
342 final PostponedAction action = new PostponedAction(getPage(), "HtmlImage.doOnLoad") {
343 @Override
344 public void execute() {
345 HtmlImage.this.fireEvent(event);
346 }
347 };
348 jsEngine.addPostponedAction(action);
349 }
350 else {
351 fireEvent(event);
352 }
353 }
354 }
355 }
356
357 /**
358 * Returns the value of the attribute {@code src}. Refer to the
359 * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
360 * documentation for details on the use of this attribute.
361 *
362 * @return the value of the attribute {@code src} or an empty string if that attribute isn't defined
363 */
364 public final String getSrcAttribute() {
365 return getSrcAttributeNormalized();
366 }
367
368 /**
369 * Returns the value of the {@code src} value.
370 * @return the value of the {@code src} value
371 */
372 public String getSrc() {
373 final String src = getSrcAttribute();
374 if (StringUtils.isEmptyString(src)) {
375 return src;
376 }
377 try {
378 final HtmlPage page = (HtmlPage) getPage();
379 return page.getFullyQualifiedUrl(src).toExternalForm();
380 }
381 catch (final MalformedURLException e) {
382 final String msg = "Unable to create fully qualified URL for src attribute of image " + e.getMessage();
383 throw new RuntimeException(msg, e);
384 }
385 }
386
387 /**
388 * Returns the value of the attribute {@code alt}. Refer to the
389 * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
390 * documentation for details on the use of this attribute.
391 *
392 * @return the value of the attribute {@code alt} or an empty string if that attribute isn't defined
393 */
394 public final String getAltAttribute() {
395 return getAttributeDirect("alt");
396 }
397
398 /**
399 * Returns the value of the attribute {@code name}. Refer to the
400 * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
401 * documentation for details on the use of this attribute.
402 *
403 * @return the value of the attribute {@code name} or an empty string if that attribute isn't defined
404 */
405 public final String getNameAttribute() {
406 return getAttributeDirect(NAME_ATTRIBUTE);
407 }
408
409 /**
410 * Returns the value of the attribute {@code longdesc}. Refer to the
411 * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
412 * documentation for details on the use of this attribute.
413 *
414 * @return the value of the attribute {@code longdesc} or an empty string if that attribute isn't defined
415 */
416 public final String getLongDescAttribute() {
417 return getAttributeDirect("longdesc");
418 }
419
420 /**
421 * Returns the value of the attribute {@code height}. Refer to the
422 * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
423 * documentation for details on the use of this attribute.
424 *
425 * @return the value of the attribute {@code height} or an empty string if that attribute isn't defined
426 */
427 public final String getHeightAttribute() {
428 return getAttributeDirect("height");
429 }
430
431 /**
432 * Returns the value of the attribute {@code width}. Refer to the
433 * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
434 * documentation for details on the use of this attribute.
435 *
436 * @return the value of the attribute {@code width} or an empty string if that attribute isn't defined
437 */
438 public final String getWidthAttribute() {
439 return getAttributeDirect("width");
440 }
441
442 /**
443 * Returns the value of the attribute {@code usemap}. Refer to the
444 * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
445 * documentation for details on the use of this attribute.
446 *
447 * @return the value of the attribute {@code usemap} or an empty string if that attribute isn't defined
448 */
449 public final String getUseMapAttribute() {
450 return getAttributeDirect("usemap");
451 }
452
453 /**
454 * Returns the value of the attribute {@code ismap}. Refer to the
455 * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
456 * documentation for details on the use of this attribute.
457 *
458 * @return the value of the attribute {@code ismap} or an empty string if that attribute isn't defined
459 */
460 public final String getIsmapAttribute() {
461 return getAttributeDirect("ismap");
462 }
463
464 /**
465 * Returns the value of the attribute {@code align}. Refer to the
466 * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
467 * documentation for details on the use of this attribute.
468 *
469 * @return the value of the attribute {@code align} or an empty string if that attribute isn't defined
470 */
471 public final String getAlignAttribute() {
472 return getAttributeDirect("align");
473 }
474
475 /**
476 * Returns the value of the attribute {@code border}. Refer to the
477 * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
478 * documentation for details on the use of this attribute.
479 *
480 * @return the value of the attribute {@code border} or an empty string if that attribute isn't defined
481 */
482 public final String getBorderAttribute() {
483 return getAttributeDirect("border");
484 }
485
486 /**
487 * Returns the value of the attribute {@code hspace}. Refer to the
488 * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
489 * documentation for details on the use of this attribute.
490 *
491 * @return the value of the attribute {@code hspace} or an empty string if that attribute isn't defined
492 */
493 public final String getHspaceAttribute() {
494 return getAttributeDirect("hspace");
495 }
496
497 /**
498 * Returns the value of the attribute {@code vspace}. Refer to the
499 * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
500 * documentation for details on the use of this attribute.
501 *
502 * @return the value of the attribute {@code vspace} or an empty string if that attribute isn't defined
503 */
504 public final String getVspaceAttribute() {
505 return getAttributeDirect("vspace");
506 }
507
508 /**
509 * <p>Returns the image's actual height (<b>not</b> the image's {@link #getHeightAttribute() height attribute}).</p>
510 * <p><span style="color:red">POTENTIAL PERFORMANCE KILLER - DOWNLOADS THE IMAGE - USE AT YOUR OWN RISK</span></p>
511 * <p>If the image has not already been downloaded, this method triggers a download and caches the image.</p>
512 *
513 * @return the image's actual height
514 * @throws IOException if an error occurs while downloading or reading the image
515 */
516 public int getHeight() throws IOException {
517 if (height_ < 0) {
518 determineWidthAndHeight();
519 }
520 return height_;
521 }
522
523 /**
524 * Returns the value same value as the js height property.
525 * @return the value of the {@code height} property
526 */
527 public int getHeightOrDefault() {
528 final String height = getHeightAttribute();
529
530 if (ATTRIBUTE_NOT_DEFINED != height) {
531 try {
532 return Integer.parseInt(height);
533 }
534 catch (final NumberFormatException ignored) {
535 // ignore
536 }
537 }
538
539 final String src = getSrcAttribute();
540 if (ATTRIBUTE_NOT_DEFINED == src) {
541 final BrowserVersion browserVersion = getPage().getWebClient().getBrowserVersion();
542 if (browserVersion.hasFeature(JS_IMAGE_WIDTH_HEIGHT_RETURNS_16x16_0x0)
543 || browserVersion.hasFeature(JS_IMAGE_WIDTH_HEIGHT_RETURNS_24x24_0x0)) {
544 return 0;
545 }
546 return 24;
547 }
548
549 final WebClient webClient = getPage().getWebClient();
550 final BrowserVersion browserVersion = webClient.getBrowserVersion();
551 if (StringUtils.isEmptyOrNull(src)) {
552 return 0;
553 }
554 if (browserVersion.hasFeature(JS_IMAGE_WIDTH_HEIGHT_RETURNS_16x16_0x0)
555 && StringUtils.isBlank(src)) {
556 return 0;
557 }
558
559 try {
560 return getHeight();
561 }
562 catch (final IOException e) {
563 if (browserVersion.hasFeature(JS_IMAGE_WIDTH_HEIGHT_RETURNS_16x16_0x0)) {
564 return 16;
565 }
566 return 24;
567 }
568 }
569
570 /**
571 * <p>Returns the image's actual width (<b>not</b> the image's {@link #getWidthAttribute() width attribute}).</p>
572 * <p><span style="color:red">POTENTIAL PERFORMANCE KILLER - DOWNLOADS THE IMAGE - USE AT YOUR OWN RISK</span></p>
573 * <p>If the image has not already been downloaded, this method triggers a download and caches the image.</p>
574 *
575 * @return the image's actual width
576 * @throws IOException if an error occurs while downloading or reading the image
577 */
578 public int getWidth() throws IOException {
579 if (width_ < 0) {
580 determineWidthAndHeight();
581 }
582 return width_;
583 }
584
585 /**
586 * Returns the value same value as the js width property.
587 * @return the value of the {@code width} property
588 */
589 public int getWidthOrDefault() {
590 final String widthAttrib = getWidthAttribute();
591
592 if (ATTRIBUTE_NOT_DEFINED != widthAttrib) {
593 try {
594 return Integer.parseInt(widthAttrib);
595 }
596 catch (final NumberFormatException ignored) {
597 // ignore
598 }
599 }
600
601 final String src = getSrcAttribute();
602 if (ATTRIBUTE_NOT_DEFINED == src) {
603 final BrowserVersion browserVersion = getPage().getWebClient().getBrowserVersion();
604 if (browserVersion.hasFeature(JS_IMAGE_WIDTH_HEIGHT_RETURNS_16x16_0x0)
605 || browserVersion.hasFeature(JS_IMAGE_WIDTH_HEIGHT_RETURNS_24x24_0x0)) {
606 return 0;
607 }
608 return 24;
609 }
610
611 final WebClient webClient = getPage().getWebClient();
612 final BrowserVersion browserVersion = webClient.getBrowserVersion();
613 if (StringUtils.isEmptyOrNull(src)) {
614 return 0;
615 }
616 if (browserVersion.hasFeature(JS_IMAGE_WIDTH_HEIGHT_RETURNS_16x16_0x0)
617 && StringUtils.isBlank(src)) {
618 return 0;
619 }
620
621 try {
622 return getWidth();
623 }
624 catch (final IOException e) {
625 if (browserVersion.hasFeature(JS_IMAGE_WIDTH_HEIGHT_RETURNS_16x16_0x0)) {
626 return 16;
627 }
628 return 24;
629 }
630 }
631
632 /**
633 * Returns the image data for this image.
634 *
635 * @return the {@link ImageData} for this image
636 * @throws IOException if an I/O error occurs while reading the image
637 */
638 public ImageData getImageData() throws IOException {
639 readImageIfNeeded();
640 return imageData_;
641 }
642
643 private void determineWidthAndHeight() throws IOException {
644 readImageIfNeeded();
645
646 final IntDimension2D dim = imageData_.getWidthHeight();
647 width_ = dim.getWidth();
648 height_ = dim.getHeight();
649
650 // ImageIO creates temp files; to save file handles
651 // we will cache the values and close this directly to free the resources
652 closeImageData();
653 }
654
655 private void closeImageData() throws IOException {
656 if (imageData_ != null) {
657 try {
658 imageData_.close();
659 }
660 catch (final Exception ex) {
661 if (ex instanceof IOException) {
662 throw (IOException) ex;
663 }
664 throw new IOException("Exception during close()", ex);
665 }
666 imageData_ = null;
667 }
668 }
669
670 /**
671 * <p>Returns the <code>WebResponse</code> for the image contained by this image element.</p>
672 * <p><span style="color:red">POTENTIAL PERFORMANCE KILLER - DOWNLOADS THE IMAGE - USE AT YOUR OWN RISK</span></p>
673 * <p>If the image has not already been downloaded and <code>downloadIfNeeded</code> is {@code true}, this method
674 * triggers a download and caches the image.</p>
675 *
676 * @param downloadIfNeeded whether or not the image should be downloaded (if it hasn't already been downloaded)
677 * @return {@code null} if no download should be performed and one hasn't already been triggered; otherwise,
678 * the response received when performing a request for the image referenced by this element
679 * @throws IOException if an error occurs while downloading the image
680 */
681 public WebResponse getWebResponse(final boolean downloadIfNeeded) throws IOException {
682 if (downloadIfNeeded) {
683 downloadImageIfNeeded();
684 }
685 return imageWebResponse_;
686 }
687
688 /**
689 * <p>Downloads the image contained by this image element.</p>
690 * <p><span style="color:red">POTENTIAL PERFORMANCE KILLER - DOWNLOADS THE IMAGE - USE AT YOUR OWN RISK</span></p>
691 * <p>If the image has not already been downloaded, this method triggers a download and caches the image.</p>
692 *
693 * @throws IOException if an error occurs while downloading the image
694 */
695 private void downloadImageIfNeeded() throws IOException {
696 if (!downloaded_ && !isInDocumentWithoutBrowsingContext()) {
697 // HTMLIMAGE_BLANK_SRC_AS_EMPTY
698 final String src = getSrcAttribute();
699
700 corsCrossOrigin_ = false;
701 if (!StringUtils.isEmptyString(src)) {
702 final HtmlPage page = (HtmlPage) getPage();
703 final WebClient webClient = page.getWebClient();
704 final BrowserVersion browser = webClient.getBrowserVersion();
705
706 final boolean blank = browser.hasFeature(HTMLIMAGE_BLANK_SRC_AS_EMPTY) && StringUtils.isBlank(src);
707 if (!blank && !isAllowedByContentSecurityPolicy(page)) {
708 // blocked by the Content-Security-Policy; forget the response of a previous src
709 imageWebResponse_ = null;
710 }
711 else if (!blank && !isLocalResourceAccessAllowed(page)) {
712 // like the browsers, a page not loaded from a file is not allowed to load a local file
713 imageWebResponse_ = null;
714 }
715 else if (!blank) {
716 // upgrade-insecure-requests of the Content-Security-Policy
717 final URL url = ContentSecurityPolicy.upgradeInsecureRequest(page,
718 page.getFullyQualifiedUrl(src));
719 final WebRequest request = new WebRequest(url, browser.getImgAcceptHeader(),
720 browser.getAcceptEncodingHeader());
721 request.setCharset(page.getCharset());
722 request.setRefererHeader(page.getUrl());
723 request.setReferrerPolicy(page.getReferrerPolicy(this));
724
725 // Sec-Fetch-* support (https://www.w3.org/TR/fetch-metadata/):
726 // an <img> load is never user-activated, and is initiated by the
727 // containing page; the crossorigin attribute (any value) forces
728 // CORS mode, otherwise images default to no-cors.
729 request.setFetchDestination(WebRequest.FetchDestination.IMAGE);
730 request.setFetchModeOverride(WebRequest.FetchMode.NO_CORS);
731 request.setRequestingUrl(page.getUrl());
732 request.setSiteForCookies(page.getSiteForCookiesUrl());
733
734 if (hasAttribute("crossorigin")) {
735 request.setFetchModeOverride(WebRequest.FetchMode.CORS);
736
737 if (browser.hasFeature(HTTP_HEADER_CH_UA)) {
738 request.setAdditionalHeader(HttpHeader.ORIGIN,
739 UrlUtils.getUrlWithProtocolAndAuthority(page.getUrl()).toExternalForm());
740 }
741 }
742
743 // Canvas tainting: in no-cors mode the response is opaque (CORS-cross-origin) as soon as
744 // one url of the redirect chain has another origin than the page - also if the chain
745 // returns to the origin of the page (same -> other -> same). The request url and the
746 // final url are known afterwards, the redirect targets in between are only visible
747 // here; therefore this filter records them. It never blocks a redirect.
748 // The origin of the page is the origin of the creator for about:blank documents.
749 final URL originUrl = page.getOriginUrl();
750 final boolean[] crossOriginRedirect = {false};
751 final Predicate<URL> trackingFilter = redirectUrl -> {
752 if (!isSameOriginImageUrl(originUrl, redirectUrl)) {
753 crossOriginRedirect[0] = true;
754 }
755 return true;
756 };
757
758 if (page.getContentSecurityPolicy() != null) {
759 // like the browsers, redirects are checked (and upgraded) also;
760 // the request has only one filter, both checks are combined
761 ContentSecurityPolicy.upgradeInsecureRedirects(page, request);
762 request.setRedirectFilter(trackingFilter.and(
763 redirectUrl -> ContentSecurityPolicy.allowsImage(page, redirectUrl, url)));
764 }
765 else {
766 request.setRedirectFilter(trackingFilter);
767 }
768
769 imageWebResponse_ = webClient.loadWebResponse(request);
770 if (isCrossOriginResponse(originUrl, url, crossOriginRedirect[0])) {
771 if (!hasAttribute("crossorigin")) {
772 // no-cors mode: the response is opaque
773 corsCrossOrigin_ = true;
774 }
775 else if (!isCorsAllowed(originUrl)) {
776 // cors mode: a response failing the CORS check is a network error;
777 // like the browsers, the image is broken (error event, drawImage() throws).
778 // A response passing the check is CORS-same-origin.
779 imageWebResponse_ = null;
780 }
781 }
782 }
783 }
784
785 closeImageData();
786
787 downloaded_ = true;
788 isComplete_ = true;
789
790 width_ = -1;
791 height_ = -1;
792 }
793 }
794
795 /**
796 * Returns whether this image is part of a document without browsing context (e.g. created by
797 * DOMImplementation.createHTMLDocument() or DOMParser); like the browsers, such an image is not loaded.
798 *
799 * @return whether the document of this image has no browsing context
800 */
801 private boolean isInDocumentWithoutBrowsingContext() {
802 return getPage().getEnclosingWindow() == null;
803 }
804
805 /**
806 * Returns whether the image data of this image is CORS-cross-origin; a canvas the image
807 * is drawn to loses its origin-clean flag (the image data can't be read back by script).
808 * The image data is CORS-cross-origin if the image (or one of the redirects) was loaded from
809 * another origin than the page without a crossorigin attribute (no-cors mode). With a
810 * crossorigin attribute a cross-origin response has to pass the CORS check; otherwise the
811 * image is broken (see {@link #isBroken()}).
812 *
813 * @return {@code true} if the image data is CORS-cross-origin
814 * @see <a href="https://html.spec.whatwg.org/multipage/canvas.html#the-image-argument-is-not-origin-clean">
815 * HTML Living Standard - the image argument is not origin-clean</a>
816 */
817 public boolean isCorsCrossOrigin() {
818 return corsCrossOrigin_;
819 }
820
821 /**
822 * Returns whether the image is broken: the image has a src but there is no usable response
823 * (e.g. the download failed, was blocked by the Content-Security-Policy or did not pass the
824 * CORS check). Like the browsers, drawing a broken image into a canvas fails.
825 * <p><span style="color:red">POTENTIAL PERFORMANCE KILLER - DOWNLOADS THE IMAGE - USE AT YOUR OWN RISK</span></p>
826 *
827 * @return {@code true} if the image is broken
828 * @throws IOException if an error occurs while downloading the image
829 * @see <a href="https://html.spec.whatwg.org/multipage/images.html#img-error">
830 * HTML Living Standard - broken</a>
831 */
832 public boolean isBroken() throws IOException {
833 final String src = getSrcAttribute();
834 if (StringUtils.isEmptyString(src)
835 || (hasFeature(HTMLIMAGE_BLANK_SRC_AS_EMPTY) && StringUtils.isBlank(src))) {
836 // no image (unavailable), nothing to draw but not broken
837 return false;
838 }
839 downloadImageIfNeeded();
840 return imageWebResponse_ == null
841 || !imageWebResponse_.isSuccess()
842 || imageWebResponse_.getStatusCode() == HttpStatus.NO_CONTENT_204;
843 }
844
845 /**
846 * Determines whether the current response is cross-origin; this is the case if the
847 * request url, one of the redirect targets or the final url has another origin than the page.
848 *
849 * @param originUrl the url of the origin of the page
850 * @param requestUrl the url of the image request
851 * @param crossOriginRedirect whether one of the redirect targets has another origin than the page
852 * @return {@code true} if the response is cross-origin
853 */
854 private boolean isCrossOriginResponse(final URL originUrl, final URL requestUrl,
855 final boolean crossOriginRedirect) {
856 if (imageWebResponse_ == null) {
857 return false;
858 }
859
860 // the final url is the last redirect target and therefore already covered by the filter;
861 // it is checked again as safety net (e.g. if the redirect filter was not called for a hop)
862 return crossOriginRedirect
863 || !isSameOriginImageUrl(originUrl, requestUrl)
864 || !isSameOriginImageUrl(originUrl, imageWebResponse_.getWebRequest().getUrl());
865 }
866
867 /**
868 * The CORS check of the fetch standard for the current image response.
869 * For crossorigin='use-credentials' the Access-Control-Allow-Origin header has to be
870 * the origin of the page and Access-Control-Allow-Credentials has to be 'true'; otherwise
871 * the Access-Control-Allow-Origin header has to be the origin of the page or '*'.
872 *
873 * @param originUrl the url of the origin of the page
874 * @return {@code true} if the response passes the CORS check
875 * @see <a href="https://fetch.spec.whatwg.org/#cors-check">Fetch Standard - CORS check</a>
876 */
877 private boolean isCorsAllowed(final URL originUrl) {
878 // the serialized origin of the page
879 String origin = originUrl.getProtocol() + "://" + originUrl.getHost();
880 final int port = originUrl.getPort();
881 if (port != -1 && port != originUrl.getDefaultPort()) {
882 origin += ":" + port;
883 }
884
885 final String allowOrigin = imageWebResponse_.getResponseHeaderValue(HttpHeader.ACCESS_CONTROL_ALLOW_ORIGIN);
886 if ("use-credentials".equalsIgnoreCase(getAttributeDirect("crossorigin"))) {
887 final String allowCredentials =
888 imageWebResponse_.getResponseHeaderValue(HttpHeader.ACCESS_CONTROL_ALLOW_CREDENTIALS);
889 return origin.equals(allowOrigin) && "true".equals(allowCredentials);
890 }
891 return "*".equals(allowOrigin) || origin.equals(allowOrigin);
892 }
893
894 /**
895 * Returns whether the url of an image (or of a redirect target) has the same origin as the page.
896 * Data urls are always same-origin (the fetch of a data url is a basic response),
897 * blob urls have the origin of the url they were created for.
898 *
899 * @param originUrl the url of the origin of the page
900 * @param url the url to check
901 * @return {@code true} if the url has the same origin as the page
902 */
903 private static boolean isSameOriginImageUrl(final URL originUrl, final URL url) {
904 final String protocol = url.getProtocol();
905 if ("data".equalsIgnoreCase(protocol)) {
906 return true;
907 }
908 if ("blob".equalsIgnoreCase(protocol)) {
909 try {
910 return UrlUtils.isSameOrigin(originUrl, new URL(url.toExternalForm().substring(5)));
911 }
912 catch (final MalformedURLException e) {
913 return false;
914 }
915 }
916 return UrlUtils.isSameOrigin(originUrl, url);
917 }
918
919 /**
920 * Checks the url of the image against the Content-Security-Policy (img-src);
921 * the check is done only once for every url.
922 *
923 * @param page the page
924 * @return {@code true} if the image is allowed (or the src is empty or invalid)
925 */
926 private boolean isLocalResourceAccessAllowed(final HtmlPage page) {
927 final URL url;
928 try {
929 url = page.getFullyQualifiedUrl(getSrcAttribute());
930 }
931 catch (final MalformedURLException e) {
932 return true;
933 }
934 if (page.isLocalResourceAccessAllowed(url)) {
935 return true;
936 }
937 notifyIncorrectness("Not allowed to load local resource: " + url);
938 return false;
939 }
940
941 private boolean isAllowedByContentSecurityPolicy(final HtmlPage page) {
942 final String src = getSrcAttribute();
943 if (StringUtils.isBlank(src)) {
944 return true;
945 }
946
947 final URL url;
948 try {
949 // upgrade-insecure-requests of the Content-Security-Policy
950 url = ContentSecurityPolicy.upgradeInsecureRequest(page, page.getFullyQualifiedUrl(src));
951 }
952 catch (final MalformedURLException e) {
953 return true;
954 }
955
956 final String urlString = url.toExternalForm();
957 if (!urlString.equals(cspCheckedUrl_)) {
958 cspCheckedUrl_ = urlString;
959 cspAllowed_ = ContentSecurityPolicy.allowsImage(page, url);
960 }
961 return cspAllowed_;
962 }
963
964 private void readImageIfNeeded() throws IOException {
965 downloadImageIfNeeded();
966 if (imageData_ == null) {
967 if (imageWebResponse_ == null) {
968 throw new IOException("No image response available (src='" + getSrcAttribute() + "')");
969 }
970 imageData_ = Platform.buildImageData(imageWebResponse_.getContentAsStream());
971 }
972 }
973
974 /**
975 * Simulates clicking this element at the specified position. This only makes sense for
976 * an image map (currently only server side), where the position matters. This method
977 * returns the page contained by this image's window after the click, which may or may not
978 * be the same as the original page, depending on JavaScript event handlers, etc.
979 *
980 * @param x the x position of the click
981 * @param y the y position of the click
982 * @return the page contained by this image's window after the click
983 * @throws IOException if an IO error occurs
984 */
985 public Page click(final int x, final int y) throws IOException {
986 lastClickX_ = x;
987 lastClickY_ = y;
988 try {
989 return super.click();
990 }
991 finally {
992 lastClickX_ = -1;
993 lastClickY_ = -1;
994 }
995 }
996
997 /**
998 * Simulates clicking this element at the position <code>(0, 0)</code>. This method returns
999 * the page contained by this image's window after the click, which may or may not be the
1000 * same as the original page, depending on JavaScript event handlers, etc.
1001 *
1002 * @return the page contained by this image's window after the click
1003 * @throws IOException if an IO error occurs
1004 */
1005 @Override
1006 @SuppressWarnings("unchecked")
1007 public Page click() throws IOException {
1008 return click(0, 0);
1009 }
1010
1011 /**
1012 * Performs the click action on the enclosing A tag (if any).
1013 * {@inheritDoc}
1014 * @throws IOException if an IO error occurred
1015 */
1016 @Override
1017 protected boolean doClickStateUpdate(final boolean shiftKey, final boolean ctrlKey) throws IOException {
1018 if (ATTRIBUTE_NOT_DEFINED != getUseMapAttribute()) {
1019 // remove initial '#'
1020 final String mapName = getUseMapAttribute().substring(1);
1021 final HtmlElement doc = ((HtmlPage) getPage()).getDocumentElement();
1022 final HtmlMap map = doc.getOneHtmlElementByAttribute("map", NAME_ATTRIBUTE, mapName);
1023 for (final DomElement element : map.getChildElements()) {
1024 if (element instanceof HtmlArea area) {
1025 if (area.containsPoint(Math.max(lastClickX_, 0), Math.max(lastClickY_, 0))) {
1026 area.doClickStateUpdate(shiftKey, ctrlKey);
1027 return false;
1028 }
1029 }
1030 }
1031 }
1032 final HtmlAnchor anchor = (HtmlAnchor) getEnclosingElement("a");
1033 if (anchor == null) {
1034 return false;
1035 }
1036 if (ATTRIBUTE_NOT_DEFINED != getIsmapAttribute()) {
1037 final String suffix = "?" + Math.max(lastClickX_, 0) + "," + Math.max(lastClickY_, 0);
1038 anchor.doClickStateUpdate(false, false, suffix);
1039 return false;
1040 }
1041 anchor.doClickStateUpdate(shiftKey, ctrlKey);
1042 return false;
1043 }
1044
1045 /**
1046 * Saves this image as the specified file.
1047 * @param file the file to save to
1048 * @throws IOException if an IO error occurs
1049 */
1050 public void saveAs(final File file) throws IOException {
1051 downloadImageIfNeeded();
1052 if (null != imageWebResponse_) {
1053 try (OutputStream fos = Files.newOutputStream(file.toPath());
1054 InputStream inputStream = imageWebResponse_.getContentAsStream()) {
1055 IOUtils.copy(inputStream, fos);
1056 }
1057 }
1058 }
1059
1060 /**
1061 * {@inheritDoc}
1062 */
1063 @Override
1064 public DisplayStyle getDefaultStyleDisplay() {
1065 return DisplayStyle.INLINE;
1066 }
1067
1068 /**
1069 * Returns whether this image has finished loading.
1070 *
1071 * @return {@code true} if the image has finished loading or has no
1072 * {@code src} attribute
1073 */
1074 public boolean isComplete() {
1075 return isComplete_ || ATTRIBUTE_NOT_DEFINED == getSrcAttribute();
1076 }
1077
1078 /**
1079 * {@inheritDoc}
1080 */
1081 @Override
1082 public boolean isDisplayed() {
1083 final String src = getSrcAttribute();
1084 if (ATTRIBUTE_NOT_DEFINED == src) {
1085 return false;
1086 }
1087 if (hasFeature(HTMLIMAGE_BLANK_SRC_AS_EMPTY) && StringUtils.isBlank(src)) {
1088 return false;
1089 }
1090 if (hasFeature(HTMLIMAGE_EMPTY_SRC_DISPLAY_FALSE) && StringUtils.isEmptyOrNull(src)) {
1091 return false;
1092 }
1093
1094 return super.isDisplayed();
1095 }
1096
1097 /**
1098 * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
1099 *
1100 * Marks this frame as created by javascript.
1101 */
1102 public void markAsCreatedByJavascript() {
1103 createdByJavascript_ = true;
1104 }
1105
1106 /**
1107 * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
1108 *
1109 * Returns true if this frame was created by javascript.
1110 * @return true or false
1111 */
1112 public boolean wasCreatedByJavascript() {
1113 return createdByJavascript_;
1114 }
1115
1116 /**
1117 * Returns the original element qualified name,
1118 * this is needed to differentiate between <code>img</code> and <code>image</code>.
1119 * @return the original element qualified name
1120 */
1121 public String getOriginalQualifiedName() {
1122 return originalQualifiedName_;
1123 }
1124
1125 /**
1126 * {@inheritDoc}
1127 */
1128 @Override
1129 public String getLocalName() {
1130 if (wasCreatedByJavascript()
1131 && (hasFeature(HTMLIMAGE_HTMLELEMENT) || hasFeature(HTMLIMAGE_HTMLUNKNOWNELEMENT))) {
1132 return originalQualifiedName_;
1133 }
1134 return super.getLocalName();
1135 }
1136
1137 /**
1138 * {@inheritDoc}
1139 */
1140 @Override
1141 public ScriptResult fireEvent(final Event event) {
1142 if (event instanceof MouseEvent mouseEvent) {
1143 if (lastClickX_ >= 0) {
1144 mouseEvent.setClientX(getPosX() + lastClickX_);
1145 }
1146 if (lastClickY_ >= 0) {
1147 mouseEvent.setClientY(getPosY() + lastClickY_);
1148 }
1149 }
1150
1151 return super.fireEvent(event);
1152 }
1153 }