File.swift 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // File.swift
  2. // This file is part of KeePassKit.
  3. //
  4. // Copyright © 2019 Maxime Epain. All rights reserved.
  5. //
  6. // KeePassKit is free software: you can redistribute it and/or modify
  7. // it under the terms of the GNU General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // KeePassKit is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU General Public License
  17. // along with KeePassKit. If not, see <https://www.gnu.org/licenses/>.
  18. import Foundation
  19. import Binary
  20. public let FileSignature: UInt32 = 0x9AA2D903
  21. public let BetaFileFormat: UInt32 = 0xB54BFB66
  22. public let FileFormat: UInt32 = 0xB54BFB67
  23. public struct Version {
  24. let major: UInt16
  25. let minor: UInt16
  26. }
  27. public class File {
  28. public let version: Version
  29. public let database: Database & Writable
  30. public required init(from input: Input, compositeKey: CompositeKey) throws {
  31. version = try input.read()
  32. if version.major > 3 {
  33. database = try Database4(from: input, compositeKey: compositeKey)
  34. } else {
  35. database = try Database3(from: input, compositeKey: compositeKey)
  36. }
  37. }
  38. public convenience init(from file: URL, compositeKey: CompositeKey) throws {
  39. let bytes = try Bytes(contentsOf: file)
  40. let stream = Input(bytes: bytes)
  41. guard try stream.read() == FileSignature else { throw KDBXError.invalidFileFormat }
  42. let format = try stream.read() as UInt32
  43. guard
  44. format == BetaFileFormat ||
  45. format == FileFormat
  46. else { throw KDBXError.invalidFileFormat }
  47. try self.init(from: stream, compositeKey: compositeKey)
  48. }
  49. }
  50. extension File: Writable {
  51. public func write(to output: Output) throws {
  52. try output.write(version)
  53. // `try output.write(version)` error: Protocol type 'Writable & Database' cannot conform to 'Writable' because only concrete types can conform to protocols
  54. try database.write(to: output)
  55. }
  56. }
  57. extension Version: Streamable {
  58. public init(from input: Input) throws {
  59. minor = try input.read()
  60. major = try input.read()
  61. }
  62. public func write(to output: Output) throws {
  63. try output.write(minor)
  64. try output.write(major)
  65. }
  66. }