MSSQLManager.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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. /// Connection string for ADO.net
  46. /// </summary>
  47. private readonly string connectionString;
  48. public MSSQLManager(string dataSource, string initialCatalog, string persistSecurityInfo, string userId,
  49. string password)
  50. {
  51. SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
  52. builder.DataSource = dataSource;
  53. builder.InitialCatalog = initialCatalog;
  54. builder.PersistSecurityInfo = Convert.ToBoolean(persistSecurityInfo);
  55. builder.UserID = userId;
  56. builder.Password = password;
  57. builder.ApplicationName = Assembly.GetEntryAssembly().Location;
  58. connectionString = builder.ToString();
  59. }
  60. private SqlConnection createConnection()
  61. {
  62. SqlConnection conn = new SqlConnection(connectionString);
  63. conn.Open();
  64. return conn;
  65. }
  66. //private DataTable createRegionsTable()
  67. //{
  68. // DataTable regions = new DataTable("regions");
  69. // createCol(regions, "regionHandle", typeof (ulong));
  70. // createCol(regions, "regionName", typeof (String));
  71. // createCol(regions, "uuid", typeof (String));
  72. // createCol(regions, "regionRecvKey", typeof (String));
  73. // createCol(regions, "regionSecret", typeof (String));
  74. // createCol(regions, "regionSendKey", typeof (String));
  75. // createCol(regions, "regionDataURI", typeof (String));
  76. // createCol(regions, "serverIP", typeof (String));
  77. // createCol(regions, "serverPort", typeof (String));
  78. // createCol(regions, "serverURI", typeof (String));
  79. // createCol(regions, "locX", typeof (uint));
  80. // createCol(regions, "locY", typeof (uint));
  81. // createCol(regions, "locZ", typeof (uint));
  82. // createCol(regions, "eastOverrideHandle", typeof (ulong));
  83. // createCol(regions, "westOverrideHandle", typeof (ulong));
  84. // createCol(regions, "southOverrideHandle", typeof (ulong));
  85. // createCol(regions, "northOverrideHandle", typeof (ulong));
  86. // createCol(regions, "regionAssetURI", typeof (String));
  87. // createCol(regions, "regionAssetRecvKey", typeof (String));
  88. // createCol(regions, "regionAssetSendKey", typeof (String));
  89. // createCol(regions, "regionUserURI", typeof (String));
  90. // createCol(regions, "regionUserRecvKey", typeof (String));
  91. // createCol(regions, "regionUserSendKey", typeof (String));
  92. // createCol(regions, "regionMapTexture", typeof (String));
  93. // createCol(regions, "serverHttpPort", typeof (String));
  94. // createCol(regions, "serverRemotingPort", typeof (uint));
  95. // // Add in contraints
  96. // regions.PrimaryKey = new DataColumn[] {regions.Columns["UUID"]};
  97. // return regions;
  98. //}
  99. /// <summary>
  100. ///
  101. /// </summary>
  102. /// <param name="dt"></param>
  103. /// <param name="name"></param>
  104. /// <param name="type"></param>
  105. protected static void createCol(DataTable dt, string name, Type type)
  106. {
  107. DataColumn col = new DataColumn(name, type);
  108. dt.Columns.Add(col);
  109. }
  110. /// <summary>
  111. /// Define Table function
  112. /// </summary>
  113. /// <param name="dt"></param>
  114. /// <returns></returns>
  115. protected static string defineTable(DataTable dt)
  116. {
  117. string sql = "create table " + dt.TableName + "(";
  118. string subsql = String.Empty;
  119. foreach (DataColumn col in dt.Columns)
  120. {
  121. if (subsql.Length > 0)
  122. {
  123. // a map function would rock so much here
  124. subsql += ",\n";
  125. }
  126. subsql += col.ColumnName + " " + SqlType(col.DataType);
  127. if (col == dt.PrimaryKey[0])
  128. {
  129. subsql += " primary key";
  130. }
  131. }
  132. sql += subsql;
  133. sql += ")";
  134. return sql;
  135. }
  136. /// <summary>
  137. /// Type conversion function
  138. /// </summary>
  139. /// <param name="type">a type</param>
  140. /// <returns>a sqltype</returns>
  141. /// <remarks>this is something we'll need to implement for each db slightly differently.</remarks>
  142. public static string SqlType(Type type)
  143. {
  144. if (type == typeof(String))
  145. {
  146. return "varchar(255)";
  147. }
  148. else if (type == typeof(Int32))
  149. {
  150. return "integer";
  151. }
  152. else if (type == typeof(Double))
  153. {
  154. return "float";
  155. }
  156. else if (type == typeof(Byte[]))
  157. {
  158. return "image";
  159. }
  160. else
  161. {
  162. return "varchar(255)";
  163. }
  164. }
  165. private static readonly Dictionary<string, string> emptyDictionary = new Dictionary<string, string>();
  166. internal AutoClosingSqlCommand Query(string sql)
  167. {
  168. return Query(sql, emptyDictionary);
  169. }
  170. /// <summary>
  171. /// Runs a query with protection against SQL Injection by using parameterised input.
  172. /// </summary>
  173. /// <param name="sql">The SQL string - replace any variables such as WHERE x = "y" with WHERE x = @y</param>
  174. /// <param name="parameters">The parameters - index so that @y is indexed as 'y'</param>
  175. /// <returns>A Sql DB Command</returns>
  176. internal AutoClosingSqlCommand Query(string sql, Dictionary<string, string> parameters)
  177. {
  178. SqlCommand dbcommand = createConnection().CreateCommand();
  179. dbcommand.CommandText = sql;
  180. foreach (KeyValuePair<string, string> param in parameters)
  181. {
  182. dbcommand.Parameters.AddWithValue(param.Key, param.Value);
  183. }
  184. return new AutoClosingSqlCommand(dbcommand);
  185. }
  186. /// <summary>
  187. /// Runs a database reader object and returns a region row
  188. /// </summary>
  189. /// <param name="reader">An active database reader</param>
  190. /// <returns>A region row</returns>
  191. public RegionProfileData getRegionRow(IDataReader reader)
  192. {
  193. RegionProfileData regionprofile = new RegionProfileData();
  194. if (reader.Read())
  195. {
  196. // Region Main
  197. regionprofile.regionHandle = Convert.ToUInt64(reader["regionHandle"]);
  198. regionprofile.regionName = (string)reader["regionName"];
  199. regionprofile.UUID = new LLUUID((string)reader["uuid"]);
  200. // Secrets
  201. regionprofile.regionRecvKey = (string)reader["regionRecvKey"];
  202. regionprofile.regionSecret = (string)reader["regionSecret"];
  203. regionprofile.regionSendKey = (string)reader["regionSendKey"];
  204. // Region Server
  205. regionprofile.regionDataURI = (string)reader["regionDataURI"];
  206. regionprofile.regionOnline = false; // Needs to be pinged before this can be set.
  207. regionprofile.serverIP = (string)reader["serverIP"];
  208. regionprofile.serverPort = Convert.ToUInt32(reader["serverPort"]);
  209. regionprofile.serverURI = (string)reader["serverURI"];
  210. regionprofile.httpPort = Convert.ToUInt32(reader["serverHttpPort"]);
  211. regionprofile.remotingPort = Convert.ToUInt32(reader["serverRemotingPort"]);
  212. // Location
  213. regionprofile.regionLocX = Convert.ToUInt32(reader["locX"]);
  214. regionprofile.regionLocY = Convert.ToUInt32(reader["locY"]);
  215. regionprofile.regionLocZ = Convert.ToUInt32(reader["locZ"]);
  216. // Neighbours - 0 = No Override
  217. regionprofile.regionEastOverrideHandle = Convert.ToUInt64(reader["eastOverrideHandle"]);
  218. regionprofile.regionWestOverrideHandle = Convert.ToUInt64(reader["westOverrideHandle"]);
  219. regionprofile.regionSouthOverrideHandle = Convert.ToUInt64(reader["southOverrideHandle"]);
  220. regionprofile.regionNorthOverrideHandle = Convert.ToUInt64(reader["northOverrideHandle"]);
  221. // Assets
  222. regionprofile.regionAssetURI = (string)reader["regionAssetURI"];
  223. regionprofile.regionAssetRecvKey = (string)reader["regionAssetRecvKey"];
  224. regionprofile.regionAssetSendKey = (string)reader["regionAssetSendKey"];
  225. // Userserver
  226. regionprofile.regionUserURI = (string)reader["regionUserURI"];
  227. regionprofile.regionUserRecvKey = (string)reader["regionUserRecvKey"];
  228. regionprofile.regionUserSendKey = (string)reader["regionUserSendKey"];
  229. regionprofile.owner_uuid = new LLUUID((string) reader["owner_uuid"]);
  230. // World Map Addition
  231. string tempRegionMap = reader["regionMapTexture"].ToString();
  232. if (tempRegionMap != String.Empty)
  233. {
  234. regionprofile.regionMapTextureID = new LLUUID(tempRegionMap);
  235. }
  236. else
  237. {
  238. regionprofile.regionMapTextureID = new LLUUID();
  239. }
  240. }
  241. else
  242. {
  243. reader.Close();
  244. throw new Exception("No rows to return");
  245. }
  246. return regionprofile;
  247. }
  248. /// <summary>
  249. /// Reads a user profile from an active data reader
  250. /// </summary>
  251. /// <param name="reader">An active database reader</param>
  252. /// <returns>A user profile</returns>
  253. public UserProfileData readUserRow(IDataReader reader)
  254. {
  255. UserProfileData retval = new UserProfileData();
  256. if (reader.Read())
  257. {
  258. retval.ID = new LLUUID((string)reader["UUID"]);
  259. retval.FirstName = (string)reader["username"];
  260. retval.SurName = (string)reader["lastname"];
  261. retval.PasswordHash = (string)reader["passwordHash"];
  262. retval.PasswordSalt = (string)reader["passwordSalt"];
  263. retval.HomeRegion = Convert.ToUInt64(reader["homeRegion"].ToString());
  264. retval.HomeLocation = new LLVector3(
  265. Convert.ToSingle(reader["homeLocationX"].ToString()),
  266. Convert.ToSingle(reader["homeLocationY"].ToString()),
  267. Convert.ToSingle(reader["homeLocationZ"].ToString()));
  268. retval.HomeLookAt = new LLVector3(
  269. Convert.ToSingle(reader["homeLookAtX"].ToString()),
  270. Convert.ToSingle(reader["homeLookAtY"].ToString()),
  271. Convert.ToSingle(reader["homeLookAtZ"].ToString()));
  272. retval.Created = Convert.ToInt32(reader["created"].ToString());
  273. retval.LastLogin = Convert.ToInt32(reader["lastLogin"].ToString());
  274. retval.UserInventoryURI = (string)reader["userInventoryURI"];
  275. retval.UserAssetURI = (string)reader["userAssetURI"];
  276. retval.CanDoMask = Convert.ToUInt32(reader["profileCanDoMask"].ToString());
  277. retval.WantDoMask = Convert.ToUInt32(reader["profileWantDoMask"].ToString());
  278. retval.AboutText = (string)reader["profileAboutText"];
  279. retval.FirstLifeAboutText = (string)reader["profileFirstText"];
  280. retval.Image = new LLUUID((string)reader["profileImage"]);
  281. retval.FirstLifeImage = new LLUUID((string)reader["profileFirstImage"]);
  282. retval.WebLoginKey = new LLUUID((string)reader["webLoginKey"]);
  283. }
  284. else
  285. {
  286. return null;
  287. }
  288. return retval;
  289. }
  290. /// <summary>
  291. /// Reads an agent row from a database reader
  292. /// </summary>
  293. /// <param name="reader">An active database reader</param>
  294. /// <returns>A user session agent</returns>
  295. public UserAgentData readAgentRow(IDataReader reader)
  296. {
  297. UserAgentData retval = new UserAgentData();
  298. if (reader.Read())
  299. {
  300. // Agent IDs
  301. retval.ProfileID = new LLUUID((string)reader["UUID"]);
  302. retval.SessionID = new LLUUID((string)reader["sessionID"]);
  303. retval.SecureSessionID = new LLUUID((string)reader["secureSessionID"]);
  304. // Agent Who?
  305. retval.AgentIP = (string)reader["agentIP"];
  306. retval.AgentPort = Convert.ToUInt32(reader["agentPort"].ToString());
  307. retval.AgentOnline = Convert.ToBoolean(reader["agentOnline"].ToString());
  308. // Login/Logout times (UNIX Epoch)
  309. retval.LoginTime = Convert.ToInt32(reader["loginTime"].ToString());
  310. retval.LogoutTime = Convert.ToInt32(reader["logoutTime"].ToString());
  311. // Current position
  312. retval.Region = (string)reader["currentRegion"];
  313. retval.Handle = Convert.ToUInt64(reader["currentHandle"].ToString());
  314. LLVector3 tmp_v;
  315. LLVector3.TryParse((string)reader["currentPos"], out tmp_v);
  316. retval.Position = tmp_v;
  317. }
  318. else
  319. {
  320. return null;
  321. }
  322. return retval;
  323. }
  324. /// <summary>
  325. ///
  326. /// </summary>
  327. /// <param name="reader"></param>
  328. /// <returns></returns>
  329. public AssetBase getAssetRow(IDataReader reader)
  330. {
  331. AssetBase asset = new AssetBase();
  332. if (reader.Read())
  333. {
  334. // Region Main
  335. asset = new AssetBase();
  336. asset.Data = (byte[])reader["data"];
  337. asset.Description = (string)reader["description"];
  338. asset.FullID = new LLUUID((string)reader["id"]);
  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. using (IDbCommand result = Query(sql, parameters))
  373. {
  374. try
  375. {
  376. if (result.ExecuteNonQuery() == 1)
  377. returnval = true;
  378. }
  379. catch (Exception e)
  380. {
  381. m_log.Error(e.ToString());
  382. return false;
  383. }
  384. }
  385. return returnval;
  386. }
  387. /// <summary>
  388. /// Execute a SQL statement stored in a resource, as a string
  389. /// </summary>
  390. /// <param name="name">the ressource string</param>
  391. public void ExecuteResourceSql(string name)
  392. {
  393. using (IDbCommand cmd = Query(getResourceString(name), new Dictionary<string,string>()))
  394. {
  395. cmd.ExecuteNonQuery();
  396. }
  397. }
  398. /// <summary>
  399. /// Given a list of tables, return the version of the tables, as seen in the database
  400. /// </summary>
  401. /// <param name="tableList"></param>
  402. public void GetTableVersion(Dictionary<string, string> tableList)
  403. {
  404. Dictionary<string, string> param = new Dictionary<string, string>();
  405. param["dbname"] = new SqlConnectionStringBuilder(connectionString).InitialCatalog;
  406. using (IDbCommand tablesCmd =
  407. Query("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_CATALOG=@dbname", param))
  408. using (IDataReader tables = tablesCmd.ExecuteReader())
  409. {
  410. while (tables.Read())
  411. {
  412. try
  413. {
  414. string tableName = (string)tables["TABLE_NAME"];
  415. if (tableList.ContainsKey(tableName))
  416. tableList[tableName] = tableName;
  417. }
  418. catch (Exception e)
  419. {
  420. m_log.Error(e.ToString());
  421. }
  422. }
  423. tables.Close();
  424. }
  425. }
  426. /// <summary>
  427. ///
  428. /// </summary>
  429. /// <param name="name"></param>
  430. /// <returns></returns>
  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. }