Zlib.swift 18 KB

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