Zlib.swift 13 KB

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