MySQLGridData.cs 15 KB

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