aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Framework/Data.MySQL/MySQLManager.cs
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--OpenSim/Framework/Data.MySQL/MySQLManager.cs602
1 files changed, 602 insertions, 0 deletions
diff --git a/OpenSim/Framework/Data.MySQL/MySQLManager.cs b/OpenSim/Framework/Data.MySQL/MySQLManager.cs
new file mode 100644
index 0000000..88365a3
--- /dev/null
+++ b/OpenSim/Framework/Data.MySQL/MySQLManager.cs
@@ -0,0 +1,602 @@
1/*
2* Copyright (c) Contributors, http://www.openmetaverse.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*/
28using System;
29using System.Collections.Generic;
30using System.Data;
31using libsecondlife;
32using MySql.Data.MySqlClient;
33
34namespace OpenSim.Framework.Data.MySQL
35{
36 /// <summary>
37 /// A MySQL Database manager
38 /// </summary>
39 class MySQLManager
40 {
41 /// <summary>
42 /// The database connection object
43 /// </summary>
44 IDbConnection dbcon;
45 /// <summary>
46 /// Connection string for ADO.net
47 /// </summary>
48 string connectionString;
49
50 /// <summary>
51 /// Initialises and creates a new MySQL connection and maintains it.
52 /// </summary>
53 /// <param name="hostname">The MySQL server being connected to</param>
54 /// <param name="database">The name of the MySQL database being used</param>
55 /// <param name="username">The username logging into the database</param>
56 /// <param name="password">The password for the user logging in</param>
57 /// <param name="cpooling">Whether to use connection pooling or not, can be one of the following: 'yes', 'true', 'no' or 'false', if unsure use 'false'.</param>
58 public MySQLManager(string hostname, string database, string username, string password, string cpooling, string port)
59 {
60 try
61 {
62 connectionString = "Server=" + hostname + ";Port=" + port + ";Database=" + database + ";User ID=" + username + ";Password=" + password + ";Pooling=" + cpooling + ";";
63 dbcon = new MySqlConnection(connectionString);
64
65 dbcon.Open();
66
67 Console.WriteLine("MySQL connection established");
68 }
69 catch (Exception e)
70 {
71 throw new Exception("Error initialising MySql Database: " + e.ToString());
72 }
73 }
74
75 /// <summary>
76 /// Shuts down the database connection
77 /// </summary>
78 public void Close()
79 {
80 dbcon.Close();
81 dbcon = null;
82 }
83
84 /// <summary>
85 /// Reconnects to the database
86 /// </summary>
87 public void Reconnect()
88 {
89 lock (dbcon)
90 {
91 try
92 {
93 // Close the DB connection
94 dbcon.Close();
95 // Try reopen it
96 dbcon = new MySqlConnection(connectionString);
97 dbcon.Open();
98 }
99 catch (Exception e)
100 {
101 Console.WriteLine("Unable to reconnect to database " + e.ToString());
102 }
103 }
104 }
105
106 /// <summary>
107 /// Runs a query with protection against SQL Injection by using parameterised input.
108 /// </summary>
109 /// <param name="sql">The SQL string - replace any variables such as WHERE x = "y" with WHERE x = @y</param>
110 /// <param name="parameters">The parameters - index so that @y is indexed as 'y'</param>
111 /// <returns>A MySQL DB Command</returns>
112 public IDbCommand Query(string sql, Dictionary<string, string> parameters)
113 {
114 try
115 {
116 MySqlCommand dbcommand = (MySqlCommand)dbcon.CreateCommand();
117 dbcommand.CommandText = sql;
118 foreach (KeyValuePair<string, string> param in parameters)
119 {
120 dbcommand.Parameters.Add(param.Key, param.Value);
121 }
122
123 return (IDbCommand)dbcommand;
124 }
125 catch
126 {
127 lock (dbcon)
128 {
129 // Close the DB connection
130 try
131 {
132 dbcon.Close();
133 }
134 catch { }
135
136 // Try reopen it
137 try
138 {
139 dbcon = new MySqlConnection(connectionString);
140 dbcon.Open();
141 }
142 catch (Exception e)
143 {
144 Console.WriteLine("Unable to reconnect to database " + e.ToString());
145 }
146
147 // Run the query again
148 try
149 {
150 MySqlCommand dbcommand = (MySqlCommand)dbcon.CreateCommand();
151 dbcommand.CommandText = sql;
152 foreach (KeyValuePair<string, string> param in parameters)
153 {
154 dbcommand.Parameters.Add(param.Key, param.Value);
155 }
156
157 return (IDbCommand)dbcommand;
158 }
159 catch (Exception e)
160 {
161 // Return null if it fails.
162 Console.WriteLine("Failed during Query generation: " + e.ToString());
163 return null;
164 }
165 }
166 }
167 }
168
169 /// <summary>
170 /// Reads a region row from a database reader
171 /// </summary>
172 /// <param name="reader">An active database reader</param>
173 /// <returns>A region profile</returns>
174 public SimProfileData readSimRow(IDataReader reader)
175 {
176 SimProfileData retval = new SimProfileData();
177
178 if (reader.Read())
179 {
180 // Region Main
181 retval.regionHandle = Convert.ToUInt64(reader["regionHandle"].ToString());
182 retval.regionName = (string)reader["regionName"];
183 retval.UUID = new LLUUID((string)reader["uuid"]);
184
185 // Secrets
186 retval.regionRecvKey = (string)reader["regionRecvKey"];
187 retval.regionSecret = (string)reader["regionSecret"];
188 retval.regionSendKey = (string)reader["regionSendKey"];
189
190 // Region Server
191 retval.regionDataURI = (string)reader["regionDataURI"];
192 retval.regionOnline = false; // Needs to be pinged before this can be set.
193 retval.serverIP = (string)reader["serverIP"];
194 retval.serverPort = (uint)reader["serverPort"];
195 retval.serverURI = (string)reader["serverURI"];
196
197 // Location
198 retval.regionLocX = Convert.ToUInt32(reader["locX"].ToString());
199 retval.regionLocY = Convert.ToUInt32(reader["locY"].ToString());
200 retval.regionLocZ = Convert.ToUInt32(reader["locZ"].ToString());
201
202 // Neighbours - 0 = No Override
203 retval.regionEastOverrideHandle = Convert.ToUInt64(reader["eastOverrideHandle"].ToString());
204 retval.regionWestOverrideHandle = Convert.ToUInt64(reader["westOverrideHandle"].ToString());
205 retval.regionSouthOverrideHandle = Convert.ToUInt64(reader["southOverrideHandle"].ToString());
206 retval.regionNorthOverrideHandle = Convert.ToUInt64(reader["northOverrideHandle"].ToString());
207
208 // Assets
209 retval.regionAssetURI = (string)reader["regionAssetURI"];
210 retval.regionAssetRecvKey = (string)reader["regionAssetRecvKey"];
211 retval.regionAssetSendKey = (string)reader["regionAssetSendKey"];
212
213 // Userserver
214 retval.regionUserURI = (string)reader["regionUserURI"];
215 retval.regionUserRecvKey = (string)reader["regionUserRecvKey"];
216 retval.regionUserSendKey = (string)reader["regionUserSendKey"];
217
218 // World Map Addition
219 string tempRegionMap = reader["regionMapTexture"].ToString();
220 if (tempRegionMap != "")
221 {
222 retval.regionMapTextureID = new LLUUID(tempRegionMap);
223 }
224 else
225 {
226 retval.regionMapTextureID = new LLUUID();
227 }
228 }
229 else
230 {
231 return null;
232 }
233 return retval;
234 }
235
236 /// <summary>
237 /// Reads a reservation row from a database reader
238 /// </summary>
239 /// <param name="reader">An active database reader</param>
240 /// <returns>A reservation data object</returns>
241 public ReservationData readReservationRow(IDataReader reader)
242 {
243 ReservationData retval = new ReservationData();
244 if (reader.Read())
245 {
246 retval.gridRecvKey = (string)reader["gridRecvKey"];
247 retval.gridSendKey = (string)reader["gridSendKey"];
248 retval.reservationCompany = (string)reader["resCompany"];
249 retval.reservationMaxX = Convert.ToInt32(reader["resXMax"].ToString());
250 retval.reservationMaxY = Convert.ToInt32(reader["resYMax"].ToString());
251 retval.reservationMinX = Convert.ToInt32(reader["resXMin"].ToString());
252 retval.reservationMinY = Convert.ToInt32(reader["resYMin"].ToString());
253 retval.reservationName = (string)reader["resName"];
254 retval.status = Convert.ToInt32(reader["status"].ToString()) == 1;
255 retval.userUUID = new LLUUID((string)reader["userUUID"]);
256
257 }
258 else
259 {
260 return null;
261 }
262 return retval;
263 }
264 /// <summary>
265 /// Reads an agent row from a database reader
266 /// </summary>
267 /// <param name="reader">An active database reader</param>
268 /// <returns>A user session agent</returns>
269 public UserAgentData readAgentRow(IDataReader reader)
270 {
271 UserAgentData retval = new UserAgentData();
272
273 if (reader.Read())
274 {
275 // Agent IDs
276 retval.UUID = new LLUUID((string)reader["UUID"]);
277 retval.sessionID = new LLUUID((string)reader["sessionID"]);
278 retval.secureSessionID = new LLUUID((string)reader["secureSessionID"]);
279
280 // Agent Who?
281 retval.agentIP = (string)reader["agentIP"];
282 retval.agentPort = Convert.ToUInt32(reader["agentPort"].ToString());
283 retval.agentOnline = Convert.ToBoolean(reader["agentOnline"].ToString());
284
285 // Login/Logout times (UNIX Epoch)
286 retval.loginTime = Convert.ToInt32(reader["loginTime"].ToString());
287 retval.logoutTime = Convert.ToInt32(reader["logoutTime"].ToString());
288
289 // Current position
290 retval.currentRegion = (string)reader["currentRegion"];
291 retval.currentHandle = Convert.ToUInt64(reader["currentHandle"].ToString());
292 LLVector3.TryParse((string)reader["currentPos"], out retval.currentPos);
293 }
294 else
295 {
296 return null;
297 }
298 return retval;
299 }
300
301 /// <summary>
302 /// Reads a user profile from an active data reader
303 /// </summary>
304 /// <param name="reader">An active database reader</param>
305 /// <returns>A user profile</returns>
306 public UserProfileData readUserRow(IDataReader reader)
307 {
308 UserProfileData retval = new UserProfileData();
309
310 if (reader.Read())
311 {
312 retval.UUID = new LLUUID((string)reader["UUID"]);
313 retval.username = (string)reader["username"];
314 retval.surname = (string)reader["lastname"];
315
316 retval.passwordHash = (string)reader["passwordHash"];
317 retval.passwordSalt = (string)reader["passwordSalt"];
318
319 retval.homeRegion = Convert.ToUInt64(reader["homeRegion"].ToString());
320 retval.homeLocation = new LLVector3(
321 Convert.ToSingle(reader["homeLocationX"].ToString()),
322 Convert.ToSingle(reader["homeLocationY"].ToString()),
323 Convert.ToSingle(reader["homeLocationZ"].ToString()));
324 retval.homeLookAt = new LLVector3(
325 Convert.ToSingle(reader["homeLookAtX"].ToString()),
326 Convert.ToSingle(reader["homeLookAtY"].ToString()),
327 Convert.ToSingle(reader["homeLookAtZ"].ToString()));
328
329 retval.created = Convert.ToInt32(reader["created"].ToString());
330 retval.lastLogin = Convert.ToInt32(reader["lastLogin"].ToString());
331
332 retval.userInventoryURI = (string)reader["userInventoryURI"];
333 retval.userAssetURI = (string)reader["userAssetURI"];
334
335 retval.profileCanDoMask = Convert.ToUInt32(reader["profileCanDoMask"].ToString());
336 retval.profileWantDoMask = Convert.ToUInt32(reader["profileWantDoMask"].ToString());
337
338 retval.profileAboutText = (string)reader["profileAboutText"];
339 retval.profileFirstText = (string)reader["profileFirstText"];
340
341 retval.profileImage = new LLUUID((string)reader["profileImage"]);
342 retval.profileFirstImage = new LLUUID((string)reader["profileFirstImage"]);
343
344 }
345 else
346 {
347 return null;
348 }
349 return retval;
350 }
351
352 /// <summary>
353 /// Reads a list of inventory folders returned by a query.
354 /// </summary>
355 /// <param name="reader">A MySQL Data Reader</param>
356 /// <returns>A List containing inventory folders</returns>
357 public List<InventoryFolderBase> readInventoryFolders(IDataReader reader)
358 {
359 List<InventoryFolderBase> rows = new List<InventoryFolderBase>();
360
361 while(reader.Read())
362 {
363 try
364 {
365 InventoryFolderBase folder = new InventoryFolderBase();
366
367 folder.agentID = new LLUUID((string)reader["agentID"]);
368 folder.parentID = new LLUUID((string)reader["parentFolderID"]);
369 folder.folderID = new LLUUID((string)reader["folderID"]);
370 folder.name = (string)reader["folderName"];
371
372 rows.Add(folder);
373 }
374 catch (Exception e)
375 {
376 Console.WriteLine(e.ToString());
377 }
378 }
379
380 return rows;
381 }
382
383 /// <summary>
384 /// Reads a collection of items from an SQL result
385 /// </summary>
386 /// <param name="reader">The SQL Result</param>
387 /// <returns>A List containing Inventory Items</returns>
388 public List<InventoryItemBase> readInventoryItems(IDataReader reader)
389 {
390 List<InventoryItemBase> rows = new List<InventoryItemBase>();
391
392 while (reader.Read())
393 {
394 try
395 {
396 InventoryItemBase item = new InventoryItemBase();
397
398 item.assetID = new LLUUID((string)reader["assetID"]);
399 item.avatarID = new LLUUID((string)reader["avatarID"]);
400 item.inventoryCurrentPermissions = Convert.ToUInt32(reader["inventoryCurrentPermissions"].ToString());
401 item.inventoryDescription = (string)reader["inventoryDescription"];
402 item.inventoryID = new LLUUID((string)reader["inventoryID"]);
403 item.inventoryName = (string)reader["inventoryName"];
404 item.inventoryNextPermissions = Convert.ToUInt32(reader["inventoryNextPermissions"].ToString());
405 item.parentFolderID = new LLUUID((string)reader["parentFolderID"]);
406 item.type = Convert.ToInt32(reader["type"].ToString());
407
408 rows.Add(item);
409 }
410 catch (Exception e)
411 {
412 Console.WriteLine(e.ToString());
413 }
414 }
415
416 return rows;
417 }
418
419 /// <summary>
420 /// Inserts a new row into the log database
421 /// </summary>
422 /// <param name="serverDaemon">The daemon which triggered this event</param>
423 /// <param name="target">Who were we operating on when this occured (region UUID, user UUID, etc)</param>
424 /// <param name="methodCall">The method call where the problem occured</param>
425 /// <param name="arguments">The arguments passed to the method</param>
426 /// <param name="priority">How critical is this?</param>
427 /// <param name="logMessage">Extra message info</param>
428 /// <returns>Saved successfully?</returns>
429 public bool insertLogRow(string serverDaemon, string target, string methodCall, string arguments, int priority, string logMessage)
430 {
431 string sql = "INSERT INTO logs (`target`, `server`, `method`, `arguments`, `priority`, `message`) VALUES ";
432 sql += "(?target, ?server, ?method, ?arguments, ?priority, ?message)";
433
434 Dictionary<string, string> parameters = new Dictionary<string, string>();
435 parameters["?server"] = serverDaemon;
436 parameters["?target"] = target;
437 parameters["?method"] = methodCall;
438 parameters["?arguments"] = arguments;
439 parameters["?priority"] = priority.ToString();
440 parameters["?message"] = logMessage;
441
442 bool returnval = false;
443
444 try
445 {
446 IDbCommand result = Query(sql, parameters);
447
448 if (result.ExecuteNonQuery() == 1)
449 returnval = true;
450
451 result.Dispose();
452 }
453 catch (Exception e)
454 {
455 Console.WriteLine(e.ToString());
456 return false;
457 }
458
459 return returnval;
460 }
461
462 /// <summary>
463 /// Inserts a new item into the database
464 /// </summary>
465 /// <param name="item">The item</param>
466 /// <returns>Success?</returns>
467 public bool insertItem(InventoryItemBase item)
468 {
469 string sql = "REPLACE INTO inventoryitems (inventoryID, assetID, type, parentFolderID, avatarID, inventoryName, inventoryDescription, inventoryNextPermissions, inventoryCurrentPermissions) VALUES ";
470 sql += "(?inventoryID, ?assetID, ?type, ?parentFolderID, ?avatarID, ?inventoryName, ?inventoryDescription, ?inventoryNextPermissions, ?inventoryCurrentPermissions)";
471
472 Dictionary<string, string> parameters = new Dictionary<string, string>();
473 parameters["?inventoryID"] = item.inventoryID.ToStringHyphenated();
474 parameters["?assetID"] = item.assetID.ToStringHyphenated();
475 parameters["?type"] = item.type.ToString();
476 parameters["?parentFolderID"] = item.parentFolderID.ToStringHyphenated();
477 parameters["?avatarID"] = item.avatarID.ToStringHyphenated();
478 parameters["?inventoryName"] = item.inventoryName;
479 parameters["?inventoryDescription"] = item.inventoryDescription;
480 parameters["?inventoryNextPermissions"] = item.inventoryNextPermissions.ToString();
481 parameters["?inventoryCurrentPermissions"] = item.inventoryCurrentPermissions.ToString();
482
483 bool returnval = false;
484
485 try
486 {
487 IDbCommand result = Query(sql, parameters);
488
489 if (result.ExecuteNonQuery() == 1)
490 returnval = true;
491
492 result.Dispose();
493 }
494 catch (Exception e)
495 {
496 Console.WriteLine(e.ToString());
497 return false;
498 }
499
500 return returnval;
501 }
502
503 /// <summary>
504 /// Inserts a new folder into the database
505 /// </summary>
506 /// <param name="folder">The folder</param>
507 /// <returns>Success?</returns>
508 public bool insertFolder(InventoryFolderBase folder)
509 {
510 string sql = "REPLACE INTO inventoryfolders (folderID, agentID, parentFolderID, folderName) VALUES ";
511 sql += "(?folderID, ?agentID, ?parentFolderID, ?folderName)";
512
513 Dictionary<string, string> parameters = new Dictionary<string, string>();
514 parameters["?folderID"] = folder.folderID.ToStringHyphenated();
515 parameters["?agentID"] = folder.agentID.ToStringHyphenated();
516 parameters["?parentFolderID"] = folder.parentID.ToStringHyphenated();
517 parameters["?folderName"] = folder.name;
518
519 bool returnval = false;
520 try
521 {
522 IDbCommand result = Query(sql, parameters);
523
524 if (result.ExecuteNonQuery() == 1)
525 returnval = true;
526
527 result.Dispose();
528 }
529 catch (Exception e)
530 {
531 Console.WriteLine(e.ToString());
532 return false;
533 }
534 return returnval;
535 }
536
537 /// <summary>
538 /// Inserts a new region into the database
539 /// </summary>
540 /// <param name="profile">The region to insert</param>
541 /// <returns>Success?</returns>
542 public bool insertRegion(SimProfileData regiondata)
543 {
544 string sql = "REPLACE INTO regions (regionHandle, regionName, uuid, regionRecvKey, regionSecret, regionSendKey, regionDataURI, ";
545 sql += "serverIP, serverPort, serverURI, locX, locY, locZ, eastOverrideHandle, westOverrideHandle, southOverrideHandle, northOverrideHandle, regionAssetURI, regionAssetRecvKey, ";
546 sql += "regionAssetSendKey, regionUserURI, regionUserRecvKey, regionUserSendKey, regionMapTexture) VALUES ";
547
548 sql += "(?regionHandle, ?regionName, ?uuid, ?regionRecvKey, ?regionSecret, ?regionSendKey, ?regionDataURI, ";
549 sql += "?serverIP, ?serverPort, ?serverURI, ?locX, ?locY, ?locZ, ?eastOverrideHandle, ?westOverrideHandle, ?southOverrideHandle, ?northOverrideHandle, ?regionAssetURI, ?regionAssetRecvKey, ";
550 sql += "?regionAssetSendKey, ?regionUserURI, ?regionUserRecvKey, ?regionUserSendKey, ?regionMapTexture);";
551
552 Dictionary<string, string> parameters = new Dictionary<string, string>();
553
554 parameters["?regionHandle"] = regiondata.regionHandle.ToString();
555 parameters["?regionName"] = regiondata.regionName.ToString();
556 parameters["?uuid"] = regiondata.UUID.ToStringHyphenated();
557 parameters["?regionRecvKey"] = regiondata.regionRecvKey.ToString();
558 parameters["?regionSecret"] = regiondata.regionSecret.ToString();
559 parameters["?regionSendKey"] = regiondata.regionSendKey.ToString();
560 parameters["?regionDataURI"] = regiondata.regionDataURI.ToString();
561 parameters["?serverIP"] = regiondata.serverIP.ToString();
562 parameters["?serverPort"] = regiondata.serverPort.ToString();
563 parameters["?serverURI"] = regiondata.serverURI.ToString();
564 parameters["?locX"] = regiondata.regionLocX.ToString();
565 parameters["?locY"] = regiondata.regionLocY.ToString();
566 parameters["?locZ"] = regiondata.regionLocZ.ToString();
567 parameters["?eastOverrideHandle"] = regiondata.regionEastOverrideHandle.ToString();
568 parameters["?westOverrideHandle"] = regiondata.regionWestOverrideHandle.ToString();
569 parameters["?northOverrideHandle"] = regiondata.regionNorthOverrideHandle.ToString();
570 parameters["?southOverrideHandle"] = regiondata.regionSouthOverrideHandle.ToString();
571 parameters["?regionAssetURI"] = regiondata.regionAssetURI.ToString();
572 parameters["?regionAssetRecvKey"] = regiondata.regionAssetRecvKey.ToString();
573 parameters["?regionAssetSendKey"] = regiondata.regionAssetSendKey.ToString();
574 parameters["?regionUserURI"] = regiondata.regionUserURI.ToString();
575 parameters["?regionUserRecvKey"] = regiondata.regionUserRecvKey.ToString();
576 parameters["?regionUserSendKey"] = regiondata.regionUserSendKey.ToString();
577 parameters["?regionMapTexture"] = regiondata.regionMapTextureID.ToStringHyphenated();
578
579 bool returnval = false;
580
581 try
582 {
583
584 IDbCommand result = Query(sql, parameters);
585
586 //Console.WriteLine(result.CommandText);
587
588 if (result.ExecuteNonQuery() == 1)
589 returnval = true;
590
591 result.Dispose();
592 }
593 catch (Exception e)
594 {
595 Console.WriteLine(e.ToString());
596 return false;
597 }
598
599 return returnval;
600 }
601 }
602}