001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.io; 003 004import static org.openstreetmap.josm.tools.I18n.tr; 005 006import java.io.BufferedReader; 007import java.io.Closeable; 008import java.io.File; 009import java.io.IOException; 010import java.io.InputStream; 011import java.math.BigInteger; 012import java.net.HttpURLConnection; 013import java.net.MalformedURLException; 014import java.net.URL; 015import java.nio.charset.StandardCharsets; 016import java.nio.file.Files; 017import java.nio.file.InvalidPathException; 018import java.nio.file.StandardCopyOption; 019import java.security.MessageDigest; 020import java.security.NoSuchAlgorithmException; 021import java.util.ArrayList; 022import java.util.Arrays; 023import java.util.Enumeration; 024import java.util.List; 025import java.util.Map; 026import java.util.Optional; 027import java.util.concurrent.ConcurrentHashMap; 028import java.util.concurrent.TimeUnit; 029import java.util.zip.ZipEntry; 030import java.util.zip.ZipFile; 031 032import org.openstreetmap.josm.data.Preferences; 033import org.openstreetmap.josm.spi.preferences.Config; 034import org.openstreetmap.josm.tools.HttpClient; 035import org.openstreetmap.josm.tools.Logging; 036import org.openstreetmap.josm.tools.Pair; 037import org.openstreetmap.josm.tools.PlatformManager; 038import org.openstreetmap.josm.tools.ResourceProvider; 039import org.openstreetmap.josm.tools.Utils; 040 041/** 042 * Downloads a file and caches it on disk in order to reduce network load. 043 * 044 * Supports URLs, local files, and a custom scheme (<code>resource:</code>) to get 045 * resources from the current JOSM *.jar file as well as plugins *.jar files. 046 * (Local caching is only done for URLs.) 047 * <p> 048 * The mirrored file is only downloaded if it has been more than 7 days since 049 * last download. (Time can be configured.) 050 * <p> 051 * The file content is normally accessed with {@link #getInputStream()}, but 052 * you can also get the mirrored copy with {@link #getFile()}. 053 */ 054public class CachedFile implements Closeable { 055 056 /** 057 * Caching strategy. 058 */ 059 public enum CachingStrategy { 060 /** 061 * If cached file on disk is older than a certain time (7 days by default), 062 * consider the cache stale and try to download the file again. 063 */ 064 MaxAge, 065 /** 066 * Similar to MaxAge, considers the cache stale when a certain age is 067 * exceeded. In addition, a If-Modified-Since HTTP header is added. 068 * When the server replies "304 Not Modified", this is considered the same 069 * as a full download. 070 */ 071 IfModifiedSince 072 } 073 074 protected String name; 075 protected long maxAge; 076 protected String destDir; 077 protected String httpAccept; 078 protected CachingStrategy cachingStrategy; 079 080 private boolean fastFail; 081 private HttpClient activeConnection; 082 protected File cacheFile; 083 protected boolean initialized; 084 protected String parameter; 085 086 public static final long DEFAULT_MAXTIME = -1L; 087 public static final long DAYS = TimeUnit.DAYS.toSeconds(1); // factor to get caching time in days 088 089 private final Map<String, String> httpHeaders = new ConcurrentHashMap<>(); 090 091 /** 092 * Constructs a CachedFile object from a given filename, URL or internal resource. 093 * 094 * @param name can be:<ul> 095 * <li>relative or absolute file name</li> 096 * <li>{@code file:///SOME/FILE} the same as above</li> 097 * <li>{@code http://...} a URL. It will be cached on disk.</li> 098 * <li>{@code resource://SOME/FILE} file from the classpath (usually in the current *.jar)</li> 099 * <li>{@code josmdir://SOME/FILE} file inside josm user data directory (since r7058)</li> 100 * <li>{@code josmplugindir://SOME/FILE} file inside josm plugin directory (since r7834)</li></ul> 101 */ 102 public CachedFile(String name) { 103 this.name = name; 104 } 105 106 /** 107 * Set the name of the resource. 108 * @param name can be:<ul> 109 * <li>relative or absolute file name</li> 110 * <li>{@code file:///SOME/FILE} the same as above</li> 111 * <li>{@code http://...} a URL. It will be cached on disk.</li> 112 * <li>{@code resource://SOME/FILE} file from the classpath (usually in the current *.jar)</li> 113 * <li>{@code josmdir://SOME/FILE} file inside josm user data directory (since r7058)</li> 114 * <li>{@code josmplugindir://SOME/FILE} file inside josm plugin directory (since r7834)</li></ul> 115 * @return this object 116 */ 117 public CachedFile setName(String name) { 118 this.name = name; 119 return this; 120 } 121 122 /** 123 * Set maximum age of cache file. Only applies to URLs. 124 * When this time has passed after the last download of the file, the 125 * cache is considered stale and a new download will be attempted. 126 * @param maxAge the maximum cache age in seconds 127 * @return this object 128 */ 129 public CachedFile setMaxAge(long maxAge) { 130 this.maxAge = maxAge; 131 return this; 132 } 133 134 /** 135 * Set the destination directory for the cache file. Only applies to URLs. 136 * @param destDir the destination directory 137 * @return this object 138 */ 139 public CachedFile setDestDir(String destDir) { 140 this.destDir = destDir; 141 return this; 142 } 143 144 /** 145 * Set the accepted MIME types sent in the HTTP Accept header. Only applies to URLs. 146 * @param httpAccept the accepted MIME types 147 * @return this object 148 */ 149 public CachedFile setHttpAccept(String httpAccept) { 150 this.httpAccept = httpAccept; 151 return this; 152 } 153 154 /** 155 * Set the caching strategy. Only applies to URLs. 156 * @param cachingStrategy caching strategy 157 * @return this object 158 */ 159 public CachedFile setCachingStrategy(CachingStrategy cachingStrategy) { 160 this.cachingStrategy = cachingStrategy; 161 return this; 162 } 163 164 /** 165 * Sets the http headers. Only applies to URL pointing to http or https resources 166 * @param headers that should be sent together with request 167 * @return this object 168 */ 169 public CachedFile setHttpHeaders(Map<String, String> headers) { 170 this.httpHeaders.putAll(headers); 171 return this; 172 } 173 174 /** 175 * Sets whether opening HTTP connections should fail fast, i.e., whether a 176 * {@link HttpClient#setConnectTimeout(int) low connect timeout} should be used. 177 * @param fastFail whether opening HTTP connections should fail fast 178 */ 179 public void setFastFail(boolean fastFail) { 180 this.fastFail = fastFail; 181 } 182 183 /** 184 * Sets additional URL parameter (used e.g. for maps) 185 * @param parameter the URL parameter 186 * @since 13536 187 */ 188 public void setParam(String parameter) { 189 this.parameter = parameter; 190 } 191 192 public String getName() { 193 if (parameter != null) 194 return name.replaceAll("%<(.*)>", ""); 195 return name; 196 } 197 198 /** 199 * Returns maximum age of cache file. Only applies to URLs. 200 * When this time has passed after the last download of the file, the 201 * cache is considered stale and a new download will be attempted. 202 * @return the maximum cache age in seconds 203 */ 204 public long getMaxAge() { 205 return maxAge; 206 } 207 208 public String getDestDir() { 209 return destDir; 210 } 211 212 public String getHttpAccept() { 213 return httpAccept; 214 } 215 216 public CachingStrategy getCachingStrategy() { 217 return cachingStrategy; 218 } 219 220 /** 221 * Get InputStream to the requested resource. 222 * @return the InputStream 223 * @throws IOException when the resource with the given name could not be retrieved 224 * @throws InvalidPathException if a Path object cannot be constructed from the inner file path 225 */ 226 public InputStream getInputStream() throws IOException { 227 File file = getFile(); 228 if (file == null) { 229 if (name != null && name.startsWith("resource://")) { 230 return Optional.ofNullable(ResourceProvider.getResourceAsStream(name.substring("resource:/".length()))) 231 .orElseThrow(() -> new IOException(tr("Failed to open input stream for resource ''{0}''", name))); 232 } else { 233 throw new IOException("No file found for: "+name); 234 } 235 } 236 return Files.newInputStream(file.toPath()); 237 } 238 239 /** 240 * Get the full content of the requested resource as a byte array. 241 * @return the full content of the requested resource as byte array 242 * @throws IOException in case of an I/O error 243 */ 244 public byte[] getByteContent() throws IOException { 245 try (InputStream is = getInputStream()) { 246 return is.readAllBytes(); 247 } 248 } 249 250 /** 251 * Returns {@link #getInputStream()} wrapped in a buffered reader. 252 * <p> 253 * Detects Unicode charset in use utilizing {@link UTFInputStreamReader}. 254 * 255 * @return buffered reader 256 * @throws IOException if any I/O error occurs 257 * @since 9411 258 */ 259 public BufferedReader getContentReader() throws IOException { 260 return new BufferedReader(UTFInputStreamReader.create(getInputStream())); 261 } 262 263 /** 264 * Get local file for the requested resource. 265 * @return The local cache file for URLs. If the resource is a local file, 266 * returns just that file. 267 * @throws IOException when the resource with the given name could not be retrieved 268 */ 269 public synchronized File getFile() throws IOException { 270 if (initialized) 271 return cacheFile; 272 initialized = true; 273 if (name == null || name.startsWith("resource://")) { 274 return null; 275 } 276 URL url; 277 try { 278 url = new URL(name); 279 if ("file".equals(url.getProtocol())) { 280 cacheFile = new File(name.substring("file:/".length() - 1)); 281 if (!cacheFile.exists()) { 282 cacheFile = new File(name.substring("file://".length() - 1)); 283 } 284 } else { 285 try { 286 cacheFile = checkLocal(url); 287 } catch (SecurityException e) { 288 throw new IOException(e); 289 } 290 } 291 } catch (MalformedURLException e) { 292 if (name.startsWith("josmdir://")) { 293 cacheFile = new File(Config.getDirs().getUserDataDirectory(false), name.substring("josmdir://".length())); 294 } else if (name.startsWith("josmplugindir://")) { 295 cacheFile = new File(Preferences.main().getPluginsDirectory(), name.substring("josmplugindir://".length())); 296 } else { 297 cacheFile = new File(name); 298 } 299 } 300 if (cacheFile == null) 301 throw new IOException("Unable to get cache file for "+getName()); 302 return cacheFile; 303 } 304 305 /** 306 * Looks for a certain entry inside a zip file and returns the entry path. 307 * 308 * Replies a file in the top level directory of the ZIP file which has an 309 * extension <code>extension</code>. If more than one files have this 310 * extension, the last file whose name includes <code>namepart</code> 311 * is opened. 312 * 313 * @param extension the extension of the file we're looking for 314 * @param namepart the name part 315 * @return The zip entry path of the matching file. <code>null</code> if this cached file 316 * doesn't represent a zip file or if there was no matching 317 * file in the ZIP file. 318 */ 319 public String findZipEntryPath(String extension, String namepart) { 320 Pair<String, Pair<ZipFile, InputStream>> ze = findZipEntryImpl(extension, namepart); 321 if (ze == null) return null; 322 Utils.close(ze.b.b); 323 Utils.close(ze.b.a); 324 return ze.a; 325 } 326 327 /** 328 * Like {@link #findZipEntryPath}, but returns the corresponding InputStream. 329 * @param extension the extension of the file we're looking for 330 * @param namepart the name part 331 * @return InputStream to the matching file. <code>null</code> if this cached file 332 * doesn't represent a zip file or if there was no matching 333 * file in the ZIP file. 334 * The returned ZipFile must be closed after use. 335 * @since 19372 336 */ 337 public Pair<ZipFile, InputStream> findZipEntryInputStream(String extension, String namepart) { 338 Pair<String, Pair<ZipFile, InputStream>> ze = findZipEntryImpl(extension, namepart); 339 if (ze == null) return null; 340 return ze.b; 341 } 342 343 private Pair<String, Pair<ZipFile, InputStream>> findZipEntryImpl(String extension, String namepart) { 344 File file = null; 345 try { 346 file = getFile(); 347 } catch (IOException ex) { 348 Logging.log(Logging.LEVEL_WARN, ex); 349 } 350 if (file == null) 351 return null; 352 Pair<String, Pair<ZipFile, InputStream>> res = null; 353 try { 354 ZipFile zipFile = new ZipFile(file, StandardCharsets.UTF_8); // NOPMD 355 ZipEntry resentry = null; 356 Enumeration<? extends ZipEntry> entries = zipFile.entries(); 357 while (entries.hasMoreElements()) { 358 ZipEntry entry = entries.nextElement(); 359 // choose any file with correct extension. When more than one file, prefer the one which matches namepart 360 if (entry.getName().endsWith('.' + extension) && (resentry == null || entry.getName().contains(namepart))) { 361 resentry = entry; 362 } 363 } 364 if (resentry != null) { 365 InputStream is = zipFile.getInputStream(resentry); // NOPMD 366 res = Pair.create(resentry.getName(), Pair.create(zipFile, is)); 367 } else { 368 Utils.close(zipFile); 369 } 370 } catch (IOException e) { 371 if (file.getName().endsWith(".zip")) { 372 Logging.log(Logging.LEVEL_WARN, 373 tr("Failed to open file with extension ''{2}'' and namepart ''{3}'' in zip file ''{0}''. Exception was: {1}", 374 file.getName(), e.toString(), extension, namepart), e); 375 } 376 } 377 return res; 378 } 379 380 /** 381 * Clear the cache for the given resource. 382 * This forces a fresh download. 383 * @param name the URL 384 */ 385 public static void cleanup(String name) { 386 cleanup(name, null); 387 } 388 389 /** 390 * Clear the cache for the given resource. 391 * This forces a fresh download. 392 * @param name the URL 393 * @param destDir the destination directory (see {@link #setDestDir(java.lang.String)}) 394 */ 395 public static void cleanup(String name, String destDir) { 396 URL url; 397 try { 398 url = new URL(name); 399 if (!"file".equals(url.getProtocol())) { 400 String prefKey = getPrefKey(url, destDir); 401 List<String> localPath = new ArrayList<>(Config.getPref().getList(prefKey)); 402 if (localPath.size() == 2) { 403 File lfile = new File(localPath.get(1)); 404 if (lfile.exists()) { 405 Utils.deleteFile(lfile); 406 } 407 } 408 Config.getPref().putList(prefKey, null); 409 } 410 } catch (MalformedURLException e) { 411 Logging.warn(e); 412 } 413 } 414 415 /** 416 * Get preference key to store the location and age of the cached file. 417 * 2 resources that point to the same url, but that are to be stored in different 418 * directories will not share a cache file. 419 * @param url URL 420 * @param destDir destination directory 421 * @return Preference key 422 */ 423 private static String getPrefKey(URL url, String destDir) { 424 StringBuilder prefKey = new StringBuilder("mirror."); 425 if (destDir != null) { 426 prefKey.append(destDir).append('.'); 427 } 428 prefKey.append(url.toString().replaceAll("%<(.*)>", "")); 429 return prefKey.toString().replace("=", "_"); 430 } 431 432 private File checkLocal(URL url) throws IOException { 433 String prefKey = getPrefKey(url, destDir); 434 String urlStr = url.toExternalForm(); 435 if (parameter != null) 436 urlStr = urlStr.replaceAll("%<(.*)>", ""); 437 long age = 0L; 438 long maxAgeMillis = TimeUnit.SECONDS.toMillis(maxAge); 439 Long ifModifiedSince = null; 440 File localFile = null; 441 List<String> localPathEntry = new ArrayList<>(Config.getPref().getList(prefKey)); 442 boolean offline = NetworkManager.isOffline(urlStr); 443 if (localPathEntry.size() == 2) { 444 localFile = new File(localPathEntry.get(1)); 445 if (!localFile.exists()) { 446 localFile = null; 447 } else { 448 if (maxAge == DEFAULT_MAXTIME 449 || maxAge <= 0 // arbitrary value <= 0 is deprecated 450 ) { 451 maxAgeMillis = TimeUnit.SECONDS.toMillis(Config.getPref().getLong("mirror.maxtime", TimeUnit.DAYS.toSeconds(7))); 452 } 453 age = System.currentTimeMillis() - Long.parseLong(localPathEntry.get(0)); 454 if (offline || age < maxAgeMillis) { 455 return localFile; 456 } else if (NetworkManager.isOffline(OnlineResource.CACHE_UPDATES)) { 457 Logging.warn(OfflineAccessException.forResource(tr("Cache update for {0}", urlStr)).getMessage()); 458 return localFile; 459 } 460 if (cachingStrategy == CachingStrategy.IfModifiedSince) { 461 ifModifiedSince = Long.valueOf(localPathEntry.get(0)); 462 } 463 } 464 } 465 if (destDir == null) { 466 destDir = Config.getDirs().getCacheDirectory(true).getPath(); 467 } 468 469 File destDirFile = new File(destDir); 470 if (!destDirFile.exists()) { 471 Utils.mkDirs(destDirFile); 472 } 473 474 // No local file + offline => nothing to do 475 if (offline) { 476 throw new IOException(OfflineAccessException.forResource(urlStr).getMessage()); 477 } 478 479 if (parameter != null) { 480 String u = url.toExternalForm(); 481 String uc; 482 if (parameter.isEmpty()) { 483 uc = u.replaceAll("%<(.*)>", ""); 484 } else { 485 uc = u.replaceAll("%<(.*)>", "$1" + Utils.encodeUrl(parameter)); 486 } 487 if (!uc.equals(u)) 488 url = new URL(uc); 489 } 490 491 String a = urlStr.replaceAll("[^A-Za-z0-9_.-]", "_"); 492 /* size 11: prefix mirror_ and suffix .tmp */ 493 Integer maxFileLength = Config.getPref().getInt("cache.filename.maxlength", 140)-11; 494 if (a.length() > maxFileLength) { 495 a = a.substring(0, maxFileLength-33) + "_" + Utils.md5Hex(urlStr); 496 } 497 String localPath = "mirror_" + a; 498 localPath = truncatePath(destDir, localPath); 499 destDirFile = new File(destDir, localPath + ".tmp"); 500 try { 501 activeConnection = HttpClient.create(url) 502 .setAccept(httpAccept) 503 .setIfModifiedSince(ifModifiedSince == null ? 0L : ifModifiedSince) 504 .setHeaders(httpHeaders); 505 if (fastFail) { 506 activeConnection.setReadTimeout(1000); 507 } 508 final HttpClient.Response con = activeConnection.connect(); 509 if (ifModifiedSince != null && con.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { 510 Logging.debug("304 Not Modified ({0})", urlStr); 511 Config.getPref().putList(prefKey, 512 Arrays.asList(Long.toString(System.currentTimeMillis()), localPathEntry.get(1))); 513 return localFile; 514 } else if (con.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) { 515 throw new IOException(tr("The requested URL {0} was not found", urlStr)); 516 } 517 try (InputStream is = con.getContent()) { 518 Files.copy(is, destDirFile.toPath(), StandardCopyOption.REPLACE_EXISTING); 519 } 520 activeConnection = null; 521 localFile = new File(destDir, localPath); 522 if (PlatformManager.getPlatform().rename(destDirFile, localFile)) { 523 Config.getPref().putList(prefKey, 524 Arrays.asList(Long.toString(System.currentTimeMillis()), localFile.toString())); 525 } else { 526 Logging.warn(tr("Failed to rename file {0} to {1}.", 527 destDirFile.getPath(), localFile.getPath())); 528 } 529 } catch (IOException e) { 530 if (age >= maxAgeMillis && age < maxAgeMillis*2) { 531 Logging.warn(tr("Failed to load {0}, use cached file and retry next time: {1}", urlStr, e)); 532 return localFile; 533 } else { 534 throw e; 535 } 536 } 537 538 return localFile; 539 } 540 541 private static String truncatePath(String directory, String fileName) { 542 if (directory.length() + fileName.length() > 255) { 543 // Windows doesn't support paths longer than 260, leave 5 chars as safe buffer, 4 will be used by ".tmp" 544 // TODO: what about filename size on other systems? 255? 545 if (directory.length() > 191 && PlatformManager.isPlatformWindows()) { 546 // digest length + name prefix == 64 547 // 255 - 64 = 191 548 // TODO: use this check only on Windows? 549 throw new IllegalArgumentException("Path " + directory + " too long to cached files"); 550 } 551 552 MessageDigest md; 553 try { 554 md = MessageDigest.getInstance("SHA-256"); 555 md.update(fileName.getBytes(StandardCharsets.UTF_8)); 556 String digest = String.format("%064x", new BigInteger(1, md.digest())); 557 return fileName.substring(0, Math.min(fileName.length(), 32)) + digest.substring(0, 32); 558 } catch (NoSuchAlgorithmException e) { 559 Logging.error(e); 560 // TODO: what better can we do here? 561 throw new IllegalArgumentException("Missing digest algorithm SHA-256", e); 562 } 563 } 564 return fileName; 565 } 566 567 /** 568 * Attempts to disconnect an URL connection. 569 * @see HttpClient#disconnect() 570 * @since 9411 571 */ 572 @Override 573 public void close() { 574 if (activeConnection != null) { 575 activeConnection.disconnect(); 576 } 577 } 578 579 /** 580 * Clears the cached file 581 * @throws IOException if any I/O error occurs 582 * @since 10993 583 */ 584 public void clear() throws IOException { 585 URL url; 586 try { 587 url = new URL(name); 588 if ("file".equals(url.getProtocol())) { 589 return; // this is local file - do not delete it 590 } 591 } catch (MalformedURLException e) { 592 return; // if it's not a URL, then it still might be a local file - better not to delete 593 } 594 File f = getFile(); 595 if (f != null && f.exists()) { 596 Utils.deleteFile(f); 597 } 598 } 599 600 @Override 601 public String toString() { 602 return getName(); 603 } 604}