Zlib.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. /*
  2. * Copyright 2024, gRPC Authors All rights reserved.
  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. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import CGRPCZlib
  17. import GRPCCore
  18. import NIOCore
  19. enum Zlib {
  20. enum Method {
  21. case deflate
  22. case gzip
  23. fileprivate var windowBits: Int32 {
  24. switch self {
  25. case .deflate:
  26. return 15
  27. case .gzip:
  28. return 31
  29. }
  30. }
  31. }
  32. }
  33. extension Zlib {
  34. /// Creates a new compressor for the given compression format.
  35. ///
  36. /// This compressor is only suitable for compressing whole messages at a time. Callers
  37. /// must ``initialize()`` the compressor before using it.
  38. struct Compressor {
  39. private var stream: z_stream
  40. private let method: Method
  41. private var isInitialized = false
  42. init(method: Method) {
  43. self.method = method
  44. self.stream = z_stream()
  45. }
  46. /// Initialize the compressor.
  47. mutating func initialize() {
  48. precondition(!self.isInitialized)
  49. self.stream.deflateInit(windowBits: self.method.windowBits)
  50. self.isInitialized = true
  51. }
  52. static func initialized(_ method: Method) -> Self {
  53. var compressor = Compressor(method: method)
  54. compressor.initialize()
  55. return compressor
  56. }
  57. /// Compresses the data in `input` into the `output` buffer.
  58. ///
  59. /// - Parameter input: The complete data to be compressed.
  60. /// - Parameter output: The `ByteBuffer` into which the compressed message should be written.
  61. /// - Returns: The number of bytes written into the `output` buffer.
  62. @discardableResult
  63. mutating func compress(_ input: [UInt8], into output: inout ByteBuffer) throws -> Int {
  64. precondition(self.isInitialized)
  65. defer { self.reset() }
  66. let upperBound = self.stream.deflateBound(inputBytes: input.count)
  67. return try self.stream.deflate(input, into: &output, upperBound: upperBound)
  68. }
  69. /// Resets compression state.
  70. private mutating func reset() {
  71. do {
  72. try self.stream.deflateReset()
  73. } catch {
  74. self.end()
  75. self.stream = z_stream()
  76. self.stream.deflateInit(windowBits: self.method.windowBits)
  77. }
  78. }
  79. /// Deallocates any resources allocated by Zlib.
  80. mutating func end() {
  81. self.stream.deflateEnd()
  82. }
  83. }
  84. }
  85. extension Zlib {
  86. /// Creates a new decompressor for the given compression format.
  87. ///
  88. /// This decompressor is only suitable for compressing whole messages at a time. Callers
  89. /// must ``initialize()`` the decompressor before using it.
  90. struct Decompressor {
  91. private var stream: z_stream
  92. private let method: Method
  93. private var isInitialized = false
  94. init(method: Method) {
  95. self.method = method
  96. self.stream = z_stream()
  97. }
  98. mutating func initialize() {
  99. precondition(!self.isInitialized)
  100. self.stream.inflateInit(windowBits: self.method.windowBits)
  101. self.isInitialized = true
  102. }
  103. /// Returns the decompressed bytes from ``input``.
  104. ///
  105. /// - Parameters:
  106. /// - input: The buffer read compressed bytes from.
  107. /// - limit: The largest size a decompressed payload may be.
  108. mutating func decompress(_ input: inout ByteBuffer, limit: Int) throws -> [UInt8] {
  109. precondition(self.isInitialized)
  110. defer { self.reset() }
  111. return try self.stream.inflate(input: &input, limit: limit)
  112. }
  113. /// Resets decompression state.
  114. private mutating func reset() {
  115. do {
  116. try self.stream.inflateReset()
  117. } catch {
  118. self.end()
  119. self.stream = z_stream()
  120. self.stream.inflateInit(windowBits: self.method.windowBits)
  121. }
  122. }
  123. /// Deallocates any resources allocated by Zlib.
  124. mutating func end() {
  125. self.stream.inflateEnd()
  126. }
  127. }
  128. }
  129. struct ZlibError: Error, Hashable {
  130. /// Error code returned from Zlib.
  131. var code: Int
  132. /// Error message produced by Zlib.
  133. var message: String
  134. init(code: Int, message: String) {
  135. self.code = code
  136. self.message = message
  137. }
  138. }
  139. extension z_stream {
  140. mutating func inflateInit(windowBits: Int32) {
  141. self.zfree = nil
  142. self.zalloc = nil
  143. self.opaque = nil
  144. let rc = CGRPCZlib_inflateInit2(&self, windowBits)
  145. // Possible return codes:
  146. // - Z_OK
  147. // - Z_MEM_ERROR: not enough memory
  148. //
  149. // If we can't allocate memory then we can't progress anyway so not throwing an error here is
  150. // okay.
  151. precondition(rc == Z_OK, "inflateInit2 failed with error (\(rc)) \(self.lastError ?? "")")
  152. }
  153. mutating func inflateReset() throws {
  154. let rc = CGRPCZlib_inflateReset(&self)
  155. // Possible return codes:
  156. // - Z_OK
  157. // - Z_STREAM_ERROR: the source stream state was inconsistent.
  158. switch rc {
  159. case Z_OK:
  160. ()
  161. case Z_STREAM_ERROR:
  162. throw ZlibError(code: Int(rc), message: self.lastError ?? "")
  163. default:
  164. preconditionFailure("inflateReset returned unexpected code (\(rc))")
  165. }
  166. }
  167. mutating func inflateEnd() {
  168. _ = CGRPCZlib_inflateEnd(&self)
  169. }
  170. mutating func deflateInit(windowBits: Int32) {
  171. self.zfree = nil
  172. self.zalloc = nil
  173. self.opaque = nil
  174. let rc = CGRPCZlib_deflateInit2(
  175. &self,
  176. Z_DEFAULT_COMPRESSION, // compression level
  177. Z_DEFLATED, // compression method (this must be Z_DEFLATED)
  178. windowBits, // window size, i.e. deflate/gzip
  179. 8, // memory level (this is the default value in the docs)
  180. Z_DEFAULT_STRATEGY // compression strategy
  181. )
  182. // Possible return codes:
  183. // - Z_OK
  184. // - Z_MEM_ERROR: not enough memory
  185. // - Z_STREAM_ERROR: a parameter was invalid
  186. //
  187. // If we can't allocate memory then we can't progress anyway, and we control the parameters
  188. // so not throwing an error here is okay.
  189. precondition(rc == Z_OK, "deflateInit2 failed with error (\(rc)) \(self.lastError ?? "")")
  190. }
  191. mutating func deflateReset() throws {
  192. let rc = CGRPCZlib_deflateReset(&self)
  193. // Possible return codes:
  194. // - Z_OK
  195. // - Z_STREAM_ERROR: the source stream state was inconsistent.
  196. switch rc {
  197. case Z_OK:
  198. ()
  199. case Z_STREAM_ERROR:
  200. throw ZlibError(code: Int(rc), message: self.lastError ?? "")
  201. default:
  202. preconditionFailure("deflateReset returned unexpected code (\(rc))")
  203. }
  204. }
  205. mutating func deflateEnd() {
  206. _ = CGRPCZlib_deflateEnd(&self)
  207. }
  208. mutating func deflateBound(inputBytes: Int) -> Int {
  209. let bound = CGRPCZlib_deflateBound(&self, UInt(inputBytes))
  210. return Int(bound)
  211. }
  212. mutating func setNextInputBuffer(_ buffer: UnsafeMutableBufferPointer<UInt8>) {
  213. if let baseAddress = buffer.baseAddress {
  214. self.next_in = baseAddress
  215. self.avail_in = UInt32(buffer.count)
  216. } else {
  217. self.next_in = nil
  218. self.avail_in = 0
  219. }
  220. }
  221. mutating func setNextInputBuffer(_ buffer: UnsafeMutableRawBufferPointer?) {
  222. if let buffer = buffer, let baseAddress = buffer.baseAddress {
  223. self.next_in = CGRPCZlib_castVoidToBytefPointer(baseAddress)
  224. self.avail_in = UInt32(buffer.count)
  225. } else {
  226. self.next_in = nil
  227. self.avail_in = 0
  228. }
  229. }
  230. mutating func setNextOutputBuffer(_ buffer: UnsafeMutableBufferPointer<UInt8>) {
  231. if let baseAddress = buffer.baseAddress {
  232. self.next_out = baseAddress
  233. self.avail_out = UInt32(buffer.count)
  234. } else {
  235. self.next_out = nil
  236. self.avail_out = 0
  237. }
  238. }
  239. mutating func setNextOutputBuffer(_ buffer: UnsafeMutableRawBufferPointer?) {
  240. if let buffer = buffer, let baseAddress = buffer.baseAddress {
  241. self.next_out = CGRPCZlib_castVoidToBytefPointer(baseAddress)
  242. self.avail_out = UInt32(buffer.count)
  243. } else {
  244. self.next_out = nil
  245. self.avail_out = 0
  246. }
  247. }
  248. /// Number of bytes available to read `self.nextInputBuffer`. See also: `z_stream.avail_in`.
  249. var availableInputBytes: Int {
  250. get {
  251. Int(self.avail_in)
  252. }
  253. set {
  254. self.avail_in = UInt32(newValue)
  255. }
  256. }
  257. /// The remaining writable space in `nextOutputBuffer`. See also: `z_stream.avail_out`.
  258. var availableOutputBytes: Int {
  259. get {
  260. Int(self.avail_out)
  261. }
  262. set {
  263. self.avail_out = UInt32(newValue)
  264. }
  265. }
  266. /// The total number of bytes written to the output buffer. See also: `z_stream.total_out`.
  267. var totalOutputBytes: Int {
  268. Int(self.total_out)
  269. }
  270. /// The last error message that zlib wrote. No message is guaranteed on error, however, `nil` is
  271. /// guaranteed if there is no error. See also `z_stream.msg`.
  272. var lastError: String? {
  273. self.msg.map { String(cString: $0) }
  274. }
  275. mutating func inflate(input: inout ByteBuffer, limit: Int) throws -> [UInt8] {
  276. return try input.readWithUnsafeMutableReadableBytes { inputPointer in
  277. self.setNextInputBuffer(inputPointer)
  278. defer {
  279. self.setNextInputBuffer(nil)
  280. self.setNextOutputBuffer(nil)
  281. }
  282. // Assume the output will be twice as large as the input.
  283. var output = [UInt8](repeating: 0, count: min(inputPointer.count * 2, limit))
  284. var offset = 0
  285. while true {
  286. let (finished, written) = try output[offset...].withUnsafeMutableBytes { outPointer in
  287. self.setNextOutputBuffer(outPointer)
  288. let finished: Bool
  289. // Possible return codes:
  290. // - Z_OK: some progress has been made
  291. // - Z_STREAM_END: the end of the compressed data has been reached and all uncompressed
  292. // output has been produced
  293. // - Z_NEED_DICT: a preset dictionary is needed at this point
  294. // - Z_DATA_ERROR: the input data was corrupted
  295. // - Z_STREAM_ERROR: the stream structure was inconsistent
  296. // - Z_MEM_ERROR there was not enough memory
  297. // - Z_BUF_ERROR if no progress was possible or if there was not enough room in the output
  298. // buffer when Z_FINISH is used.
  299. //
  300. // Note that Z_OK is not okay here since we always flush with Z_FINISH and therefore
  301. // use Z_STREAM_END as our success criteria.
  302. let rc = CGRPCZlib_inflate(&self, Z_FINISH)
  303. switch rc {
  304. case Z_STREAM_END:
  305. finished = true
  306. case Z_BUF_ERROR:
  307. finished = false
  308. default:
  309. throw RPCError(
  310. code: .internalError,
  311. message: "Decompression error",
  312. cause: ZlibError(code: Int(rc), message: self.lastError ?? "")
  313. )
  314. }
  315. let size = outPointer.count - self.availableOutputBytes
  316. return (finished, size)
  317. }
  318. if finished {
  319. output.removeLast(output.count - self.totalOutputBytes)
  320. let bytesRead = inputPointer.count - self.availableInputBytes
  321. return (bytesRead, output)
  322. } else {
  323. offset += written
  324. let newSize = min(output.count * 2, limit)
  325. if newSize == output.count {
  326. throw RPCError(code: .resourceExhausted, message: "Message is too large to decompress.")
  327. } else {
  328. output.append(contentsOf: repeatElement(0, count: newSize - output.count))
  329. }
  330. }
  331. }
  332. }
  333. }
  334. mutating func deflate(
  335. _ input: [UInt8],
  336. into output: inout ByteBuffer,
  337. upperBound: Int
  338. ) throws -> Int {
  339. defer {
  340. self.setNextInputBuffer(nil)
  341. self.setNextOutputBuffer(nil)
  342. }
  343. var input = input
  344. return try input.withUnsafeMutableBytes { input in
  345. self.setNextInputBuffer(input)
  346. return try output.writeWithUnsafeMutableBytes(minimumWritableBytes: upperBound) { output in
  347. self.setNextOutputBuffer(output)
  348. let rc = CGRPCZlib_deflate(&self, Z_FINISH)
  349. // Possible return codes:
  350. // - Z_OK: some progress has been made
  351. // - Z_STREAM_END: all input has been consumed and all output has been produced (only when
  352. // flush is set to Z_FINISH)
  353. // - Z_STREAM_ERROR: the stream state was inconsistent
  354. // - Z_BUF_ERROR: no progress is possible
  355. //
  356. // The documentation notes that Z_BUF_ERROR is not fatal, and deflate() can be called again
  357. // with more input and more output space to continue compressing. However, we
  358. // call `deflateBound()` before `deflate()` which guarantees that the output size will not be
  359. // larger than the value returned by `deflateBound()` if `Z_FINISH` flush is used. As such,
  360. // the only acceptable outcome is `Z_STREAM_END`.
  361. guard rc == Z_STREAM_END else {
  362. throw RPCError(
  363. code: .internalError,
  364. message: "Compression error",
  365. cause: ZlibError(code: Int(rc), message: self.lastError ?? "")
  366. )
  367. }
  368. return output.count - self.availableOutputBytes
  369. }
  370. }
  371. }
  372. }