Fixed SCA warnings

This commit is contained in:
high 2011-08-06 16:49:40 -04:00
parent 72d49d421c
commit 56eca71853
13 changed files with 299 additions and 236 deletions

View file

@ -797,9 +797,10 @@ namespace TShockAPI
{ {
if (args.Parameters.Count == 1) if (args.Parameters.Count == 1)
{ {
TextWriter tw = new StreamWriter(FileTools.WhitelistPath, true); using (var tw = new StreamWriter(FileTools.WhitelistPath, true))
tw.WriteLine(args.Parameters[0]); {
tw.Close(); tw.WriteLine(args.Parameters[0]);
}
args.Player.SendMessage("Added " + args.Parameters[0] + " to the whitelist."); args.Player.SendMessage("Added " + args.Parameters[0] + " to the whitelist.");
} }
} }
@ -862,31 +863,38 @@ namespace TShockAPI
ThreadPool.QueueUserWorkItem(UpdateManager.CheckUpdate); ThreadPool.QueueUserWorkItem(UpdateManager.CheckUpdate);
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
private static void UpdateNow(CommandArgs args) private static void UpdateNow(CommandArgs args)
{ {
Process TServer = Process.GetCurrentProcess(); Process TServer = Process.GetCurrentProcess();
StreamWriter sw = new StreamWriter("pid"); using (var sw = new StreamWriter("pid"))
sw.Write(TServer.Id); {
sw.Close(); sw.Write(TServer.Id);
}
sw = new StreamWriter("pn"); using (var sw = new StreamWriter("pn"))
sw.Write(TServer.ProcessName + " " + Environment.CommandLine); {
sw.Close(); sw.Write(TServer.ProcessName + " " + Environment.CommandLine);
}
WebClient client = new WebClient(); using (var client = new WebClient())
client.Headers.Add("user-agent", "TShock"); {
byte[] updatefile = client.DownloadData("http://tsupdate.shankshock.com/UpdateTShock.exe"); client.Headers.Add("user-agent", "TShock");
byte[] updatefile = client.DownloadData("http://tsupdate.shankshock.com/UpdateTShock.exe");
BinaryWriter bw = new BinaryWriter(new FileStream("UpdateTShock.exe", FileMode.Create)); using (var bw = new BinaryWriter(new FileStream("UpdateTShock.exe", FileMode.Create)))
bw.Write(updatefile); {
bw.Close(); bw.Write(updatefile);
}
}
Process.Start(new ProcessStartInfo("UpdateTShock.exe")); Process.Start(new ProcessStartInfo("UpdateTShock.exe"));
Tools.ForceKickAll("Server shutting down for update!"); Tools.ForceKickAll("Server shutting down for update!");
WorldGen.saveWorld(); WorldGen.saveWorld();
Netplay.disconnect = true; Netplay.disconnect = true;
} }
#endregion Server Maintenence Commands #endregion Server Maintenence Commands
@ -1237,7 +1245,7 @@ namespace TShockAPI
args.Player.SendMessage("Could not find specified warp", Color.Red); args.Player.SendMessage("Could not find specified warp", Color.Red);
} }
else else
args.Player.SendMessage("Invalid syntax! Proper syntax: /hidewarp [name] <true/false>", Color.Red); args.Player.SendMessage("Invalid syntax! Proper syntax: /hidewarp [name] <true/false>", Color.Red);
} }
else else
args.Player.SendMessage("Invalid syntax! Proper syntax: /hidewarp [name] <true/false>", Color.Red); args.Player.SendMessage("Invalid syntax! Proper syntax: /hidewarp [name] <true/false>", Color.Red);
@ -1330,10 +1338,10 @@ namespace TShockAPI
{ {
String groupname = args.Parameters[0]; String groupname = args.Parameters[0];
args.Parameters.RemoveAt(0); args.Parameters.RemoveAt(0);
String permissions = String.Join(",", args.Parameters ); String permissions = String.Join(",", args.Parameters);
String response = TShock.Groups.AddGroup(groupname, permissions); String response = TShock.Groups.AddGroup(groupname, permissions);
if( response.Length > 0 ) if (response.Length > 0)
args.Player.SendMessage(response, Color.Green); args.Player.SendMessage(response, Color.Green);
} }
else else
@ -1389,7 +1397,7 @@ namespace TShockAPI
#endregion Group Management #endregion Group Management
#region Item Management #region Item Management
private static void AddItem(CommandArgs args) private static void AddItem(CommandArgs args)
{ {
if (args.Parameters.Count > 0) if (args.Parameters.Count > 0)
@ -2231,9 +2239,9 @@ namespace TShockAPI
args.Parameters.RemoveAt(0); args.Parameters.RemoveAt(0);
string plStr = args.Parameters[0]; string plStr = args.Parameters[0];
args.Parameters.RemoveAt(0); args.Parameters.RemoveAt(0);
if( args.Parameters.Count > 0 ) if (args.Parameters.Count > 0)
int.TryParse(args.Parameters[args.Parameters.Count - 1], out itemAmount); int.TryParse(args.Parameters[args.Parameters.Count - 1], out itemAmount);
if (items.Count == 0) if (items.Count == 0)
{ {

View file

@ -54,6 +54,7 @@ namespace TShockAPI.DB
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
public void ImportOld() public void ImportOld()
{ {
String file = Path.Combine(TShock.SavePath, "regions.xml"); String file = Path.Combine(TShock.SavePath, "regions.xml");
@ -62,77 +63,74 @@ namespace TShockAPI.DB
Region region; Region region;
Rectangle rect; Rectangle rect;
using (var sr = new StreamReader(file))
using (var reader = XmlReader.Create(new StreamReader(file), new XmlReaderSettings { CloseInput = true }))
{ {
using (var reader = XmlReader.Create(sr)) // Parse the file and display each of the nodes.
while (reader.Read())
{ {
// Parse the file and display each of the nodes. if (reader.NodeType != XmlNodeType.Element || reader.Name != "ProtectedRegion")
while (reader.Read()) continue;
region = new Region();
rect = new Rectangle();
bool endregion = false;
while (reader.Read() && !endregion)
{ {
if (reader.NodeType != XmlNodeType.Element || reader.Name != "ProtectedRegion") if (reader.NodeType != XmlNodeType.Element)
continue; continue;
region = new Region(); string name = reader.Name;
rect = new Rectangle();
bool endregion = false; while (reader.Read() && reader.NodeType != XmlNodeType.Text) ;
while (reader.Read() && !endregion)
switch (name)
{ {
if (reader.NodeType != XmlNodeType.Element) case "RegionName":
continue; region.Name = reader.Value;
break;
string name = reader.Name; case "Point1X":
int.TryParse(reader.Value, out rect.X);
while (reader.Read() && reader.NodeType != XmlNodeType.Text) ; break;
case "Point1Y":
switch (name) int.TryParse(reader.Value, out rect.Y);
{ break;
case "RegionName": case "Point2X":
region.Name = reader.Value; int.TryParse(reader.Value, out rect.Width);
break; break;
case "Point1X": case "Point2Y":
int.TryParse(reader.Value, out rect.X); int.TryParse(reader.Value, out rect.Height);
break; break;
case "Point1Y": case "Protected":
int.TryParse(reader.Value, out rect.Y); region.DisableBuild = reader.Value.ToLower().Equals("true");
break; break;
case "Point2X": case "WorldName":
int.TryParse(reader.Value, out rect.Width); region.WorldID = reader.Value;
break; break;
case "Point2Y": case "AllowedUserCount":
int.TryParse(reader.Value, out rect.Height); break;
break; case "IP":
case "Protected": region.AllowedIDs.Add(int.Parse(reader.Value));
region.DisableBuild = reader.Value.ToLower().Equals("true"); break;
break; default:
case "WorldName": endregion = true;
region.WorldID = reader.Value; break;
break;
case "AllowedUserCount":
break;
case "IP":
region.AllowedIDs.Add(int.Parse(reader.Value));
break;
default:
endregion = true;
break;
}
}
region.Area = rect;
using (var com = database.CreateCommand())
{
string query = (TShock.Config.StorageType.ToLower() == "sqlite") ?
"INSERT OR IGNORE INTO Regions VALUES (@0, @1, @2, @3, @4, @5, @6, @7);" :
"INSERT IGNORE INTO Regions SET X1=@0, Y1=@1, height=@2, width=@3, RegionName=@4, WorldID=@5, UserIds=@6, Protected=@7;";
database.Query(query, region.Area.X, region.Area.Y, region.Area.Width, region.Area.Height, region.Name, region.WorldID, "", region.DisableBuild);
//Todo: What should this be? We don't really have a way to go from ips to userids
/*string.Join(",", region.AllowedIDs)*/
} }
} }
region.Area = rect;
string query = (TShock.Config.StorageType.ToLower() == "sqlite") ?
"INSERT OR IGNORE INTO Regions VALUES (@0, @1, @2, @3, @4, @5, @6, @7);" :
"INSERT IGNORE INTO Regions SET X1=@0, Y1=@1, height=@2, width=@3, RegionName=@4, WorldID=@5, UserIds=@6, Protected=@7;";
database.Query(query, region.Area.X, region.Area.Y, region.Area.Width, region.Area.Height, region.Name, region.WorldID, "", region.DisableBuild);
//Todo: What should this be? We don't really have a way to go from ips to userids
/*string.Join(",", region.AllowedIDs)*/
} }
} }
String path = Path.Combine(TShock.SavePath, "old_configs"); String path = Path.Combine(TShock.SavePath, "old_configs");
String file2 = Path.Combine(path, "regions.xml"); String file2 = Path.Combine(path, "regions.xml");
if (!Directory.Exists(path)) if (!Directory.Exists(path))

View file

@ -350,6 +350,7 @@ namespace TShockAPI.DB
} }
} }
[Serializable]
public class UserManagerException : Exception public class UserManagerException : Exception
{ {
public UserManagerException(string message) public UserManagerException(string message)
@ -363,6 +364,7 @@ namespace TShockAPI.DB
} }
} }
[Serializable]
public class UserExistsException : UserManagerException public class UserExistsException : UserManagerException
{ {
public UserExistsException(string name) public UserExistsException(string name)
@ -370,6 +372,7 @@ namespace TShockAPI.DB
{ {
} }
} }
[Serializable]
public class UserNotExistException : UserManagerException public class UserNotExistException : UserManagerException
{ {
public UserNotExistException(string name) public UserNotExistException(string name)
@ -377,7 +380,7 @@ namespace TShockAPI.DB
{ {
} }
} }
[Serializable]
public class GroupNotExistsException : UserManagerException public class GroupNotExistsException : UserManagerException
{ {
public GroupNotExistsException(string group) public GroupNotExistsException(string group)

View file

@ -31,12 +31,13 @@ namespace TShockAPI.DB
{ {
private IDbConnection database; private IDbConnection database;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
public WarpManager(IDbConnection db) public WarpManager(IDbConnection db)
{ {
database = db; database = db;
var table = new SqlTable("Warps", var table = new SqlTable("Warps",
new SqlColumn("WarpName", MySqlDbType.VarChar, 50) { Primary = true}, new SqlColumn("WarpName", MySqlDbType.VarChar, 50) { Primary = true },
new SqlColumn("X", MySqlDbType.Int32), new SqlColumn("X", MySqlDbType.Int32),
new SqlColumn("Y", MySqlDbType.Int32), new SqlColumn("Y", MySqlDbType.Int32),
new SqlColumn("WorldID", MySqlDbType.Text), new SqlColumn("WorldID", MySqlDbType.Text),
@ -50,78 +51,76 @@ namespace TShockAPI.DB
String world = ""; String world = "";
int x1 = 0; int x1 = 0;
int y1 = 0; int y1 = 0;
if (File.Exists(file)) if (!File.Exists(file))
return;
using (var reader = XmlReader.Create(new StreamReader(file), new XmlReaderSettings { CloseInput = true }))
{ {
XmlReader reader; // Parse the file and display each of the nodes.
using (reader = XmlReader.Create(new StreamReader(file))) while (reader.Read())
{ {
// Parse the file and display each of the nodes. switch (reader.NodeType)
while (reader.Read())
{ {
switch (reader.NodeType) case XmlNodeType.Element:
{ switch (reader.Name)
case XmlNodeType.Element: {
switch (reader.Name) case "Warp":
{ name = "";
case "Warp": world = "";
name = ""; x1 = 0;
world = ""; y1 = 0;
x1 = 0; break;
y1 = 0; case "WarpName":
break; while (reader.NodeType != XmlNodeType.Text)
case "WarpName": reader.Read();
while (reader.NodeType != XmlNodeType.Text) name = reader.Value;
reader.Read(); break;
name = reader.Value; case "X":
break; while (reader.NodeType != XmlNodeType.Text)
case "X": reader.Read();
while (reader.NodeType != XmlNodeType.Text) int.TryParse(reader.Value, out x1);
reader.Read(); break;
int.TryParse(reader.Value, out x1); case "Y":
break; while (reader.NodeType != XmlNodeType.Text)
case "Y": reader.Read();
while (reader.NodeType != XmlNodeType.Text) int.TryParse(reader.Value, out y1);
reader.Read(); break;
int.TryParse(reader.Value, out y1); case "WorldName":
break; while (reader.NodeType != XmlNodeType.Text)
case "WorldName": reader.Read();
while (reader.NodeType != XmlNodeType.Text) world = reader.Value;
reader.Read(); break;
world = reader.Value; }
break; break;
} case XmlNodeType.Text:
break;
case XmlNodeType.Text:
break; break;
case XmlNodeType.XmlDeclaration: case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction: case XmlNodeType.ProcessingInstruction:
break; break;
case XmlNodeType.Comment: case XmlNodeType.Comment:
break; break;
case XmlNodeType.EndElement: case XmlNodeType.EndElement:
if (reader.Name.Equals("Warp")) if (reader.Name.Equals("Warp"))
{ {
string query = (TShock.Config.StorageType.ToLower() == "sqlite") ? string query = (TShock.Config.StorageType.ToLower() == "sqlite")
"INSERT OR IGNORE INTO Warps VALUES (@0, @1,@2, @3);" : ? "INSERT OR IGNORE INTO Warps VALUES (@0, @1,@2, @3);"
"INSERT IGNORE INTO Warps SET X=@0, Y=@1, WarpName=@2, WorldID=@3;"; : "INSERT IGNORE INTO Warps SET X=@0, Y=@1, WarpName=@2, WorldID=@3;";
database.Query(query, x1, y1, name, world); database.Query(query, x1, y1, name, world);
} }
break; break;
}
} }
} }
reader.Close();
String path = Path.Combine(TShock.SavePath, "old_configs");
String file2 = Path.Combine(path, "warps.xml");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
if (File.Exists(file2))
File.Delete(file2);
//File.Move(file, file2);
} }
String path = Path.Combine(TShock.SavePath, "old_configs");
String file2 = Path.Combine(path, "warps.xml");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
if (File.Exists(file2))
File.Delete(file2);
File.Move(file, file2);
} }
public void ConvertDB() public void ConvertDB()

View file

@ -14,6 +14,7 @@ namespace TShockAPI.DB
/// <param name="query">Query string with parameters as @0, @1, etc.</param> /// <param name="query">Query string with parameters as @0, @1, etc.</param>
/// <param name="args">Parameters to be put in the query</param> /// <param name="args">Parameters to be put in the query</param>
/// <returns>Rows affected by query</returns> /// <returns>Rows affected by query</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")]
public static int Query(this IDbConnection olddb, string query, params object[] args) public static int Query(this IDbConnection olddb, string query, params object[] args)
{ {
using (var db = olddb.CloneEx()) using (var db = olddb.CloneEx())
@ -36,6 +37,7 @@ namespace TShockAPI.DB
/// <param name="query">Query string with parameters as @0, @1, etc.</param> /// <param name="query">Query string with parameters as @0, @1, etc.</param>
/// <param name="args">Parameters to be put in the query</param> /// <param name="args">Parameters to be put in the query</param>
/// <returns>Query result as IDataReader</returns> /// <returns>Query result as IDataReader</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")]
public static QueryResult QueryReader(this IDbConnection olddb, string query, params object[] args) public static QueryResult QueryReader(this IDbConnection olddb, string query, params object[] args)
{ {
var db = olddb.CloneEx(); var db = olddb.CloneEx();
@ -125,10 +127,32 @@ namespace TShockAPI.DB
Reader = reader; Reader = reader;
} }
~QueryResult()
{
Dispose(false);
}
public void Dispose() public void Dispose()
{ {
Reader.Dispose(); Dispose(true);
Connection.Dispose(); GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (Reader != null)
{
Reader.Dispose();
Reader = null;
}
if (Connection != null)
{
Connection.Dispose();
Connection = null;
}
}
} }
public bool Read() public bool Read()

View file

@ -73,7 +73,7 @@ namespace TShockAPI
Log.Error(ex.ToString()); Log.Error(ex.ToString());
} }
} }
/// <summary> /// <summary>
@ -88,26 +88,25 @@ namespace TShockAPI
return true; return true;
} }
CreateIfNot(WhitelistPath, "127.0.0.1"); CreateIfNot(WhitelistPath, "127.0.0.1");
TextReader tr = new StreamReader(WhitelistPath); using (var tr = new StreamReader(WhitelistPath))
string whitelist = tr.ReadToEnd();
ip = Tools.GetRealIP(ip);
bool contains = whitelist.Contains(ip);
if (!contains)
{ {
var char2 = Environment.NewLine.ToCharArray(); string whitelist = tr.ReadToEnd();
var array = whitelist.Split(Environment.NewLine.ToCharArray()); ip = Tools.GetRealIP(ip);
foreach (var line in whitelist.Split(Environment.NewLine.ToCharArray())) bool contains = whitelist.Contains(ip);
if (!contains)
{ {
if (string.IsNullOrWhiteSpace(line)) foreach (var line in whitelist.Split(Environment.NewLine.ToCharArray()))
continue; {
contains = Tools.GetIPv4Address(line).Equals(ip); if (string.IsNullOrWhiteSpace(line))
if (contains) continue;
return true; contains = Tools.GetIPv4Address(line).Equals(ip);
if (contains)
return true;
}
return false;
} }
return false;
}
else
return true; return true;
}
} }
} }
} }

