Zlib.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. /*
  2. * Copyright 2020, 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 NIOCore
  18. import struct Foundation.Data
  19. /// Provides minimally configurable wrappers around zlib's compression and decompression
  20. /// functionality.
  21. ///
  22. /// See also: https://www.zlib.net/manual.html
  23. enum Zlib {
  24. // MARK: Deflate (compression)
  25. /// Creates a new compressor for the given compression format.
  26. ///
  27. /// This compressor is only suitable for compressing whole messages at a time. Callers
  28. /// must `reset()` the compressor between subsequent calls to `deflate`.
  29. ///
  30. /// - Parameter format:The expected compression type.
  31. class Deflate {
  32. private var stream: ZStream
  33. private let format: CompressionFormat
  34. init(format: CompressionFormat) {
  35. self.stream = ZStream()
  36. self.format = format
  37. self.initialize()
  38. }
  39. deinit {
  40. self.end()
  41. }
  42. /// Compresses the data in `input` into the `output` buffer.
  43. ///
  44. /// - Parameter input: The complete data to be compressed.
  45. /// - Parameter output: The `ByteBuffer` into which the compressed message should be written.
  46. /// - Returns: The number of bytes written into the `output` buffer.
  47. func deflate(_ input: inout ByteBuffer, into output: inout ByteBuffer) throws -> Int {
  48. // Note: This is only valid because we always use Z_FINISH to flush.
  49. //
  50. // From the documentation:
  51. // Note that it is possible for the compressed size to be larger than the value returned
  52. // by deflateBound() if flush options other than Z_FINISH or Z_NO_FLUSH are used.
  53. let upperBound = CGRPCZlib_deflateBound(&self.stream.zstream, UInt(input.readableBytes))
  54. return try input.readWithUnsafeMutableReadableBytes { inputPointer -> (Int, Int) in
  55. self.stream.nextInputBuffer = CGRPCZlib_castVoidToBytefPointer(inputPointer.baseAddress!)
  56. self.stream.availableInputBytes = inputPointer.count
  57. defer {
  58. self.stream.nextInputBuffer = nil
  59. self.stream.availableInputBytes = 0
  60. }
  61. let writtenBytes =
  62. try output
  63. .writeWithUnsafeMutableBytes(minimumWritableBytes: Int(upperBound)) { outputPointer in
  64. try self.stream.deflate(
  65. outputBuffer: CGRPCZlib_castVoidToBytefPointer(outputPointer.baseAddress!),
  66. outputBufferSize: outputPointer.count
  67. )
  68. }
  69. let bytesRead = inputPointer.count - self.stream.availableInputBytes
  70. return (bytesRead, writtenBytes)
  71. }
  72. }
  73. /// Resets compression state. This must be called after each call to `deflate` if more
  74. /// messages are to be compressed by this instance.
  75. func reset() {
  76. let rc = CGRPCZlib_deflateReset(&self.stream.zstream)
  77. // Possible return codes:
  78. // - Z_OK
  79. // - Z_STREAM_ERROR: the source stream state was inconsistent.
  80. //
  81. // If we're in an inconsistent state we can just replace the stream and initialize it.
  82. switch rc {
  83. case Z_OK:
  84. ()
  85. case Z_STREAM_ERROR:
  86. self.end()
  87. self.stream = ZStream()
  88. self.initialize()
  89. default:
  90. preconditionFailure("deflateReset: unexpected return code rc=\(rc)")
  91. }
  92. }
  93. /// Initialize the `z_stream` used for deflate.
  94. private func initialize() {
  95. let rc = CGRPCZlib_deflateInit2(
  96. &self.stream.zstream,
  97. Z_DEFAULT_COMPRESSION, // compression level
  98. Z_DEFLATED, // compression method (this must be Z_DEFLATED)
  99. self.format.windowBits, // window size, i.e. deflate/gzip
  100. 8, // memory level (this is the default value in the docs)
  101. Z_DEFAULT_STRATEGY // compression strategy
  102. )
  103. // Possible return codes:
  104. // - Z_OK
  105. // - Z_MEM_ERROR: not enough memory
  106. // - Z_STREAM_ERROR: a parameter was invalid
  107. //
  108. // If we can't allocate memory then we can't progress anyway, and we control the parameters
  109. // so not throwing an error here is okay.
  110. assert(rc == Z_OK, "deflateInit2 error: rc=\(rc) \(self.stream.lastErrorMessage ?? "")")
  111. }
  112. /// Calls `deflateEnd` on the underlying `z_stream` to deallocate resources allocated by zlib.
  113. private func end() {
  114. _ = CGRPCZlib_deflateEnd(&self.stream.zstream)
  115. // Possible return codes:
  116. // - Z_OK
  117. // - Z_STREAM_ERROR: the source stream state was inconsistent.
  118. //
  119. // Since we're going away there's no reason to fail here.
  120. }
  121. }
  122. // MARK: Inflate (decompression)
  123. /// Creates a new decompressor for the given compression format.
  124. ///
  125. /// This decompressor is only suitable for decompressing whole messages at a time. Callers
  126. /// must `reset()` the decompressor between subsequent calls to `inflate`.
  127. ///
  128. /// - Parameter format:The expected compression type.
  129. class Inflate {
  130. enum InflationState {
  131. /// Inflation is in progress.
  132. case inflating(InflatingState)
  133. /// Inflation completed successfully.
  134. case inflated
  135. init(compressedSize: Int, limit: DecompressionLimit) {
  136. self = .inflating(InflatingState(compressedSize: compressedSize, limit: limit))
  137. }
  138. /// Update the state with the result of `Zlib.ZStream.inflate(outputBuffer:outputBufferSize:)`.
  139. mutating func update(with result: Zlib.ZStream.InflateResult) throws {
  140. switch (result.outcome, self) {
  141. case var (.outputBufferTooSmall, .inflating(state)):
  142. guard state.outputBufferSize < state.maxDecompressedSize else {
  143. // We hit the decompression limit and last time we clamped our output buffer size; we
  144. // can't use a larger buffer without exceeding the limit.
  145. throw GRPCError.DecompressionLimitExceeded(compressedSize: state.compressedSize)
  146. .captureContext()
  147. }
  148. state.increaseOutputBufferSize()
  149. self = .inflating(state)
  150. case let (.complete, .inflating(state)):
  151. // Since we request a _minimum_ output buffer size from `ByteBuffer` it's possible that
  152. // the decompressed size exceeded the decompression limit.
  153. guard result.totalBytesWritten <= state.maxDecompressedSize else {
  154. throw GRPCError.DecompressionLimitExceeded(compressedSize: state.compressedSize)
  155. .captureContext()
  156. }
  157. self = .inflated
  158. case (.complete, .inflated),
  159. (.outputBufferTooSmall, .inflated):
  160. preconditionFailure("invalid outcome '\(result.outcome)'; inflation is already complete")
  161. }
  162. }
  163. }
  164. struct InflatingState {
  165. /// The compressed size of the data to inflate.
  166. let compressedSize: Int
  167. /// The maximum size the decompressed data may be, according to the user-defined
  168. /// decompression limit.
  169. let maxDecompressedSize: Int
  170. /// The minimum size requested for the output buffer.
  171. private(set) var outputBufferSize: Int
  172. init(compressedSize: Int, limit: DecompressionLimit) {
  173. self.compressedSize = compressedSize
  174. self.maxDecompressedSize = limit.maximumDecompressedSize(compressedSize: compressedSize)
  175. self.outputBufferSize = compressedSize
  176. self.increaseOutputBufferSize()
  177. }
  178. /// Increase the output buffer size without exceeding `maxDecompressedSize`.
  179. mutating func increaseOutputBufferSize() {
  180. let nextOutputBufferSize = 2 * self.outputBufferSize
  181. if nextOutputBufferSize > self.maxDecompressedSize {
  182. self.outputBufferSize = self.maxDecompressedSize
  183. } else {
  184. self.outputBufferSize = nextOutputBufferSize
  185. }
  186. }
  187. }
  188. private var stream: ZStream
  189. private let format: CompressionFormat
  190. private let limit: DecompressionLimit
  191. init(format: CompressionFormat, limit: DecompressionLimit) {
  192. self.stream = ZStream()
  193. self.format = format
  194. self.limit = limit
  195. self.initialize()
  196. }
  197. deinit {
  198. self.end()
  199. }
  200. /// Resets decompression state. This must be called after each call to `inflate` if more
  201. /// messages are to be decompressed by this instance.
  202. func reset() {
  203. let rc = CGRPCZlib_inflateReset(&self.stream.zstream)
  204. // Possible return codes:
  205. // - Z_OK
  206. // - Z_STREAM_ERROR: the source stream state was inconsistent.
  207. //
  208. // If we're in an inconsistent state we can just replace the stream and initialize it.
  209. switch rc {
  210. case Z_OK:
  211. ()
  212. case Z_STREAM_ERROR:
  213. self.end()
  214. self.stream = ZStream()
  215. self.initialize()
  216. default:
  217. preconditionFailure("inflateReset: unexpected return code rc=\(rc)")
  218. }
  219. }
  220. /// Inflate the readable bytes from the `input` buffer into the `output` buffer.
  221. ///
  222. /// - Parameters:
  223. /// - input: The buffer read compressed bytes from.
  224. /// - output: The buffer to write the decompressed bytes into.
  225. /// - Returns: The number of bytes written into `output`.
  226. @discardableResult
  227. func inflate(_ input: inout ByteBuffer, into output: inout ByteBuffer) throws -> Int {
  228. return try input.readWithUnsafeMutableReadableBytes { inputPointer -> (Int, Int) in
  229. // Setup the input buffer.
  230. self.stream.availableInputBytes = inputPointer.count
  231. self.stream.nextInputBuffer = CGRPCZlib_castVoidToBytefPointer(inputPointer.baseAddress!)
  232. defer {
  233. self.stream.availableInputBytes = 0
  234. self.stream.nextInputBuffer = nil
  235. }
  236. var bytesWritten = 0
  237. var state = InflationState(compressedSize: inputPointer.count, limit: self.limit)
  238. while case let .inflating(inflationState) = state {
  239. // Each call to inflate writes into the buffer, so we need to take the writer index into
  240. // account here.
  241. let writerIndex = output.writerIndex
  242. let minimumWritableBytes = inflationState.outputBufferSize - writerIndex
  243. bytesWritten =
  244. try output
  245. .writeWithUnsafeMutableBytes(minimumWritableBytes: minimumWritableBytes) {
  246. outputPointer in
  247. let inflateResult = try self.stream.inflate(
  248. outputBuffer: CGRPCZlib_castVoidToBytefPointer(outputPointer.baseAddress!),
  249. outputBufferSize: outputPointer.count
  250. )
  251. try state.update(with: inflateResult)
  252. return inflateResult.bytesWritten
  253. }
  254. }
  255. let bytesRead = inputPointer.count - self.stream.availableInputBytes
  256. return (bytesRead, bytesWritten)
  257. }
  258. }
  259. private func initialize() {
  260. let rc = CGRPCZlib_inflateInit2(&self.stream.zstream, self.format.windowBits)
  261. // Possible return codes:
  262. // - Z_OK
  263. // - Z_MEM_ERROR: not enough memory
  264. //
  265. // If we can't allocate memory then we can't progress anyway so not throwing an error here is
  266. // okay.
  267. precondition(rc == Z_OK, "inflateInit2 error: rc=\(rc) \(self.stream.lastErrorMessage ?? "")")
  268. }
  269. func end() {
  270. _ = CGRPCZlib_inflateEnd(&self.stream.zstream)
  271. // Possible return codes:
  272. // - Z_OK
  273. // - Z_STREAM_ERROR: the source stream state was inconsistent.
  274. //
  275. // Since we're going away there's no reason to fail here.
  276. }
  277. }
  278. // MARK: ZStream
  279. /// This wraps a zlib `z_stream` to provide more Swift-like access to the underlying C-struct.
  280. struct ZStream {
  281. var zstream: z_stream
  282. init() {
  283. self.zstream = z_stream()
  284. self.zstream.next_in = nil
  285. self.zstream.avail_in = 0
  286. self.zstream.next_out = nil
  287. self.zstream.avail_out = 0
  288. self.zstream.zalloc = nil
  289. self.zstream.zfree = nil
  290. self.zstream.opaque = nil
  291. }
  292. /// Number of bytes available to read `self.nextInputBuffer`. See also: `z_stream.avail_in`.
  293. var availableInputBytes: Int {
  294. get {
  295. return Int(self.zstream.avail_in)
  296. }
  297. set {
  298. self.zstream.avail_in = UInt32(newValue)
  299. }
  300. }
  301. /// The next input buffer that zlib should read from. See also: `z_stream.next_in`.
  302. var nextInputBuffer: UnsafeMutablePointer<Bytef>! {
  303. get {
  304. return self.zstream.next_in
  305. }
  306. set {
  307. self.zstream.next_in = newValue
  308. }
  309. }
  310. /// The remaining writable space in `nextOutputBuffer`. See also: `z_stream.avail_out`.
  311. var availableOutputBytes: Int {
  312. get {
  313. return Int(self.zstream.avail_out)
  314. }
  315. set {
  316. self.zstream.avail_out = UInt32(newValue)
  317. return
  318. }
  319. }
  320. /// The next output buffer where zlib should write bytes to. See also: `z_stream.next_out`.
  321. var nextOutputBuffer: UnsafeMutablePointer<Bytef>! {
  322. get {
  323. return self.zstream.next_out
  324. }
  325. set {
  326. self.zstream.next_out = newValue
  327. }
  328. }
  329. /// The total number of bytes written to the output buffer. See also: `z_stream.total_out`.
  330. var totalOutputBytes: Int {
  331. return Int(self.zstream.total_out)
  332. }
  333. /// The last error message that zlib wrote. No message is guaranteed on error, however, `nil` is
  334. /// guaranteed if there is no error. See also `z_stream.msg`.
  335. var lastErrorMessage: String? {
  336. guard let bytes = self.zstream.msg else {
  337. return nil
  338. }
  339. return String(cString: bytes)
  340. }
  341. enum InflateOutcome {
  342. /// The data was successfully inflated.
  343. case complete
  344. /// A larger output buffer is required.
  345. case outputBufferTooSmall
  346. }
  347. struct InflateResult {
  348. var bytesWritten: Int
  349. var totalBytesWritten: Int
  350. var outcome: InflateOutcome
  351. }
  352. /// Decompress the stream into the given output buffer.
  353. ///
  354. /// - Parameter outputBuffer: The buffer into which to write the decompressed data.
  355. /// - Parameter outputBufferSize: The space available in `outputBuffer`.
  356. /// - Returns: The result of the `inflate`, whether it was successful or whether a larger
  357. /// output buffer is required.
  358. mutating func inflate(
  359. outputBuffer: UnsafeMutablePointer<UInt8>,
  360. outputBufferSize: Int
  361. ) throws -> InflateResult {
  362. self.nextOutputBuffer = outputBuffer
  363. self.availableOutputBytes = outputBufferSize
  364. defer {
  365. self.nextOutputBuffer = nil
  366. self.availableOutputBytes = 0
  367. }
  368. let rc = CGRPCZlib_inflate(&self.zstream, Z_FINISH)
  369. let outcome: InflateOutcome
  370. // Possible return codes:
  371. // - Z_OK: some progress has been made
  372. // - Z_STREAM_END: the end of the compressed data has been reached and all uncompressed output
  373. // has been produced
  374. // - Z_NEED_DICT: a preset dictionary is needed at this point
  375. // - Z_DATA_ERROR: the input data was corrupted
  376. // - Z_STREAM_ERROR: the stream structure was inconsistent
  377. // - Z_MEM_ERROR there was not enough memory
  378. // - Z_BUF_ERROR if no progress was possible or if there was not enough room in the output
  379. // buffer when Z_FINISH is used.
  380. //
  381. // Note that Z_OK is not okay here since we always flush with Z_FINISH and therefore
  382. // use Z_STREAM_END as our success criteria.
  383. switch rc {
  384. case Z_STREAM_END:
  385. outcome = .complete
  386. case Z_BUF_ERROR:
  387. outcome = .outputBufferTooSmall
  388. default:
  389. throw GRPCError.ZlibCompressionFailure(code: rc, message: self.lastErrorMessage)
  390. .captureContext()
  391. }
  392. return InflateResult(
  393. bytesWritten: outputBufferSize - self.availableOutputBytes,
  394. totalBytesWritten: self.totalOutputBytes,
  395. outcome: outcome
  396. )
  397. }
  398. /// Compresses the `inputBuffer` into the `outputBuffer`.
  399. ///
  400. /// `outputBuffer` must be large enough to store the compressed data, `deflateBound()` provides
  401. /// an upper bound for this value.
  402. ///
  403. /// - Parameter outputBuffer: The buffer into which to write the compressed data.
  404. /// - Parameter outputBufferSize: The space available in `outputBuffer`.
  405. /// - Returns: The number of bytes written into the `outputBuffer`.
  406. mutating func deflate(
  407. outputBuffer: UnsafeMutablePointer<UInt8>,
  408. outputBufferSize: Int
  409. ) throws -> Int {
  410. self.nextOutputBuffer = outputBuffer
  411. self.availableOutputBytes = outputBufferSize
  412. defer {
  413. self.nextOutputBuffer = nil
  414. self.availableOutputBytes = 0
  415. }
  416. let rc = CGRPCZlib_deflate(&self.zstream, Z_FINISH)
  417. // Possible return codes:
  418. // - Z_OK: some progress has been made
  419. // - Z_STREAM_END: all input has been consumed and all output has been produced (only when
  420. // flush is set to Z_FINISH)
  421. // - Z_STREAM_ERROR: the stream state was inconsistent
  422. // - Z_BUF_ERROR: no progress is possible
  423. //
  424. // The documentation notes that Z_BUF_ERROR is not fatal, and deflate() can be called again
  425. // with more input and more output space to continue compressing. However, we
  426. // call `deflateBound()` before `deflate()` which guarantees that the output size will not be
  427. // larger than the value returned by `deflateBound()` if `Z_FINISH` flush is used. As such,
  428. // the only acceptable outcome is `Z_STREAM_END`.
  429. guard rc == Z_STREAM_END else {
  430. throw GRPCError.ZlibCompressionFailure(code: rc, message: self.lastErrorMessage)
  431. .captureContext()
  432. }
  433. return outputBufferSize - self.availableOutputBytes
  434. }
  435. }
  436. enum CompressionFormat {
  437. case deflate
  438. case gzip
  439. var windowBits: Int32 {
  440. switch self {
  441. case .deflate:
  442. return 15
  443. case .gzip:
  444. return 31
  445. }
  446. }
  447. }
  448. }