LocalDBAPI.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. //------------------------------------------------------------------------------
  2. // <copyright file="LocalDB.cs" company="Microsoft">
  3. // Copyright (c) Microsoft Corporation. All rights reserved.
  4. // </copyright>
  5. // <owner current="true" primary="true">antonam</owner>
  6. //------------------------------------------------------------------------------
  7. namespace System.Data
  8. {
  9. using System.Configuration;
  10. using System.Threading;
  11. using System.Runtime.InteropServices;
  12. using System.Data.Common;
  13. using System.Globalization;
  14. using System.Data.SqlClient;
  15. using System.Collections.Generic;
  16. using System.Runtime.CompilerServices;
  17. using System.Text;
  18. using System.Diagnostics;
  19. using System.Security;
  20. using System.Security.Permissions;
  21. internal static class LocalDBAPI
  22. {
  23. const string const_localDbPrefix = @"(localdb)\";
  24. const string const_partialTrustFlagKey = "ALLOW_LOCALDB_IN_PARTIAL_TRUST";
  25. static PermissionSet _fullTrust = null;
  26. static bool _partialTrustFlagChecked = false;
  27. static bool _partialTrustAllowed = false;
  28. // check if name is in format (localdb)\<InstanceName - not empty> and return instance name if it is
  29. internal static string GetLocalDbInstanceNameFromServerName(string serverName)
  30. {
  31. if (serverName == null)
  32. return null;
  33. serverName = serverName.TrimStart(); // it can start with spaces if specified in quotes
  34. if (!serverName.StartsWith(const_localDbPrefix, StringComparison.OrdinalIgnoreCase))
  35. return null;
  36. string instanceName = serverName.Substring(const_localDbPrefix.Length).Trim();
  37. if (instanceName.Length == 0)
  38. return null;
  39. else
  40. return instanceName;
  41. }
  42. internal static void ReleaseDLLHandles()
  43. {
  44. s_userInstanceDLLHandle = IntPtr.Zero;
  45. s_localDBFormatMessage = null;
  46. s_localDBCreateInstance = null;
  47. }
  48. //This is copy of handle that SNI maintains, so we are responsible for freeing it - therefore there we are not using SafeHandle
  49. static IntPtr s_userInstanceDLLHandle = IntPtr.Zero;
  50. static object s_dllLock = new object();
  51. static IntPtr UserInstanceDLLHandle
  52. {
  53. get
  54. {
  55. if (s_userInstanceDLLHandle==IntPtr.Zero)
  56. {
  57. bool lockTaken = false;
  58. RuntimeHelpers.PrepareConstrainedRegions();
  59. try
  60. {
  61. Monitor.Enter(s_dllLock, ref lockTaken);
  62. if (s_userInstanceDLLHandle == IntPtr.Zero)
  63. {
  64. SNINativeMethodWrapper.SNIQueryInfo(SNINativeMethodWrapper.QTypes.SNI_QUERY_LOCALDB_HMODULE, ref s_userInstanceDLLHandle);
  65. if (s_userInstanceDLLHandle != IntPtr.Zero)
  66. {
  67. Bid.Trace("<sc.LocalDBAPI.UserInstanceDLLHandle> LocalDB - handle obtained");
  68. }
  69. else
  70. {
  71. SNINativeMethodWrapper.SNI_Error sniError = new SNINativeMethodWrapper.SNI_Error();
  72. SNINativeMethodWrapper.SNIGetLastError(sniError);
  73. throw CreateLocalDBException(errorMessage: Res.GetString("LocalDB_FailedGetDLLHandle"), sniError: (int)sniError.sniError);
  74. }
  75. }
  76. }
  77. finally
  78. {
  79. if (lockTaken)
  80. Monitor.Exit(s_dllLock);
  81. }
  82. }
  83. return s_userInstanceDLLHandle;
  84. }
  85. }
  86. [SuppressUnmanagedCodeSecurity]
  87. [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
  88. private delegate int LocalDBCreateInstanceDelegate([MarshalAs(UnmanagedType.LPWStr)] string version, [MarshalAs(UnmanagedType.LPWStr)] string instance, UInt32 flags);
  89. static LocalDBCreateInstanceDelegate s_localDBCreateInstance = null;
  90. static LocalDBCreateInstanceDelegate LocalDBCreateInstance
  91. {
  92. get
  93. {
  94. if (s_localDBCreateInstance==null)
  95. {
  96. bool lockTaken = false;
  97. RuntimeHelpers.PrepareConstrainedRegions();
  98. try
  99. {
  100. Monitor.Enter(s_dllLock, ref lockTaken);
  101. if (s_localDBCreateInstance == null)
  102. {
  103. IntPtr functionAddr = SafeNativeMethods.GetProcAddress(UserInstanceDLLHandle, "LocalDBCreateInstance");
  104. if (functionAddr == IntPtr.Zero)
  105. {
  106. int hResult=Marshal.GetLastWin32Error();
  107. Bid.Trace("<sc.LocalDBAPI.LocalDBCreateInstance> GetProcAddress for LocalDBCreateInstance error 0x{%X}",hResult);
  108. throw CreateLocalDBException(errorMessage: Res.GetString("LocalDB_MethodNotFound"));
  109. }
  110. s_localDBCreateInstance = (LocalDBCreateInstanceDelegate)Marshal.GetDelegateForFunctionPointer(functionAddr, typeof(LocalDBCreateInstanceDelegate));
  111. }
  112. }
  113. finally
  114. {
  115. if (lockTaken)
  116. Monitor.Exit(s_dllLock);
  117. }
  118. }
  119. return s_localDBCreateInstance;
  120. }
  121. }
  122. [SuppressUnmanagedCodeSecurity]
  123. [UnmanagedFunctionPointer(CallingConvention.Cdecl,CharSet=CharSet.Unicode)]
  124. private delegate int LocalDBFormatMessageDelegate(int hrLocalDB, UInt32 dwFlags, UInt32 dwLanguageId, StringBuilder buffer, ref UInt32 buflen);
  125. static LocalDBFormatMessageDelegate s_localDBFormatMessage = null;
  126. static LocalDBFormatMessageDelegate LocalDBFormatMessage
  127. {
  128. get
  129. {
  130. if (s_localDBFormatMessage==null)
  131. {
  132. bool lockTaken = false;
  133. RuntimeHelpers.PrepareConstrainedRegions();
  134. try
  135. {
  136. Monitor.Enter(s_dllLock, ref lockTaken);
  137. if (s_localDBFormatMessage == null)
  138. {
  139. IntPtr functionAddr = SafeNativeMethods.GetProcAddress(UserInstanceDLLHandle, "LocalDBFormatMessage");
  140. if (functionAddr == IntPtr.Zero)
  141. {
  142. // SNI checks for LocalDBFormatMessage during DLL loading, so it is practically impossibe to get this error.
  143. int hResult=Marshal.GetLastWin32Error();
  144. Bid.Trace("<sc.LocalDBAPI.LocalDBFormatMessage> GetProcAddress for LocalDBFormatMessage error 0x{%X}", hResult);
  145. throw CreateLocalDBException(errorMessage: Res.GetString("LocalDB_MethodNotFound"));
  146. }
  147. s_localDBFormatMessage = (LocalDBFormatMessageDelegate)Marshal.GetDelegateForFunctionPointer(functionAddr, typeof(LocalDBFormatMessageDelegate));
  148. }
  149. }
  150. finally
  151. {
  152. if (lockTaken)
  153. Monitor.Exit(s_dllLock);
  154. }
  155. }
  156. return s_localDBFormatMessage;
  157. }
  158. }
  159. const UInt32 const_LOCALDB_TRUNCATE_ERR_MESSAGE = 1;// flag for LocalDBFormatMessage that indicates that message can be truncated if it does not fit in the buffer
  160. const int const_ErrorMessageBufferSize = 1024; // Buffer size for Local DB error message, according to Serverless team, 1K will be enough for all messages
  161. internal static string GetLocalDBMessage(int hrCode)
  162. {
  163. Debug.Assert(hrCode < 0, "HRCode does not indicate error");
  164. try
  165. {
  166. StringBuilder buffer = new StringBuilder((int)const_ErrorMessageBufferSize);
  167. UInt32 len = (UInt32)buffer.Capacity;
  168. // First try for current culture
  169. int hResult=LocalDBFormatMessage(hrLocalDB: hrCode, dwFlags: const_LOCALDB_TRUNCATE_ERR_MESSAGE, dwLanguageId: (UInt32)CultureInfo.CurrentCulture.LCID,
  170. buffer: buffer, buflen: ref len);
  171. if (hResult>=0)
  172. return buffer.ToString();
  173. else
  174. {
  175. // Message is not available for current culture, try default
  176. buffer = new StringBuilder((int)const_ErrorMessageBufferSize);
  177. len = (UInt32) buffer.Capacity;
  178. hResult=LocalDBFormatMessage(hrLocalDB: hrCode, dwFlags: const_LOCALDB_TRUNCATE_ERR_MESSAGE, dwLanguageId: 0 /* thread locale with fallback to English */,
  179. buffer: buffer, buflen: ref len);
  180. if (hResult >= 0)
  181. return buffer.ToString();
  182. else
  183. return string.Format(CultureInfo.CurrentCulture, "{0} (0x{1:X}).", Res.GetString("LocalDB_UnobtainableMessage"), hResult);
  184. }
  185. }
  186. catch (SqlException exc)
  187. {
  188. return string.Format(CultureInfo.CurrentCulture, "{0} ({1}).", Res.GetString("LocalDB_UnobtainableMessage"), exc.Message);
  189. }
  190. }
  191. static SqlException CreateLocalDBException(string errorMessage, string instance = null, int localDbError = 0, int sniError = 0)
  192. {
  193. Debug.Assert((localDbError == 0) || (sniError == 0), "LocalDB error and SNI error cannot be specified simultaneously");
  194. Debug.Assert(!string.IsNullOrEmpty(errorMessage), "Error message should not be null or empty");
  195. SqlErrorCollection collection = new SqlErrorCollection();
  196. int errorCode = (localDbError == 0) ? sniError : localDbError;
  197. if (sniError!=0)
  198. {
  199. string sniErrorMessage = SQL.GetSNIErrorMessage(sniError);
  200. errorMessage = String.Format((IFormatProvider)null, "{0} (error: {1} - {2})",
  201. errorMessage, sniError, sniErrorMessage);
  202. }
  203. collection.Add(new SqlError(errorCode, 0, TdsEnums.FATAL_ERROR_CLASS, instance, errorMessage, null, 0));
  204. if (localDbError != 0)
  205. collection.Add(new SqlError(errorCode, 0, TdsEnums.FATAL_ERROR_CLASS, instance, GetLocalDBMessage(localDbError), null, 0));
  206. SqlException exc = SqlException.CreateException(collection, null);
  207. exc._doNotReconnect = true;
  208. return exc;
  209. }
  210. private class InstanceInfo
  211. {
  212. internal InstanceInfo(string version)
  213. {
  214. this.version = version;
  215. this.created = false;
  216. }
  217. internal readonly string version;
  218. internal bool created;
  219. }
  220. static object s_configLock=new object();
  221. static Dictionary<string, InstanceInfo> s_configurableInstances = null;
  222. internal static void DemandLocalDBPermissions()
  223. {
  224. if (!_partialTrustAllowed)
  225. {
  226. if (!_partialTrustFlagChecked)
  227. {
  228. object partialTrustFlagValue = AppDomain.CurrentDomain.GetData(const_partialTrustFlagKey);
  229. if (partialTrustFlagValue != null && partialTrustFlagValue is bool)
  230. {
  231. _partialTrustAllowed = (bool)partialTrustFlagValue;
  232. }
  233. _partialTrustFlagChecked = true;
  234. if (_partialTrustAllowed)
  235. {
  236. return;
  237. }
  238. }
  239. if (_fullTrust == null)
  240. {
  241. _fullTrust = new NamedPermissionSet("FullTrust");
  242. }
  243. _fullTrust.Demand();
  244. }
  245. }
  246. internal static void AssertLocalDBPermissions()
  247. {
  248. _partialTrustAllowed = true;
  249. }
  250. internal static void CreateLocalDBInstance(string instance)
  251. {
  252. DemandLocalDBPermissions();
  253. if (s_configurableInstances == null)
  254. {
  255. // load list of instances from configuration, mark them as not created
  256. bool lockTaken = false;
  257. RuntimeHelpers.PrepareConstrainedRegions();
  258. try
  259. {
  260. Monitor.Enter(s_configLock, ref lockTaken);
  261. if (s_configurableInstances == null)
  262. {
  263. Dictionary<string, InstanceInfo> tempConfigurableInstances = new Dictionary<string, InstanceInfo>(StringComparer.OrdinalIgnoreCase);
  264. #if !NO_CONFIGURATION
  265. object section = PrivilegedConfigurationManager.GetSection("system.data.localdb");
  266. if (section != null) // if no section just skip creation
  267. {
  268. // validate section type
  269. LocalDBConfigurationSection configSection = section as LocalDBConfigurationSection;
  270. if (configSection == null)
  271. throw CreateLocalDBException(errorMessage: Res.GetString("LocalDB_BadConfigSectionType"));
  272. foreach (LocalDBInstanceElement confElement in configSection.LocalDbInstances)
  273. {
  274. Debug.Assert(confElement.Name != null && confElement.Version != null, "Both name and version should not be null");
  275. tempConfigurableInstances.Add(confElement.Name.Trim(), new InstanceInfo(confElement.Version.Trim()));
  276. }
  277. }
  278. else
  279. #endif
  280. Bid.Trace( "<sc.LocalDBAPI.CreateLocalDBInstance> No system.data.localdb section found in configuration");
  281. s_configurableInstances = tempConfigurableInstances;
  282. }
  283. }
  284. finally
  285. {
  286. if (lockTaken)
  287. Monitor.Exit(s_configLock);
  288. }
  289. }
  290. InstanceInfo instanceInfo = null;
  291. if (!s_configurableInstances.TryGetValue(instance,out instanceInfo))
  292. return; // instance name was not in the config
  293. if (instanceInfo.created)
  294. return; // instance has already been created
  295. Debug.Assert(!instance.Contains("\0"), "Instance name should contain embedded nulls");
  296. if (instanceInfo.version.Contains("\0"))
  297. throw CreateLocalDBException(errorMessage: Res.GetString("LocalDB_InvalidVersion"), instance: instance);
  298. // LocalDBCreateInstance is thread- and cross-process safe method, it is OK to call from two threads simultaneously
  299. int hr = LocalDBCreateInstance(instanceInfo.version, instance, flags: 0);
  300. Bid.Trace("<sc.LocalDBAPI.CreateLocalDBInstance> Starting creation of instance %ls version %ls", instance, instanceInfo.version);
  301. if (hr < 0)
  302. throw CreateLocalDBException(errorMessage: Res.GetString("LocalDB_CreateFailed"), instance: instance, localDbError: hr);
  303. Bid.Trace("<sc.LocalDBAPI.CreateLocalDBInstance> Finished creation of instance %ls", instance);
  304. instanceInfo.created=true; // mark instance as created
  305. } // CreateLocalDbInstance
  306. }
  307. }