TdsParserStaticMethods.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. //------------------------------------------------------------------------------
  2. // <copyright file="TdsParserStaticFunctionality.cs" company="Microsoft">
  3. // Copyright (c) Microsoft Corporation. All rights reserved.
  4. // </copyright>
  5. // <owner current="true" primary="true">[....]</owner>
  6. // <owner current="true" primary="false">[....]</owner>
  7. //------------------------------------------------------------------------------
  8. namespace System.Data.SqlClient {
  9. using System;
  10. using System.Data.Common;
  11. using System.Data.ProviderBase;
  12. using System.Data.Sql;
  13. using System.Data.SqlTypes;
  14. using System.Diagnostics;
  15. using System.Globalization;
  16. using System.Runtime.CompilerServices;
  17. using System.Runtime.InteropServices;
  18. using System.Security;
  19. using System.Security.Permissions;
  20. using System.Text;
  21. using System.Threading;
  22. using System.Runtime.Versioning;
  23. internal sealed class TdsParserStaticMethods {
  24. private TdsParserStaticMethods() { /* prevent utility class from being insantiated*/ }
  25. //
  26. // Static methods
  27. //
  28. // SxS: this method accesses registry to resolve the alias.
  29. [ResourceExposure(ResourceScope.None)]
  30. [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
  31. static internal void AliasRegistryLookup(ref string host, ref string protocol) {
  32. #if !MOBILE
  33. if (!ADP.IsEmpty(host)) {
  34. const String folder = "SOFTWARE\\Microsoft\\MSSQLServer\\Client\\ConnectTo";
  35. // Put a try...catch... around this so we don't abort ANY connection if we can't read the registry.
  36. string aliasLookup = (string) ADP.LocalMachineRegistryValue(folder, host);
  37. if (!ADP.IsEmpty(aliasLookup)) {
  38. /* Result will be in the form of: "DBNMPNTW,\\blained1\pipe\sql\query". or
  39. Result will be in the form of: "DBNETLIB, via:\\blained1\pipe\sql\query".
  40. supported formats:
  41. tcp - DBMSSOCN,[server|server\instance][,port]
  42. np - DBNMPNTW,[\\server\pipe\sql\query | \\server\pipe\MSSQL$instance\sql\query]
  43. where \sql\query is the pipename and can be replaced with any other pipe name
  44. via - [DBMSGNET,server,port | DBNETLIB, via:server, port]
  45. sm - DBMSLPCN,server
  46. unsupported formats:
  47. rpc - DBMSRPCN,server,[parameters] where parameters could be "username,password"
  48. bv - DBMSVINN,service@group@organization
  49. appletalk - DBMSADSN,objectname@zone
  50. spx - DBMSSPXN,[service | address,port,network]
  51. */
  52. // We must parse into the two component pieces, then map the first protocol piece to the
  53. // appropriate value.
  54. int index = aliasLookup.IndexOf(',');
  55. // If we found the key, but there was no "," in the string, it is a bad Alias so return.
  56. if (-1 != index) {
  57. string parsedProtocol = aliasLookup.Substring(0, index).ToLower(CultureInfo.InvariantCulture);
  58. // If index+1 >= length, Alias consisted of "FOO," which is a bad alias so return.
  59. if (index+1 < aliasLookup.Length) {
  60. string parsedAliasName = aliasLookup.Substring(index+1);
  61. // Fix bug 298286
  62. if ("dbnetlib" == parsedProtocol) {
  63. index = parsedAliasName.IndexOf(':');
  64. if (-1 != index && index + 1 < parsedAliasName.Length) {
  65. parsedProtocol = parsedAliasName.Substring (0, index);
  66. if (SqlConnectionString.ValidProtocal (parsedProtocol)) {
  67. protocol = parsedProtocol;
  68. host = parsedAliasName.Substring(index + 1);
  69. }
  70. }
  71. }
  72. else {
  73. protocol = (string)SqlConnectionString.NetlibMapping()[parsedProtocol];
  74. if (null != protocol) {
  75. host = parsedAliasName;
  76. }
  77. }
  78. }
  79. }
  80. }
  81. }
  82. #endif
  83. }
  84. // Encrypt password to be sent to SQL Server
  85. // Note: The same logic is used in SNIPacketSetData (SniManagedWrapper) to encrypt passwords stored in SecureString
  86. // If this logic changed, SNIPacketSetData needs to be changed as well
  87. static internal Byte[] EncryptPassword(string password) {
  88. Byte[] bEnc = new Byte[password.Length << 1];
  89. int s;
  90. byte bLo;
  91. byte bHi;
  92. for (int i = 0; i < password.Length; i ++) {
  93. s = (int) password[i];
  94. bLo = (byte) (s & 0xff);
  95. bHi = (byte) ((s >> 8) & 0xff);
  96. bEnc[i<<1] = (Byte) ( (((bLo & 0x0f) << 4) | (bLo >> 4)) ^ 0xa5 );
  97. bEnc[(i<<1)+1] = (Byte) ( (((bHi & 0x0f) << 4) | (bHi >> 4)) ^ 0xa5);
  98. }
  99. return bEnc;
  100. }
  101. [ResourceExposure(ResourceScope.None)] // SxS: we use this method for TDS login only
  102. [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
  103. static internal int GetCurrentProcessIdForTdsLoginOnly() {
  104. #if MOBILE
  105. return 0;
  106. #else
  107. return SafeNativeMethods.GetCurrentProcessId();
  108. #endif
  109. }
  110. [SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode)]
  111. [ResourceExposure(ResourceScope.None)] // SxS: we use this method for TDS login only
  112. [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
  113. static internal Int32 GetCurrentThreadIdForTdsLoginOnly() {
  114. #pragma warning disable 618
  115. return AppDomain.GetCurrentThreadId(); // don't need this to be support fibres;
  116. #pragma warning restore 618
  117. }
  118. [ResourceExposure(ResourceScope.None)] // SxS: we use MAC address for TDS login only
  119. [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
  120. static internal byte[] GetNetworkPhysicalAddressForTdsLoginOnly() {
  121. // NIC address is stored in NetworkAddress key. However, if NetworkAddressLocal key
  122. // has a value that is not zero, then we cannot use the NetworkAddress key and must
  123. // instead generate a random one. I do not fully understand why, this is simply what
  124. // the native providers do. As for generation, I use a random number generator, which
  125. // means that different processes on the same machine will have different NIC address
  126. // values on the server. It is not ideal, but native does not have the same value for
  127. // different processes either.
  128. const string key = "NetworkAddress";
  129. const string localKey = "NetworkAddressLocal";
  130. const string folder = "SOFTWARE\\Description\\Microsoft\\Rpc\\UuidTemporaryData";
  131. int result = 0;
  132. byte[] nicAddress = null;
  133. object temp = ADP.LocalMachineRegistryValue(folder, localKey);
  134. if (temp is int) {
  135. result = (int) temp;
  136. }
  137. if (result <= 0) {
  138. temp = ADP.LocalMachineRegistryValue(folder, key);
  139. if (temp is byte[]) {
  140. nicAddress = (byte[]) temp;
  141. }
  142. }
  143. if (null == nicAddress) {
  144. nicAddress = new byte[TdsEnums.MAX_NIC_SIZE];
  145. Random random = new Random();
  146. random.NextBytes(nicAddress);
  147. }
  148. return nicAddress;
  149. }
  150. // translates remaining time in stateObj (from user specified timeout) to timout value for SNI
  151. static internal Int32 GetTimeoutMilliseconds(long timeoutTime) {
  152. // User provided timeout t | timeout value for SNI | meaning
  153. // ------------------------+-----------------------+------------------------------
  154. // t == long.MaxValue | -1 | infinite timeout (no timeout)
  155. // t>0 && t<int.MaxValue | t |
  156. // t>int.MaxValue | int.MaxValue | must not exceed int.MaxValue
  157. if (Int64.MaxValue == timeoutTime) {
  158. return -1; // infinite timeout
  159. }
  160. long msecRemaining = ADP.TimerRemainingMilliseconds(timeoutTime);
  161. if (msecRemaining < 0) {
  162. return 0;
  163. }
  164. if (msecRemaining > (long)Int32.MaxValue) {
  165. return Int32.MaxValue;
  166. }
  167. return (Int32)msecRemaining;
  168. }
  169. static internal long GetTimeoutSeconds(int timeout) {
  170. return GetTimeout((long)timeout * 1000L);
  171. }
  172. static internal long GetTimeout(long timeoutMilliseconds) {
  173. long result;
  174. if (timeoutMilliseconds <= 0) {
  175. result = Int64.MaxValue; // no timeout...
  176. }
  177. else {
  178. try
  179. {
  180. result = checked(ADP.TimerCurrent() + ADP.TimerFromMilliseconds(timeoutMilliseconds));
  181. }
  182. catch (OverflowException)
  183. {
  184. // In case of overflow, set to 'infinite' timeout
  185. result = Int64.MaxValue;
  186. }
  187. }
  188. return result;
  189. }
  190. static internal bool TimeoutHasExpired(long timeoutTime) {
  191. bool result = false;
  192. if (0 != timeoutTime && Int64.MaxValue != timeoutTime) {
  193. result = ADP.TimerHasExpired(timeoutTime);
  194. }
  195. return result;
  196. }
  197. static internal int NullAwareStringLength(string str) {
  198. if (str == null) {
  199. return 0;
  200. }
  201. else {
  202. return str.Length;
  203. }
  204. }
  205. static internal int GetRemainingTimeout(int timeout, long start) {
  206. if (timeout <= 0) {
  207. return timeout;
  208. }
  209. long remaining = ADP.TimerRemainingSeconds(start + ADP.TimerFromSeconds(timeout));
  210. if (remaining <= 0) {
  211. return 1;
  212. }
  213. else {
  214. return checked((int)remaining);
  215. }
  216. }
  217. }
  218. }