SevenZipBase.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. #if UNMANAGED
  2. namespace SevenZip
  3. {
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Collections.ObjectModel;
  7. using System.Globalization;
  8. using System.Threading;
  9. /// <summary>
  10. /// SevenZip Extractor/Compressor base class. Implements Password string, ReportErrors flag.
  11. /// </summary>
  12. public abstract class SevenZipBase : MarshalByRefObject
  13. {
  14. private readonly bool _reportErrors;
  15. private readonly int _uniqueId;
  16. private static int _incrementingUniqueId = int.MinValue;
  17. /// <summary>
  18. /// True if the instance of the class needs to be recreated in new thread context; otherwise, false.
  19. /// </summary>
  20. protected internal bool NeedsToBeRecreated;
  21. internal virtual void SaveContext()
  22. {
  23. Context = SynchronizationContext.Current;
  24. NeedsToBeRecreated = true;
  25. }
  26. internal virtual void ReleaseContext()
  27. {
  28. Context = null;
  29. NeedsToBeRecreated = true;
  30. GC.SuppressFinalize(this);
  31. }
  32. private delegate void EventHandlerDelegate<T>(EventHandler<T> handler, T e) where T : EventArgs;
  33. internal void OnEvent<T>(EventHandler<T> handler, T e, bool synchronous) where T : EventArgs
  34. {
  35. try
  36. {
  37. if (handler != null)
  38. {
  39. switch (EventSynchronization)
  40. {
  41. case EventSynchronizationStrategy.AlwaysAsynchronous:
  42. synchronous = false;
  43. break;
  44. case EventSynchronizationStrategy.AlwaysSynchronous:
  45. synchronous = true;
  46. break;
  47. }
  48. if (Context == null)
  49. {
  50. // Usual synchronous call
  51. handler(this, e);
  52. }
  53. else
  54. {
  55. var callback = new SendOrPostCallback(obj =>
  56. {
  57. var array = (object[])obj;
  58. ((EventHandler<T>)array[0])(array[1], (T)array[2]);
  59. });
  60. if (synchronous)
  61. {
  62. // Could be just handler(this, e);
  63. Context.Send(callback, new object[] { handler, this, e });
  64. }
  65. else
  66. {
  67. Context.Post(callback, new object[] { handler, this, e });
  68. }
  69. }
  70. }
  71. }
  72. catch (Exception ex)
  73. {
  74. AddException(ex);
  75. }
  76. }
  77. internal SynchronizationContext Context { get; set; }
  78. /// <summary>
  79. /// Gets or sets the event synchronization strategy.
  80. /// </summary>
  81. public EventSynchronizationStrategy EventSynchronization { get; set; }
  82. /// <summary>
  83. /// Gets the unique identifier of this SevenZipBase instance.
  84. /// </summary>
  85. public int UniqueID => _uniqueId;
  86. /// <summary>
  87. /// User exceptions thrown during the requested operations, for example, in events.
  88. /// </summary>
  89. private readonly List<Exception> _exceptions = new List<Exception>();
  90. private static int GetUniqueID()
  91. {
  92. var newUniqueId = Interlocked.Increment(ref _incrementingUniqueId);
  93. return newUniqueId;
  94. }
  95. /// <summary>
  96. /// Initializes a new instance of the SevenZipBase class.
  97. /// </summary>
  98. /// <param name="password">The archive password.</param>
  99. protected SevenZipBase(string password = "")
  100. {
  101. Password = password;
  102. _reportErrors = true;
  103. _uniqueId = GetUniqueID();
  104. }
  105. /// <summary>
  106. /// Gets or sets the archive password
  107. /// </summary>
  108. public string Password { get; protected set; }
  109. /// <summary>
  110. /// Gets or sets throw exceptions on archive errors flag
  111. /// </summary>
  112. internal bool ReportErrors => _reportErrors;
  113. /// <summary>
  114. /// Gets the user exceptions thrown during the requested operations, for example, in events.
  115. /// </summary>
  116. internal ReadOnlyCollection<Exception> Exceptions => new ReadOnlyCollection<Exception>(_exceptions);
  117. internal void AddException(Exception e)
  118. {
  119. _exceptions.Add(e);
  120. }
  121. internal void ClearExceptions()
  122. {
  123. _exceptions.Clear();
  124. }
  125. internal bool HasExceptions => _exceptions.Count > 0;
  126. /// <summary>
  127. /// Throws the specified exception when is able to.
  128. /// </summary>
  129. /// <param name="e">The exception to throw.</param>
  130. /// <param name="handler">The handler responsible for the exception.</param>
  131. internal bool ThrowException(CallbackBase handler, params Exception[] e)
  132. {
  133. if (_reportErrors && (handler == null || !handler.Canceled))
  134. {
  135. throw e[0];
  136. }
  137. return false;
  138. }
  139. internal void ThrowUserException()
  140. {
  141. if (HasExceptions)
  142. {
  143. throw new SevenZipException(SevenZipException.USER_EXCEPTION_MESSAGE);
  144. }
  145. }
  146. /// <summary>
  147. /// Throws exception if HRESULT != 0.
  148. /// </summary>
  149. /// <param name="hresult">Result code to check.</param>
  150. /// <param name="message">Exception message.</param>
  151. /// <param name="handler">The class responsible for the callback.</param>
  152. internal void CheckedExecute(int hresult, string message, CallbackBase handler)
  153. {
  154. if (hresult != (int)OperationResult.Ok || handler.HasExceptions)
  155. {
  156. if (!handler.HasExceptions)
  157. {
  158. if (hresult < -2000000000)
  159. {
  160. SevenZipException exception;
  161. switch (hresult)
  162. {
  163. case -2146233067:
  164. exception = new SevenZipException("Operation is not supported. (0x80131515: E_NOTSUPPORTED)");
  165. break;
  166. case -2147024784:
  167. exception = new SevenZipException("There is not enough space on the disk. (0x80070070: ERROR_DISK_FULL)");
  168. break;
  169. case -2147024864:
  170. exception = new SevenZipException("The file is being used by another process. (0x80070020: ERROR_SHARING_VIOLATION)");
  171. break;
  172. case -2147024882:
  173. exception = new SevenZipException("There is not enough memory (RAM). (0x8007000E: E_OUTOFMEMORY)");
  174. break;
  175. case -2147024809:
  176. exception = new SevenZipException("Invalid arguments provided. (0x80070057: E_INVALIDARG)");
  177. break;
  178. case -2147467263:
  179. exception = new SevenZipException("Functionality not implemented. (0x80004001: E_NOTIMPL)");
  180. break;
  181. case -2147024891:
  182. exception = new SevenZipException("Access is denied. (0x80070005: E_ACCESSDENIED)");
  183. break;
  184. case -2146233086:
  185. exception = new SevenZipException("Argument is out of range. (0x80131502: E_ARGUMENTOUTOFRANGE)");
  186. break;
  187. case -2147024690:
  188. exception = new SevenZipException("Filename or extension is too long. (0x800700CE: ERROR_FILENAME_EXCED_RANGE)");
  189. break;
  190. default:
  191. exception = new SevenZipException(
  192. $"Execution has failed due to an internal SevenZipSharp issue (0x{hresult:x} / {hresult}).\n" +
  193. "You might find more info at https://github.com/squid-box/SevenZipSharp/issues/, but this library is no longer actively supported.");
  194. break;
  195. }
  196. ThrowException(handler, exception);
  197. }
  198. else
  199. {
  200. ThrowException(handler, new SevenZipException(message + hresult.ToString(CultureInfo.InvariantCulture) + '.'));
  201. }
  202. }
  203. else
  204. {
  205. ThrowException(handler, handler.Exceptions[0]);
  206. }
  207. }
  208. }
  209. /// <summary>
  210. /// Changes the path to the 7-zip native library.
  211. /// </summary>
  212. /// <param name="libraryPath">The path to the 7-zip native library.</param>
  213. public static void SetLibraryPath(string libraryPath)
  214. {
  215. SevenZipLibraryManager.SetLibraryPath(libraryPath);
  216. }
  217. /// <summary>
  218. /// Gets the current library features.
  219. /// </summary>
  220. [CLSCompliant(false)]
  221. public static LibraryFeature CurrentLibraryFeatures => SevenZipLibraryManager.CurrentLibraryFeatures;
  222. /// <summary>
  223. /// Determines whether the specified System.Object is equal to the current SevenZipBase.
  224. /// </summary>
  225. /// <param name="obj">The System.Object to compare with the current SevenZipBase.</param>
  226. /// <returns>true if the specified System.Object is equal to the current SevenZipBase; otherwise, false.</returns>
  227. public override bool Equals(object obj)
  228. {
  229. if (!(obj is SevenZipBase instance))
  230. {
  231. return false;
  232. }
  233. return _uniqueId == instance._uniqueId;
  234. }
  235. /// <summary>
  236. /// Serves as a hash function for a particular type.
  237. /// </summary>
  238. /// <returns> A hash code for the current SevenZipBase.</returns>
  239. public override int GetHashCode()
  240. {
  241. return _uniqueId;
  242. }
  243. /// <summary>
  244. /// Returns a System.String that represents the current SevenZipBase.
  245. /// </summary>
  246. /// <returns>A System.String that represents the current SevenZipBase.</returns>
  247. public override string ToString()
  248. {
  249. var type = "SevenZipBase";
  250. if (this is SevenZipExtractor)
  251. {
  252. type = "SevenZipExtractor";
  253. }
  254. if (this is SevenZipCompressor)
  255. {
  256. type = "SevenZipCompressor";
  257. }
  258. return $"{type} [{_uniqueId}]";
  259. }
  260. }
  261. }
  262. #endif