View file

@ -24,8 +24,10 @@ namespace TShockAPI
int[] Packets = new int[52]; int[] Packets = new int[52];
int[] Compressed = new int[52]; int[] Compressed = new int[52];
#if DEBUG_NET
Command dump; Command dump;
Command flush; Command flush;
#endif
public PacketBufferer() public PacketBufferer()
{ {
@ -45,15 +47,29 @@ namespace TShockAPI
GameHooks.PostUpdate += GameHooks_Update; GameHooks.PostUpdate += GameHooks_Update;
} }
~PacketBufferer()
{
Dispose(false);
}
public void Dispose() public void Dispose()
{ {
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
#if DEBUG_NET #if DEBUG_NET
Commands.ChatCommands.Remove(dump); Commands.ChatCommands.Remove(dump);
Commands.ChatCommands.Remove(flush); Commands.ChatCommands.Remove(flush);
#endif #endif
ServerHooks.SendBytes -= ServerHooks_SendBytes; ServerHooks.SendBytes -= ServerHooks_SendBytes;
ServerHooks.SocketReset -= ServerHooks_SocketReset; ServerHooks.SocketReset -= ServerHooks_SocketReset;
GameHooks.PostUpdate -= GameHooks_Update; GameHooks.PostUpdate -= GameHooks_Update;
}
} }
void Dump(CommandArgs args) void Dump(CommandArgs args)
@ -120,7 +136,10 @@ namespace TShockAPI
Bytes[pt] += size; Bytes[pt] += size;
Compressed[pt] += Compress(buffer, offset, count); Compressed[pt] += Compress(buffer, offset, count);
#endif #endif
buffers[socket.whoAmI].AddRange(new MemoryStream(buffer, offset, count).ToArray()); using (var ms = new MemoryStream(buffer, offset, count))
{
buffers[socket.whoAmI].AddRange(ms.ToArray());
}
} }
} }
#if DEBUG_NET #if DEBUG_NET

