DeflateStream.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. /* -*- Mode: csharp; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
  2. //
  3. // DeflateStream.cs
  4. //
  5. // Authors:
  6. // Christopher James Lahey <[email protected]>
  7. // Gonzalo Paniagua Javier ([email protected])
  8. // Marek Safar ([email protected])
  9. //
  10. // (c) Copyright 2004,2009 Novell, Inc. <http://www.novell.com>
  11. // Copyright (C) 2013 Xamarin Inc (http://www.xamarin.com)
  12. //
  13. // Permission is hereby granted, free of charge, to any person obtaining
  14. // a copy of this software and associated documentation files (the
  15. // "Software"), to deal in the Software without restriction, including
  16. // without limitation the rights to use, copy, modify, merge, publish,
  17. // distribute, sublicense, and/or sell copies of the Software, and to
  18. // permit persons to whom the Software is furnished to do so, subject to
  19. // the following conditions:
  20. //
  21. // The above copyright notice and this permission notice shall be
  22. // included in all copies or substantial portions of the Software.
  23. //
  24. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  25. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  27. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  28. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  29. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  30. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  31. //
  32. using System;
  33. using System.IO;
  34. using System.Runtime.InteropServices;
  35. using System.Runtime.Remoting.Messaging;
  36. using System.Threading;
  37. using System.Threading.Tasks;
  38. namespace System.IO.Compression
  39. {
  40. public class DeflateStream : Stream
  41. {
  42. delegate int ReadMethod (byte[] array, int offset, int count);
  43. delegate void WriteMethod (byte[] array, int offset, int count);
  44. Stream base_stream;
  45. CompressionMode mode;
  46. bool leaveOpen;
  47. bool disposed;
  48. DeflateStreamNative native;
  49. public DeflateStream (Stream stream, CompressionMode mode) :
  50. this (stream, mode, false, false)
  51. {
  52. }
  53. public DeflateStream (Stream stream, CompressionMode mode, bool leaveOpen) :
  54. this (stream, mode, leaveOpen, false)
  55. {
  56. }
  57. internal DeflateStream (Stream stream, CompressionMode mode, bool leaveOpen, int windowsBits) :
  58. this (stream, mode, leaveOpen, true)
  59. {
  60. }
  61. internal DeflateStream (Stream compressedStream, CompressionMode mode, bool leaveOpen, bool gzip)
  62. {
  63. if (compressedStream == null)
  64. throw new ArgumentNullException ("compressedStream");
  65. if (mode != CompressionMode.Compress && mode != CompressionMode.Decompress)
  66. throw new ArgumentException ("mode");
  67. this.base_stream = compressedStream;
  68. this.native = DeflateStreamNative.Create (compressedStream, mode, gzip);
  69. if (this.native == null) {
  70. throw new NotImplementedException ("Failed to initialize zlib. You probably have an old zlib installed. Version 1.2.0.4 or later is required.");
  71. }
  72. this.mode = mode;
  73. this.leaveOpen = leaveOpen;
  74. }
  75. public DeflateStream (Stream stream, CompressionLevel compressionLevel)
  76. : this (stream, compressionLevel, false, false)
  77. {
  78. }
  79. public DeflateStream (Stream stream, CompressionLevel compressionLevel, bool leaveOpen)
  80. : this (stream, compressionLevel, leaveOpen, false)
  81. {
  82. }
  83. internal DeflateStream (Stream stream, CompressionLevel compressionLevel, bool leaveOpen, int windowsBits)
  84. : this (stream, compressionLevel, leaveOpen, true)
  85. {
  86. }
  87. internal DeflateStream (Stream stream, CompressionLevel compressionLevel, bool leaveOpen, bool gzip)
  88. : this (stream, CompressionMode.Compress, leaveOpen, gzip)
  89. {
  90. }
  91. protected override void Dispose (bool disposing)
  92. {
  93. native.Dispose (disposing);
  94. if (disposing && !disposed) {
  95. disposed = true;
  96. if (!leaveOpen) {
  97. Stream st = base_stream;
  98. if (st != null)
  99. st.Close ();
  100. base_stream = null;
  101. }
  102. }
  103. base.Dispose (disposing);
  104. }
  105. unsafe int ReadInternal (byte[] array, int offset, int count)
  106. {
  107. if (count == 0)
  108. return 0;
  109. fixed (byte *b = array) {
  110. IntPtr ptr = new IntPtr (b + offset);
  111. return native.ReadZStream (ptr, count);
  112. }
  113. }
  114. internal ValueTask<int> ReadAsyncMemory (Memory<byte> destination, CancellationToken cancellationToken)
  115. {
  116. throw new NotImplementedException ();
  117. }
  118. internal int ReadCore (Span<byte> destination)
  119. {
  120. throw new NotImplementedException ();
  121. }
  122. public override int Read (byte[] array, int offset, int count)
  123. {
  124. if (disposed)
  125. throw new ObjectDisposedException (GetType ().FullName);
  126. if (array == null)
  127. throw new ArgumentNullException ("Destination array is null.");
  128. if (!CanRead)
  129. throw new InvalidOperationException ("Stream does not support reading.");
  130. int len = array.Length;
  131. if (offset < 0 || count < 0)
  132. throw new ArgumentException ("Dest or count is negative.");
  133. if (offset > len)
  134. throw new ArgumentException ("destination offset is beyond array size");
  135. if ((offset + count) > len)
  136. throw new ArgumentException ("Reading would overrun buffer");
  137. return ReadInternal (array, offset, count);
  138. }
  139. unsafe void WriteInternal (byte[] array, int offset, int count)
  140. {
  141. if (count == 0)
  142. return;
  143. fixed (byte *b = array) {
  144. IntPtr ptr = new IntPtr (b + offset);
  145. native.WriteZStream (ptr, count);
  146. }
  147. }
  148. internal Task WriteAsyncMemory (ReadOnlyMemory<byte> source, CancellationToken cancellationToken)
  149. {
  150. throw new NotImplementedException ();
  151. }
  152. internal void WriteCore (ReadOnlySpan<byte> source)
  153. {
  154. throw new NotImplementedException ();
  155. }
  156. public override void Write (byte[] array, int offset, int count)
  157. {
  158. if (disposed)
  159. throw new ObjectDisposedException (GetType ().FullName);
  160. if (array == null)
  161. throw new ArgumentNullException ("array");
  162. if (offset < 0)
  163. throw new ArgumentOutOfRangeException ("offset");
  164. if (count < 0)
  165. throw new ArgumentOutOfRangeException ("count");
  166. if (!CanWrite)
  167. throw new NotSupportedException ("Stream does not support writing");
  168. if (offset > array.Length - count)
  169. throw new ArgumentException ("Buffer too small. count/offset wrong.");
  170. WriteInternal (array, offset, count);
  171. }
  172. public override void Flush ()
  173. {
  174. if (disposed)
  175. throw new ObjectDisposedException (GetType ().FullName);
  176. if (CanWrite) {
  177. native.Flush ();
  178. }
  179. }
  180. public override IAsyncResult BeginRead (byte [] array, int offset, int count,
  181. AsyncCallback asyncCallback, object asyncState)
  182. {
  183. if (disposed)
  184. throw new ObjectDisposedException (GetType ().FullName);
  185. if (!CanRead)
  186. throw new NotSupportedException ("This stream does not support reading");
  187. if (array == null)
  188. throw new ArgumentNullException ("array");
  189. if (count < 0)
  190. throw new ArgumentOutOfRangeException ("count", "Must be >= 0");
  191. if (offset < 0)
  192. throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
  193. if (count + offset > array.Length)
  194. throw new ArgumentException ("Buffer too small. count/offset wrong.");
  195. ReadMethod r = new ReadMethod (ReadInternal);
  196. return r.BeginInvoke (array, offset, count, asyncCallback, asyncState);
  197. }
  198. public override IAsyncResult BeginWrite (byte [] array, int offset, int count,
  199. AsyncCallback asyncCallback, object asyncState)
  200. {
  201. if (disposed)
  202. throw new ObjectDisposedException (GetType ().FullName);
  203. if (!CanWrite)
  204. throw new InvalidOperationException ("This stream does not support writing");
  205. if (array == null)
  206. throw new ArgumentNullException ("array");
  207. if (count < 0)
  208. throw new ArgumentOutOfRangeException ("count", "Must be >= 0");
  209. if (offset < 0)
  210. throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
  211. if (count + offset > array.Length)
  212. throw new ArgumentException ("Buffer too small. count/offset wrong.");
  213. WriteMethod w = new WriteMethod (WriteInternal);
  214. return w.BeginInvoke (array, offset, count, asyncCallback, asyncState);
  215. }
  216. public override int EndRead(IAsyncResult asyncResult)
  217. {
  218. if (asyncResult == null)
  219. throw new ArgumentNullException ("asyncResult");
  220. AsyncResult ares = asyncResult as AsyncResult;
  221. if (ares == null)
  222. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  223. ReadMethod r = ares.AsyncDelegate as ReadMethod;
  224. if (r == null)
  225. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  226. return r.EndInvoke (asyncResult);
  227. }
  228. public override void EndWrite (IAsyncResult asyncResult)
  229. {
  230. if (asyncResult == null)
  231. throw new ArgumentNullException ("asyncResult");
  232. AsyncResult ares = asyncResult as AsyncResult;
  233. if (ares == null)
  234. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  235. WriteMethod w = ares.AsyncDelegate as WriteMethod;
  236. if (w == null)
  237. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  238. w.EndInvoke (asyncResult);
  239. return;
  240. }
  241. public override long Seek (long offset, SeekOrigin origin)
  242. {
  243. throw new NotSupportedException();
  244. }
  245. public override void SetLength (long value)
  246. {
  247. throw new NotSupportedException();
  248. }
  249. public Stream BaseStream {
  250. get { return base_stream; }
  251. }
  252. public override bool CanRead {
  253. get { return !disposed && mode == CompressionMode.Decompress && base_stream.CanRead; }
  254. }
  255. public override bool CanSeek {
  256. get { return false; }
  257. }
  258. public override bool CanWrite {
  259. get { return !disposed && mode == CompressionMode.Compress && base_stream.CanWrite; }
  260. }
  261. public override long Length {
  262. get { throw new NotSupportedException(); }
  263. }
  264. public override long Position {
  265. get { throw new NotSupportedException(); }
  266. set { throw new NotSupportedException(); }
  267. }
  268. }
  269. class DeflateStreamNative
  270. {
  271. const int BufferSize = 4096;
  272. [UnmanagedFunctionPointer (CallingConvention.Cdecl)]
  273. delegate int UnmanagedReadOrWrite (IntPtr buffer, int length, IntPtr data);
  274. UnmanagedReadOrWrite feeder; // This will be passed to unmanaged code and used there
  275. Stream base_stream;
  276. SafeDeflateStreamHandle z_stream;
  277. GCHandle data;
  278. bool disposed;
  279. byte [] io_buffer;
  280. private DeflateStreamNative ()
  281. {
  282. }
  283. public static DeflateStreamNative Create (Stream compressedStream, CompressionMode mode, bool gzip)
  284. {
  285. var dsn = new DeflateStreamNative ();
  286. dsn.data = GCHandle.Alloc (dsn);
  287. dsn.feeder = mode == CompressionMode.Compress ? new UnmanagedReadOrWrite (UnmanagedWrite) : new UnmanagedReadOrWrite (UnmanagedRead);
  288. dsn.z_stream = CreateZStream (mode, gzip, dsn.feeder, GCHandle.ToIntPtr (dsn.data));
  289. if (dsn.z_stream.IsInvalid) {
  290. dsn.Dispose (true);
  291. return null;
  292. }
  293. dsn.base_stream = compressedStream;
  294. return dsn;
  295. }
  296. ~DeflateStreamNative ()
  297. {
  298. Dispose (false);
  299. }
  300. public void Dispose (bool disposing)
  301. {
  302. if (disposing && !disposed) {
  303. disposed = true;
  304. GC.SuppressFinalize (this);
  305. io_buffer = null;
  306. z_stream.Dispose();
  307. }
  308. if (data.IsAllocated) {
  309. data.Free ();
  310. }
  311. }
  312. public void Flush ()
  313. {
  314. var res = Flush (z_stream);
  315. CheckResult (res, "Flush");
  316. }
  317. public int ReadZStream (IntPtr buffer, int length)
  318. {
  319. var res = ReadZStream (z_stream, buffer, length);
  320. CheckResult (res, "ReadInternal");
  321. return res;
  322. }
  323. public void WriteZStream (IntPtr buffer, int length)
  324. {
  325. var res = WriteZStream (z_stream, buffer, length);
  326. CheckResult (res, "WriteInternal");
  327. }
  328. [Mono.Util.MonoPInvokeCallback (typeof (UnmanagedReadOrWrite))]
  329. static int UnmanagedRead (IntPtr buffer, int length, IntPtr data)
  330. {
  331. GCHandle s = GCHandle.FromIntPtr (data);
  332. var self = s.Target as DeflateStreamNative;
  333. if (self == null)
  334. return -1;
  335. return self.UnmanagedRead (buffer, length);
  336. }
  337. int UnmanagedRead (IntPtr buffer, int length)
  338. {
  339. if (io_buffer == null)
  340. io_buffer = new byte [BufferSize];
  341. int count = Math.Min (length, io_buffer.Length);
  342. int n = base_stream.Read (io_buffer, 0, count);
  343. if (n > 0)
  344. Marshal.Copy (io_buffer, 0, buffer, n);
  345. return n;
  346. }
  347. [Mono.Util.MonoPInvokeCallback (typeof (UnmanagedReadOrWrite))]
  348. static int UnmanagedWrite (IntPtr buffer, int length, IntPtr data)
  349. {
  350. GCHandle s = GCHandle.FromIntPtr (data);
  351. var self = s.Target as DeflateStreamNative;
  352. if (self == null)
  353. return -1;
  354. return self.UnmanagedWrite (buffer, length);
  355. }
  356. int UnmanagedWrite (IntPtr buffer, int length)
  357. {
  358. int total = 0;
  359. while (length > 0) {
  360. if (io_buffer == null)
  361. io_buffer = new byte [BufferSize];
  362. int count = Math.Min (length, io_buffer.Length);
  363. Marshal.Copy (buffer, io_buffer, 0, count);
  364. base_stream.Write (io_buffer, 0, count);
  365. unsafe {
  366. buffer = new IntPtr ((byte *) buffer.ToPointer () + count);
  367. }
  368. length -= count;
  369. total += count;
  370. }
  371. return total;
  372. }
  373. static void CheckResult (int result, string where)
  374. {
  375. if (result >= 0)
  376. return;
  377. string error;
  378. switch (result) {
  379. case -1: // Z_ERRNO
  380. error = "Unknown error"; // Marshal.GetLastWin32() ?
  381. break;
  382. case -2: // Z_STREAM_ERROR
  383. error = "Internal error";
  384. break;
  385. case -3: // Z_DATA_ERROR
  386. error = "Corrupted data";
  387. break;
  388. case -4: // Z_MEM_ERROR
  389. error = "Not enough memory";
  390. break;
  391. case -5: // Z_BUF_ERROR
  392. error = "Internal error (no progress possible)";
  393. break;
  394. case -6: // Z_VERSION_ERROR
  395. error = "Invalid version";
  396. break;
  397. case -10:
  398. error = "Invalid argument(s)";
  399. break;
  400. case -11:
  401. error = "IO error";
  402. break;
  403. default:
  404. error = "Unknown error";
  405. break;
  406. }
  407. throw new IOException (error + " " + where);
  408. }
  409. #if MONOTOUCH || MONODROID
  410. const string LIBNAME = "__Internal";
  411. #else
  412. const string LIBNAME = "MonoPosixHelper";
  413. #endif
  414. #if !ORBIS
  415. [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
  416. static extern SafeDeflateStreamHandle CreateZStream (CompressionMode compress, bool gzip, UnmanagedReadOrWrite feeder, IntPtr data);
  417. [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
  418. static extern int CloseZStream (IntPtr stream);
  419. [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
  420. static extern int Flush (SafeDeflateStreamHandle stream);
  421. [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
  422. static extern int ReadZStream (SafeDeflateStreamHandle stream, IntPtr buffer, int length);
  423. [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
  424. static extern int WriteZStream (SafeDeflateStreamHandle stream, IntPtr buffer, int length);
  425. #else
  426. static SafeDeflateStreamHandle CreateZStream (CompressionMode compress, bool gzip, UnmanagedReadOrWrite feeder, IntPtr data)
  427. {
  428. throw new PlatformNotSupportedException ();
  429. }
  430. static int CloseZStream (IntPtr stream)
  431. {
  432. throw new PlatformNotSupportedException ();
  433. }
  434. static int Flush (SafeDeflateStreamHandle stream)
  435. {
  436. throw new PlatformNotSupportedException ();
  437. }
  438. static int ReadZStream (SafeDeflateStreamHandle stream, IntPtr buffer, int length)
  439. {
  440. throw new PlatformNotSupportedException ();
  441. }
  442. static int WriteZStream (SafeDeflateStreamHandle stream, IntPtr buffer, int length)
  443. {
  444. throw new PlatformNotSupportedException ();
  445. }
  446. #endif
  447. sealed class SafeDeflateStreamHandle : SafeHandle
  448. {
  449. public override bool IsInvalid
  450. {
  451. get { return handle == IntPtr.Zero; }
  452. }
  453. private SafeDeflateStreamHandle() : base(IntPtr.Zero, true)
  454. {
  455. }
  456. override protected bool ReleaseHandle()
  457. {
  458. DeflateStreamNative.CloseZStream(handle);
  459. return true;
  460. }
  461. }
  462. }
  463. }