Zlib.swift 14 KB

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