DbConnectionOptions.cs 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970
  1. //------------------------------------------------------------------------------
  2. // <copyright file="DBConnectionOptions.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.Common {
  9. using System;
  10. using System.Collections;
  11. using System.Data;
  12. using System.Diagnostics;
  13. using System.Globalization;
  14. using System.Runtime.Serialization;
  15. using System.Security.Permissions;
  16. using System.Text;
  17. using System.Text.RegularExpressions;
  18. using System.Runtime.Versioning;
  19. internal class DbConnectionOptions {
  20. // instances of this class are intended to be immutable, i.e readonly
  21. // used by pooling classes so it is much easier to verify correctness
  22. // when not worried about the class being modified during execution
  23. #if DEBUG
  24. /*private const string ConnectionStringPatternV1 =
  25. "[\\s;]*"
  26. +"(?<key>([^=\\s]|\\s+[^=\\s]|\\s+==|==)+)"
  27. + "\\s*=(?!=)\\s*"
  28. +"(?<value>("
  29. + "(" + "\"" + "([^\"]|\"\")*" + "\"" + ")"
  30. + "|"
  31. + "(" + "'" + "([^']|'')*" + "'" + ")"
  32. + "|"
  33. + "(" + "(?![\"'])" + "([^\\s;]|\\s+[^\\s;])*" + "(?<![\"'])" + ")"
  34. + "))"
  35. + "[\\s;]*"
  36. ;*/
  37. private const string ConnectionStringPattern = // may not contain embedded null except trailing last value
  38. "([\\s;]*" // leading whitespace and extra semicolons
  39. + "(?![\\s;])" // key does not start with space or semicolon
  40. + "(?<key>([^=\\s\\p{Cc}]|\\s+[^=\\s\\p{Cc}]|\\s+==|==)+)" // allow any visible character for keyname except '=' which must quoted as '=='
  41. + "\\s*=(?!=)\\s*" // the equal sign divides the key and value parts
  42. + "(?<value>"
  43. + "(\"([^\"\u0000]|\"\")*\")" // double quoted string, " must be quoted as ""
  44. + "|"
  45. + "('([^'\u0000]|'')*')" // single quoted string, ' must be quoted as ''
  46. + "|"
  47. + "((?![\"'\\s])" // unquoted value must not start with " or ' or space, would also like = but too late to change
  48. + "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" // control characters must be quoted
  49. + "(?<![\"']))" // unquoted value must not stop with " or '
  50. + ")(\\s*)(;|[\u0000\\s]*$)" // whitespace after value up to semicolon or end-of-line
  51. + ")*" // repeat the key-value pair
  52. + "[\\s;]*[\u0000\\s]*" // traling whitespace/semicolons (DataSourceLocator), embedded nulls are allowed only in the end
  53. ;
  54. private const string ConnectionStringPatternOdbc = // may not contain embedded null except trailing last value
  55. "([\\s;]*" // leading whitespace and extra semicolons
  56. + "(?![\\s;])" // key does not start with space or semicolon
  57. + "(?<key>([^=\\s\\p{Cc}]|\\s+[^=\\s\\p{Cc}])+)" // allow any visible character for keyname except '='
  58. + "\\s*=\\s*" // the equal sign divides the key and value parts
  59. + "(?<value>"
  60. + "(\\{([^\\}\u0000]|\\}\\})*\\})" // quoted string, starts with { and ends with }
  61. + "|"
  62. + "((?![\\{\\s])" // unquoted value must not start with { or space, would also like = but too late to change
  63. + "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" // control characters must be quoted
  64. + ")" // VSTFDEVDIV 94761: although the spec does not allow {}
  65. // embedded within a value, the retail code does.
  66. // + "(?<![\\}]))" // unquoted value must not stop with }
  67. + ")(\\s*)(;|[\u0000\\s]*$)" // whitespace after value up to semicolon or end-of-line
  68. + ")*" // repeat the key-value pair
  69. + "[\\s;]*[\u0000\\s]*" // traling whitespace/semicolons (DataSourceLocator), embedded nulls are allowed only in the end
  70. ;
  71. private static readonly Regex ConnectionStringRegex = new Regex(ConnectionStringPattern, RegexOptions.ExplicitCapture | RegexOptions.Compiled);
  72. private static readonly Regex ConnectionStringRegexOdbc = new Regex(ConnectionStringPatternOdbc, RegexOptions.ExplicitCapture | RegexOptions.Compiled);
  73. #endif
  74. private const string ConnectionStringValidKeyPattern = "^(?![;\\s])[^\\p{Cc}]+(?<!\\s)$"; // key not allowed to start with semi-colon or space or contain non-visible characters or end with space
  75. private const string ConnectionStringValidValuePattern = "^[^\u0000]*$"; // value not allowed to contain embedded null
  76. private const string ConnectionStringQuoteValuePattern = "^[^\"'=;\\s\\p{Cc}]*$"; // generally do not quote the value if it matches the pattern
  77. private const string ConnectionStringQuoteOdbcValuePattern = "^\\{([^\\}\u0000]|\\}\\})*\\}$"; // do not quote odbc value if it matches this pattern
  78. internal const string DataDirectory = "|datadirectory|";
  79. private static readonly Regex ConnectionStringValidKeyRegex = new Regex(ConnectionStringValidKeyPattern, RegexOptions.Compiled);
  80. private static readonly Regex ConnectionStringValidValueRegex = new Regex(ConnectionStringValidValuePattern, RegexOptions.Compiled);
  81. private static readonly Regex ConnectionStringQuoteValueRegex = new Regex(ConnectionStringQuoteValuePattern, RegexOptions.Compiled);
  82. private static readonly Regex ConnectionStringQuoteOdbcValueRegex = new Regex(ConnectionStringQuoteOdbcValuePattern, RegexOptions.ExplicitCapture | RegexOptions.Compiled);
  83. // connection string common keywords
  84. private static class KEY {
  85. internal const string Integrated_Security = "integrated security";
  86. internal const string Password = "password";
  87. internal const string Persist_Security_Info = "persist security info";
  88. internal const string User_ID = "user id";
  89. };
  90. // known connection string common synonyms
  91. private static class SYNONYM {
  92. internal const string Pwd = "pwd";
  93. internal const string UID = "uid";
  94. };
  95. private readonly string _usersConnectionString;
  96. private readonly Hashtable _parsetable;
  97. internal readonly NameValuePair KeyChain;
  98. internal readonly bool HasPasswordKeyword;
  99. // differences between OleDb and Odbc
  100. // ODBC:
  101. // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odbc/htm/odbcsqldriverconnect.asp
  102. // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odbcsql/od_odbc_d_4x4k.asp
  103. // do not support == -> = in keywords
  104. // first key-value pair wins
  105. // quote values using \{ and \}, only driver= and pwd= appear to generically allow quoting
  106. // do not strip quotes from value, or add quotes except for driver keyword
  107. // OLEDB:
  108. // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/oledb/htm/oledbconnectionstringsyntax.asp
  109. // support == -> = in keywords
  110. // last key-value pair wins
  111. // quote values using \" or \'
  112. // strip quotes from value
  113. internal readonly bool UseOdbcRules;
  114. private System.Security.PermissionSet _permissionset;
  115. // called by derived classes that may cache based on connectionString
  116. public DbConnectionOptions(string connectionString)
  117. : this(connectionString, null, false) {
  118. }
  119. // synonyms hashtable is meant to be read-only translation of parsed string
  120. // keywords/synonyms to a known keyword string
  121. public DbConnectionOptions(string connectionString, Hashtable synonyms, bool useOdbcRules) {
  122. UseOdbcRules = useOdbcRules;
  123. _parsetable = new Hashtable();
  124. _usersConnectionString = ((null != connectionString) ? connectionString : "");
  125. // first pass on parsing, initial syntax check
  126. if (0 < _usersConnectionString.Length) {
  127. KeyChain = ParseInternal(_parsetable, _usersConnectionString, true, synonyms, UseOdbcRules);
  128. HasPasswordKeyword = (_parsetable.ContainsKey(KEY.Password) || _parsetable.ContainsKey(SYNONYM.Pwd));
  129. }
  130. }
  131. protected DbConnectionOptions(DbConnectionOptions connectionOptions) { // Clone used by SqlConnectionString
  132. _usersConnectionString = connectionOptions._usersConnectionString;
  133. HasPasswordKeyword = connectionOptions.HasPasswordKeyword;
  134. UseOdbcRules = connectionOptions.UseOdbcRules;
  135. _parsetable = connectionOptions._parsetable;
  136. KeyChain = connectionOptions.KeyChain;
  137. }
  138. public string UsersConnectionString(bool hidePassword) {
  139. return UsersConnectionString(hidePassword, false);
  140. }
  141. private string UsersConnectionString(bool hidePassword, bool forceHidePassword) {
  142. string connectionString = _usersConnectionString;
  143. if (HasPasswordKeyword && (forceHidePassword || (hidePassword && !HasPersistablePassword))) {
  144. ReplacePasswordPwd(out connectionString, false);
  145. }
  146. return ((null != connectionString) ? connectionString : "");
  147. }
  148. internal string UsersConnectionStringForTrace() {
  149. return UsersConnectionString(true, true);
  150. }
  151. internal bool HasBlankPassword {
  152. get {
  153. if (!ConvertValueToIntegratedSecurity()) {
  154. if (_parsetable.ContainsKey(KEY.Password)) {
  155. return ADP.IsEmpty((string)_parsetable[KEY.Password]);
  156. } else
  157. if (_parsetable.ContainsKey(SYNONYM.Pwd)) {
  158. return ADP.IsEmpty((string)_parsetable[SYNONYM.Pwd]); // MDAC 83097
  159. } else {
  160. return ((_parsetable.ContainsKey(KEY.User_ID) && !ADP.IsEmpty((string)_parsetable[KEY.User_ID])) || (_parsetable.ContainsKey(SYNONYM.UID) && !ADP.IsEmpty((string)_parsetable[SYNONYM.UID])));
  161. }
  162. }
  163. return false;
  164. }
  165. }
  166. internal bool HasPersistablePassword {
  167. get {
  168. if (HasPasswordKeyword) {
  169. return ConvertValueToBoolean(KEY.Persist_Security_Info, false);
  170. }
  171. return true; // no password means persistable password so we don't have to munge
  172. }
  173. }
  174. public bool IsEmpty {
  175. get { return (null == KeyChain); }
  176. }
  177. internal Hashtable Parsetable {
  178. get { return _parsetable; }
  179. }
  180. public ICollection Keys {
  181. get { return _parsetable.Keys; }
  182. }
  183. public string this[string keyword] {
  184. get { return (string)_parsetable[keyword]; }
  185. }
  186. internal static void AppendKeyValuePairBuilder(StringBuilder builder, string keyName, string keyValue, bool useOdbcRules) {
  187. ADP.CheckArgumentNull(builder, "builder");
  188. ADP.CheckArgumentLength(keyName, "keyName");
  189. if ((null == keyName) || !ConnectionStringValidKeyRegex.IsMatch(keyName)) {
  190. throw ADP.InvalidKeyname(keyName);
  191. }
  192. if ((null != keyValue) && !IsValueValidInternal(keyValue)) {
  193. throw ADP.InvalidValue(keyName);
  194. }
  195. if ((0 < builder.Length) && (';' != builder[builder.Length-1])) {
  196. builder.Append(";");
  197. }
  198. if (useOdbcRules) {
  199. builder.Append(keyName);
  200. }
  201. else {
  202. builder.Append(keyName.Replace("=", "=="));
  203. }
  204. builder.Append("=");
  205. if (null != keyValue) { // else <keyword>=;
  206. if (useOdbcRules) {
  207. if ((0 < keyValue.Length) &&
  208. (('{' == keyValue[0]) || (0 <= keyValue.IndexOf(';')) || (0 == String.Compare(DbConnectionStringKeywords.Driver, keyName, StringComparison.OrdinalIgnoreCase))) &&
  209. !ConnectionStringQuoteOdbcValueRegex.IsMatch(keyValue))
  210. {
  211. // always quote Driver value (required for ODBC Version 2.65 and earlier)
  212. // always quote values that contain a ';'
  213. builder.Append('{').Append(keyValue.Replace("}", "}}")).Append('}');
  214. }
  215. else {
  216. builder.Append(keyValue);
  217. }
  218. }
  219. else if (ConnectionStringQuoteValueRegex.IsMatch(keyValue)) {
  220. // <value> -> <value>
  221. builder.Append(keyValue);
  222. }
  223. else if ((-1 != keyValue.IndexOf('\"')) && (-1 == keyValue.IndexOf('\''))) {
  224. // <val"ue> -> <'val"ue'>
  225. builder.Append('\'');
  226. builder.Append(keyValue);
  227. builder.Append('\'');
  228. }
  229. else {
  230. // <val'ue> -> <"val'ue">
  231. // <=value> -> <"=value">
  232. // <;value> -> <";value">
  233. // < value> -> <" value">
  234. // <va lue> -> <"va lue">
  235. // <va'"lue> -> <"va'""lue">
  236. builder.Append('\"');
  237. builder.Append(keyValue.Replace("\"", "\"\""));
  238. builder.Append('\"');
  239. }
  240. }
  241. }
  242. public bool ConvertValueToBoolean(string keyName, bool defaultValue) {
  243. object value = _parsetable[keyName];
  244. if (null == value) {
  245. return defaultValue;
  246. }
  247. return ConvertValueToBooleanInternal(keyName, (string) value);
  248. }
  249. internal static bool ConvertValueToBooleanInternal(string keyName, string stringValue) {
  250. if (CompareInsensitiveInvariant(stringValue, "true") || CompareInsensitiveInvariant(stringValue, "yes"))
  251. return true;
  252. else if (CompareInsensitiveInvariant(stringValue, "false") || CompareInsensitiveInvariant(stringValue, "no"))
  253. return false;
  254. else {
  255. string tmp = stringValue.Trim(); // Remove leading & trailing white space.
  256. if (CompareInsensitiveInvariant(tmp, "true") || CompareInsensitiveInvariant(tmp, "yes"))
  257. return true;
  258. else if (CompareInsensitiveInvariant(tmp, "false") || CompareInsensitiveInvariant(tmp, "no"))
  259. return false;
  260. else {
  261. throw ADP.InvalidConnectionOptionValue(keyName);
  262. }
  263. }
  264. }
  265. // same as Boolean, but with SSPI thrown in as valid yes
  266. public bool ConvertValueToIntegratedSecurity() {
  267. object value = _parsetable[KEY.Integrated_Security];
  268. if (null == value) {
  269. return false;
  270. }
  271. return ConvertValueToIntegratedSecurityInternal((string) value);
  272. }
  273. internal bool ConvertValueToIntegratedSecurityInternal(string stringValue) {
  274. if (CompareInsensitiveInvariant(stringValue, "sspi") || CompareInsensitiveInvariant(stringValue, "true") || CompareInsensitiveInvariant(stringValue, "yes"))
  275. return true;
  276. else if (CompareInsensitiveInvariant(stringValue, "false") || CompareInsensitiveInvariant(stringValue, "no"))
  277. return false;
  278. else {
  279. string tmp = stringValue.Trim(); // Remove leading & trailing white space.
  280. if (CompareInsensitiveInvariant(tmp, "sspi") || CompareInsensitiveInvariant(tmp, "true") || CompareInsensitiveInvariant(tmp, "yes"))
  281. return true;
  282. else if (CompareInsensitiveInvariant(tmp, "false") || CompareInsensitiveInvariant(tmp, "no"))
  283. return false;
  284. else {
  285. throw ADP.InvalidConnectionOptionValue(KEY.Integrated_Security);
  286. }
  287. }
  288. }
  289. public int ConvertValueToInt32(string keyName, int defaultValue) {
  290. object value = _parsetable[keyName];
  291. if (null == value) {
  292. return defaultValue;
  293. }
  294. return ConvertToInt32Internal(keyName, (string) value);
  295. }
  296. internal static int ConvertToInt32Internal(string keyname, string stringValue) {
  297. try {
  298. return System.Int32.Parse(stringValue, System.Globalization.NumberStyles.Integer, CultureInfo.InvariantCulture);
  299. }
  300. catch (FormatException e) {
  301. throw ADP.InvalidConnectionOptionValue(keyname, e);
  302. }
  303. catch (OverflowException e) {
  304. throw ADP.InvalidConnectionOptionValue(keyname, e);
  305. }
  306. }
  307. public string ConvertValueToString(string keyName, string defaultValue) {
  308. string value = (string)_parsetable[keyName];
  309. return ((null != value) ? value : defaultValue);
  310. }
  311. static private bool CompareInsensitiveInvariant(string strvalue, string strconst) {
  312. return (0 == StringComparer.OrdinalIgnoreCase.Compare(strvalue, strconst));
  313. }
  314. public bool ContainsKey(string keyword) {
  315. return _parsetable.ContainsKey(keyword);
  316. }
  317. protected internal virtual System.Security.PermissionSet CreatePermissionSet() {
  318. return null;
  319. }
  320. internal void DemandPermission() {
  321. if (null == _permissionset) {
  322. _permissionset = CreatePermissionSet();
  323. }
  324. _permissionset.Demand();
  325. }
  326. protected internal virtual string Expand() {
  327. return _usersConnectionString;
  328. }
  329. // SxS notes:
  330. // * this method queries "DataDirectory" value from the current AppDomain.
  331. // This string is used for to replace "!DataDirectory!" values in the connection string, it is not considered as an "exposed resource".
  332. // * This method uses GetFullPath to validate that root path is valid, the result is not exposed out.
  333. [ResourceExposure(ResourceScope.None)]
  334. [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
  335. internal static string ExpandDataDirectory(string keyword, string value, ref string datadir) {
  336. string fullPath = null;
  337. if ((null != value) && value.StartsWith(DataDirectory, StringComparison.OrdinalIgnoreCase)) {
  338. string rootFolderPath = datadir;
  339. if (null == rootFolderPath) {
  340. // find the replacement path
  341. object rootFolderObject = AppDomain.CurrentDomain.GetData("DataDirectory");
  342. rootFolderPath = (rootFolderObject as string);
  343. if ((null != rootFolderObject) && (null == rootFolderPath)) {
  344. throw ADP.InvalidDataDirectory();
  345. }
  346. else if (ADP.IsEmpty(rootFolderPath)) {
  347. rootFolderPath = AppDomain.CurrentDomain.BaseDirectory;
  348. }
  349. if (null == rootFolderPath) {
  350. rootFolderPath = "";
  351. }
  352. // cache the |DataDir| for ExpandDataDirectories
  353. datadir = rootFolderPath;
  354. }
  355. // We don't know if rootFolderpath ends with '\', and we don't know if the given name starts with onw
  356. int fileNamePosition = DataDirectory.Length; // filename starts right after the '|datadirectory|' keyword
  357. bool rootFolderEndsWith = (0 < rootFolderPath.Length) && rootFolderPath[rootFolderPath.Length-1] == '\\';
  358. bool fileNameStartsWith = (fileNamePosition < value.Length) && value[fileNamePosition] == '\\';
  359. // replace |datadirectory| with root folder path
  360. if (!rootFolderEndsWith && !fileNameStartsWith) {
  361. // need to insert '\'
  362. fullPath = rootFolderPath + '\\' + value.Substring(fileNamePosition);
  363. }
  364. else if (rootFolderEndsWith && fileNameStartsWith) {
  365. // need to strip one out
  366. fullPath = rootFolderPath + value.Substring(fileNamePosition+1);
  367. }
  368. else {
  369. // simply concatenate the strings
  370. fullPath = rootFolderPath + value.Substring(fileNamePosition);
  371. }
  372. // verify root folder path is a real path without unexpected "..\"
  373. if (!ADP.GetFullPath(fullPath).StartsWith(rootFolderPath, StringComparison.Ordinal)) {
  374. throw ADP.InvalidConnectionOptionValue(keyword);
  375. }
  376. }
  377. return fullPath;
  378. }
  379. internal string ExpandDataDirectories(ref string filename, ref int position) {
  380. string value = null;
  381. StringBuilder builder = new StringBuilder(_usersConnectionString.Length);
  382. string datadir = null;
  383. int copyPosition = 0;
  384. bool expanded = false;
  385. for(NameValuePair current = KeyChain; null != current; current = current.Next) {
  386. value = current.Value;
  387. // remove duplicate keyswords from connectionstring
  388. //if ((object)this[current.Name] != (object)value) {
  389. // expanded = true;
  390. // copyPosition += current.Length;
  391. // continue;
  392. //}
  393. // There is a set of keywords we explictly do NOT want to expand |DataDirectory| on
  394. if (UseOdbcRules) {
  395. switch(current.Name) {
  396. case DbConnectionOptionKeywords.Driver:
  397. case DbConnectionOptionKeywords.Pwd:
  398. case DbConnectionOptionKeywords.UID:
  399. break;
  400. default:
  401. value = ExpandDataDirectory(current.Name, value, ref datadir);
  402. break;
  403. }
  404. }
  405. else {
  406. switch(current.Name) {
  407. case DbConnectionOptionKeywords.Provider:
  408. case DbConnectionOptionKeywords.DataProvider:
  409. case DbConnectionOptionKeywords.RemoteProvider:
  410. case DbConnectionOptionKeywords.ExtendedProperties:
  411. case DbConnectionOptionKeywords.UserID:
  412. case DbConnectionOptionKeywords.Password:
  413. case DbConnectionOptionKeywords.UID:
  414. case DbConnectionOptionKeywords.Pwd:
  415. break;
  416. default:
  417. value = ExpandDataDirectory(current.Name, value, ref datadir);
  418. break;
  419. }
  420. }
  421. if (null == value) {
  422. value = current.Value;
  423. }
  424. if (UseOdbcRules || (DbConnectionOptionKeywords.FileName != current.Name)) {
  425. if (value != current.Value) {
  426. expanded = true;
  427. AppendKeyValuePairBuilder(builder, current.Name, value, UseOdbcRules);
  428. builder.Append(';');
  429. }
  430. else {
  431. builder.Append(_usersConnectionString, copyPosition, current.Length);
  432. }
  433. }
  434. else {
  435. // strip out 'File Name=myconnection.udl' for OleDb
  436. // remembering is value for which UDL file to open
  437. // and where to insert the strnig
  438. expanded = true;
  439. filename = value;
  440. position = builder.Length;
  441. }
  442. copyPosition += current.Length;
  443. }
  444. if (expanded) {
  445. value = builder.ToString();
  446. }
  447. else {
  448. value = null;
  449. }
  450. return value;
  451. }
  452. internal string ExpandKeyword(string keyword, string replacementValue) {
  453. // preserve duplicates, updated keyword value with replacement value
  454. // if keyword not specified, append to end of the string
  455. bool expanded = false;
  456. int copyPosition = 0;
  457. StringBuilder builder = new StringBuilder(_usersConnectionString.Length);
  458. for(NameValuePair current = KeyChain; null != current; current = current.Next) {
  459. if ((current.Name == keyword) && (current.Value == this[keyword])) {
  460. // only replace the parse end-result value instead of all values
  461. // so that when duplicate-keywords occur other original values remain in place
  462. AppendKeyValuePairBuilder(builder, current.Name, replacementValue, UseOdbcRules);
  463. builder.Append(';');
  464. expanded = true;
  465. }
  466. else {
  467. builder.Append(_usersConnectionString, copyPosition, current.Length);
  468. }
  469. copyPosition += current.Length;
  470. }
  471. if (!expanded) {
  472. //
  473. Debug.Assert(!UseOdbcRules, "ExpandKeyword not ready for Odbc");
  474. AppendKeyValuePairBuilder(builder, keyword, replacementValue, UseOdbcRules);
  475. }
  476. return builder.ToString();
  477. }
  478. #if DEBUG
  479. [System.Diagnostics.Conditional("DEBUG")]
  480. private static void DebugTraceKeyValuePair(string keyname, string keyvalue, Hashtable synonyms) {
  481. if (Bid.AdvancedOn) {
  482. Debug.Assert(keyname == keyname.ToLower(CultureInfo.InvariantCulture), "missing ToLower");
  483. string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname);
  484. if ((KEY.Password != realkeyname) && (SYNONYM.Pwd != realkeyname)) { // don't trace passwords ever!
  485. if (null != keyvalue) {
  486. Bid.Trace("<comm.DbConnectionOptions|INFO|ADV> KeyName='%ls', KeyValue='%ls'\n", keyname, keyvalue);
  487. }
  488. else {
  489. Bid.Trace("<comm.DbConnectionOptions|INFO|ADV> KeyName='%ls'\n", keyname);
  490. }
  491. }
  492. }
  493. }
  494. #endif
  495. static private string GetKeyName(StringBuilder buffer) {
  496. int count = buffer.Length;
  497. while ((0 < count) && Char.IsWhiteSpace(buffer[count-1])) {
  498. count--; // trailing whitespace
  499. }
  500. return buffer.ToString(0, count).ToLower(CultureInfo.InvariantCulture);
  501. }
  502. static private string GetKeyValue(StringBuilder buffer, bool trimWhitespace) {
  503. int count = buffer.Length;
  504. int index = 0;
  505. if (trimWhitespace) {
  506. while ((index < count) && Char.IsWhiteSpace(buffer[index])) {
  507. index++; // leading whitespace
  508. }
  509. while ((0 < count) && Char.IsWhiteSpace(buffer[count-1])) {
  510. count--; // trailing whitespace
  511. }
  512. }
  513. return buffer.ToString(index, count - index);
  514. }
  515. // transistion states used for parsing
  516. private enum ParserState {
  517. NothingYet=1, //start point
  518. Key,
  519. KeyEqual,
  520. KeyEnd,
  521. UnquotedValue,
  522. DoubleQuoteValue,
  523. DoubleQuoteValueQuote,
  524. SingleQuoteValue,
  525. SingleQuoteValueQuote,
  526. BraceQuoteValue,
  527. BraceQuoteValueQuote,
  528. QuotedValueEnd,
  529. NullTermination,
  530. };
  531. static internal int GetKeyValuePair(string connectionString, int currentPosition, StringBuilder buffer, bool useOdbcRules, out string keyname, out string keyvalue) {
  532. int startposition = currentPosition;
  533. buffer.Length = 0;
  534. keyname = null;
  535. keyvalue = null;
  536. char currentChar = '\0';
  537. ParserState parserState = ParserState.NothingYet;
  538. int length = connectionString.Length;
  539. for (; currentPosition < length; ++currentPosition) {
  540. currentChar = connectionString[currentPosition];
  541. switch(parserState) {
  542. case ParserState.NothingYet: // [\\s;]*
  543. if ((';' == currentChar) || Char.IsWhiteSpace(currentChar)) {
  544. continue;
  545. }
  546. if ('\0' == currentChar) { parserState = ParserState.NullTermination; continue; } // MDAC 83540
  547. if (Char.IsControl(currentChar)) { throw ADP.ConnectionStringSyntax(startposition); }
  548. startposition = currentPosition;
  549. if ('=' != currentChar) { // MDAC 86902
  550. parserState = ParserState.Key;
  551. break;
  552. }
  553. else {
  554. parserState = ParserState.KeyEqual;
  555. continue;
  556. }
  557. case ParserState.Key: // (?<key>([^=\\s\\p{Cc}]|\\s+[^=\\s\\p{Cc}]|\\s+==|==)+)
  558. if ('=' == currentChar) { parserState = ParserState.KeyEqual; continue; }
  559. if (Char.IsWhiteSpace(currentChar)) { break; }
  560. if (Char.IsControl(currentChar)) { throw ADP.ConnectionStringSyntax(startposition); }
  561. break;
  562. case ParserState.KeyEqual: // \\s*=(?!=)\\s*
  563. if (!useOdbcRules && '=' == currentChar) { parserState = ParserState.Key; break; }
  564. keyname = GetKeyName(buffer);
  565. if (ADP.IsEmpty(keyname)) { throw ADP.ConnectionStringSyntax(startposition); }
  566. buffer.Length = 0;
  567. parserState = ParserState.KeyEnd;
  568. goto case ParserState.KeyEnd;
  569. case ParserState.KeyEnd:
  570. if (Char.IsWhiteSpace(currentChar)) { continue; }
  571. if (useOdbcRules) {
  572. if ('{' == currentChar) { parserState = ParserState.BraceQuoteValue; break; }
  573. }
  574. else {
  575. if ('\'' == currentChar) { parserState = ParserState.SingleQuoteValue; continue; }
  576. if ('"' == currentChar) { parserState = ParserState.DoubleQuoteValue; continue; }
  577. }
  578. if (';' == currentChar) { goto ParserExit; }
  579. if ('\0' == currentChar) { goto ParserExit; }
  580. if (Char.IsControl(currentChar)) { throw ADP.ConnectionStringSyntax(startposition); }
  581. parserState = ParserState.UnquotedValue;
  582. break;
  583. case ParserState.UnquotedValue: // "((?![\"'\\s])" + "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" + "(?<![\"']))"
  584. if (Char.IsWhiteSpace(currentChar)) { break; }
  585. if (Char.IsControl(currentChar) || ';' == currentChar) { goto ParserExit; }
  586. break;
  587. case ParserState.DoubleQuoteValue: // "(\"([^\"\u0000]|\"\")*\")"
  588. if ('"' == currentChar) { parserState = ParserState.DoubleQuoteValueQuote; continue; }
  589. if ('\0' == currentChar) { throw ADP.ConnectionStringSyntax(startposition); }
  590. break;
  591. case ParserState.DoubleQuoteValueQuote:
  592. if ('"' == currentChar) { parserState = ParserState.DoubleQuoteValue; break; }
  593. keyvalue = GetKeyValue(buffer, false);
  594. parserState = ParserState.QuotedValueEnd;
  595. goto case ParserState.QuotedValueEnd;
  596. case ParserState.SingleQuoteValue: // "('([^'\u0000]|'')*')"
  597. if ('\'' == currentChar) { parserState = ParserState.SingleQuoteValueQuote; continue; }
  598. if ('\0' == currentChar) { throw ADP.ConnectionStringSyntax(startposition); }
  599. break;
  600. case ParserState.SingleQuoteValueQuote:
  601. if ('\'' == currentChar) { parserState = ParserState.SingleQuoteValue; break; }
  602. keyvalue = GetKeyValue(buffer, false);
  603. parserState = ParserState.QuotedValueEnd;
  604. goto case ParserState.QuotedValueEnd;
  605. case ParserState.BraceQuoteValue: // "(\\{([^\\}\u0000]|\\}\\})*\\})"
  606. if ('}' == currentChar) { parserState = ParserState.BraceQuoteValueQuote; break; }
  607. if ('\0' == currentChar) { throw ADP.ConnectionStringSyntax(startposition); }
  608. break;
  609. case ParserState.BraceQuoteValueQuote:
  610. if ('}' == currentChar) { parserState = ParserState.BraceQuoteValue; break; }
  611. keyvalue = GetKeyValue(buffer, false);
  612. parserState = ParserState.QuotedValueEnd;
  613. goto case ParserState.QuotedValueEnd;
  614. case ParserState.QuotedValueEnd:
  615. if (Char.IsWhiteSpace(currentChar)) { continue; }
  616. if (';' == currentChar) { goto ParserExit; }
  617. if ('\0' == currentChar) { parserState = ParserState.NullTermination; continue; } // MDAC 83540
  618. throw ADP.ConnectionStringSyntax(startposition); // unbalanced single quote
  619. case ParserState.NullTermination: // [\\s;\u0000]*
  620. if ('\0' == currentChar) { continue; }
  621. if (Char.IsWhiteSpace(currentChar)) { continue; } // MDAC 83540
  622. throw ADP.ConnectionStringSyntax(currentPosition);
  623. default:
  624. throw ADP.InternalError(ADP.InternalErrorCode.InvalidParserState1);
  625. }
  626. buffer.Append(currentChar);
  627. }
  628. ParserExit:
  629. switch (parserState) {
  630. case ParserState.Key:
  631. case ParserState.DoubleQuoteValue:
  632. case ParserState.SingleQuoteValue:
  633. case ParserState.BraceQuoteValue:
  634. // keyword not found/unbalanced double/single quote
  635. throw ADP.ConnectionStringSyntax(startposition);
  636. case ParserState.KeyEqual:
  637. // equal sign at end of line
  638. keyname = GetKeyName(buffer);
  639. if (ADP.IsEmpty(keyname)) { throw ADP.ConnectionStringSyntax(startposition); }
  640. break;
  641. case ParserState.UnquotedValue:
  642. // unquoted value at end of line
  643. keyvalue = GetKeyValue(buffer, true);
  644. char tmpChar = keyvalue[keyvalue.Length - 1];
  645. if (!useOdbcRules && (('\'' == tmpChar) || ('"' == tmpChar))) {
  646. throw ADP.ConnectionStringSyntax(startposition); // unquoted value must not end in quote, except for odbc
  647. }
  648. break;
  649. case ParserState.DoubleQuoteValueQuote:
  650. case ParserState.SingleQuoteValueQuote:
  651. case ParserState.BraceQuoteValueQuote:
  652. case ParserState.QuotedValueEnd:
  653. // quoted value at end of line
  654. keyvalue = GetKeyValue(buffer, false);
  655. break;
  656. case ParserState.NothingYet:
  657. case ParserState.KeyEnd:
  658. case ParserState.NullTermination:
  659. // do nothing
  660. break;
  661. default:
  662. throw ADP.InternalError(ADP.InternalErrorCode.InvalidParserState2);
  663. }
  664. if ((';' == currentChar) && (currentPosition < connectionString.Length)) {
  665. currentPosition++;
  666. }
  667. return currentPosition;
  668. }
  669. static private bool IsValueValidInternal(string keyvalue) {
  670. if (null != keyvalue)
  671. {
  672. #if DEBUG
  673. bool compValue = ConnectionStringValidValueRegex.IsMatch(keyvalue);
  674. Debug.Assert((-1 == keyvalue.IndexOf('\u0000')) == compValue, "IsValueValid mismatch with regex");
  675. #endif
  676. return (-1 == keyvalue.IndexOf('\u0000'));
  677. }
  678. return true;
  679. }
  680. static private bool IsKeyNameValid(string keyname) {
  681. if (null != keyname) {
  682. #if DEBUG
  683. bool compValue = ConnectionStringValidKeyRegex.IsMatch(keyname);
  684. Debug.Assert(((0 < keyname.Length) && (';' != keyname[0]) && !Char.IsWhiteSpace(keyname[0]) && (-1 == keyname.IndexOf('\u0000'))) == compValue, "IsValueValid mismatch with regex");
  685. #endif
  686. return ((0 < keyname.Length) && (';' != keyname[0]) && !Char.IsWhiteSpace(keyname[0]) && (-1 == keyname.IndexOf('\u0000')));
  687. }
  688. return false;
  689. }
  690. #if DEBUG
  691. private static Hashtable SplitConnectionString(string connectionString, Hashtable synonyms, bool firstKey) {
  692. Hashtable parsetable = new Hashtable();
  693. Regex parser = (firstKey ? ConnectionStringRegexOdbc : ConnectionStringRegex);
  694. const int KeyIndex = 1, ValueIndex = 2;
  695. Debug.Assert(KeyIndex == parser.GroupNumberFromName("key"), "wrong key index");
  696. Debug.Assert(ValueIndex == parser.GroupNumberFromName("value"), "wrong value index");
  697. if (null != connectionString) {
  698. Match match = parser.Match(connectionString);
  699. if (!match.Success || (match.Length != connectionString.Length)) {
  700. throw ADP.ConnectionStringSyntax(match.Length);
  701. }
  702. int indexValue = 0;
  703. CaptureCollection keyvalues = match.Groups[ValueIndex].Captures;
  704. foreach(Capture keypair in match.Groups[KeyIndex].Captures) {
  705. string keyname = (firstKey ? keypair.Value : keypair.Value.Replace("==", "=")).ToLower(CultureInfo.InvariantCulture);
  706. string keyvalue = keyvalues[indexValue++].Value;
  707. if (0 < keyvalue.Length) {
  708. if (!firstKey) {
  709. switch(keyvalue[0]) {
  710. case '\"':
  711. keyvalue = keyvalue.Substring(1, keyvalue.Length-2).Replace("\"\"", "\"");
  712. break;
  713. case '\'':
  714. keyvalue = keyvalue.Substring(1, keyvalue.Length-2).Replace("\'\'", "\'");
  715. break;
  716. default:
  717. break;
  718. }
  719. }
  720. }
  721. else {
  722. keyvalue = null;
  723. }
  724. DebugTraceKeyValuePair(keyname, keyvalue, synonyms);
  725. string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname);
  726. if (!IsKeyNameValid(realkeyname)) {
  727. throw ADP.KeywordNotSupported(keyname);
  728. }
  729. if (!firstKey || !parsetable.ContainsKey(realkeyname)) {
  730. parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first)
  731. }
  732. }
  733. }
  734. return parsetable;
  735. }
  736. private static void ParseComparison(Hashtable parsetable, string connectionString, Hashtable synonyms, bool firstKey, Exception e) {
  737. try {
  738. Hashtable parsedvalues = SplitConnectionString(connectionString, synonyms, firstKey);
  739. foreach(DictionaryEntry entry in parsedvalues) {
  740. string keyname = (string) entry.Key;
  741. string value1 = (string) entry.Value;
  742. string value2 = (string) parsetable[keyname];
  743. Debug.Assert(parsetable.Contains(keyname), "ParseInternal code vs. regex mismatch keyname <" + keyname + ">");
  744. Debug.Assert(value1 == value2, "ParseInternal code vs. regex mismatch keyvalue <" + value1 + "> <" + value2 +">");
  745. }
  746. }
  747. catch(ArgumentException f) {
  748. if (null != e) {
  749. string msg1 = e.Message;
  750. string msg2 = f.Message;
  751. const string KeywordNotSupportedMessagePrefix = "Keyword not supported:";
  752. const string WrongFormatMessagePrefix = "Format of the initialization string";
  753. bool isEquivalent = (msg1 == msg2);
  754. if (!isEquivalent)
  755. {
  756. // VSTFDEVDIV 479587: we also accept cases were Regex parser (debug only) reports "wrong format" and
  757. // retail parsing code reports format exception in different location or "keyword not supported"
  758. if (msg2.StartsWith(WrongFormatMessagePrefix, StringComparison.Ordinal)) {
  759. if (msg1.StartsWith(KeywordNotSupportedMessagePrefix, StringComparison.Ordinal) || msg1.StartsWith(WrongFormatMessagePrefix, StringComparison.Ordinal)) {
  760. isEquivalent = true;
  761. }
  762. }
  763. }
  764. Debug.Assert(isEquivalent, "ParseInternal code vs regex message mismatch: <"+msg1+"> <"+msg2+">");
  765. }
  766. else {
  767. Debug.Assert(false, "ParseInternal code vs regex throw mismatch " + f.Message);
  768. }
  769. e = null;
  770. }
  771. if (null != e) {
  772. Debug.Assert(false, "ParseInternal code threw exception vs regex mismatch");
  773. }
  774. }
  775. #endif
  776. private static NameValuePair ParseInternal(Hashtable parsetable, string connectionString, bool buildChain, Hashtable synonyms, bool firstKey) {
  777. Debug.Assert(null != connectionString, "null connectionstring");
  778. StringBuilder buffer = new StringBuilder();
  779. NameValuePair localKeychain = null, keychain = null;
  780. #if DEBUG
  781. try {
  782. #endif
  783. int nextStartPosition = 0;
  784. int endPosition = connectionString.Length;
  785. while (nextStartPosition < endPosition) {
  786. int startPosition = nextStartPosition;
  787. string keyname, keyvalue;
  788. nextStartPosition = GetKeyValuePair(connectionString, startPosition, buffer, firstKey, out keyname, out keyvalue);
  789. if (ADP.IsEmpty(keyname)) {
  790. // if (nextStartPosition != endPosition) { throw; }
  791. break;
  792. }
  793. #if DEBUG
  794. DebugTraceKeyValuePair(keyname, keyvalue, synonyms);
  795. Debug.Assert(IsKeyNameValid(keyname), "ParseFailure, invalid keyname");
  796. Debug.Assert(IsValueValidInternal(keyvalue), "parse failure, invalid keyvalue");
  797. #endif
  798. string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname);
  799. if (!IsKeyNameValid(realkeyname)) {
  800. throw ADP.KeywordNotSupported(keyname);
  801. }
  802. if (!firstKey || !parsetable.Contains(realkeyname)) {
  803. parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first)
  804. }
  805. if(null != localKeychain) {
  806. localKeychain = localKeychain.Next = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition);
  807. }
  808. else if (buildChain) { // first time only - don't contain modified chain from UDL file
  809. keychain = localKeychain = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition);
  810. }
  811. }
  812. #if DEBUG
  813. }
  814. catch(ArgumentException e) {
  815. ParseComparison(parsetable, connectionString, synonyms, firstKey, e);
  816. throw;
  817. }
  818. ParseComparison(parsetable, connectionString, synonyms, firstKey, null);
  819. #endif
  820. return keychain;
  821. }
  822. internal NameValuePair ReplacePasswordPwd(out string constr, bool fakePassword) {
  823. bool expanded = false;
  824. int copyPosition = 0;
  825. NameValuePair head = null, tail = null, next = null;
  826. StringBuilder builder = new StringBuilder(_usersConnectionString.Length);
  827. for(NameValuePair current = KeyChain; null != current; current = current.Next) {
  828. if ((KEY.Password != current.Name) && (SYNONYM.Pwd != current.Name)) {
  829. builder.Append(_usersConnectionString, copyPosition, current.Length);
  830. if (fakePassword) {
  831. next = new NameValuePair(current.Name, current.Value, current.Length);
  832. }
  833. }
  834. else if (fakePassword) { // replace user password/pwd value with *
  835. const string equalstar = "=*;";
  836. builder.Append(current.Name).Append(equalstar);
  837. next = new NameValuePair(current.Name, "*", current.Name.Length + equalstar.Length);
  838. expanded = true;
  839. }
  840. else { // drop the password/pwd completely in returning for user
  841. expanded = true;
  842. }
  843. if (fakePassword) {
  844. if (null != tail) {
  845. tail = tail.Next = next;
  846. }
  847. else {
  848. tail = head = next;
  849. }
  850. }
  851. copyPosition += current.Length;
  852. }
  853. Debug.Assert(expanded, "password/pwd was not removed");
  854. constr = builder.ToString();
  855. return head;
  856. }
  857. internal static void ValidateKeyValuePair(string keyword, string value) {
  858. if ((null == keyword) || !ConnectionStringValidKeyRegex.IsMatch(keyword)) {
  859. throw ADP.InvalidKeyname(keyword);
  860. }
  861. if ((null != value) && !ConnectionStringValidValueRegex.IsMatch(value)) {
  862. throw ADP.InvalidValue(keyword);
  863. }
  864. }
  865. }
  866. }