DeflateStream.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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. namespace System.IO.Compression
  37. {
  38. public class DeflateStream : Stream
  39. {
  40. delegate int ReadMethod (byte[] array, int offset, int count);
  41. delegate void WriteMethod (byte[] array, int offset, int count);
  42. Stream base_stream;
  43. CompressionMode mode;
  44. bool leaveOpen;
  45. bool disposed;
  46. DeflateStreamNative native;
  47. public DeflateStream (Stream stream, CompressionMode mode) :
  48. this (stream, mode, false, false)
  49. {
  50. }
  51. public DeflateStream (Stream stream, CompressionMode mode, bool leaveOpen) :
  52. this (stream, mode, leaveOpen, false)
  53. {
  54. }
  55. internal DeflateStream (Stream stream, CompressionMode mode, bool leaveOpen, int windowsBits) :
  56. this (stream, mode, leaveOpen, true)
  57. {
  58. }
  59. internal DeflateStream (Stream compressedStream, CompressionMode mode, bool leaveOpen, bool gzip)
  60. {
  61. if (compressedStream == null)
  62. throw new ArgumentNullException ("compressedStream");
  63. if (mode != CompressionMode.Compress && mode != CompressionMode.Decompress)
  64. throw new ArgumentException ("mode");
  65. this.base_stream = compressedStream;
  66. this.native = DeflateStreamNative.Create (compressedStream, mode, gzip);
  67. if (this.native == null) {
  68. throw new NotImplementedException ("Failed to initialize zlib. You probably have an old zlib installed. Version 1.2.0.4 or later is required.");
  69. }
  70. this.mode = mode;
  71. this.leaveOpen = leaveOpen;
  72. }
  73. public DeflateStream (Stream stream, CompressionLevel compressionLevel)
  74. : this (stream, compressionLevel, false, false)
  75. {
  76. }
  77. public DeflateStream (Stream stream, CompressionLevel compressionLevel, bool leaveOpen)
  78. : this (stream, compressionLevel, leaveOpen, false)
  79. {
  80. }
  81. internal DeflateStream (Stream stream, CompressionLevel compressionLevel, bool leaveOpen, int windowsBits)
  82. : this (stream, compressionLevel, leaveOpen, true)
  83. {
  84. }
  85. internal DeflateStream (Stream stream, CompressionLevel compressionLevel, bool leaveOpen, bool gzip)
  86. : this (stream, CompressionMode.Compress, leaveOpen, gzip)
  87. {
  88. }
  89. protected override void Dispose (bool disposing)
  90. {
  91. native.Dispose (disposing);
  92. if (disposing && !disposed) {
  93. disposed = true;
  94. if (!leaveOpen) {
  95. Stream st = base_stream;
  96. if (st != null)
  97. st.Close ();
  98. base_stream = null;
  99. }
  100. }
  101. base.Dispose (disposing);
  102. }
  103. unsafe int ReadInternal (byte[] array, int offset, int count)
  104. {
  105. if (count == 0)
  106. return 0;
  107. fixed (byte *b = array) {
  108. IntPtr ptr = new IntPtr (b + offset);
  109. return native.ReadZStream (ptr, count);
  110. }
  111. }
  112. internal int ReadCore (Span<byte> destination)
  113. {
  114. throw new NotImplementedException ();
  115. }
  116. public override int Read (byte[] array, int offset, int count)
  117. {
  118. if (disposed)
  119. throw new ObjectDisposedException (GetType ().FullName);
  120. if (array == null)
  121. throw new ArgumentNullException ("Destination array is null.");
  122. if (!CanRead)
  123. throw new InvalidOperationException ("Stream does not support reading.");
  124. int len = array.Length;
  125. if (offset < 0 || count < 0)
  126. throw new ArgumentException ("Dest or count is negative.");
  127. if (offset > len)
  128. throw new ArgumentException ("destination offset is beyond array size");
  129. if ((offset + count) > len)
  130. throw new ArgumentException ("Reading would overrun buffer");
  131. return ReadInternal (array, offset, count);
  132. }
  133. unsafe void WriteInternal (byte[] array, int offset, int count)
  134. {
  135. if (count == 0)
  136. return;
  137. fixed (byte *b = array) {
  138. IntPtr ptr = new IntPtr (b + offset);
  139. native.WriteZStream (ptr, count);
  140. }
  141. }
  142. internal void WriteCore (ReadOnlySpan<byte> source)
  143. {
  144. throw new NotImplementedException ();
  145. }
  146. public override void Write (byte[] array, int offset, int count)
  147. {
  148. if (disposed)
  149. throw new ObjectDisposedException (GetType ().FullName);
  150. if (array == null)
  151. throw new ArgumentNullException ("array");
  152. if (offset < 0)
  153. throw new ArgumentOutOfRangeException ("offset");
  154. if (count < 0)
  155. throw new ArgumentOutOfRangeException ("count");
  156. if (!CanWrite)
  157. throw new NotSupportedException ("Stream does not support writing");
  158. if (offset > array.Length - count)
  159. throw new ArgumentException ("Buffer too small. count/offset wrong.");
  160. WriteInternal (array, offset, count);
  161. }
  162. public override void Flush ()
  163. {
  164. if (disposed)
  165. throw new ObjectDisposedException (GetType ().FullName);
  166. if (CanWrite) {
  167. native.Flush ();
  168. }
  169. }
  170. public override IAsyncResult BeginRead (byte [] array, int offset, int count,
  171. AsyncCallback asyncCallback, object asyncState)
  172. {
  173. if (disposed)
  174. throw new ObjectDisposedException (GetType ().FullName);
  175. if (!CanRead)
  176. throw new NotSupportedException ("This stream does not support reading");
  177. if (array == null)
  178. throw new ArgumentNullException ("array");
  179. if (count < 0)
  180. throw new ArgumentOutOfRangeException ("count", "Must be >= 0");
  181. if (offset < 0)
  182. throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
  183. if (count + offset > array.Length)
  184. throw new ArgumentException ("Buffer too small. count/offset wrong.");
  185. ReadMethod r = new ReadMethod (ReadInternal);
  186. return r.BeginInvoke (array, offset, count, asyncCallback, asyncState);
  187. }
  188. public override IAsyncResult BeginWrite (byte [] array, int offset, int count,
  189. AsyncCallback asyncCallback, object asyncState)
  190. {
  191. if (disposed)
  192. throw new ObjectDisposedException (GetType ().FullName);
  193. if (!CanWrite)
  194. throw new InvalidOperationException ("This stream does not support writing");
  195. if (array == null)
  196. throw new ArgumentNullException ("array");
  197. if (count < 0)
  198. throw new ArgumentOutOfRangeException ("count", "Must be >= 0");
  199. if (offset < 0)
  200. throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
  201. if (count + offset > array.Length)
  202. throw new ArgumentException ("Buffer too small. count/offset wrong.");
  203. WriteMethod w = new WriteMethod (WriteInternal);
  204. return w.BeginInvoke (array, offset, count, asyncCallback, asyncState);
  205. }
  206. public override int EndRead(IAsyncResult asyncResult)
  207. {
  208. if (asyncResult == null)
  209. throw new ArgumentNullException ("asyncResult");
  210. AsyncResult ares = asyncResult as AsyncResult;
  211. if (ares == null)
  212. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  213. ReadMethod r = ares.AsyncDelegate as ReadMethod;
  214. if (r == null)
  215. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  216. return r.EndInvoke (asyncResult);
  217. }
  218. public override void EndWrite (IAsyncResult asyncResult)
  219. {
  220. if (asyncResult == null)
  221. throw new ArgumentNullException ("asyncResult");
  222. AsyncResult ares = asyncResult as AsyncResult;
  223. if (ares == null)
  224. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  225. WriteMethod w = ares.AsyncDelegate as WriteMethod;
  226. if (w == null)
  227. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  228. w.EndInvoke (asyncResult);
  229. return;
  230. }
  231. public override long Seek (long offset, SeekOrigin origin)
  232. {
  233. throw new NotSupportedException();
  234. }
  235. public override void SetLength (long value)
  236. {
  237. throw new NotSupportedException();
  238. }
  239. public Stream BaseStream {
  240. get { return base_stream; }
  241. }
  242. public override bool CanRead {
  243. get { return !disposed && mode == CompressionMode.Decompress && base_stream.CanRead; }
  244. }
  245. public override bool CanSeek {
  246. get { return false; }
  247. }
  248. public override bool CanWrite {
  249. get { return !disposed && mode == CompressionMode.Compress && base_stream.CanWrite; }
  250. }
  251. public override long Length {
  252. get { throw new NotSupportedException(); }
  253. }
  254. public override long Position {
  255. get { throw new NotSupportedException(); }
  256. set { throw new NotSupportedException(); }
  257. }
  258. }
  259. class DeflateStreamNative
  260. {
  261. const int BufferSize = 4096;
  262. [UnmanagedFunctionPointer (CallingConvention.Cdecl)]
  263. delegate int UnmanagedReadOrWrite (IntPtr buffer, int length, IntPtr data);
  264. UnmanagedReadOrWrite feeder; // This will be passed to unmanaged code and used there
  265. Stream base_stream;
  266. SafeDeflateStreamHandle z_stream;
  267. GCHandle data;
  268. bool disposed;
  269. byte [] io_buffer;
  270. private DeflateStreamNative ()
  271. {
  272. }
  273. public static DeflateStreamNative Create (Stream compressedStream, CompressionMode mode, bool gzip)
  274. {
  275. var dsn = new DeflateStreamNative ();
  276. dsn.data = GCHandle.Alloc (dsn);
  277. dsn.feeder = mode == CompressionMode.Compress ? new UnmanagedReadOrWrite (UnmanagedWrite) : new UnmanagedReadOrWrite (UnmanagedRead);
  278. dsn.z_stream = CreateZStream (mode, gzip, dsn.feeder, GCHandle.ToIntPtr (dsn.data));
  279. if (dsn.z_stream.IsInvalid) {
  280. dsn.Dispose (true);
  281. return null;
  282. }
  283. dsn.base_stream = compressedStream;
  284. return dsn;
  285. }
  286. ~DeflateStreamNative ()
  287. {
  288. Dispose (false);
  289. }
  290. public void Dispose (bool disposing)
  291. {
  292. if (disposing && !disposed) {
  293. disposed = true;
  294. GC.SuppressFinalize (this);
  295. io_buffer = null;
  296. z_stream.Dispose();
  297. }
  298. if (data.IsAllocated) {
  299. data.Free ();
  300. }
  301. }
  302. public void Flush ()
  303. {
  304. var res = Flush (z_stream);
  305. CheckResult (res, "Flush");
  306. }
  307. public int ReadZStream (IntPtr buffer, int length)
  308. {
  309. var res = ReadZStream (z_stream, buffer, length);
  310. CheckResult (res, "ReadInternal");
  311. return res;
  312. }
  313. public void WriteZStream (IntPtr buffer, int length)
  314. {
  315. var res = WriteZStream (z_stream, buffer, length);
  316. CheckResult (res, "WriteInternal");
  317. }
  318. [Mono.Util.MonoPInvokeCallback (typeof (UnmanagedReadOrWrite))]
  319. static int UnmanagedRead (IntPtr buffer, int length, IntPtr data)
  320. {
  321. GCHandle s = GCHandle.FromIntPtr (data);
  322. var self = s.Target as DeflateStreamNative;
  323. if (self == null)
  324. return -1;
  325. return self.UnmanagedRead (buffer, length);
  326. }
  327. int UnmanagedRead (IntPtr buffer, int length)
  328. {
  329. if (io_buffer == null)
  330. io_buffer = new byte [BufferSize];
  331. int count = Math.Min (length, io_buffer.Length);
  332. int n = base_stream.Read (io_buffer, 0, count);
  333. if (n > 0)
  334. Marshal.Copy (io_buffer, 0, buffer, n);
  335. return n;
  336. }
  337. [Mono.Util.MonoPInvokeCallback (typeof (UnmanagedReadOrWrite))]
  338. static int UnmanagedWrite (IntPtr buffer, int length, IntPtr data)
  339. {
  340. GCHandle s = GCHandle.FromIntPtr (data);
  341. var self = s.Target as DeflateStreamNative;
  342. if (self == null)
  343. return -1;
  344. return self.UnmanagedWrite (buffer, length);
  345. }
  346. int UnmanagedWrite (IntPtr buffer, int length)
  347. {
  348. int total = 0;
  349. while (length > 0) {
  350. if (io_buffer == null)
  351. io_buffer = new byte [BufferSize];
  352. int count = Math.Min (length, io_buffer.Length);
  353. Marshal.Copy (buffer, io_buffer, 0, count);
  354. base_stream.Write (io_buffer, 0, count);
  355. unsafe {
  356. buffer = new IntPtr ((byte *) buffer.ToPointer () + count);
  357. }
  358. length -= count;
  359. total += count;
  360. }
  361. return total;
  362. }
  363. static void CheckResult (int result, string where)
  364. {
  365. if (result >= 0)
  366. return;
  367. string error;
  368. switch (result) {
  369. case -1: // Z_ERRNO
  370. error = "Unknown error"; // Marshal.GetLastWin32() ?
  371. break;
  372. case -2: // Z_STREAM_ERROR
  373. error = "Internal error";
  374. break;
  375. case -3: // Z_DATA_ERROR
  376. error = "Corrupted data";
  377. break;
  378. case -4: // Z_MEM_ERROR
  379. error = "Not enough memory";
  380. break;
  381. case -5: // Z_BUF_ERROR
  382. error = "Internal error (no progress possible)";
  383. break;
  384. case -6: // Z_VERSION_ERROR
  385. error = "Invalid version";
  386. break;
  387. case -10:
  388. error = "Invalid argument(s)";
  389. break;
  390. case -11:
  391. error = "IO error";
  392. break;
  393. default:
  394. error = "Unknown error";
  395. break;
  396. }
  397. throw new IOException (error + " " + where);
  398. }
  399. #if MONOTOUCH || MONODROID
  400. const string LIBNAME = "__Internal";
  401. #else
  402. const string LIBNAME = "MonoPosixHelper";
  403. #endif
  404. #if !ORBIS
  405. [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
  406. static extern SafeDeflateStreamHandle CreateZStream (CompressionMode compress, bool gzip, UnmanagedReadOrWrite feeder, IntPtr data);
  407. [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
  408. static extern int CloseZStream (IntPtr stream);
  409. [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
  410. static extern int Flush (SafeDeflateStreamHandle stream);
  411. [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
  412. static extern int ReadZStream (SafeDeflateStreamHandle stream, IntPtr buffer, int length);
  413. [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
  414. static extern int WriteZStream (SafeDeflateStreamHandle stream, IntPtr buffer, int length);
  415. #else
  416. static SafeDeflateStreamHandle CreateZStream (CompressionMode compress, bool gzip, UnmanagedReadOrWrite feeder, IntPtr data)
  417. {
  418. throw new PlatformNotSupportedException ();
  419. }
  420. static int CloseZStream (IntPtr stream)
  421. {
  422. throw new PlatformNotSupportedException ();
  423. }
  424. static int Flush (SafeDeflateStreamHandle stream)
  425. {
  426. throw new PlatformNotSupportedException ();
  427. }
  428. static int ReadZStream (SafeDeflateStreamHandle stream, IntPtr buffer, int length)
  429. {
  430. throw new PlatformNotSupportedException ();
  431. }
  432. static int WriteZStream (SafeDeflateStreamHandle stream, IntPtr buffer, int length)
  433. {
  434. throw new PlatformNotSupportedException ();
  435. }
  436. #endif
  437. sealed class SafeDeflateStreamHandle : SafeHandle
  438. {
  439. public override bool IsInvalid
  440. {
  441. get { return handle == IntPtr.Zero; }
  442. }
  443. private SafeDeflateStreamHandle() : base(IntPtr.Zero, true)
  444. {
  445. }
  446. override protected bool ReleaseHandle()
  447. {
  448. DeflateStreamNative.CloseZStream(handle);
  449. return true;
  450. }
  451. }
  452. }
  453. }