MSSQLManager.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSim Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Data;
  30. using System.Data.SqlClient;
  31. using System.IO;
  32. using System.Reflection;
  33. using libsecondlife;
  34. using OpenSim.Framework.Console;
  35. namespace OpenSim.Framework.Data.MSSQL
  36. {
  37. /// <summary>
  38. /// A management class for the MS SQL Storage Engine
  39. /// </summary>
  40. public class MSSQLManager
  41. {
  42. private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  43. /// <summary>
  44. /// The database connection object
  45. /// </summary>
  46. private IDbConnection dbcon;
  47. /// <summary>
  48. /// Connection string for ADO.net
  49. /// </summary>
  50. private readonly string connectionString;
  51. public MSSQLManager(string dataSource, string initialCatalog, string persistSecurityInfo, string userId,
  52. string password)
  53. {
  54. connectionString = "Data Source=" + dataSource + ";Initial Catalog=" + initialCatalog +
  55. ";Persist Security Info=" + persistSecurityInfo + ";User ID=" + userId + ";Password=" +
  56. password + ";";
  57. dbcon = new SqlConnection(connectionString);
  58. dbcon.Open();
  59. }
  60. //private DataTable createRegionsTable()
  61. //{
  62. // DataTable regions = new DataTable("regions");
  63. // createCol(regions, "regionHandle", typeof (ulong));
  64. // createCol(regions, "regionName", typeof (String));
  65. // createCol(regions, "uuid", typeof (String));
  66. // createCol(regions, "regionRecvKey", typeof (String));
  67. // createCol(regions, "regionSecret", typeof (String));
  68. // createCol(regions, "regionSendKey", typeof (String));
  69. // createCol(regions, "regionDataURI", typeof (String));
  70. // createCol(regions, "serverIP", typeof (String));
  71. // createCol(regions, "serverPort", typeof (String));
  72. // createCol(regions, "serverURI", typeof (String));
  73. // createCol(regions, "locX", typeof (uint));
  74. // createCol(regions, "locY", typeof (uint));
  75. // createCol(regions, "locZ", typeof (uint));
  76. // createCol(regions, "eastOverrideHandle", typeof (ulong));
  77. // createCol(regions, "westOverrideHandle", typeof (ulong));
  78. // createCol(regions, "southOverrideHandle", typeof (ulong));
  79. // createCol(regions, "northOverrideHandle", typeof (ulong));
  80. // createCol(regions, "regionAssetURI", typeof (String));
  81. // createCol(regions, "regionAssetRecvKey", typeof (String));
  82. // createCol(regions, "regionAssetSendKey", typeof (String));
  83. // createCol(regions, "regionUserURI", typeof (String));
  84. // createCol(regions, "regionUserRecvKey", typeof (String));
  85. // createCol(regions, "regionUserSendKey", typeof (String));
  86. // createCol(regions, "regionMapTexture", typeof (String));
  87. // createCol(regions, "serverHttpPort", typeof (String));
  88. // createCol(regions, "serverRemotingPort", typeof (uint));
  89. // // Add in contraints
  90. // regions.PrimaryKey = new DataColumn[] {regions.Columns["UUID"]};
  91. // return regions;
  92. //}
  93. protected static void createCol(DataTable dt, string name, Type type)
  94. {
  95. DataColumn col = new DataColumn(name, type);
  96. dt.Columns.Add(col);
  97. }
  98. protected static string defineTable(DataTable dt)
  99. {
  100. string sql = "create table " + dt.TableName + "(";
  101. string subsql = String.Empty;
  102. foreach (DataColumn col in dt.Columns)
  103. {
  104. if (subsql.Length > 0)
  105. {
  106. // a map function would rock so much here
  107. subsql += ",\n";
  108. }
  109. subsql += col.ColumnName + " " + SqlType(col.DataType);
  110. if (col == dt.PrimaryKey[0])
  111. {
  112. subsql += " primary key";
  113. }
  114. }
  115. sql += subsql;
  116. sql += ")";
  117. return sql;
  118. }
  119. // this is something we'll need to implement for each db
  120. // slightly differently.
  121. public static string SqlType(Type type)
  122. {
  123. if (type == typeof(String))
  124. {
  125. return "varchar(255)";
  126. }
  127. else if (type == typeof(Int32))
  128. {
  129. return "integer";
  130. }
  131. else if (type == typeof(Double))
  132. {
  133. return "float";
  134. }
  135. else if (type == typeof(Byte[]))
  136. {
  137. return "image";
  138. }
  139. else
  140. {
  141. return "varchar(255)";
  142. }
  143. }
  144. /// <summary>
  145. /// Shuts down the database connection
  146. /// </summary>
  147. public void Close()
  148. {
  149. dbcon.Close();
  150. dbcon = null;
  151. }
  152. /// <summary>
  153. /// Reconnects to the database
  154. /// </summary>
  155. public void Reconnect()
  156. {
  157. lock (dbcon)
  158. {
  159. try
  160. {
  161. // Close the DB connection
  162. dbcon.Close();
  163. // Try reopen it
  164. dbcon = new SqlConnection(connectionString);
  165. dbcon.Open();
  166. }
  167. catch (Exception e)
  168. {
  169. m_log.Error("Unable to reconnect to database " + e.ToString());
  170. }
  171. }
  172. }
  173. /// <summary>
  174. /// Runs a query with protection against SQL Injection by using parameterised input.
  175. /// </summary>
  176. /// <param name="sql">The SQL string - replace any variables such as WHERE x = "y" with WHERE x = @y</param>
  177. /// <param name="parameters">The parameters - index so that @y is indexed as 'y'</param>
  178. /// <returns>A Sql DB Command</returns>
  179. public IDbCommand Query(string sql, Dictionary<string, string> parameters)
  180. {
  181. SqlCommand dbcommand = (SqlCommand)dbcon.CreateCommand();
  182. dbcommand.CommandText = sql;
  183. foreach (KeyValuePair<string, string> param in parameters)
  184. {
  185. dbcommand.Parameters.AddWithValue(param.Key, param.Value);
  186. }
  187. return (IDbCommand)dbcommand;
  188. }
  189. /// <summary>
  190. /// Runs a database reader object and returns a region row
  191. /// </summary>
  192. /// <param name="reader">An active database reader</param>
  193. /// <returns>A region row</returns>
  194. public RegionProfileData getRegionRow(IDataReader reader)
  195. {
  196. RegionProfileData regionprofile = new RegionProfileData();
  197. if (reader.Read())
  198. {
  199. // Region Main
  200. regionprofile.regionHandle = Convert.ToUInt64(reader["regionHandle"]);
  201. regionprofile.regionName = (string)reader["regionName"];
  202. regionprofile.UUID = new LLUUID((string)reader["uuid"]);
  203. // Secrets
  204. regionprofile.regionRecvKey = (string)reader["regionRecvKey"];
  205. regionprofile.regionSecret = (string)reader["regionSecret"];
  206. regionprofile.regionSendKey = (string)reader["regionSendKey"];
  207. // Region Server
  208. regionprofile.regionDataURI = (string)reader["regionDataURI"];
  209. regionprofile.regionOnline = false; // Needs to be pinged before this can be set.
  210. regionprofile.serverIP = (string)reader["serverIP"];
  211. regionprofile.serverPort = Convert.ToUInt32(reader["serverPort"]);
  212. regionprofile.serverURI = (string)reader["serverURI"];
  213. regionprofile.httpPort = Convert.ToUInt32(reader["serverHttpPort"]);
  214. regionprofile.remotingPort = Convert.ToUInt32(reader["serverRemotingPort"]);
  215. // Location
  216. regionprofile.regionLocX = Convert.ToUInt32(reader["locX"]);
  217. regionprofile.regionLocY = Convert.ToUInt32(reader["locY"]);
  218. regionprofile.regionLocZ = Convert.ToUInt32(reader["locZ"]);
  219. // Neighbours - 0 = No Override
  220. regionprofile.regionEastOverrideHandle = Convert.ToUInt64(reader["eastOverrideHandle"]);
  221. regionprofile.regionWestOverrideHandle = Convert.ToUInt64(reader["westOverrideHandle"]);
  222. regionprofile.regionSouthOverrideHandle = Convert.ToUInt64(reader["southOverrideHandle"]);
  223. regionprofile.regionNorthOverrideHandle = Convert.ToUInt64(reader["northOverrideHandle"]);
  224. // Assets
  225. regionprofile.regionAssetURI = (string)reader["regionAssetURI"];
  226. regionprofile.regionAssetRecvKey = (string)reader["regionAssetRecvKey"];
  227. regionprofile.regionAssetSendKey = (string)reader["regionAssetSendKey"];
  228. // Userserver
  229. regionprofile.regionUserURI = (string)reader["regionUserURI"];
  230. regionprofile.regionUserRecvKey = (string)reader["regionUserRecvKey"];
  231. regionprofile.regionUserSendKey = (string)reader["regionUserSendKey"];
  232. try
  233. {
  234. regionprofile.owner_uuid = new LLUUID((string)reader["owner_uuid"]);
  235. }
  236. catch(Exception)
  237. {}
  238. // World Map Addition
  239. string tempRegionMap = reader["regionMapTexture"].ToString();
  240. if (tempRegionMap != String.Empty)
  241. {
  242. regionprofile.regionMapTextureID = new LLUUID(tempRegionMap);
  243. }
  244. else
  245. {
  246. regionprofile.regionMapTextureID = new LLUUID();
  247. }
  248. }
  249. else
  250. {
  251. reader.Close();
  252. throw new Exception("No rows to return");
  253. }
  254. return regionprofile;
  255. }
  256. /// <summary>
  257. /// Reads a user profile from an active data reader
  258. /// </summary>
  259. /// <param name="reader">An active database reader</param>
  260. /// <returns>A user profile</returns>
  261. public UserProfileData readUserRow(IDataReader reader)
  262. {
  263. UserProfileData retval = new UserProfileData();
  264. if (reader.Read())
  265. {
  266. retval.UUID = new LLUUID((string)reader["UUID"]);
  267. retval.username = (string)reader["username"];
  268. retval.surname = (string)reader["lastname"];
  269. retval.passwordHash = (string)reader["passwordHash"];
  270. retval.passwordSalt = (string)reader["passwordSalt"];
  271. retval.homeRegion = Convert.ToUInt64(reader["homeRegion"].ToString());
  272. retval.homeLocation = new LLVector3(
  273. Convert.ToSingle(reader["homeLocationX"].ToString()),
  274. Convert.ToSingle(reader["homeLocationY"].ToString()),
  275. Convert.ToSingle(reader["homeLocationZ"].ToString()));
  276. retval.homeLookAt = new LLVector3(
  277. Convert.ToSingle(reader["homeLookAtX"].ToString()),
  278. Convert.ToSingle(reader["homeLookAtY"].ToString()),
  279. Convert.ToSingle(reader["homeLookAtZ"].ToString()));
  280. retval.created = Convert.ToInt32(reader["created"].ToString());
  281. retval.lastLogin = Convert.ToInt32(reader["lastLogin"].ToString());
  282. retval.userInventoryURI = (string)reader["userInventoryURI"];
  283. retval.userAssetURI = (string)reader["userAssetURI"];
  284. retval.profileCanDoMask = Convert.ToUInt32(reader["profileCanDoMask"].ToString());
  285. retval.profileWantDoMask = Convert.ToUInt32(reader["profileWantDoMask"].ToString());
  286. retval.profileAboutText = (string)reader["profileAboutText"];
  287. retval.profileFirstText = (string)reader["profileFirstText"];
  288. retval.profileImage = new LLUUID((string)reader["profileImage"]);
  289. retval.profileFirstImage = new LLUUID((string)reader["profileFirstImage"]);
  290. retval.webLoginKey = new LLUUID((string)reader["webLoginKey"]);
  291. }
  292. else
  293. {
  294. return null;
  295. }
  296. return retval;
  297. }
  298. /// <summary>
  299. /// Reads an agent row from a database reader
  300. /// </summary>
  301. /// <param name="reader">An active database reader</param>
  302. /// <returns>A user session agent</returns>
  303. public UserAgentData readAgentRow(IDataReader reader)
  304. {
  305. UserAgentData retval = new UserAgentData();
  306. if (reader.Read())
  307. {
  308. // Agent IDs
  309. retval.UUID = new LLUUID((string)reader["UUID"]);
  310. retval.sessionID = new LLUUID((string)reader["sessionID"]);
  311. retval.secureSessionID = new LLUUID((string)reader["secureSessionID"]);
  312. // Agent Who?
  313. retval.agentIP = (string)reader["agentIP"];
  314. retval.agentPort = Convert.ToUInt32(reader["agentPort"].ToString());
  315. retval.agentOnline = Convert.ToBoolean(reader["agentOnline"].ToString());
  316. // Login/Logout times (UNIX Epoch)
  317. retval.loginTime = Convert.ToInt32(reader["loginTime"].ToString());
  318. retval.logoutTime = Convert.ToInt32(reader["logoutTime"].ToString());
  319. // Current position
  320. retval.currentRegion = (string)reader["currentRegion"];
  321. retval.currentHandle = Convert.ToUInt64(reader["currentHandle"].ToString());
  322. LLVector3.TryParse((string)reader["currentPos"], out retval.currentPos);
  323. }
  324. else
  325. {
  326. return null;
  327. }
  328. return retval;
  329. }
  330. public AssetBase getAssetRow(IDataReader reader)
  331. {
  332. AssetBase asset = new AssetBase();
  333. if (reader.Read())
  334. {
  335. // Region Main
  336. asset = new AssetBase();
  337. asset.Data = (byte[])reader["data"];
  338. asset.Description = (string)reader["description"];
  339. asset.FullID = new LLUUID((string)reader["id"]);
  340. asset.InvType = Convert.ToSByte(reader["invType"]);
  341. asset.Local = Convert.ToBoolean(reader["local"]); // ((sbyte)reader["local"]) != 0 ? true : false;
  342. asset.Name = (string)reader["name"];
  343. asset.Type = Convert.ToSByte(reader["assetType"]);
  344. }
  345. else
  346. {
  347. return null; // throw new Exception("No rows to return");
  348. }
  349. return asset;
  350. }
  351. /// <summary>
  352. /// Inserts a new row into the log database
  353. /// </summary>
  354. /// <param name="serverDaemon">The daemon which triggered this event</param>
  355. /// <param name="target">Who were we operating on when this occured (region UUID, user UUID, etc)</param>
  356. /// <param name="methodCall">The method call where the problem occured</param>
  357. /// <param name="arguments">The arguments passed to the method</param>
  358. /// <param name="priority">How critical is this?</param>
  359. /// <param name="logMessage">Extra message info</param>
  360. /// <returns>Saved successfully?</returns>
  361. public bool insertLogRow(string serverDaemon, string target, string methodCall, string arguments, int priority,
  362. string logMessage)
  363. {
  364. string sql = "INSERT INTO logs ([target], [server], [method], [arguments], [priority], [message]) VALUES ";
  365. sql += "(@target, @server, @method, @arguments, @priority, @message);";
  366. Dictionary<string, string> parameters = new Dictionary<string, string>();
  367. parameters["server"] = serverDaemon;
  368. parameters["target"] = target;
  369. parameters["method"] = methodCall;
  370. parameters["arguments"] = arguments;
  371. parameters["priority"] = priority.ToString();
  372. parameters["message"] = logMessage;
  373. bool returnval = false;
  374. try
  375. {
  376. IDbCommand result = Query(sql, parameters);
  377. if (result.ExecuteNonQuery() == 1)
  378. returnval = true;
  379. result.Dispose();
  380. }
  381. catch (Exception e)
  382. {
  383. m_log.Error(e.ToString());
  384. return false;
  385. }
  386. return returnval;
  387. }
  388. /// <summary>
  389. /// Execute a SQL statement stored in a resource, as a string
  390. /// </summary>
  391. /// <param name="name"></param>
  392. public void ExecuteResourceSql(string name)
  393. {
  394. SqlCommand cmd = new SqlCommand(getResourceString(name), (SqlConnection)dbcon);
  395. cmd.ExecuteNonQuery();
  396. cmd.Dispose();
  397. }
  398. public SqlConnection getConnection()
  399. {
  400. return (SqlConnection)dbcon;
  401. }
  402. /// <summary>
  403. /// Given a list of tables, return the version of the tables, as seen in the database
  404. /// </summary>
  405. /// <param name="tableList"></param>
  406. public void GetTableVersion(Dictionary<string, string> tableList)
  407. {
  408. lock (dbcon)
  409. {
  410. Dictionary<string, string> param = new Dictionary<string, string>();
  411. param["dbname"] = dbcon.Database;
  412. IDbCommand tablesCmd =
  413. Query("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_CATALOG=@dbname", param);
  414. using (IDataReader tables = tablesCmd.ExecuteReader())
  415. {
  416. while (tables.Read())
  417. {
  418. try
  419. {
  420. string tableName = (string)tables["TABLE_NAME"];
  421. if (tableList.ContainsKey(tableName))
  422. tableList[tableName] = tableName;
  423. }
  424. catch (Exception e)
  425. {
  426. m_log.Error(e.ToString());
  427. }
  428. }
  429. tables.Close();
  430. }
  431. }
  432. }
  433. private string getResourceString(string name)
  434. {
  435. Assembly assem = GetType().Assembly;
  436. string[] names = assem.GetManifestResourceNames();
  437. foreach (string s in names)
  438. if (s.EndsWith(name))
  439. using (Stream resource = assem.GetManifestResourceStream(s))
  440. {
  441. using (StreamReader resourceReader = new StreamReader(resource))
  442. {
  443. string resourceString = resourceReader.ReadToEnd();
  444. return resourceString;
  445. }
  446. }
  447. throw new Exception(string.Format("Resource '{0}' was not found", name));
  448. }
  449. /// <summary>
  450. /// Returns the version of this DB provider
  451. /// </summary>
  452. /// <returns>A string containing the DB provider</returns>
  453. public string getVersion()
  454. {
  455. Module module = GetType().Module;
  456. string dllName = module.Assembly.ManifestModule.Name;
  457. Version dllVersion = module.Assembly.GetName().Version;
  458. return
  459. string.Format("{0}.{1}.{2}.{3}", dllVersion.Major, dllVersion.Minor, dllVersion.Build,
  460. dllVersion.Revision);
  461. }
  462. }
  463. }