Zlib.swift 18 KB

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