View file

@ -36,5 +36,5 @@ using System.Runtime.InteropServices;
// [assembly: AssemblyVersion("1.0.*")] // [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.2.1.0805")] [assembly: AssemblyVersion("3.2.1.0806")]
[assembly: AssemblyFileVersion("3.2.1.0805")] [assembly: AssemblyFileVersion("3.2.1.0806")]

View file

@ -24,6 +24,7 @@ using System.Net.Sockets;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using Terraria; using Terraria;
using XNAHelpers;
namespace TShockAPI namespace TShockAPI
{ {
@ -116,11 +117,13 @@ namespace TShockAPI
try try
{ {
var EP = new IPEndPoint(IPAddress.Any, port); var EP = new IPEndPoint(IPAddress.Any, port);
UdpClient client = new UdpClient(); using (var client = new UdpClient())
client.Connect(hostname, port); {
client.Client.ReceiveTimeout = 500; client.Connect(hostname, port);
client.Send(bytes, bytes.Length); client.Client.ReceiveTimeout = 500;
response = Encoding.UTF8.GetString(client.Receive(ref EP)); client.Send(bytes, bytes.Length);
response = Encoding.UTF8.GetString(client.Receive(ref EP));
}
} }
catch (Exception e) catch (Exception e)
{ {
@ -259,7 +262,7 @@ namespace TShockAPI
if (player != null && player.Active) if (player != null && player.Active)
{ {
count++; count++;
Response += (string.Format("{0} 0 0 {1}({2}) {3} {4} 0 0", count, player.Name, player.Group.Name, Netplay.serverSock[player.Index].tcpClient.Client.RemoteEndPoint)) + "\n"; Response += (string.Format("{0} 0 0 {1}({2}) {3} {4} 0 0", count, player.Name, player.Group.Name, Netplay.serverSock[player.Index].tcpClient.Client.RemoteEndPoint, "")) + "\n";
} }
} }
} }
@ -288,17 +291,18 @@ namespace TShockAPI
private static byte[] ConstructPacket(string response, bool print) private static byte[] ConstructPacket(string response, bool print)
{ {
var oob = new byte[] { 0xFF, 0xFF, 0xFF, 0xFF }; var oob = new byte[] { 0xFF, 0xFF, 0xFF, 0xFF };
MemoryStream stream = new MemoryStream(); using (var stream = new MemoryStream())
BinaryWriter writer = new BinaryWriter(stream); {
writer.Write(oob); stream.WriteBytes(oob);
if (print) if (print)
writer.Write(Encoding.UTF8.GetBytes(string.Format("print\n{0}", response))); stream.WriteBytes(Encoding.UTF8.GetBytes(string.Format("print\n{0}", response)));
else else
writer.Write(Encoding.UTF8.GetBytes(response)); stream.WriteBytes(Encoding.UTF8.GetBytes(response));
var trimmedpacket = new byte[(int)stream.Length]; var trimmedpacket = new byte[(int)stream.Length];
var packet = stream.GetBuffer(); var packet = stream.GetBuffer();
Array.Copy(packet, trimmedpacket, (int)stream.Length); Array.Copy(packet, trimmedpacket, (int)stream.Length);
return trimmedpacket; return trimmedpacket;
}
} }
private static byte[] PadPacket(byte[] packet) private static byte[] PadPacket(byte[] packet)

