MySQLGridData.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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 OpenSimulator 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.Threading;
  32. using log4net;
  33. using OpenMetaverse;
  34. using OpenSim.Framework;
  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. /// Better DB manager. Swap-in replacement too.
  49. /// </summary>
  50. public Dictionary<int, MySQLSuperManager> m_dbconnections = new Dictionary<int, MySQLSuperManager>();
  51. public int m_maxConnections = 10;
  52. public int m_lastConnect;
  53. public MySQLSuperManager GetLockedConnection()
  54. {
  55. int lockedCons = 0;
  56. while (true)
  57. {
  58. m_lastConnect++;
  59. // Overflow protection
  60. if (m_lastConnect == int.MaxValue)
  61. m_lastConnect = 0;
  62. MySQLSuperManager x = m_dbconnections[m_lastConnect % m_maxConnections];
  63. if (!x.Locked)
  64. {
  65. x.GetLock();
  66. return x;
  67. }
  68. lockedCons++;
  69. if (lockedCons > m_maxConnections)
  70. {
  71. lockedCons = 0;
  72. Thread.Sleep(1000); // Wait some time before searching them again.
  73. m_log.Debug(
  74. "WARNING: All threads are in use. Probable cause: Something didnt release a mutex properly, or high volume of requests inbound.");
  75. }
  76. }
  77. }
  78. override public void Initialise()
  79. {
  80. m_log.Info("[MySQLGridData]: " + Name + " cannot be default-initialized!");
  81. throw new PluginNotInitialisedException (Name);
  82. }
  83. /// <summary>
  84. /// <para>Initialises Grid interface</para>
  85. /// <para>
  86. /// <list type="bullet">
  87. /// <item>Loads and initialises the MySQL storage plugin</item>
  88. /// <item>Warns and uses the obsolete mysql_connection.ini if connect string is empty.</item>
  89. /// <item>Check for migration</item>
  90. /// </list>
  91. /// </para>
  92. /// </summary>
  93. /// <param name="connect">connect string.</param>
  94. override public void Initialise(string connect)
  95. {
  96. if (connect != String.Empty)
  97. {
  98. database = new MySQLManager(connect);
  99. m_log.Info("Creating " + m_maxConnections + " DB connections...");
  100. for (int i = 0; i < m_maxConnections; i++)
  101. {
  102. m_log.Info("Connecting to DB... [" + i + "]");
  103. MySQLSuperManager msm = new MySQLSuperManager();
  104. msm.Manager = new MySQLManager(connect);
  105. m_dbconnections.Add(i, msm);
  106. }
  107. }
  108. else
  109. {
  110. m_log.Warn("Using deprecated mysql_connection.ini. Please update database_connect in GridServer_Config.xml and we'll use that instead");
  111. IniFile GridDataMySqlFile = new IniFile("mysql_connection.ini");
  112. string settingHostname = GridDataMySqlFile.ParseFileReadValue("hostname");
  113. string settingDatabase = GridDataMySqlFile.ParseFileReadValue("database");
  114. string settingUsername = GridDataMySqlFile.ParseFileReadValue("username");
  115. string settingPassword = GridDataMySqlFile.ParseFileReadValue("password");
  116. string settingPooling = GridDataMySqlFile.ParseFileReadValue("pooling");
  117. string settingPort = GridDataMySqlFile.ParseFileReadValue("port");
  118. database = new MySQLManager(settingHostname, settingDatabase, settingUsername, settingPassword,
  119. settingPooling, settingPort);
  120. m_log.Info("Creating " + m_maxConnections + " DB connections...");
  121. for (int i = 0; i < m_maxConnections; i++)
  122. {
  123. m_log.Info("Connecting to DB... [" + i + "]");
  124. MySQLSuperManager msm = new MySQLSuperManager();
  125. msm.Manager = new MySQLManager(settingHostname, settingDatabase, settingUsername, settingPassword,
  126. settingPooling, settingPort);
  127. m_dbconnections.Add(i, msm);
  128. }
  129. }
  130. // This actually does the roll forward assembly stuff
  131. Assembly assem = GetType().Assembly;
  132. Migration m = new Migration(database.Connection, assem, "GridStore");
  133. m.Update();
  134. }
  135. /// <summary>
  136. /// Shuts down the grid interface
  137. /// </summary>
  138. override public void Dispose()
  139. {
  140. database.Close();
  141. }
  142. /// <summary>
  143. /// Returns the plugin name
  144. /// </summary>
  145. /// <returns>Plugin name</returns>
  146. override public string Name
  147. {
  148. get { return "MySql OpenGridData"; }
  149. }
  150. /// <summary>
  151. /// Returns the plugin version
  152. /// </summary>
  153. /// <returns>Plugin version</returns>
  154. override public string Version
  155. {
  156. get { return "0.1"; }
  157. }
  158. /// <summary>
  159. /// Returns all the specified region profiles within coordates -- coordinates are inclusive
  160. /// </summary>
  161. /// <param name="xmin">Minimum X coordinate</param>
  162. /// <param name="ymin">Minimum Y coordinate</param>
  163. /// <param name="xmax">Maximum X coordinate</param>
  164. /// <param name="ymax">Maximum Y coordinate</param>
  165. /// <returns>Array of sim profiles</returns>
  166. override public RegionProfileData[] GetProfilesInRange(uint xmin, uint ymin, uint xmax, uint ymax)
  167. {
  168. MySQLSuperManager dbm = GetLockedConnection();
  169. try
  170. {
  171. Dictionary<string, object> param = new Dictionary<string, object>();
  172. param["?xmin"] = xmin.ToString();
  173. param["?ymin"] = ymin.ToString();
  174. param["?xmax"] = xmax.ToString();
  175. param["?ymax"] = ymax.ToString();
  176. using (IDbCommand result = dbm.Manager.Query(
  177. "SELECT * FROM regions WHERE locX >= ?xmin AND locX <= ?xmax AND locY >= ?ymin AND locY <= ?ymax",
  178. param))
  179. {
  180. using (IDataReader reader = result.ExecuteReader())
  181. {
  182. RegionProfileData row;
  183. List<RegionProfileData> rows = new List<RegionProfileData>();
  184. while ((row = dbm.Manager.readSimRow(reader)) != null)
  185. rows.Add(row);
  186. return rows.ToArray();
  187. }
  188. }
  189. }
  190. catch (Exception e)
  191. {
  192. dbm.Manager.Reconnect();
  193. m_log.Error(e.Message, e);
  194. return null;
  195. }
  196. finally
  197. {
  198. dbm.Release();
  199. }
  200. }
  201. /// <summary>
  202. /// Returns up to maxNum profiles of regions that have a name starting with namePrefix
  203. /// </summary>
  204. /// <param name="name">The name to match against</param>
  205. /// <param name="maxNum">Maximum number of profiles to return</param>
  206. /// <returns>A list of sim profiles</returns>
  207. override public List<RegionProfileData> GetRegionsByName(string namePrefix, uint maxNum)
  208. {
  209. MySQLSuperManager dbm = GetLockedConnection();
  210. try
  211. {
  212. Dictionary<string, object> param = new Dictionary<string, object>();
  213. param["?name"] = namePrefix + "%";
  214. using (IDbCommand result = dbm.Manager.Query(
  215. "SELECT * FROM regions WHERE regionName LIKE ?name",
  216. param))
  217. {
  218. using (IDataReader reader = result.ExecuteReader())
  219. {
  220. RegionProfileData row;
  221. List<RegionProfileData> rows = new List<RegionProfileData>();
  222. while (rows.Count < maxNum && (row = dbm.Manager.readSimRow(reader)) != null)
  223. rows.Add(row);
  224. return rows;
  225. }
  226. }
  227. }
  228. catch (Exception e)
  229. {
  230. dbm.Manager.Reconnect();
  231. m_log.Error(e.Message, e);
  232. return null;
  233. }
  234. finally
  235. {
  236. dbm.Release();
  237. }
  238. }
  239. /// <summary>
  240. /// Returns a sim profile from it's location
  241. /// </summary>
  242. /// <param name="handle">Region location handle</param>
  243. /// <returns>Sim profile</returns>
  244. override public RegionProfileData GetProfileByHandle(ulong handle)
  245. {
  246. MySQLSuperManager dbm = GetLockedConnection();
  247. try
  248. {
  249. Dictionary<string, object> param = new Dictionary<string, object>();
  250. param["?handle"] = handle.ToString();
  251. using (IDbCommand result = dbm.Manager.Query("SELECT * FROM regions WHERE regionHandle = ?handle", param))
  252. {
  253. using (IDataReader reader = result.ExecuteReader())
  254. {
  255. RegionProfileData row = dbm.Manager.readSimRow(reader);
  256. return row;
  257. }
  258. }
  259. }
  260. catch (Exception e)
  261. {
  262. dbm.Manager.Reconnect();
  263. m_log.Error(e.Message, e);
  264. return null;
  265. }
  266. finally
  267. {
  268. dbm.Release();
  269. }
  270. }
  271. /// <summary>
  272. /// Returns a sim profile from it's UUID
  273. /// </summary>
  274. /// <param name="uuid">The region UUID</param>
  275. /// <returns>The sim profile</returns>
  276. override public RegionProfileData GetProfileByUUID(UUID uuid)
  277. {
  278. MySQLSuperManager dbm = GetLockedConnection();
  279. try
  280. {
  281. Dictionary<string, object> param = new Dictionary<string, object>();
  282. param["?uuid"] = uuid.ToString();
  283. using (IDbCommand result = dbm.Manager.Query("SELECT * FROM regions WHERE uuid = ?uuid", param))
  284. {
  285. using (IDataReader reader = result.ExecuteReader())
  286. {
  287. RegionProfileData row = dbm.Manager.readSimRow(reader);
  288. return row;
  289. }
  290. }
  291. }
  292. catch (Exception e)
  293. {
  294. dbm.Manager.Reconnect();
  295. m_log.Error(e.Message, e);
  296. return null;
  297. }
  298. finally
  299. {
  300. dbm.Release();
  301. }
  302. }
  303. /// <summary>
  304. /// Returns a sim profile from it's Region name string
  305. /// </summary>
  306. /// <returns>The sim profile</returns>
  307. override public RegionProfileData GetProfileByString(string regionName)
  308. {
  309. if (regionName.Length > 2)
  310. {
  311. MySQLSuperManager dbm = GetLockedConnection();
  312. try
  313. {
  314. Dictionary<string, object> param = new Dictionary<string, object>();
  315. // Add % because this is a like query.
  316. param["?regionName"] = regionName + "%";
  317. // Order by statement will return shorter matches first. Only returns one record or no record.
  318. using (IDbCommand result = dbm.Manager.Query(
  319. "SELECT * FROM regions WHERE regionName like ?regionName order by LENGTH(regionName) asc LIMIT 1",
  320. param))
  321. {
  322. using (IDataReader reader = result.ExecuteReader())
  323. {
  324. RegionProfileData row = dbm.Manager.readSimRow(reader);
  325. return row;
  326. }
  327. }
  328. }
  329. catch (Exception e)
  330. {
  331. dbm.Manager.Reconnect();
  332. m_log.Error(e.Message, e);
  333. return null;
  334. }
  335. finally
  336. {
  337. dbm.Release();
  338. }
  339. }
  340. m_log.Error("[GRID DB]: Searched for a Region Name shorter then 3 characters");
  341. return null;
  342. }
  343. /// <summary>
  344. /// Adds a new profile to the database
  345. /// </summary>
  346. /// <param name="profile">The profile to add</param>
  347. /// <returns>Successful?</returns>
  348. override public DataResponse StoreProfile(RegionProfileData profile)
  349. {
  350. MySQLSuperManager dbm = GetLockedConnection();
  351. try
  352. {
  353. if (dbm.Manager.insertRegion(profile))
  354. return DataResponse.RESPONSE_OK;
  355. else
  356. return DataResponse.RESPONSE_ERROR;
  357. }
  358. finally
  359. {
  360. dbm.Release();
  361. }
  362. }
  363. /// <summary>
  364. /// Deletes a sim profile from the database
  365. /// </summary>
  366. /// <param name="uuid">the sim UUID</param>
  367. /// <returns>Successful?</returns>
  368. //public DataResponse DeleteProfile(RegionProfileData profile)
  369. override public DataResponse DeleteProfile(string uuid)
  370. {
  371. MySQLSuperManager dbm = GetLockedConnection();
  372. try
  373. {
  374. if (dbm.Manager.deleteRegion(uuid))
  375. return DataResponse.RESPONSE_OK;
  376. else
  377. return DataResponse.RESPONSE_ERROR;
  378. }
  379. finally
  380. {
  381. dbm.Release();
  382. }
  383. }
  384. /// <summary>
  385. /// DEPRECATED. Attempts to authenticate a region by comparing a shared secret.
  386. /// </summary>
  387. /// <param name="uuid">The UUID of the challenger</param>
  388. /// <param name="handle">The attempted regionHandle of the challenger</param>
  389. /// <param name="authkey">The secret</param>
  390. /// <returns>Whether the secret and regionhandle match the database entry for UUID</returns>
  391. override public bool AuthenticateSim(UUID uuid, ulong handle, string authkey)
  392. {
  393. bool throwHissyFit = false; // Should be true by 1.0
  394. if (throwHissyFit)
  395. throw new Exception("CRYPTOWEAK AUTHENTICATE: Refusing to authenticate due to replay potential.");
  396. RegionProfileData data = GetProfileByUUID(uuid);
  397. return (handle == data.regionHandle && authkey == data.regionSecret);
  398. }
  399. /// <summary>
  400. /// NOT YET FUNCTIONAL. Provides a cryptographic authentication of a region
  401. /// </summary>
  402. /// <remarks>This requires a security audit.</remarks>
  403. /// <param name="uuid"></param>
  404. /// <param name="handle"></param>
  405. /// <param name="authhash"></param>
  406. /// <param name="challenge"></param>
  407. /// <returns></returns>
  408. public bool AuthenticateSim(UUID uuid, ulong handle, string authhash, string challenge)
  409. {
  410. // SHA512Managed HashProvider = new SHA512Managed();
  411. // Encoding TextProvider = new UTF8Encoding();
  412. // byte[] stream = TextProvider.GetBytes(uuid.ToString() + ":" + handle.ToString() + ":" + challenge);
  413. // byte[] hash = HashProvider.ComputeHash(stream);
  414. return false;
  415. }
  416. /// <summary>
  417. /// Adds a location reservation
  418. /// </summary>
  419. /// <param name="x">x coordinate</param>
  420. /// <param name="y">y coordinate</param>
  421. /// <returns></returns>
  422. override public ReservationData GetReservationAtPoint(uint x, uint y)
  423. {
  424. MySQLSuperManager dbm = GetLockedConnection();
  425. try
  426. {
  427. Dictionary<string, object> param = new Dictionary<string, object>();
  428. param["?x"] = x.ToString();
  429. param["?y"] = y.ToString();
  430. using (IDbCommand result = dbm.Manager.Query(
  431. "SELECT * FROM reservations WHERE resXMin <= ?x AND resXMax >= ?x AND resYMin <= ?y AND resYMax >= ?y",
  432. param))
  433. {
  434. using (IDataReader reader = result.ExecuteReader())
  435. {
  436. ReservationData row = dbm.Manager.readReservationRow(reader);
  437. return row;
  438. }
  439. }
  440. }
  441. catch (Exception e)
  442. {
  443. dbm.Manager.Reconnect();
  444. m_log.Error(e.Message, e);
  445. return null;
  446. }
  447. finally
  448. {
  449. dbm.Release();
  450. }
  451. }
  452. }
  453. }