MySQLGridData.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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.Reflection;
  31. using System.Security.Cryptography;
  32. using System.Text;
  33. using libsecondlife;
  34. using log4net;
  35. namespace OpenSim.Data.MySQL
  36. {
  37. /// <summary>
  38. /// A MySQL Interface for the Grid Server
  39. /// </summary>
  40. public class MySQLGridData : GridDataBase
  41. {
  42. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  43. /// <summary>
  44. /// MySQL Database Manager
  45. /// </summary>
  46. private MySQLManager database;
  47. /// <summary>
  48. /// <para>Initialises Grid interface</para>
  49. /// <para>
  50. /// <list type="bullet">
  51. /// <item>Loads and initialises the MySQL storage plugin</item>
  52. /// <item>Warns and uses the obsolete mysql_connection.ini if connect string is empty.</item>
  53. /// <item>Check for migration</item>
  54. /// </list>
  55. /// </para>
  56. /// </summary>
  57. /// <param name="connect">connect string.</param>
  58. override public void Initialise(string connect)
  59. {
  60. if (connect != String.Empty)
  61. {
  62. database = new MySQLManager(connect);
  63. }
  64. else
  65. {
  66. m_log.Warn("Using deprecated mysql_connection.ini. Please update database_connect in GridServer_Config.xml and we'll use that instead");
  67. IniFile GridDataMySqlFile = new IniFile("mysql_connection.ini");
  68. string settingHostname = GridDataMySqlFile.ParseFileReadValue("hostname");
  69. string settingDatabase = GridDataMySqlFile.ParseFileReadValue("database");
  70. string settingUsername = GridDataMySqlFile.ParseFileReadValue("username");
  71. string settingPassword = GridDataMySqlFile.ParseFileReadValue("password");
  72. string settingPooling = GridDataMySqlFile.ParseFileReadValue("pooling");
  73. string settingPort = GridDataMySqlFile.ParseFileReadValue("port");
  74. database = new MySQLManager(settingHostname, settingDatabase, settingUsername, settingPassword,
  75. settingPooling, settingPort);
  76. }
  77. // This actually does the roll forward assembly stuff
  78. Assembly assem = GetType().Assembly;
  79. Migration m = new Migration(database.Connection, assem, "GridStore");
  80. // TODO: After rev 6000, remove this. People should have
  81. // been rolled onto the new migration code by then.
  82. TestTables(m);
  83. m.Update();
  84. }
  85. #region Test and initialization code
  86. /// <summary>
  87. /// Ensure that the user related tables exists and are at the latest version
  88. /// </summary>
  89. private void TestTables(Migration m)
  90. {
  91. // we already have migrations, get out of here
  92. if (m.Version > 0)
  93. return;
  94. Dictionary<string, string> tableList = new Dictionary<string, string>();
  95. tableList["regions"] = null;
  96. database.GetTableVersion(tableList);
  97. UpgradeRegionsTable(tableList["regions"]);
  98. // we have tables, but not a migration model yet
  99. if (m.Version == 0)
  100. m.Version = 1;
  101. }
  102. /// <summary>
  103. /// Create or upgrade the table if necessary
  104. /// </summary>
  105. /// <param name="oldVersion">A null indicates that the table does not
  106. /// currently exist</param>
  107. private void UpgradeRegionsTable(string oldVersion)
  108. {
  109. // null as the version, indicates that the table didn't exist
  110. if (oldVersion == null)
  111. {
  112. database.ExecuteResourceSql("CreateRegionsTable.sql");
  113. return;
  114. }
  115. if (oldVersion.Contains("Rev. 1"))
  116. {
  117. database.ExecuteResourceSql("UpgradeRegionsTableToVersion2.sql");
  118. return;
  119. }
  120. if (oldVersion.Contains("Rev. 2"))
  121. {
  122. database.ExecuteResourceSql("UpgradeRegionsTableToVersion3.sql");
  123. return;
  124. }
  125. }
  126. #endregion
  127. /// <summary>
  128. /// Shuts down the grid interface
  129. /// </summary>
  130. override public void Close()
  131. {
  132. database.Close();
  133. }
  134. /// <summary>
  135. /// Returns the plugin name
  136. /// </summary>
  137. /// <returns>Plugin name</returns>
  138. override public string getName()
  139. {
  140. return "MySql OpenGridData";
  141. }
  142. /// <summary>
  143. /// Returns the plugin version
  144. /// </summary>
  145. /// <returns>Plugin version</returns>
  146. override public string getVersion()
  147. {
  148. return "0.1";
  149. }
  150. /// <summary>
  151. /// Returns all the specified region profiles within coordates -- coordinates are inclusive
  152. /// </summary>
  153. /// <param name="xmin">Minimum X coordinate</param>
  154. /// <param name="ymin">Minimum Y coordinate</param>
  155. /// <param name="xmax">Maximum X coordinate</param>
  156. /// <param name="ymax">Maximum Y coordinate</param>
  157. /// <returns>Array of sim profiles</returns>
  158. override public RegionProfileData[] GetProfilesInRange(uint xmin, uint ymin, uint xmax, uint ymax)
  159. {
  160. try
  161. {
  162. lock (database)
  163. {
  164. Dictionary<string, string> param = new Dictionary<string, string>();
  165. param["?xmin"] = xmin.ToString();
  166. param["?ymin"] = ymin.ToString();
  167. param["?xmax"] = xmax.ToString();
  168. param["?ymax"] = ymax.ToString();
  169. IDbCommand result =
  170. database.Query(
  171. "SELECT * FROM regions WHERE locX >= ?xmin AND locX <= ?xmax AND locY >= ?ymin AND locY <= ?ymax",
  172. param);
  173. IDataReader reader = result.ExecuteReader();
  174. RegionProfileData row;
  175. List<RegionProfileData> rows = new List<RegionProfileData>();
  176. while ((row = database.readSimRow(reader)) != null)
  177. {
  178. rows.Add(row);
  179. }
  180. reader.Close();
  181. result.Dispose();
  182. return rows.ToArray();
  183. }
  184. }
  185. catch (Exception e)
  186. {
  187. database.Reconnect();
  188. m_log.Error(e.ToString());
  189. return null;
  190. }
  191. }
  192. /// <summary>
  193. /// Returns a sim profile from it's location
  194. /// </summary>
  195. /// <param name="handle">Region location handle</param>
  196. /// <returns>Sim profile</returns>
  197. override public RegionProfileData GetProfileByHandle(ulong handle)
  198. {
  199. try
  200. {
  201. lock (database)
  202. {
  203. Dictionary<string, string> param = new Dictionary<string, string>();
  204. param["?handle"] = handle.ToString();
  205. IDbCommand result = database.Query("SELECT * FROM regions WHERE regionHandle = ?handle", param);
  206. IDataReader reader = result.ExecuteReader();
  207. RegionProfileData row = database.readSimRow(reader);
  208. reader.Close();
  209. result.Dispose();
  210. return row;
  211. }
  212. }
  213. catch (Exception e)
  214. {
  215. database.Reconnect();
  216. m_log.Error(e.ToString());
  217. return null;
  218. }
  219. }
  220. /// <summary>
  221. /// Returns a sim profile from it's UUID
  222. /// </summary>
  223. /// <param name="uuid">The region UUID</param>
  224. /// <returns>The sim profile</returns>
  225. override public RegionProfileData GetProfileByLLUUID(LLUUID uuid)
  226. {
  227. try
  228. {
  229. lock (database)
  230. {
  231. Dictionary<string, string> param = new Dictionary<string, string>();
  232. param["?uuid"] = uuid.ToString();
  233. IDbCommand result = database.Query("SELECT * FROM regions WHERE uuid = ?uuid", param);
  234. IDataReader reader = result.ExecuteReader();
  235. RegionProfileData row = database.readSimRow(reader);
  236. reader.Close();
  237. result.Dispose();
  238. return row;
  239. }
  240. }
  241. catch (Exception e)
  242. {
  243. database.Reconnect();
  244. m_log.Error(e.ToString());
  245. return null;
  246. }
  247. }
  248. /// <summary>
  249. /// Returns a sim profile from it's Region name string
  250. /// </summary>
  251. /// <param name="uuid">The region name search query</param>
  252. /// <returns>The sim profile</returns>
  253. override public RegionProfileData GetProfileByString(string regionName)
  254. {
  255. if (regionName.Length > 2)
  256. {
  257. try
  258. {
  259. lock (database)
  260. {
  261. Dictionary<string, string> param = new Dictionary<string, string>();
  262. // Add % because this is a like query.
  263. param["?regionName"] = regionName + "%";
  264. // Order by statement will return shorter matches first. Only returns one record or no record.
  265. IDbCommand result = database.Query("SELECT * FROM regions WHERE regionName like ?regionName order by LENGTH(regionName) asc LIMIT 1", param);
  266. IDataReader reader = result.ExecuteReader();
  267. RegionProfileData row = database.readSimRow(reader);
  268. reader.Close();
  269. result.Dispose();
  270. return row;
  271. }
  272. }
  273. catch (Exception e)
  274. {
  275. database.Reconnect();
  276. m_log.Error(e.ToString());
  277. return null;
  278. }
  279. }
  280. else
  281. {
  282. m_log.Error("[GRID DB]: Searched for a Region Name shorter then 3 characters");
  283. return null;
  284. }
  285. }
  286. /// <summary>
  287. /// Adds a new profile to the database
  288. /// </summary>
  289. /// <param name="profile">The profile to add</param>
  290. /// <returns>Successful?</returns>
  291. override public DataResponse AddProfile(RegionProfileData profile)
  292. {
  293. lock (database)
  294. {
  295. if (database.insertRegion(profile))
  296. {
  297. return DataResponse.RESPONSE_OK;
  298. }
  299. else
  300. {
  301. return DataResponse.RESPONSE_ERROR;
  302. }
  303. }
  304. }
  305. /// <summary>
  306. /// Update a sim profile
  307. /// </summary>
  308. /// <param name="profile">The profile to update</param>
  309. /// <returns>Sucessful?</returns>
  310. /// <remarks>Same as AddProfile</remarks>
  311. override public DataResponse UpdateProfile(RegionProfileData profile)
  312. {
  313. return AddProfile(profile);
  314. }
  315. /// <summary>
  316. /// Deletes a sim profile from the database
  317. /// </summary>
  318. /// <param name="uuid">the sim UUID</param>
  319. /// <returns>Successful?</returns>
  320. //public DataResponse DeleteProfile(RegionProfileData profile)
  321. public DataResponse DeleteProfile(string uuid)
  322. {
  323. lock (database)
  324. {
  325. if (database.deleteRegion(uuid))
  326. {
  327. return DataResponse.RESPONSE_OK;
  328. }
  329. else
  330. {
  331. return DataResponse.RESPONSE_ERROR;
  332. }
  333. }
  334. }
  335. /// <summary>
  336. /// DEPRECATED. Attempts to authenticate a region by comparing a shared secret.
  337. /// </summary>
  338. /// <param name="uuid">The UUID of the challenger</param>
  339. /// <param name="handle">The attempted regionHandle of the challenger</param>
  340. /// <param name="authkey">The secret</param>
  341. /// <returns>Whether the secret and regionhandle match the database entry for UUID</returns>
  342. override public bool AuthenticateSim(LLUUID uuid, ulong handle, string authkey)
  343. {
  344. bool throwHissyFit = false; // Should be true by 1.0
  345. if (throwHissyFit)
  346. throw new Exception("CRYPTOWEAK AUTHENTICATE: Refusing to authenticate due to replay potential.");
  347. RegionProfileData data = GetProfileByLLUUID(uuid);
  348. return (handle == data.regionHandle && authkey == data.regionSecret);
  349. }
  350. /// <summary>
  351. /// NOT YET FUNCTIONAL. Provides a cryptographic authentication of a region
  352. /// </summary>
  353. /// <remarks>This requires a security audit.</remarks>
  354. /// <param name="uuid"></param>
  355. /// <param name="handle"></param>
  356. /// <param name="authhash"></param>
  357. /// <param name="challenge"></param>
  358. /// <returns></returns>
  359. public bool AuthenticateSim(LLUUID uuid, ulong handle, string authhash, string challenge)
  360. {
  361. // SHA512Managed HashProvider = new SHA512Managed();
  362. // Encoding TextProvider = new UTF8Encoding();
  363. // byte[] stream = TextProvider.GetBytes(uuid.ToString() + ":" + handle.ToString() + ":" + challenge);
  364. // byte[] hash = HashProvider.ComputeHash(stream);
  365. return false;
  366. }
  367. /// <summary>
  368. /// Adds a location reservation
  369. /// </summary>
  370. /// <param name="x">x coordinate</param>
  371. /// <param name="y">y coordinate</param>
  372. /// <returns></returns>
  373. override public ReservationData GetReservationAtPoint(uint x, uint y)
  374. {
  375. try
  376. {
  377. lock (database)
  378. {
  379. Dictionary<string, string> param = new Dictionary<string, string>();
  380. param["?x"] = x.ToString();
  381. param["?y"] = y.ToString();
  382. IDbCommand result =
  383. database.Query(
  384. "SELECT * FROM reservations WHERE resXMin <= ?x AND resXMax >= ?x AND resYMin <= ?y AND resYMax >= ?y",
  385. param);
  386. IDataReader reader = result.ExecuteReader();
  387. ReservationData row = database.readReservationRow(reader);
  388. reader.Close();
  389. result.Dispose();
  390. return row;
  391. }
  392. }
  393. catch (Exception e)
  394. {
  395. database.Reconnect();
  396. m_log.Error(e.ToString());
  397. return null;
  398. }
  399. }
  400. }
  401. }