View file

@ -178,9 +178,11 @@ namespace TShockAPI
}; };
var ms = new MemoryStream(); using (var ms = new MemoryStream())
msg.PackFull(ms); {
SendRawData(ms.ToArray()); msg.PackFull(ms);
SendRawData(ms.ToArray());
}
} }
public bool Teleport(int tilex, int tiley) public bool Teleport(int tilex, int tiley)

View file

@ -94,6 +94,7 @@ namespace TShockAPI
Order = 0; Order = 0;
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
public override void Initialize() public override void Initialize()
{ {
if (!Directory.Exists(SavePath)) if (!Directory.Exists(SavePath))
@ -315,15 +316,17 @@ namespace TShockAPI
Console.WriteLine("This token will display until disabled by verification. (/auth-verify)"); Console.WriteLine("This token will display until disabled by verification. (/auth-verify)");
Console.ForegroundColor = ConsoleColor.Gray; Console.ForegroundColor = ConsoleColor.Gray;
FileTools.CreateFile(Path.Combine(SavePath, "authcode.txt")); FileTools.CreateFile(Path.Combine(SavePath, "authcode.txt"));
TextWriter tw = new StreamWriter(Path.Combine(SavePath, "authcode.txt")); using (var tw = new StreamWriter(Path.Combine(SavePath, "authcode.txt")))
tw.WriteLine(AuthToken); {
tw.Close(); tw.WriteLine(AuthToken);
}
} }
else if (File.Exists(Path.Combine(SavePath, "authcode.txt"))) else if (File.Exists(Path.Combine(SavePath, "authcode.txt")))
{ {
TextReader tr = new StreamReader(Path.Combine(SavePath, "authcode.txt")); using (var tr = new StreamReader(Path.Combine(SavePath, "authcode.txt")))
AuthToken = Convert.ToInt32(tr.ReadLine()); {
tr.Close(); AuthToken = Convert.ToInt32(tr.ReadLine());
}
Console.ForegroundColor = ConsoleColor.Yellow; Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine( Console.WriteLine(
"TShock Notice: authcode.txt is still present, and the AuthToken located in that file will be used."); "TShock Notice: authcode.txt is still present, and the AuthToken located in that file will be used.");

View file

@ -428,34 +428,36 @@ namespace TShockAPI
public static void ShowFileToUser(TSPlayer player, string file) public static void ShowFileToUser(TSPlayer player, string file)
{ {
string foo = ""; string foo = "";
TextReader tr = new StreamReader(Path.Combine(TShock.SavePath, file)); using (var tr = new StreamReader(Path.Combine(TShock.SavePath, file)))
while ((foo = tr.ReadLine()) != null)
{ {
foo = foo.Replace("%map%", Main.worldName); while ((foo = tr.ReadLine()) != null)
foo = foo.Replace("%players%", GetPlayers());
if (foo.Substring(0, 1) == "%" && foo.Substring(12, 1) == "%") //Look for a beginning color code.
{ {
string possibleColor = foo.Substring(0, 13); foo = foo.Replace("%map%", Main.worldName);
foo = foo.Remove(0, 13); foo = foo.Replace("%players%", GetPlayers());
float[] pC = { 0, 0, 0 }; if (foo.Substring(0, 1) == "%" && foo.Substring(12, 1) == "%") //Look for a beginning color code.
possibleColor = possibleColor.Replace("%", "");
string[] pCc = possibleColor.Split(',');
if (pCc.Length == 3)
{ {
try string possibleColor = foo.Substring(0, 13);
foo = foo.Remove(0, 13);
float[] pC = {0, 0, 0};
possibleColor = possibleColor.Replace("%", "");
string[] pCc = possibleColor.Split(',');
if (pCc.Length == 3)
{ {
player.SendMessage(foo, (byte)Convert.ToInt32(pCc[0]), (byte)Convert.ToInt32(pCc[1]), (byte)Convert.ToInt32(pCc[2])); try
continue; {
} player.SendMessage(foo, (byte) Convert.ToInt32(pCc[0]), (byte) Convert.ToInt32(pCc[1]),
catch (Exception e) (byte) Convert.ToInt32(pCc[2]));
{ continue;
Log.Error(e.ToString()); }
catch (Exception e)
{
Log.Error(e.ToString());
}
} }
} }
player.SendMessage(foo);
} }
player.SendMessage(foo);
} }
tr.Close();
} }
/// <summary> /// <summary>

View file

@ -55,26 +55,28 @@ namespace TShockAPI
/// <returns></returns> /// <returns></returns>
private static bool ServerIsOutOfDate() private static bool ServerIsOutOfDate()
{ {
WebClient client = new WebClient(); using (var client = new WebClient())
client.Headers.Add("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705;)");
try
{ {
string updateString = client.DownloadString(updateUrl); client.Headers.Add("user-agent",
string[] changes = updateString.Split(','); "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705;)");
Version updateVersion = new Version(Convert.ToInt32(changes[0]), Convert.ToInt32(changes[1]), try
Convert.ToInt32(changes[2]), Convert.ToInt32(changes[3]));
if (TShock.VersionNum.CompareTo(updateVersion) < 0)
{ {
globalChanges = changes; string updateString = client.DownloadString(updateUrl);
return true; string[] changes = updateString.Split(',');
Version updateVersion = new Version(Convert.ToInt32(changes[0]), Convert.ToInt32(changes[1]),
Convert.ToInt32(changes[2]), Convert.ToInt32(changes[3]));
if (TShock.VersionNum.CompareTo(updateVersion) < 0)
{
globalChanges = changes;
return true;
}
} }
catch (Exception e)
{
Log.Error(e.ToString());
}
return false;
} }
catch (Exception e)
{
Log.Error(e.ToString());
}
return false;
} }
private static void NotifyAdministrators(string[] changes) private static void NotifyAdministrators(string[] changes)