MSSQLManager.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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. regionprofile.owner_uuid = new LLUUID((string) reader["owner_uuid"]);
  234. // World Map Addition
  235. string tempRegionMap = reader["regionMapTexture"].ToString();
  236. if (tempRegionMap != String.Empty)
  237. {
  238. regionprofile.regionMapTextureID = new LLUUID(tempRegionMap);
  239. }
  240. else
  241. {
  242. regionprofile.regionMapTextureID = new LLUUID();
  243. }
  244. }
  245. else
  246. {
  247. reader.Close();
  248. throw new Exception("No rows to return");
  249. }
  250. return regionprofile;
  251. }
  252. /// <summary>
  253. /// Reads a user profile from an active data reader
  254. /// </summary>
  255. /// <param name="reader">An active database reader</param>
  256. /// <returns>A user profile</returns>
  257. public UserProfileData readUserRow(IDataReader reader)
  258. {
  259. UserProfileData retval = new UserProfileData();
  260. if (reader.Read())
  261. {
  262. retval.ID = new LLUUID((string)reader["UUID"]);
  263. retval.FirstName = (string)reader["username"];
  264. retval.SurName = (string)reader["lastname"];
  265. retval.PasswordHash = (string)reader["passwordHash"];
  266. retval.PasswordSalt = (string)reader["passwordSalt"];
  267. retval.HomeRegion = Convert.ToUInt64(reader["homeRegion"].ToString());
  268. retval.HomeLocation = new LLVector3(
  269. Convert.ToSingle(reader["homeLocationX"].ToString()),
  270. Convert.ToSingle(reader["homeLocationY"].ToString()),
  271. Convert.ToSingle(reader["homeLocationZ"].ToString()));
  272. retval.HomeLookAt = new LLVector3(
  273. Convert.ToSingle(reader["homeLookAtX"].ToString()),
  274. Convert.ToSingle(reader["homeLookAtY"].ToString()),
  275. Convert.ToSingle(reader["homeLookAtZ"].ToString()));
  276. retval.Created = Convert.ToInt32(reader["created"].ToString());
  277. retval.LastLogin = Convert.ToInt32(reader["lastLogin"].ToString());
  278. retval.UserInventoryURI = (string)reader["userInventoryURI"];
  279. retval.UserAssetURI = (string)reader["userAssetURI"];
  280. retval.CanDoMask = Convert.ToUInt32(reader["profileCanDoMask"].ToString());
  281. retval.WantDoMask = Convert.ToUInt32(reader["profileWantDoMask"].ToString());
  282. retval.AboutText = (string)reader["profileAboutText"];
  283. retval.FirstLifeAboutText = (string)reader["profileFirstText"];
  284. retval.Image = new LLUUID((string)reader["profileImage"]);
  285. retval.FirstLifeImage = new LLUUID((string)reader["profileFirstImage"]);
  286. retval.WebLoginKey = new LLUUID((string)reader["webLoginKey"]);
  287. }
  288. else
  289. {
  290. return null;
  291. }
  292. return retval;
  293. }
  294. /// <summary>
  295. /// Reads an agent row from a database reader
  296. /// </summary>
  297. /// <param name="reader">An active database reader</param>
  298. /// <returns>A user session agent</returns>
  299. public UserAgentData readAgentRow(IDataReader reader)
  300. {
  301. UserAgentData retval = new UserAgentData();
  302. if (reader.Read())
  303. {
  304. // Agent IDs
  305. retval.ProfileID = new LLUUID((string)reader["UUID"]);
  306. retval.SessionID = new LLUUID((string)reader["sessionID"]);
  307. retval.SecureSessionID = new LLUUID((string)reader["secureSessionID"]);
  308. // Agent Who?
  309. retval.AgentIP = (string)reader["agentIP"];
  310. retval.AgentPort = Convert.ToUInt32(reader["agentPort"].ToString());
  311. retval.AgentOnline = Convert.ToBoolean(reader["agentOnline"].ToString());
  312. // Login/Logout times (UNIX Epoch)
  313. retval.LoginTime = Convert.ToInt32(reader["loginTime"].ToString());
  314. retval.LogoutTime = Convert.ToInt32(reader["logoutTime"].ToString());
  315. // Current position
  316. retval.Region = (string)reader["currentRegion"];
  317. retval.Handle = Convert.ToUInt64(reader["currentHandle"].ToString());
  318. LLVector3 tmp_v;
  319. LLVector3.TryParse((string)reader["currentPos"], out tmp_v);
  320. retval.Position = tmp_v;
  321. }
  322. else
  323. {
  324. return null;
  325. }
  326. return retval;
  327. }
  328. public AssetBase getAssetRow(IDataReader reader)
  329. {
  330. AssetBase asset = new AssetBase();
  331. if (reader.Read())
  332. {
  333. // Region Main
  334. asset = new AssetBase();
  335. asset.Data = (byte[])reader["data"];
  336. asset.Description = (string)reader["description"];
  337. asset.FullID = new LLUUID((string)reader["id"]);
  338. asset.InvType = Convert.ToSByte(reader["invType"]);
  339. asset.Local = Convert.ToBoolean(reader["local"]); // ((sbyte)reader["local"]) != 0 ? true : false;
  340. asset.Name = (string)reader["name"];
  341. asset.Type = Convert.ToSByte(reader["assetType"]);
  342. }
  343. else
  344. {
  345. return null; // throw new Exception("No rows to return");
  346. }
  347. return asset;
  348. }
  349. /// <summary>
  350. /// Inserts a new row into the log database
  351. /// </summary>
  352. /// <param name="serverDaemon">The daemon which triggered this event</param>
  353. /// <param name="target">Who were we operating on when this occured (region UUID, user UUID, etc)</param>
  354. /// <param name="methodCall">The method call where the problem occured</param>
  355. /// <param name="arguments">The arguments passed to the method</param>
  356. /// <param name="priority">How critical is this?</param>
  357. /// <param name="logMessage">Extra message info</param>
  358. /// <returns>Saved successfully?</returns>
  359. public bool insertLogRow(string serverDaemon, string target, string methodCall, string arguments, int priority,
  360. string logMessage)
  361. {
  362. string sql = "INSERT INTO logs ([target], [server], [method], [arguments], [priority], [message]) VALUES ";
  363. sql += "(@target, @server, @method, @arguments, @priority, @message);";
  364. Dictionary<string, string> parameters = new Dictionary<string, string>();
  365. parameters["server"] = serverDaemon;
  366. parameters["target"] = target;
  367. parameters["method"] = methodCall;
  368. parameters["arguments"] = arguments;
  369. parameters["priority"] = priority.ToString();
  370. parameters["message"] = logMessage;
  371. bool returnval = false;
  372. try
  373. {
  374. IDbCommand result = Query(sql, parameters);
  375. if (result.ExecuteNonQuery() == 1)
  376. returnval = true;
  377. result.Dispose();
  378. }
  379. catch (Exception e)
  380. {
  381. m_log.Error(e.ToString());
  382. return false;
  383. }
  384. return returnval;
  385. }
  386. /// <summary>
  387. /// Execute a SQL statement stored in a resource, as a string
  388. /// </summary>
  389. /// <param name="name"></param>
  390. public void ExecuteResourceSql(string name)
  391. {
  392. SqlCommand cmd = new SqlCommand(getResourceString(name), (SqlConnection)dbcon);
  393. cmd.ExecuteNonQuery();
  394. cmd.Dispose();
  395. }
  396. public SqlConnection getConnection()
  397. {
  398. return (SqlConnection)dbcon;
  399. }
  400. /// <summary>
  401. /// Given a list of tables, return the version of the tables, as seen in the database
  402. /// </summary>
  403. /// <param name="tableList"></param>
  404. public void GetTableVersion(Dictionary<string, string> tableList)
  405. {
  406. lock (dbcon)
  407. {
  408. Dictionary<string, string> param = new Dictionary<string, string>();
  409. param["dbname"] = dbcon.Database;
  410. IDbCommand tablesCmd =
  411. Query("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_CATALOG=@dbname", param);
  412. using (IDataReader tables = tablesCmd.ExecuteReader())
  413. {
  414. while (tables.Read())
  415. {
  416. try
  417. {
  418. string tableName = (string)tables["TABLE_NAME"];
  419. if (tableList.ContainsKey(tableName))
  420. tableList[tableName] = tableName;
  421. }
  422. catch (Exception e)
  423. {
  424. m_log.Error(e.ToString());
  425. }
  426. }
  427. tables.Close();
  428. }
  429. }
  430. }
  431. private string getResourceString(string name)
  432. {
  433. Assembly assem = GetType().Assembly;
  434. string[] names = assem.GetManifestResourceNames();
  435. foreach (string s in names)
  436. if (s.EndsWith(name))
  437. using (Stream resource = assem.GetManifestResourceStream(s))
  438. {
  439. using (StreamReader resourceReader = new StreamReader(resource))
  440. {
  441. string resourceString = resourceReader.ReadToEnd();
  442. return resourceString;
  443. }
  444. }
  445. throw new Exception(string.Format("Resource '{0}' was not found", name));
  446. }
  447. /// <summary>
  448. /// Returns the version of this DB provider
  449. /// </summary>
  450. /// <returns>A string containing the DB provider</returns>
  451. public string getVersion()
  452. {
  453. Module module = GetType().Module;
  454. string dllName = module.Assembly.ManifestModule.Name;
  455. Version dllVersion = module.Assembly.GetName().Version;
  456. return
  457. string.Format("{0}.{1}.{2}.{3}", dllVersion.Major, dllVersion.Minor, dllVersion.Build,
  458. dllVersion.Revision);
  459. }
  460. }
  461. }