MSSQLManager.cs 21 KB

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