| 1 |
/* |
| 2 |
* Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0, |
| 3 |
* and the EPL 1.0 (https://h2database.com/html/license.html). |
| 4 |
* Initial Developer: H2 Group |
| 5 |
*/ |
| 6 |
package org.h2.store; |
| 7 |
|
| 8 |
import java.io.IOException; |
| 9 |
import java.lang.ref.Reference; |
| 10 |
import java.nio.ByteBuffer; |
| 11 |
import java.nio.channels.FileChannel; |
| 12 |
import java.nio.charset.StandardCharsets; |
| 13 |
import java.util.Arrays; |
| 14 |
import org.h2.api.ErrorCode; |
| 15 |
import org.h2.engine.Constants; |
| 16 |
import org.h2.engine.SysProperties; |
| 17 |
import org.h2.message.DbException; |
| 18 |
import org.h2.security.SecureFileStore; |
| 19 |
import org.h2.store.fs.FileUtils; |
| 20 |
|
| 21 |
/** |
| 22 |
* This class is an abstraction of a random access file. |
| 23 |
* Each file contains a magic header, and reading / writing is done in blocks. |
| 24 |
* See also {@link SecureFileStore} |
| 25 |
*/ |
| 26 |
public class FileStore { |
| 27 |
|
| 28 |
/** |
| 29 |
* The size of the file header in bytes. |
| 30 |
*/ |
| 31 |
public static final int HEADER_LENGTH = 3 * Constants.FILE_BLOCK_SIZE; |
| 32 |
|
| 33 |
/** |
| 34 |
* The magic file header. |
| 35 |
*/ |
| 36 |
private static final String HEADER = |
| 37 |
"-- H2 0.5/B -- ".substring(0, Constants.FILE_BLOCK_SIZE - 1) + "\n"; |
| 38 |
|
| 39 |
private static final boolean ASSERT; |
| 40 |
|
| 41 |
static { |
| 42 |
boolean a = false; |
| 43 |
// Intentional side-effect |
| 44 |
assert a = true; |
| 45 |
ASSERT = a; |
| 46 |
} |
| 47 |
|
| 48 |
/** |
| 49 |
* The file name. |
| 50 |
*/ |
| 51 |
protected String name; |
| 52 |
|
| 53 |
/** |
| 54 |
* The callback object is responsible to check access rights, and free up |
| 55 |
* disk space if required. |
| 56 |
*/ |
| 57 |
private final DataHandler handler; |
| 58 |
|
| 59 |
private FileChannel file; |
| 60 |
private long filePos; |
| 61 |
private long fileLength; |
| 62 |
private Reference<?> autoDeleteReference; |
| 63 |
private boolean checkedWriting = true; |
| 64 |
private final String mode; |
| 65 |
private java.nio.channels.FileLock lock; |
| 66 |
|
| 67 |
/** |
| 68 |
* Create a new file using the given settings. |
| 69 |
* |
| 70 |
* @param handler the callback object |
| 71 |
* @param name the file name |
| 72 |
* @param mode the access mode ("r", "rw", "rws", "rwd") |
| 73 |
*/ |
| 74 |
protected FileStore(DataHandler handler, String name, String mode) { |
| 75 |
this.handler = handler; |
| 76 |
this.name = name; |
| 77 |
try { |
| 78 |
boolean exists = FileUtils.exists(name); |
| 79 |
if (exists && !FileUtils.canWrite(name)) { |
| 80 |
mode = "r"; |
| 81 |
} else { |
| 82 |
FileUtils.createDirectories(FileUtils.getParent(name)); |
| 83 |
} |
| 84 |
file = FileUtils.open(name, mode); |
| 85 |
if (exists) { |
| 86 |
fileLength = file.size(); |
| 87 |
} |
| 88 |
} catch (IOException e) { |
| 89 |
throw DbException.convertIOException( |
| 90 |
e, "name: " + name + " mode: " + mode); |
| 91 |
} |
| 92 |
this.mode = mode; |
| 93 |
} |
| 94 |
|
| 95 |
/** |
| 96 |
* Open a non encrypted file store with the given settings. |
| 97 |
* |
| 98 |
* @param handler the data handler |
| 99 |
* @param name the file name |
| 100 |
* @param mode the access mode (r, rw, rws, rwd) |
| 101 |
* @return the created object |
| 102 |
*/ |
| 103 |
public static FileStore open(DataHandler handler, String name, String mode) { |
| 104 |
return open(handler, name, mode, null, null, 0); |
| 105 |
} |
| 106 |
|
| 107 |
/** |
| 108 |
* Open an encrypted file store with the given settings. |
| 109 |
* |
| 110 |
* @param handler the data handler |
| 111 |
* @param name the file name |
| 112 |
* @param mode the access mode (r, rw, rws, rwd) |
| 113 |
* @param cipher the name of the cipher algorithm |
| 114 |
* @param key the encryption key |
| 115 |
* @return the created object |
| 116 |
*/ |
| 117 |
public static FileStore open(DataHandler handler, String name, String mode, |
| 118 |
String cipher, byte[] key) { |
| 119 |
return open(handler, name, mode, cipher, key, |
| 120 |
Constants.ENCRYPTION_KEY_HASH_ITERATIONS); |
| 121 |
} |
| 122 |
|
| 123 |
/** |
| 124 |
* Open an encrypted file store with the given settings. |
| 125 |
* |
| 126 |
* @param handler the data handler |
| 127 |
* @param name the file name |
| 128 |
* @param mode the access mode (r, rw, rws, rwd) |
| 129 |
* @param cipher the name of the cipher algorithm |
| 130 |
* @param key the encryption key |
| 131 |
* @param keyIterations the number of iterations the key should be hashed |
| 132 |
* @return the created object |
| 133 |
*/ |
| 134 |
public static FileStore open(DataHandler handler, String name, String mode, |
| 135 |
String cipher, byte[] key, int keyIterations) { |
| 136 |
FileStore store; |
| 137 |
if (cipher == null) { |
| 138 |
store = new FileStore(handler, name, mode); |
| 139 |
} else { |
| 140 |
store = new SecureFileStore(handler, name, mode, |
| 141 |
cipher, key, keyIterations); |
| 142 |
} |
| 143 |
return store; |
| 144 |
} |
| 145 |
|
| 146 |
/** |
| 147 |
* Generate the random salt bytes if required. |
| 148 |
* |
| 149 |
* @return the random salt or the magic |
| 150 |
*/ |
| 151 |
protected byte[] generateSalt() { |
| 152 |
return HEADER.getBytes(StandardCharsets.UTF_8); |
| 153 |
} |
| 154 |
|
| 155 |
/** |
| 156 |
* Initialize the key using the given salt. |
| 157 |
* |
| 158 |
* @param salt the salt |
| 159 |
*/ |
| 160 |
@SuppressWarnings("unused") |
| 161 |
protected void initKey(byte[] salt) { |
| 162 |
// do nothing |
| 163 |
} |
| 164 |
|
| 165 |
public void setCheckedWriting(boolean value) { |
| 166 |
this.checkedWriting = value; |
| 167 |
} |
| 168 |
|
| 169 |
private void checkWritingAllowed() { |
| 170 |
if (handler != null && checkedWriting) { |
| 171 |
handler.checkWritingAllowed(); |
| 172 |
} |
| 173 |
} |
| 174 |
|
| 175 |
private void checkPowerOff() { |
| 176 |
if (handler != null) { |
| 177 |
handler.checkPowerOff(); |
| 178 |
} |
| 179 |
} |
| 180 |
|
| 181 |
/** |
| 182 |
* Initialize the file. This method will write or check the file header if |
| 183 |
* required. |
| 184 |
*/ |
| 185 |
public void init() { |
| 186 |
int len = Constants.FILE_BLOCK_SIZE; |
| 187 |
byte[] salt; |
| 188 |
byte[] magic = HEADER.getBytes(StandardCharsets.UTF_8); |
| 189 |
if (length() < HEADER_LENGTH) { |
| 190 |
// write unencrypted |
| 191 |
checkedWriting = false; |
| 192 |
writeDirect(magic, 0, len); |
| 193 |
salt = generateSalt(); |
| 194 |
writeDirect(salt, 0, len); |
| 195 |
initKey(salt); |
| 196 |
// write (maybe) encrypted |
| 197 |
write(magic, 0, len); |
| 198 |
checkedWriting = true; |
| 199 |
} else { |
| 200 |
// read unencrypted |
| 201 |
seek(0); |
| 202 |
byte[] buff = new byte[len]; |
| 203 |
readFullyDirect(buff, 0, len); |
| 204 |
if (!Arrays.equals(buff, magic)) { |
| 205 |
throw DbException.get(ErrorCode.FILE_VERSION_ERROR_1, name); |
| 206 |
} |
| 207 |
salt = new byte[len]; |
| 208 |
readFullyDirect(salt, 0, len); |
| 209 |
initKey(salt); |
| 210 |
// read (maybe) encrypted |
| 211 |
readFully(buff, 0, Constants.FILE_BLOCK_SIZE); |
| 212 |
if (!Arrays.equals(buff, magic)) { |
| 213 |
throw DbException.get(ErrorCode.FILE_ENCRYPTION_ERROR_1, name); |
| 214 |
} |
| 215 |
} |
| 216 |
} |
| 217 |
|
| 218 |
/** |
| 219 |
* Close the file. |
| 220 |
*/ |
| 221 |
public void close() { |
| 222 |
if (file != null) { |
| 223 |
try { |
| 224 |
trace("close", name, file); |
| 225 |
file.close(); |
| 226 |
} catch (IOException e) { |
| 227 |
throw DbException.convertIOException(e, name); |
| 228 |
} finally { |
| 229 |
file = null; |
| 230 |
} |
| 231 |
} |
| 232 |
} |
| 233 |
|
| 234 |
/** |
| 235 |
* Close the file without throwing any exceptions. Exceptions are simply |
| 236 |
* ignored. |
| 237 |
*/ |
| 238 |
public void closeSilently() { |
| 239 |
try { |
| 240 |
close(); |
| 241 |
} catch (Exception e) { |
| 242 |
// ignore |
| 243 |
} |
| 244 |
} |
| 245 |
|
| 246 |
/** |
| 247 |
* Close the file (ignoring exceptions) and delete the file. |
| 248 |
*/ |
| 249 |
public void closeAndDeleteSilently() { |
| 250 |
if (file != null) { |
| 251 |
closeSilently(); |
| 252 |
handler.getTempFileDeleter().deleteFile(autoDeleteReference, name); |
| 253 |
name = null; |
| 254 |
} |
| 255 |
} |
| 256 |
|
| 257 |
/** |
| 258 |
* Read a number of bytes without decrypting. |
| 259 |
* |
| 260 |
* @param b the target buffer |
| 261 |
* @param off the offset |
| 262 |
* @param len the number of bytes to read |
| 263 |
*/ |
| 264 |
public void readFullyDirect(byte[] b, int off, int len) { |
| 265 |
readFully(b, off, len); |
| 266 |
} |
| 267 |
|
| 268 |
/** |
| 269 |
* Read a number of bytes. |
| 270 |
* |
| 271 |
* @param b the target buffer |
| 272 |
* @param off the offset |
| 273 |
* @param len the number of bytes to read |
| 274 |
*/ |
| 275 |
public void readFully(byte[] b, int off, int len) { |
| 276 |
if (len < 0 || len % Constants.FILE_BLOCK_SIZE != 0) { |
| 277 |
throw DbException.getInternalError("unaligned read " + name + " len " + len); |
| 278 |
} |
| 279 |
checkPowerOff(); |
| 280 |
try { |
| 281 |
FileUtils.readFully(file, ByteBuffer.wrap(b, off, len)); |
| 282 |
} catch (IOException e) { |
| 283 |
throw DbException.convertIOException(e, name); |
| 284 |
} |
| 285 |
filePos += len; |
| 286 |
} |
| 287 |
|
| 288 |
/** |
| 289 |
* Go to the specified file location. |
| 290 |
* |
| 291 |
* @param pos the location |
| 292 |
*/ |
| 293 |
public void seek(long pos) { |
| 294 |
if (pos % Constants.FILE_BLOCK_SIZE != 0) { |
| 295 |
throw DbException.getInternalError("unaligned seek " + name + " pos " + pos); |
| 296 |
} |
| 297 |
try { |
| 298 |
if (pos != filePos) { |
| 299 |
file.position(pos); |
| 300 |
filePos = pos; |
| 301 |
} |
| 302 |
} catch (IOException e) { |
| 303 |
throw DbException.convertIOException(e, name); |
| 304 |
} |
| 305 |
} |
| 306 |
|
| 307 |
/** |
| 308 |
* Write a number of bytes without encrypting. |
| 309 |
* |
| 310 |
* @param b the source buffer |
| 311 |
* @param off the offset |
| 312 |
* @param len the number of bytes to write |
| 313 |
*/ |
| 314 |
protected void writeDirect(byte[] b, int off, int len) { |
| 315 |
write(b, off, len); |
| 316 |
} |
| 317 |
|
| 318 |
/** |
| 319 |
* Write a number of bytes. |
| 320 |
* |
| 321 |
* @param b the source buffer |
| 322 |
* @param off the offset |
| 323 |
* @param len the number of bytes to write |
| 324 |
*/ |
| 325 |
public void write(byte[] b, int off, int len) { |
| 326 |
if (len < 0 || len % Constants.FILE_BLOCK_SIZE != 0) { |
| 327 |
throw DbException.getInternalError("unaligned write " + name + " len " + len); |
| 328 |
} |
| 329 |
checkWritingAllowed(); |
| 330 |
checkPowerOff(); |
| 331 |
try { |
| 332 |
FileUtils.writeFully(file, ByteBuffer.wrap(b, off, len)); |
| 333 |
} catch (IOException e) { |
| 334 |
closeFileSilently(); |
| 335 |
throw DbException.convertIOException(e, name); |
| 336 |
} |
| 337 |
filePos += len; |
| 338 |
fileLength = Math.max(filePos, fileLength); |
| 339 |
} |
| 340 |
|
| 341 |
/** |
| 342 |
* Set the length of the file. This will expand or shrink the file. |
| 343 |
* |
| 344 |
* @param newLength the new file size |
| 345 |
*/ |
| 346 |
public void setLength(long newLength) { |
| 347 |
if (newLength % Constants.FILE_BLOCK_SIZE != 0) { |
| 348 |
throw DbException.getInternalError("unaligned setLength " + name + " pos " + newLength); |
| 349 |
} |
| 350 |
checkPowerOff(); |
| 351 |
checkWritingAllowed(); |
| 352 |
try { |
| 353 |
if (newLength > fileLength) { |
| 354 |
long pos = filePos; |
| 355 |
file.position(newLength - 1); |
| 356 |
FileUtils.writeFully(file, ByteBuffer.wrap(new byte[1])); |
| 357 |
file.position(pos); |
| 358 |
} else { |
| 359 |
file.truncate(newLength); |
| 360 |
} |
| 361 |
fileLength = newLength; |
| 362 |
} catch (IOException e) { |
| 363 |
closeFileSilently(); |
| 364 |
throw DbException.convertIOException(e, name); |
| 365 |
} |
| 366 |
} |
| 367 |
|
| 368 |
/** |
| 369 |
* Get the file size in bytes. |
| 370 |
* |
| 371 |
* @return the file size |
| 372 |
*/ |
| 373 |
public long length() { |
| 374 |
long len = fileLength; |
| 375 |
if (ASSERT) { |
| 376 |
try { |
| 377 |
len = file.size(); |
| 378 |
if (len != fileLength) { |
| 379 |
throw DbException.getInternalError("file " + name + " length " + len + " expected " + fileLength); |
| 380 |
} |
| 381 |
if (len % Constants.FILE_BLOCK_SIZE != 0) { |
| 382 |
long newLength = len + Constants.FILE_BLOCK_SIZE - |
| 383 |
(len % Constants.FILE_BLOCK_SIZE); |
| 384 |
file.truncate(newLength); |
| 385 |
fileLength = newLength; |
| 386 |
throw DbException.getInternalError("unaligned file length " + name + " len " + len); |
| 387 |
} |
| 388 |
} catch (IOException e) { |
| 389 |
throw DbException.convertIOException(e, name); |
| 390 |
} |
| 391 |
} |
| 392 |
return len; |
| 393 |
} |
| 394 |
|
| 395 |
/** |
| 396 |
* Get the current location of the file pointer. |
| 397 |
* |
| 398 |
* @return the location |
| 399 |
*/ |
| 400 |
public long getFilePointer() { |
| 401 |
if (ASSERT) { |
| 402 |
try { |
| 403 |
if (file.position() != filePos) { |
| 404 |
throw DbException.getInternalError(file.position() + " " + filePos); |
| 405 |
} |
| 406 |
} catch (IOException e) { |
| 407 |
throw DbException.convertIOException(e, name); |
| 408 |
} |
| 409 |
} |
| 410 |
return filePos; |
| 411 |
} |
| 412 |
|
| 413 |
/** |
| 414 |
* Call fsync. Depending on the operating system and hardware, this may or |
| 415 |
* may not in fact write the changes. |
| 416 |
*/ |
| 417 |
public void sync() { |
| 418 |
try { |
| 419 |
file.force(true); |
| 420 |
} catch (IOException e) { |
| 421 |
closeFileSilently(); |
| 422 |
throw DbException.convertIOException(e, name); |
| 423 |
} |
| 424 |
} |
| 425 |
|
| 426 |
/** |
| 427 |
* Automatically delete the file once it is no longer in use. |
| 428 |
*/ |
| 429 |
public void autoDelete() { |
| 430 |
if (autoDeleteReference == null) { |
| 431 |
autoDeleteReference = handler.getTempFileDeleter().addFile(name, this); |
| 432 |
} |
| 433 |
} |
| 434 |
|
| 435 |
/** |
| 436 |
* No longer automatically delete the file once it is no longer in use. |
| 437 |
*/ |
| 438 |
public void stopAutoDelete() { |
| 439 |
handler.getTempFileDeleter().stopAutoDelete(autoDeleteReference, name); |
| 440 |
autoDeleteReference = null; |
| 441 |
} |
| 442 |
|
| 443 |
/** |
| 444 |
* Close the file. The file may later be re-opened using openFile. |
| 445 |
* @throws IOException on failure |
| 446 |
*/ |
| 447 |
public void closeFile() throws IOException { |
| 448 |
file.close(); |
| 449 |
file = null; |
| 450 |
} |
| 451 |
|
| 452 |
/** |
| 453 |
* Just close the file, without setting the reference to null. This method |
| 454 |
* is called when writing failed. The reference is not set to null so that |
| 455 |
* there are no NullPointerExceptions later on. |
| 456 |
*/ |
| 457 |
private void closeFileSilently() { |
| 458 |
try { |
| 459 |
file.close(); |
| 460 |
} catch (IOException e) { |
| 461 |
// ignore |
| 462 |
} |
| 463 |
} |
| 464 |
|
| 465 |
/** |
| 466 |
* Re-open the file. The file pointer will be reset to the previous |
| 467 |
* location. |
| 468 |
* @throws IOException on failure |
| 469 |
*/ |
| 470 |
public void openFile() throws IOException { |
| 471 |
if (file == null) { |
| 472 |
file = FileUtils.open(name, mode); |
| 473 |
file.position(filePos); |
| 474 |
} |
| 475 |
} |
| 476 |
|
| 477 |
private static void trace(String method, String fileName, Object o) { |
| 478 |
if (SysProperties.TRACE_IO) { |
| 479 |
System.out.println("FileStore." + method + " " + fileName + " " + o); |
| 480 |
} |
| 481 |
} |
| 482 |
|
| 483 |
/** |
| 484 |
* Try to lock the file. |
| 485 |
* |
| 486 |
* @return true if successful |
| 487 |
*/ |
| 488 |
public synchronized boolean tryLock() { |
| 489 |
try { |
| 490 |
lock = file.tryLock(); |
| 491 |
return lock != null; |
| 492 |
} catch (Exception e) { |
| 493 |
// ignore OverlappingFileLockException |
| 494 |
return false; |
| 495 |
} |
| 496 |
} |
| 497 |
|
| 498 |
/** |
| 499 |
* Release the file lock. |
| 500 |
*/ |
| 501 |
public synchronized void releaseLock() { |
| 502 |
if (file != null && lock != null) { |
| 503 |
try { |
| 504 |
lock.release(); |
| 505 |
} catch (Exception e) { |
| 506 |
// ignore |
| 507 |
} |
| 508 |
lock = null; |
| 509 |
} |
| 510 |
} |
| 511 |
|
| 512 |
} |