Zlib.swift 13 KB

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